fluxflow-cli 4.22.1 → 4.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/TOOLS.md +1 -2
- package/dist/chunks/{ai-RFTQLPYD.js → ai-JW7FGVQF.js} +1 -1
- package/dist/chunks/{app-D7ZS4M6W.js → app-ZUPKVM5U.js} +2 -2
- package/dist/chunks/{chunk-NXJB3LHY.js → chunk-NUZCHZRM.js} +76 -78
- package/dist/chunks/{chunk-IU4E277E.js → chunk-S25OD4YB.js} +9 -9
- package/dist/chunks/{chunk-57DBJNK7.js → chunk-XCUZ3OIF.js} +1 -1
- package/dist/chunks/{exec_command-BP3TON5E.js → exec_command-2AU2ICOX.js} +1 -1
- package/dist/chunks/{invoke-NX4ZZRZI.js → invoke-TNCJFZDK.js} +2 -2
- package/dist/chunks/{invokeSync-KKRTA6RL.js → invokeSync-MWJR3YU7.js} +2 -2
- package/dist/cli.js +18 -14
- package/dist/package.json +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Kt}from"./chunk-56EJGQU3.js";import{a as ao}from"./chunk-ORXN6WUW.js";import{a as Ai,c as Ei}from"./chunk-
|
|
1
|
+
import{a as Kt}from"./chunk-56EJGQU3.js";import{a as ao}from"./chunk-ORXN6WUW.js";import{a as Ai,c as Ei}from"./chunk-S25OD4YB.js";import{a as Es,g as Ci}from"./chunk-NPYHHQDC.js";import{a as Ri}from"./chunk-2KD7V3OK.js";import{c as _s,g as Ti,h as Si,i as _i,m as As}from"./chunk-UDJ2C3N3.js";import{a as Oo}from"./chunk-YUJMCXJA.js";import{a as re}from"./chunk-Y5JU726N.js";import{b as Ts}from"./chunk-Y6DZDEJ5.js";import{d as Do,i as Et,k as Bt,m as Ss,n as wi}from"./chunk-74DZYKIT.js";import{a as ro}from"./chunk-PS3TUC3G.js";import{k as ft,l as Io,o as pe}from"./chunk-QGPOMXO4.js";import{c as At,d as Jn}from"./chunk-SIINYZWE.js";import{a as on,d as Mn,e as Ro,k as Wn,l as vo,m as ks,r as ws,v as Mo}from"./chunk-RI37VZYB.js";import{GoogleGenAI as Yr,ThinkingLevel as Qe,HarmBlockThreshold as On,HarmCategory as Ln}from"@google/genai";var vi=(e=!0,t=!0)=>`
|
|
2
2
|
To use tools, must output exactly '[tool:ToolName(arg1="value1")]' structured string in chat response \u2190 no exception
|
|
3
3
|
|
|
4
4
|
-- Chat Management Tools --
|
|
@@ -46,7 +46,7 @@ Dont waste tokens, be efficient, use least thinking tokens, focus on result
|
|
|
46
46
|
Gather useful context
|
|
47
47
|
Brief thoughts, think only enough to avoid mistakes, verify imports, system stability`,Off:`Effort: Lowest
|
|
48
48
|
No thinking. Immediate response
|
|
49
|
-
Verify imports, tool results & system stability`};import lo from"fs";var bn=null,Cs=()=>{try{if(lo.existsSync(Mo)){let e=lo.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return bn=t,bn}}catch{}return bn=bn||{},bn},Mi=e=>{try{return lo.existsSync(on)||lo.mkdirSync(on,{recursive:!0}),lo.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),bn=e,!0}catch{return!1}},Ve=(e,t,n)=>{if(!e||!t||!n)return null;let s=bn||Cs(),o=`${e}::${t}`,l=s[o];if(l&&typeof l=="object"){let u=n.toLowerCase();if(l[u]!==void 0&&l[u]!==null)return l[u];for(let[a,p]of Object.entries(l))if(a.toLowerCase()===u)return p}return null},gl=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=bn||Cs(),l=`${e}::${t}`;return(!o[l]||typeof o[l]!="object")&&(o[l]={}),o[l][n.toLowerCase()]=s,{success:Mi(o)}},hl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=bn||Cs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Mi(s)),{success:!0}};import sn from"fs";import fn from"path";import pa from"os";import dn from"fs";import In from"path";import Gi from"fs";import
|
|
49
|
+
Verify imports, tool results & system stability`};import lo from"fs";var bn=null,Cs=()=>{try{if(lo.existsSync(Mo)){let e=lo.readFileSync(Mo,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return bn=t,bn}}catch{}return bn=bn||{},bn},Mi=e=>{try{return lo.existsSync(on)||lo.mkdirSync(on,{recursive:!0}),lo.writeFileSync(Mo,JSON.stringify(e,null,2),"utf-8"),bn=e,!0}catch{return!1}},Ve=(e,t,n)=>{if(!e||!t||!n)return null;let s=bn||Cs(),o=`${e}::${t}`,l=s[o];if(l&&typeof l=="object"){let u=n.toLowerCase();if(l[u]!==void 0&&l[u]!==null)return l[u];for(let[a,p]of Object.entries(l))if(a.toLowerCase()===u)return p}return null},gl=(e,t,n,s)=>{if(!e||!t||!n||!s)return{success:!1,reason:"Invalid arguments"};let o=bn||Cs(),l=`${e}::${t}`;return(!o[l]||typeof o[l]!="object")&&(o[l]={}),o[l][n.toLowerCase()]=s,{success:Mi(o)}},hl=(e,t,n)=>{if(!e||!t)return{success:!1,reason:"Invalid arguments"};let s=bn||Cs(),o=`${e}::${t}`;return s[o]&&(n?(delete s[o][n.toLowerCase()],Object.keys(s[o]).length===0&&delete s[o]):delete s[o],Mi(s)),{success:!0}};import sn from"fs";import fn from"path";import pa from"os";import dn from"fs";import In from"path";import Gi from"fs";import Rs from"path";import{execSync as ji}from"child_process";import{fileURLToPath as ma}from"url";var Ii=`# FluxFlow CLI Startup & Flags Reference
|
|
50
50
|
|
|
51
51
|
Launch command syntax:
|
|
52
52
|
fluxflow [options]
|
|
@@ -444,7 +444,7 @@ Instruction for this model ID across all providers.
|
|
|
444
444
|
|
|
445
445
|
* On-Demand Reference System:
|
|
446
446
|
* Reference: Offload deep/contexual specs to **/{SKILL.md,skill-reference-folder/*.md} & reference in SKILL.md. Saves tokens
|
|
447
|
-
`;var Po="v4";try{let e=
|
|
447
|
+
`;var Po="v4";try{let e=Rs.dirname(ma(import.meta.url)),t=[Rs.join(e,"../../package.json"),Rs.join(e,"../package.json")],n=!1;for(let s of t)if(Gi.existsSync(s)){let o=JSON.parse(Gi.readFileSync(s,"utf8"));if(o.version){Po=o.version,n=!0;break}}if(!n)try{let s=ji("fluxflow -v",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"],timeout:2e3}).trim();s&&(s.startsWith("v")||/^\d+\.\d+/.test(s))&&(Po=s,n=!0)}catch{}if(!n)try{let s=ji("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(s);o.version&&(Po=o.version)}catch{}}catch{}var vs={"SKILL.md":`---
|
|
448
448
|
name: fluxflow
|
|
449
449
|
description: System Generated Documentation. Read this if asked anything regarding FluxFlow Harness
|
|
450
450
|
---
|
|
@@ -473,7 +473,7 @@ Public Docs: https://fluxflow-cli.onrender.com
|
|
|
473
473
|
|
|
474
474
|
Default Context Length: 256k Tokens. Can be changed via ENV/In-app Settings \u2192 references/{SETTINGS,ENV}.md
|
|
475
475
|
|
|
476
|
-
Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ui,"references/PROVIDERS.md":Wi,"references/PLUGINS.md":Hi,"references/STARTUP.md":Ii,"references/ENV.md":Di,"references/COMMANDS.md":Oi,"references/SETTINGS.md":Li,"references/TOOLS.md":Pi,"references/ARCHITECTURE.md":$i,"references/SUB_AGENTS.md":Ni,"references/SECURITY.md":Fi,"references/IDE.md":Bi};var Vi=()=>{try{let e=In.join(on,"skills","fluxflow"),t=In.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){dn.existsSync(e)&&dn.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(
|
|
476
|
+
Docs missing required info? Say you are not sure enough to answer. Dont give wrong info`,"references/MODES.md":Ui,"references/PROVIDERS.md":Wi,"references/PLUGINS.md":Hi,"references/STARTUP.md":Ii,"references/ENV.md":Di,"references/COMMANDS.md":Oi,"references/SETTINGS.md":Li,"references/TOOLS.md":Pi,"references/ARCHITECTURE.md":$i,"references/SUB_AGENTS.md":Ni,"references/SECURITY.md":Fi,"references/IDE.md":Bi};var Vi=()=>{try{let e=In.join(on,"skills","fluxflow"),t=In.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){dn.existsSync(e)&&dn.rmSync(e,{recursive:!0,force:!0});return}let s=new Set(Object.keys(vs).map(o=>In.normalize(o)));for(let[o,l]of Object.entries(vs)){let u=In.join(e,o),a=In.dirname(u);dn.existsSync(a)||dn.mkdirSync(a,{recursive:!0});let p=l.trim()+`
|
|
477
477
|
`,h=null;dn.existsSync(u)&&(h=dn.readFileSync(u,"utf8")),h!==p&&dn.writeFileSync(u,p,"utf8")}if(dn.existsSync(t)){let o=dn.readdirSync(t);for(let l of o){let u=In.normalize(In.join("references",l));if(!s.has(u)){let a=In.join(t,l);try{dn.rmSync(a,{recursive:!0,force:!0})}catch{}}}}}catch{}};var go=(e,t)=>{try{if(!sn.existsSync(e))return null;let n=Array.isArray(t)?t.map(o=>o.toLowerCase()):[t.toLowerCase()],s=sn.readdirSync(e);for(let o of n){let l=s.find(u=>u.toLowerCase()===o);if(l){let u=fn.join(e,l);if(sn.statSync(u).isFile())return u}}}catch{}return null},Ps=(e,t)=>{let n=go(e,t);if(n)try{return sn.readFileSync(n,"utf8")}catch{}return""},Ki=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"]),$s=(e=process.cwd(),t=0,n=8)=>{let s=[];if(t>n)return s;try{if(!sn.existsSync(e))return s;let o=sn.readdirSync(e,{withFileTypes:!0});for(let l of o){let u=l.name,a=fn.join(e,u);if(l.isDirectory())!Ki.has(u)&&!Ki.has(u.toLowerCase())&&s.push(...$s(a,t+1,n));else if(l.isFile()){let p=u.toLowerCase();(p==="agents.md"||p==="agent.md")&&s.push(a)}}}catch{}return s},Yi=(e,t=2)=>{if(!e)return"";let n=" ".repeat(t);return e.split(/\r?\n/).map(s=>n+s).join(`
|
|
478
478
|
`)},Qi=()=>go(on,["agents.md","agent.md"]),Zi=()=>go(process.cwd(),["agents.md","agent.md"]),er=()=>go(on,["fluxflow.md"]),tr=()=>go(process.cwd(),["fluxflow.md"]),$o=Qi(),Os=Zi(),Dn=$s(),No=er(),Fo=tr(),qi=null,Ls="",nr=!1,ya=e=>{if(!e||!/^<<<[\s\S]*?Identity:/m.test(e))return e;let t=e.match(/^<<<\s*\r?\n([\s\S]*?)\r?\n>>>\s*(?:\r?\n)?([\s\S]*)$/);if(!t)return e;let n=t[1],s=t[2],o=n.match(/^Identity:\s*([\s\S]*?)(?=\r?\n\s*(?:<><|>>>)|$)/m);return o&&(Ls=o[1].trim(),process.env.NO_INS=!0),/<><\s*NO_INS/.test(n)&&(nr=!0),s.trim()},xa=()=>($o=Qi(),$o?Ps(on,["agents.md","agent.md"]).trim():""),ba=()=>{if(Dn=$s(),Os=Zi(),!Dn||Dn.length===0)return"";let e=process.cwd(),t=[...Dn].sort((s,o)=>{let l=fn.relative(e,s).replace(/\\/g,"/"),u=fn.relative(e,o).replace(/\\/g,"/"),a=!l.includes("/"),p=!u.includes("/");return a&&!p?-1:!a&&p?1:l.localeCompare(u)}),n=[];for(let s of t)try{let o=sn.readFileSync(s,"utf8").trim();if(!o)continue;let l=fn.relative(e,s).replace(/\\/g,"/");if(!l.includes("/"))n.push(Yi(o,2));else{let a=fn.dirname(l)+"/:";n.push(`${a}
|
|
479
479
|
${Yi(o,2)}`)}}catch{}return n.join(`
|
|
@@ -505,35 +505,35 @@ ${w.length||c.length?"":`
|
|
|
505
505
|
`}`:"",x=process.cwd(),_=Sa(h,o),O=_?.length>0?`--- Saved Memories ---
|
|
506
506
|
${_}
|
|
507
507
|
|
|
508
|
-
`:"";ka(u,m);let E=zi(fo,m,u).trim(),
|
|
508
|
+
`:"";ka(u,m);let E=zi(fo,m,u).trim(),R=[Bs,E].filter(Q=>Q&&Q.length>0).join(`
|
|
509
509
|
|
|
510
510
|
`).trim(),P=zi(uo,m,u).trim(),d=[Bo,P].filter(Q=>Q&&Q.length>0).join(`
|
|
511
511
|
|
|
512
|
-
`).trim(),C=
|
|
513
|
-
${
|
|
514
|
-
${
|
|
512
|
+
`).trim(),C=R.length>0||d.length>0?`--- Additional Instructions ---
|
|
513
|
+
${R.length>0?`-- Global --
|
|
514
|
+
${R}`:""}${d.length>0?`${R.length>0?`
|
|
515
515
|
|
|
516
516
|
`:""}-- Project --
|
|
517
517
|
${d}`:""}
|
|
518
518
|
|
|
519
|
-
`:"",f=(()=>{let Q=process.cwd().toLowerCase();if(process.platform==="win32"){let ue=process.env.SystemRoot?.toLowerCase()||"c:\\windows",Me=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",We=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Q.startsWith(ue)||Q.startsWith(Me)||Q.startsWith(We)}else return Q==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(Me=>Q.startsWith(Me))})(),r=new Date,A=r.getFullYear(),I=r.toLocaleString("en-US",{month:"short"}).toUpperCase(),W=String(r.getDate()).padStart(2,"0"),$=`${A}-${I}-${W}`,
|
|
520
|
-
Identity: ${Ls.length>1?Ls:"Flux Flow. Sassy,
|
|
521
|
-
${nr?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests
|
|
519
|
+
`:"",f=(()=>{let Q=process.cwd().toLowerCase();if(process.platform==="win32"){let ue=process.env.SystemRoot?.toLowerCase()||"c:\\windows",Me=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",We=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return Q.startsWith(ue)||Q.startsWith(Me)||Q.startsWith(We)}else return Q==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(Me=>Q.startsWith(Me))})(),r=new Date,A=r.getFullYear(),I=r.toLocaleString("en-US",{month:"short"}).toUpperCase(),W=String(r.getDate()).padStart(2,"0"),$=`${A}-${I}-${W}`,v=!!s?.autoExcludeMetadata,ne=process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0||!1,fe=process.env.NO_DEV==="true"||process.env.NO_DEV==="1"||process.env.NO_DEV===!0||!1;return`${ne?`${" ".repeat(Math.floor(Math.random()*4)+1)}`:""}=== SYSTEM PROMPT ===
|
|
520
|
+
Identity: ${Ls.length>1?Ls:"Flux Flow. Sassy, CLI Assistant"}
|
|
521
|
+
${nr?"":`${n==="Flux"?"Stepwise Execution, Run Automated Tests":n==="Flow"?"Concise, Humorous, Sarcastic":n==="ICU"?"Computer Use Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks":"Computer Use & Workspace Capabilities. Screenshot as ground truth, analyze grid ids overlapping/close to target, keyboard shortcuts > mouse clicks. Workspace Tools if faster. Focus on Productivity"}`}${dr&&n.toLowerCase().includes("cu")?`
|
|
522
522
|
- 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`:""}
|
|
523
523
|
|
|
524
524
|
- OS: ${Xi}${!fe&&m.length>1?`
|
|
525
|
-
- Model: ${fn.basename(m.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Q=>Q.toUpperCase())}`.trimEnd():""}${
|
|
525
|
+
- Model: ${fn.basename(m.trim()).replace(":free","").replace("-free","").replace("/free","").replace("_free","").replace("free_","").replaceAll("-"," ").replaceAll("_"," ").replace(/\b\w/g,Q=>Q.toUpperCase())}`.trimEnd():""}${v?`
|
|
526
526
|
- Date: ${$}`:""}${o?`
|
|
527
527
|
- Use relative time reference eg. few mins ago
|
|
528
528
|
-- Chat Context > Metadata`:""}${(Ms.length>0||Is.length>0)&&n.toLowerCase().includes("flux")?`
|
|
529
|
-
- Read relevant skills for tasks before proceeding (scope: global/project): Use ReadFile,
|
|
529
|
+
- Read relevant skills for tasks before proceeding (scope: global/project): Use ReadFile, path="#skills/scope?/skillName". In-skill references: path="#skills/scope?/skillName/skill-reference-folder/file-name.md"`:""}
|
|
530
530
|
|
|
531
531
|
-- THINKING GUIDANCE --
|
|
532
532
|
${u==="Mistral"||u==="Google"&&!p?`${i}
|
|
533
533
|
${b||t!=="Fast"&&(u==="Mistral"&&t==="Low"&&!p||t!=="High"&&!p)?`critical thinking policy
|
|
534
534
|
Use <think>...</think> for reasoning before responding any queries
|
|
535
535
|
`:""}`:`${i}
|
|
536
|
-
`}${g?"":`
|
|
536
|
+
`}${g?"":`Before calling tools, MUST provide a summary of your reasoning, plans, decisions, course of actions in chat
|
|
537
537
|
`}
|
|
538
538
|
|
|
539
539
|
${Ei(n,Xi,a,u,s?.advanceRollback,s?.subAgents!==!1,!!s?.autoExec,!!s?.disableTodo)}${o?`
|
|
@@ -573,11 +573,11 @@ identity: silent background system process, have no mouth, only output is valid
|
|
|
573
573
|
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
|
|
574
574
|
${t?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
|
|
575
575
|
|
|
576
|
-
${
|
|
576
|
+
${vi(t,n)}
|
|
577
577
|
=== END SYSTEM PROMPT ===${e?`
|
|
578
578
|
|
|
579
579
|
-- current saved user memories --
|
|
580
|
-
${e}`:""}`.trim();var hr=()=>import("./web_search-D2GOWARI.js").then(e=>e.web_search),mr=()=>import("./web_scrape-LAQI7CVA.js").then(e=>e.web_scrape),pr=()=>import("./memory-TVFFXCSD.js").then(e=>e.memory),yr=()=>import("./chat-HHMMKXDE.js").then(e=>e.chat),xr=()=>import("./view_file-4UCCUBFK.js").then(e=>e.view_file),br=()=>import("./write_file-SP26GOE3.js").then(e=>e.write_file),kr=()=>import("./update_file-IW7GUUIG.js").then(e=>e.update_file),wr=()=>import("./exec_command-BP3TON5E.js").then(e=>e.exec_command),Tr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Us=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Sr=()=>import("./write_pdf-UM6Z2J4K.js").then(e=>e.write_pdf),_r=()=>import("./write_docx-IUKMO7XL.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-EAMQWPPI.js").then(e=>e.search_keyword),Ar=()=>import("./generate_image-J5SWUTUI.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-HFAPNJJH.js").then(e=>e.saveSummary),ho=()=>import("./addMemScore-HPTGXICT.js").then(e=>e.addMemScore),Er=()=>import("./file_map-XK7BFZFI.js").then(e=>e.file_map),Ho=()=>import("./todo-7Q2JBEVP.js").then(e=>e.todo),Cr=()=>import("./invokeSync-KKRTA6RL.js").then(e=>e.invokeSync),_a=()=>import("./invoke-NX4ZZRZI.js").then(e=>e.invoke),vr=()=>import("./getProgress-VG2IBPZU.js").then(e=>e.getProgress),Aa=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),Rr=()=>import("./emergency_rollback-ZVBFZBFU.js").then(e=>e.emergency_rollback),mo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),po=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-GP5ARBTA.js").then(e=>e.computer_action),Mr=()=>import("./click-E6NYFK47.js").then(e=>e.click),Ir=()=>import("./drag-3QT4IG5X.js").then(e=>e.drag),Dr=()=>import("./scroll-HV6GUO5L.js").then(e=>e.scroll),Ws=()=>import("./keyboard_typing-IOO3FFFJ.js").then(e=>e.keyboard_typing),Hs=()=>import("./key_press-4ZHQKB6I.js").then(e=>e.key_press),Gs=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Ea={web_search:hr,web_scrape:mr,memory:pr,chat:yr,view_file:xr,write_file:br,update_file:kr,exec_command:wr,read_folder:Tr,write_pdf:Sr,write_docx:_r,search_keyword:Uo,generate_image:Ar,saveSummary:Wo,addMemScore:ho,file_map:Er,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Cr,invoke:_a,getProgress:vr,cancel:Aa,awaitSubagent:mo,answerSubagent:po,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:Mr,Click:Mr,drag:Ir,Drag:Ir,scroll:Dr,Scroll:Dr,keyboard_typing:Ws,KeyboardTyping:Ws,keyboardtyping:Ws,key_press:Hs,KeyPress:Hs,keypress:Hs,recapture_screen:Gs,RecaptureScreen:Gs,recapturescreen:Gs,invoke_sync:Cr,get_progress:vr,await_subagent:mo,answer_subagent:po,steer_subagent:Go,steer:Go,Steer:Go,ask:Us,Ask:Us,AskUser:Us,WebSearch:hr,WebScrape:mr,ReadFile:xr,ReadFolder:Tr,WriteFile:br,PatchFile:kr,WritePDF:Sr,WriteDoc:_r,Run:wr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:pr,Chat:yr,GenerateImage:Ar,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:ho,AddMemScore:ho,addMemoryScore:ho,AddMemoryScore:ho,FileMap:Er,answer:po,Answer:po,AnswerSubagent:po,await:mo,Await:mo,AwaitSubagent:mo,EmergencyRollback:Rr,emergency_rollback:Rr},yo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),u=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",p=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!u){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!p)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Ea[e];if(!h){let g=["ReadFile","ReadFolder","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","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:"CodeSearch",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"},b=o.replace(/[^a-z0-9]/g,""),i=m[b]||null;if(!i){let w=0,M=_=>{let O=new Set;for(let E=0;E<_.length-1;E++)O.add(_.slice(E,E+2));return O},x=M(b);for(let _ of g){let O=_.toLowerCase().replace(/[^a-z0-9]/g,"");if(b===O){i=_;break}let E=0;(O.includes(b)||b.includes(O))&&(E+=.6);let S=M(O),v=0;for(let k of x)S.has(k)&&v++;let P=2*v/(x.size+S.size||1);E=Math.max(E,P),E>w&&E>=.35&&(w=E,i=_)}}let c=i?` Do you mean '${i}'?`:"";return`ERROR: Tool [${e}] not found in registry.${c}`}try{return await(await h())(t,n)}catch(g){let m=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${m}`}};import te from"path";import Ge from"fs";import Ca from"gradient-string";var js=["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 Or=[{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"]}],xo={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 Vo=null;var Lr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Or[Math.floor(Math.random()*Or.length)]),t={...Vo,id:"Mystery"}):(Vo=null,xo[e]?t=xo[e]:e==="GitHub"?t=xo["GitHub Dark"]:e==="Transparent"?t=xo["Transparent Dark"]:t=xo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var va=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",xc=(e=2)=>{let t=va();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},bc=(e="...",t="Loading...",n="Dark")=>{let s=js[Math.floor(Math.random()*js.length)],o=Lr(n),l=o.logoTextAnsi,u=o.logoBodyAnsi,a=o.logoMutedAnsi,p="\x1B[0m",h=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],g=o.logoGradient||["#0077ff","#ff00ff"],m=Ca(g).multiline(h.join(`
|
|
580
|
+
${e}`:""}`.trim();var hr=()=>import("./web_search-D2GOWARI.js").then(e=>e.web_search),mr=()=>import("./web_scrape-LAQI7CVA.js").then(e=>e.web_scrape),pr=()=>import("./memory-TVFFXCSD.js").then(e=>e.memory),yr=()=>import("./chat-HHMMKXDE.js").then(e=>e.chat),xr=()=>import("./view_file-4UCCUBFK.js").then(e=>e.view_file),br=()=>import("./write_file-SP26GOE3.js").then(e=>e.write_file),kr=()=>import("./update_file-IW7GUUIG.js").then(e=>e.update_file),wr=()=>import("./exec_command-2AU2ICOX.js").then(e=>e.exec_command),Tr=()=>import("./read_folder-OOKZITME.js").then(e=>e.read_folder),Us=()=>import("./ask_user-K2DLZF6H.js").then(e=>e.ask_user),Sr=()=>import("./write_pdf-UM6Z2J4K.js").then(e=>e.write_pdf),_r=()=>import("./write_docx-IUKMO7XL.js").then(e=>e.write_docx),Uo=()=>import("./search_keyword-EAMQWPPI.js").then(e=>e.search_keyword),Ar=()=>import("./generate_image-J5SWUTUI.js").then(e=>e.generate_image),Wo=()=>import("./saveSummary-HFAPNJJH.js").then(e=>e.saveSummary),ho=()=>import("./addMemScore-HPTGXICT.js").then(e=>e.addMemScore),Er=()=>import("./file_map-XK7BFZFI.js").then(e=>e.file_map),Ho=()=>import("./todo-7Q2JBEVP.js").then(e=>e.todo),Cr=()=>import("./invokeSync-MWJR3YU7.js").then(e=>e.invokeSync),_a=()=>import("./invoke-TNCJFZDK.js").then(e=>e.invoke),Rr=()=>import("./getProgress-VG2IBPZU.js").then(e=>e.getProgress),Aa=()=>import("./cancel-7IMADALP.js").then(e=>e.cancel),vr=()=>import("./emergency_rollback-ZVBFZBFU.js").then(e=>e.emergency_rollback),mo=()=>import("./awaitSubagent-JTUSJDKD.js").then(e=>e.awaitSubagent),po=()=>import("./answerSubagent-JUVFNLE5.js").then(e=>e.answerSubagent),Go=()=>import("./steerSubagent-L2JVT4QN.js").then(e=>e.steerSubagent),jo=()=>import("./computer_action-GP5ARBTA.js").then(e=>e.computer_action),Mr=()=>import("./click-E6NYFK47.js").then(e=>e.click),Ir=()=>import("./drag-3QT4IG5X.js").then(e=>e.drag),Dr=()=>import("./scroll-HV6GUO5L.js").then(e=>e.scroll),Ws=()=>import("./keyboard_typing-IOO3FFFJ.js").then(e=>e.keyboard_typing),Hs=()=>import("./key_press-4ZHQKB6I.js").then(e=>e.key_press),Gs=()=>import("./recapture_screen-5FKLOHJL.js").then(e=>e.recapture_screen),Ea={web_search:hr,web_scrape:mr,memory:pr,chat:yr,view_file:xr,write_file:br,update_file:kr,exec_command:wr,read_folder:Tr,write_pdf:Sr,write_docx:_r,search_keyword:Uo,generate_image:Ar,saveSummary:Wo,addMemScore:ho,file_map:Er,todo:Ho,Todo:Ho,goal:Ho,Goal:Ho,invokeSync:Cr,invoke:_a,getProgress:Rr,cancel:Aa,awaitSubagent:mo,answerSubagent:po,steerSubagent:Go,computer_action:jo,computer_use:jo,ComputerAction:jo,ComputerUse:jo,click:Mr,Click:Mr,drag:Ir,Drag:Ir,scroll:Dr,Scroll:Dr,keyboard_typing:Ws,KeyboardTyping:Ws,keyboardtyping:Ws,key_press:Hs,KeyPress:Hs,keypress:Hs,recapture_screen:Gs,RecaptureScreen:Gs,recapturescreen:Gs,invoke_sync:Cr,get_progress:Rr,await_subagent:mo,answer_subagent:po,steer_subagent:Go,steer:Go,Steer:Go,ask:Us,Ask:Us,AskUser:Us,WebSearch:hr,WebScrape:mr,ReadFile:xr,ReadFolder:Tr,WriteFile:br,PatchFile:kr,WritePDF:Sr,WriteDoc:_r,Run:wr,SearchKeyword:Uo,CodeSearch:Uo,code_search:Uo,Memory:pr,Chat:yr,GenerateImage:Ar,saveSumary:Wo,SaveSummary:Wo,SaveSumary:Wo,add_mem_score:ho,AddMemScore:ho,addMemoryScore:ho,AddMemoryScore:ho,FileMap:Er,answer:po,Answer:po,AnswerSubagent:po,await:mo,Await:mo,AwaitSubagent:mo,EmergencyRollback:vr,emergency_rollback:vr},yo=async(e,t,n={})=>{let s=n.mode?n.mode.toLowerCase():"flux",o=e.toLowerCase(),u=["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(g=>o.includes(g))||o==="ask",p=["click","drag","scroll","keyboardtyping","keyboard_typing","keypress","key_press","recapturescreen","recapture_screen","computer"].some(g=>o.includes(g));if(!u){if(s==="flow"){if(!(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image")))return`ERROR: Tool [${e}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s==="icu"){if(!p)return`ERROR: Tool [${e}] is not available in Computer Use mode. ICU mode only supports Computer Use tools (Click, Drag, Scroll, KeyboardTyping, KeyPress, RecaptureScreen).`}else if(o.includes("write_pdf")||o.includes("write_docx")||o.includes("generate_image"))return`ERROR: Tool [${e}] is not available in ${n.mode||"Flux"} mode. Tell user to switch (\`/mode flow\`) for document generation.`}let h=Ea[e];if(!h){let g=["ReadFile","ReadFolder","PatchFile","WriteFile","CodeSearch","Run","Goal","AskUser","WebSearch","WebScrape","WritePDF","WriteDoc","Click","Drag","Scroll","KeyboardTyping","KeyPress","RecaptureScreen","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:"CodeSearch",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"},b=o.replace(/[^a-z0-9]/g,""),i=m[b]||null;if(!i){let w=0,M=_=>{let O=new Set;for(let E=0;E<_.length-1;E++)O.add(_.slice(E,E+2));return O},x=M(b);for(let _ of g){let O=_.toLowerCase().replace(/[^a-z0-9]/g,"");if(b===O){i=_;break}let E=0;(O.includes(b)||b.includes(O))&&(E+=.6);let S=M(O),R=0;for(let k of x)S.has(k)&&R++;let P=2*R/(x.size+S.size||1);E=Math.max(E,P),E>w&&E>=.35&&(w=E,i=_)}}let c=i?` Do you mean '${i}'?`:"";return`ERROR: Tool [${e}] not found in registry.${c}`}try{return await(await h())(t,n)}catch(g){let m=g instanceof Error?g.message:String(g);return`ERROR: Execution failed for [${e}]: ${m}`}};import te from"path";import Ge from"fs";import Ca from"gradient-string";var js=["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 Or=[{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"]}],xo={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 Vo=null;var Lr=(e="Dark")=>{let t;e==="Mystery"||e==="Chaos"?(Vo||(Vo=Or[Math.floor(Math.random()*Or.length)]),t={...Vo,id:"Mystery"}):(Vo=null,xo[e]?t=xo[e]:e==="GitHub"?t=xo["GitHub Dark"]:e==="Transparent"?t=xo["Transparent Dark"]:t=xo.Dark);let n=t.codeText||t.secondary||t.info||t.logoGradient&&t.logoGradient[0]||"cyan";return{...t,codeText:n}};var Ra=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",xc=(e=2)=>{let t=Ra();return t==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)},bc=(e="...",t="Loading...",n="Dark")=>{let s=js[Math.floor(Math.random()*js.length)],o=Lr(n),l=o.logoTextAnsi,u=o.logoBodyAnsi,a=o.logoMutedAnsi,p="\x1B[0m",h=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],g=o.logoGradient||["#0077ff","#ff00ff"],m=Ca(g).multiline(h.join(`
|
|
581
581
|
`)).split(`
|
|
582
582
|
`),b=i=>`${a}${i}${p}`;return`${m[0]}
|
|
583
583
|
${m[1]} ${l}Selected Provider: ${t}${p}
|
|
@@ -587,7 +587,7 @@ ${m[4]}
|
|
|
587
587
|
${m[5]} ${u}See /help for additional commands.${p}
|
|
588
588
|
${m[6]} ${b(s)}
|
|
589
589
|
${m[7]}
|
|
590
|
-
`};import{WebSocket as Ko}from"ws";var Ut=null,Xn=!1,
|
|
590
|
+
`};import{WebSocket as Ko}from"ws";var Ut=null,Xn=!1,va="ws://localhost:56832",Vs=[],Qn=null,Ks=null,Pr="2.0.0",Tc=e=>{Pr=e,$r()},Ys=e=>{Ks=e},$r=()=>{if(Ut||Xn)return;Xn=!0;let e=new Ko(va);e.on("open",()=>{for(Ut=e,Xn=!1,Ut.send(JSON.stringify({command:"version",version:Pr,pid:process.pid,ppid:process.ppid,commitMsgCommand:"fluxflow --commit_8f4a2b9c"}));Vs.length>0;)Ut.send(JSON.stringify(Vs.shift()))}),e.on("message",t=>{try{let n=JSON.parse(t.toString());n.command==="contextResponse"&&Qn?(Qn(n.data),Qn=null):n.command==="securityResponse"&&Ks&&Ks(n.result)}catch{}}),e.on("error",()=>{Xn=!1,Ut=null}),e.on("close",()=>{Xn=!1,Ut=null})},Yo=e=>{Ut&&Ut.readyState===Ko.OPEN?Ut.send(JSON.stringify(e)):(Vs.push(e),Xn||$r())},qo=()=>Ut!==null&&Ut.readyState===Ko.OPEN,Sc=e=>{Yo({command:"status",status:e})},Hn=()=>new Promise(e=>{if(!Ut||Ut.readyState!==Ko.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Qn=e,Ut.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Qn===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Qn=null)},1e3)}),Nr=e=>{Yo({command:"open",filePath:e})},qs=(e,t,n)=>{Yo({command:"showDiff",filePath:e,originalContent:t,modifiedContent:n})},Fr=(e,t)=>{Yo({command:"closeDiff",filePath:e,result:t})};import Br from"path";import Ma from"fs";var Ia=e=>{try{return Ma.readdirSync(e,{withFileTypes:!0})}catch{return[]}},zs=(e,t,n=1,s=Ia,o=[],l=null)=>{let u=l||s(e),a=" ".repeat(n-1);if(u.length>100)return`${a}${Br.basename(e)}/ (>100 files)
|
|
591
591
|
`;let p="",h=o,g=u.filter(c=>!h.includes(c.name)&&!c.name.startsWith(".")),m=u.filter(c=>h.includes(c.name)||c.name.startsWith(".")).map(c=>c.name).sort();m.length>0&&(p+=`${a}[ignored: ${m.map(c=>c+"/").join(", ")}]
|
|
592
592
|
`);let b=g.filter(c=>c.isDirectory()).sort((c,w)=>c.name.localeCompare(w.name)),i=g.filter(c=>!c.isDirectory()).map(c=>c.name).sort();for(let c of b){let w=Br.join(e,c.name);if(n>t)p+=`${a}${c.name}/ (max depth)
|
|
593
593
|
`;else{let M=s(w);M.length>80?p+=`${a}${c.name}/ (>80 files)
|
|
@@ -599,39 +599,39 @@ ${m[7]}
|
|
|
599
599
|
`:o(M).length>80?p+=`${n}${x}${i.name}${a} ...80+ files...
|
|
600
600
|
`:(p+=`${n}${x}${i.name}${a}
|
|
601
601
|
`,p+=Xs(M,t,_,s+1,o,l)):p+=`${n}${x}${i.name}
|
|
602
|
-
`}),p};import"@google/genai";var tt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let u=0;u<n;u++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||u===n-1)throw a}o?await new Promise((a,p)=>{let h=setTimeout(()=>{o.removeEventListener("abort",g),a()},Math.min(24e3,s*Math.pow(2,u))),g=()=>{clearTimeout(h),p(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",g)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,u))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function zo(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var kn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Jo=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let
|
|
603
|
-
`);x=k.pop();for(let d of k){let C=d.trim();if(!C||!C.startsWith("data: "))continue;let f=!1;if(C==="data: [DONE]")f=!0;else try{let r=JSON.parse(C.substring(6)),A=r.choices?.[0]?.delta,I=r.usage;if(r.choices?.[0]?.finish_reason&&(f=!0),I&&(O={totalTokenCount:I.total_tokens||I.prompt_tokens+I.completion_tokens,promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},S=!0),A){let W=A.reasoning_content||null;W&&(_.push({text:W,thought:!0}),S=!0),A.content&&(_.push({text:A.content}),S=!0)}}catch{}if((f||Date.now()-E>=150)&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1),f)break}Date.now()-E>=150&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1)}};var Xo=async function*(e,t,n,s,o,l,u,a,p=1,h=null){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:`data:${A};base64,${I}`})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}f.length>0&&g.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let m={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},b=`${e.slice(-5)}${h||""}${o}${t}`,i=await zo(b),c={model:t,messages:g,stream:!0,temperature:p,prompt_cache_key:i},w=Ve("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(c.reasoning_effort=w):o&&m[o]!=="none"&&(c.reasoning_effort=m[o]||"high");let M=await tt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!M.ok){let d=await M.text().catch(()=>""),C=M.statusText;try{let f=JSON.parse(d);C=f.error?.message||f.message||JSON.stringify(f.detail||f)}catch{d&&(C=d)}throw new Error(`Mistral Error (${M.status}): ${JSON.stringify(C)}`)}let x=M.body.getReader(),_=new TextDecoder,O="",E=[],S=null,
|
|
604
|
-
`);O=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,
|
|
605
|
-
`);Oe=Be.pop();let Ct=!1;for(let un of Be){let Wt=un.trim();if(Wt){if(Wt==="data: [DONE]"){Ct=!0;break}if(Wt.startsWith("data: ")){let zt;try{zt=JSON.parse(Wt.substring(6))}catch{continue}if(zt.error)throw new Error(`NVIDIA Stream Error: ${zt.error.message||JSON.stringify(zt.error)}`);try{let ke=zt.usage;ke&&(U={totalTokenCount:ke.total_tokens||ke.prompt_tokens+ke.completion_tokens,promptTokenCount:ke.prompt_tokens||0,candidatesTokenCount:ke.completion_tokens||0,cachedContentTokenCount:ke.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ke.completion_tokens_details?.reasoning_tokens||0)+(ke.completion_tokens_details?.thoughts_tokens||0)},ye=!0);let oe=zt.choices?.[0]?.delta?.reasoning||zt.choices?.[0]?.delta?.reasoning_content||"",le=zt.choices?.[0]?.delta?.content||"";oe&&(q.push({text:oe,thought:!0}),ye=!0),le&&(q.push({text:le}),ye=!0)}catch{}}}}if((Ct||Date.now()-K>=350)&&ye&&(yield{candidates:q.length>0?[{content:{parts:[...q]}}]:[],usageMetadata:U},Q=!0,q=[],K=Date.now(),ye=!1),Ct)break}break}catch(We){if(Q||ne>=fe)throw We;await new Promise(L=>setTimeout(L,3500))}}},Ur=async function*(e,t){let n=[],s=null,o=!1,l=null,u=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let p=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=!1,m=null,b=async()=>{try{let c=await(await Promise.any([p,h].map(async w=>{let M=await fetch(w);if(!M.ok)throw new Error(`HTTP ${M.status}`);return M}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let w=c.queues[0].queueDepth;g||u({value:{type:"status",content:`Queue ${w||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(b(),m=setInterval(b,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:w}=await i.next();if(w)break;g=!0,m&&(clearInterval(m),m=null),u({value:c,done:!1})}o=!0,u(null)}catch(i){if(l=i,m&&(clearInterval(m),m=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{m&&(clearInterval(m),m=null)}};var Zo=async function*(e,t,n,s,o,l,u,a,p=1,h=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let A of n){let I=A.role==="user"?"user":"assistant",W=[];if(Array.isArray(A.parts)){for(let $ of A.parts)if($.text)W.push({type:"text",text:$.text});else if($.inlineData&&u){let
|
|
606
|
-
`);k=W.pop();for(let $ of W){let
|
|
607
|
-
`);for(let r of k.parts){let A=r.inlineData||r.inline_data;A&&A.data&&f.push(A.data)}}else C=k.text||"";if(C||f.length>0){let r={role:d,content:C};f.length>0&&(r.images=f),g.push(r)}}let m=h==="Local"||!e||e==="LOCAL",i={host:m?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!m&&e&&(i.headers={Authorization:"Bearer "+e});let c=new La(i),w=[],M=null,x=Date.now(),_=!1,O=Ve("Ollama",t,o),E={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=O!==null?O==="false"||O===!1?!1:O==="true"||O===!0?!0:O:E[o]!==void 0?E[o]:!0,
|
|
608
|
-
`:"")+r.text);else f=d.text||"";h.push({role:C,content:f})}let g=Ve("InferX",t,o),b=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&g===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:h.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:p};!i&&b&&(w.stream_options={include_usage:!0},w.reasoning_effort=b);let M=await tt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:a});if(!M.ok){let d=await M.text().catch(()=>""),C="";try{let f=JSON.parse(d);C=f.error?.message||f.error?.detail||f.message||f.detail||(typeof f.error=="string"?f.error:"")||(d&&d!=="{}"?d:"")}catch{C=d}throw(!C||C==="{}")&&(C=M.statusText||"Unknown error"),new Error(`InferX Error (${M.status}): ${C}`)}let x=M.body.getReader(),_=new TextDecoder,O="",E=[],S=null,
|
|
609
|
-
`);O=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,
|
|
610
|
-
`);x=k.pop();for(let d of k){let C=d.trim();if(!C||!C.startsWith("data: "))continue;let f=!1;if(C==="data: [DONE]")f=!0;else try{let r=JSON.parse(C.substring(6)),A=r.choices?.[0]?.delta,I=r.usage;if(I&&(O={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},S=!0),A){let W=A.reasoning||A.reasoning_content||null;W&&(_.push({text:W,thought:!0}),S=!0),A.content&&(_.push({text:A.content}),S=!0)}}catch{}if((f||Date.now()-E>=150||O)&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1),f)break}Date.now()-E>=150&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1)}};var ns=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let
|
|
611
|
-
`);x=k.pop();for(let d of k){let C=d.trim();if(!C||!C.startsWith("data: "))continue;let f=!1;if(C==="data: [DONE]")f=!0;else try{let r=JSON.parse(C.substring(6)),A=r.choices?.[0]?.delta,I=r.usage;if(r.choices?.[0]?.finish_reason&&(f=!0),I&&(O={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},S=!0),A){let W=A.reasoning_content||null;W&&(_.push({text:W,thought:!0}),S=!0),A.content&&(_.push({text:A.content}),S=!0)}}catch{}if((f||Date.now()-E>=150)&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1),f)break}Date.now()-E>=150&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1)}};var os=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let S of n){let
|
|
612
|
-
`);M=P.pop();for(let k of P){let d=k.trim();if(!d||!d.startsWith("data: "))continue;let C=!1;if(d==="data: [DONE]")C=!0;else try{let f=JSON.parse(d.substring(6)),r=f.choices?.[0]?.delta,A=f.usage;if(f.choices?.[0]?.finish_reason&&(C=!0),A&&(_={totalTokenCount:A.total_tokens||(A.prompt_tokens||0)+(A.completion_tokens||0),promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||A.reasoning_tokens||0},E=!0),r){let I=r.reasoning_content||r.reasoning||null;I&&(x.push({text:I,thought:!0}),E=!0),r.content&&(x.push({text:r.content}),E=!0)}}catch{}if((C||Date.now()-O>=150)&&E&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],O=Date.now(),E=!1),C)break}Date.now()-O>=150&&E&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],O=Date.now(),E=!1)}};var ss=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:{url:`data:${A};base64,${I}`}})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}h.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let g=Ve("9router",t,o)||Ve("9Router",t,o),b=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&b!=="none"&&(g!==null||o!=="Fast")&&(i.reasoning_effort=b);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},M=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";w.Authorization=`Bearer ${M}`;let x=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!x.ok){let d=await x.json().catch(()=>({}));throw new Error(`9router Error (${x.status}): ${d.error?.message||x.statusText}`)}let _=x.body.getReader(),O=new TextDecoder,E="",S=[],
|
|
613
|
-
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,
|
|
614
|
-
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,
|
|
615
|
-
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,
|
|
616
|
-
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,
|
|
602
|
+
`}),p};import"@google/genai";var tt=async(e,t,n=5,s=1e3)=>{let o=t?.signal;for(let u=0;u<n;u++){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(e,t);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||o?.aborted||u===n-1)throw a}o?await new Promise((a,p)=>{let h=setTimeout(()=>{o.removeEventListener("abort",g),a()},Math.min(24e3,s*Math.pow(2,u))),g=()=>{clearTimeout(h),p(new DOMException("The user aborted a request.","AbortError"))};o.addEventListener("abort",g)}):await new Promise(a=>setTimeout(a,Math.min(24e3,s*Math.pow(2,u))))}if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");let l=await fetch(e,t);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),l};async function zo(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n).slice(0,16)].map(s=>s.toString(16).padStart(2,"0")).join("")}var kn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var Jo=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let R of n){let P=R.role==="user"?"user":"assistant",k=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)k.push({type:"text",text:d.text});else if((d.inlineData||d.inline_data)&&u){let C=d.inlineData||d.inline_data,f=C.mimeType||C.mime_type||"image/jpeg",r=C.data;f.startsWith("image/")&&k.push({type:"image_url",image_url:{url:`data:${f};base64,${r}`}})}}else{let d=R.text||"";d&&k.push({type:"text",text:d})}h.push({role:P,content:k.length===1&&k[0].type==="text"?k[0].text:k})}let g={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p},m=Ve("DeepSeek",t,o),i=m!==null?m:o!=="Fast"?{Low:"low",Medium:"high",Standard:"high",High:"max",xHigh:"max"}[o]||"high":null;i&&i!=="disabled"&&i!=="none"&&i!=="false"&&i!==!1?(g.reasoning_effort=i,g.extra_body={thinking:{type:"enabled"}}):g.extra_body={thinking:{type:"disabled"}};let c=await tt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(g),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`DeepSeek Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),M=new TextDecoder,x="",_=[],O=null,E=Date.now(),S=!1;for(;;){let{done:R,value:P}=await w.read();if(R){S&&(_.length>0||O)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:O});break}x+=M.decode(P,{stream:!0});let k=x.split(`
|
|
603
|
+
`);x=k.pop();for(let d of k){let C=d.trim();if(!C||!C.startsWith("data: "))continue;let f=!1;if(C==="data: [DONE]")f=!0;else try{let r=JSON.parse(C.substring(6)),A=r.choices?.[0]?.delta,I=r.usage;if(r.choices?.[0]?.finish_reason&&(f=!0),I&&(O={totalTokenCount:I.total_tokens||I.prompt_tokens+I.completion_tokens,promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||0},S=!0),A){let W=A.reasoning_content||null;W&&(_.push({text:W,thought:!0}),S=!0),A.content&&(_.push({text:A.content}),S=!0)}}catch{}if((f||Date.now()-E>=150)&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1),f)break}Date.now()-E>=150&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1)}};var Xo=async function*(e,t,n,s,o,l,u,a,p=1,h=null){let g=[];s&&g.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:`data:${A};base64,${I}`})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}f.length>0&&g.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let m={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},b=`${e.slice(-5)}${h||""}${o}${t}`,i=await zo(b),c={model:t,messages:g,stream:!0,temperature:p,prompt_cache_key:i},w=Ve("Mistral",t,o);w!==null&&w!=="none"?w&&w!=="none"&&w!=="disabled"&&w!==!1&&(c.reasoning_effort=w):o&&m[o]!=="none"&&(c.reasoning_effort=m[o]||"high");let M=await tt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:a});if(!M.ok){let d=await M.text().catch(()=>""),C=M.statusText;try{let f=JSON.parse(d);C=f.error?.message||f.message||JSON.stringify(f.detail||f)}catch{d&&(C=d)}throw new Error(`Mistral Error (${M.status}): ${JSON.stringify(C)}`)}let x=M.body.getReader(),_=new TextDecoder,O="",E=[],S=null,R=Date.now(),P=!1,k=d=>d?typeof d=="string"?kn(d):Array.isArray(d)?d.map(k).filter(Boolean).join(""):typeof d=="object"&&d!==null?typeof d.text=="string"?kn(d.text):typeof d.content=="string"?kn(d.content):typeof d.thinking=="string"?kn(d.thinking):typeof d.reasoning_content=="string"?kn(d.reasoning_content):typeof d.reasoning=="string"?kn(d.reasoning):typeof d.value=="string"?kn(d.value):d.text?k(d.text):d.content?k(d.content):d.thinking?k(d.thinking):d.reasoning_content?k(d.reasoning_content):d.reasoning?k(d.reasoning):d.value?k(d.value):"":kn(String(d)):"";for(;;){let{done:d,value:C}=await x.read();if(d){P&&(E.length>0||S)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:S});break}O+=_.decode(C,{stream:!0});let f=O.split(`
|
|
604
|
+
`);O=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,v=W.usage;if(W.choices?.[0]?.finish_reason&&(I=!0),v&&(S={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},P=!0),$){let ne=$.thinking||$.reasoning_content||$.reasoning,fe=k(ne);fe&&(E.push({text:fe,thought:!0}),P=!0);let Q=$.content||(!$.thinking&&!$.reasoning_content&&!$.reasoning?$.text:null);if(Q)if(Array.isArray(Q))for(let ue of Q)if(typeof ue=="object"&&ue!==null){let Me=ue.type==="thinking"||ue.type==="reasoning"||!!ue.thought,We=k(ue);We&&(E.push({text:We,...Me?{thought:!0}:{}}),P=!0)}else{let Me=k(ue);Me&&(E.push({text:Me}),P=!0)}else if(typeof Q=="object"&&Q!==null){let ue=Q.type==="thinking"||Q.type==="reasoning"||!!Q.thought,Me=k(Q);Me&&(E.push({text:Me,...ue?{thought:!0}:{}}),P=!0)}else{let ue=k(Q);ue&&(E.push({text:ue}),P=!0)}}}catch{}if((I||Date.now()-R>=150)&&P&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:S},E=[],R=Date.now(),P=!1),I)break}Date.now()-R>=150&&P&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:S},E=[],R=Date.now(),P=!1)}};var Qo=async function*(e,t,n,s,o,l,u=!1,a,p=1){let h=[];s&&h.push({role:"system",content:s}),n.forEach(We=>{let L=We.role==="model"?"assistant":"user",B=[];Array.isArray(We.parts)&&We.parts.forEach(Oe=>{if(Oe.text)B.push({type:"text",text:Oe.text});else if(Oe.inlineData&&u){let q=Oe.inlineData.mimeType,U=Oe.inlineData.data;q.startsWith("image/")&&ft(t)&&B.push({type:"image_url",image_url:{url:`data:${q};base64,${U}`}})}}),h.push({role:L,content:B.length===1&&B[0].type==="text"?B[0].text:B})});let g=Ve("NVIDIA",t,o),b=g!==null?g:{Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[o]||"High",i=b!=="Fast"&&b!=="none"&&b!=="disabled"&&b!==!1,c=t.includes("kimi"),w=t.includes("gemma"),M=t.includes("deepseek"),x=t.includes("glm"),_=t.includes("mistral"),O=t.includes("minimax"),E=t.includes("gpt"),S=t.includes("qwen"),R=t.includes("nemotron"),P=t.includes("llama-3"),k=t.includes("seed"),d=t.includes("poolside"),C=t.includes("thinkingmachines")||t.includes("muse"),f=P,r=null,A={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},I={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},W={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},$=O||M||d||C?16384:32768;$=process.env.NVIDIA_BASE_URL?1024:$,$=r?1024:$;let v={model:t,messages:h,max_tokens:$,stream:!0,stream_options:{include_usage:!0},temperature:p,...E&&{thinking:A[o]||"high"}};if(!(process.env.NVIDIA_BASE_URL||f||r))if(c)v.chat_template_kwargs={thinking:i};else if(w)v.chat_template_kwargs={enable_thinking:i};else if(M)if(i){let We=b==="High"?"max":"high";v.chat_template_kwargs={thinking:!0,reasoning_effort:We}}else v.chat_template_kwargs={thinking:!1};else x?v.chat_template_kwargs={enable_thinking:i,clear_thinking:!i}:_?v.reasoning_effort=i?"high":"none":O&&t.includes("minimax-m3")?v.chat_template_kwargs={thinking_mode:i?"enabled":"disabled"}:S?v.chat_template_kwargs={enable_thinking:i}:R?b==="High"?v.chat_template_kwargs={enable_thinking:!0}:b==="Standard"?v.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:v.chat_template_kwargs={enable_thinking:!1}:k?i&&(v.extra_body={thinking_budget:parseInt(I[b]??"4096")}):d?v.chat_template_kwargs={enable_thinking:i}:C&&(v.reasoning_effort=W[b]||"medium");let ne=0,fe=6,Q=!1,ue=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",Me=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(ue.endsWith("/chat/completions")||(ue=ue.replace(/\/+$/,"")+"/chat/completions");ne<fe;){ne++;try{let We=await tt(ue,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Me}`},body:JSON.stringify(v),signal:a});if(!We.ok){let Ae=await We.text().catch(()=>""),Re=We.statusText;try{let Ct=JSON.parse(Ae);Re=Ct.error?.message||Ct.message||JSON.stringify(Ct.detail||Ct)}catch{Ae&&(Re=Ae)}let Be=new Error(`NVIDIA API Error (${We.status}): ${Re}`);throw Be.status=We.status,Be}let L=We.body.getReader(),B=new TextDecoder,Oe="",q=[],U=null,K=Date.now(),ye=!1;for(;;){let{done:Ae,value:Re}=await L.read();if(Ae){ye&&(q.length>0||U)&&(yield{candidates:q.length>0?[{content:{parts:q}}]:[],usageMetadata:U},Q=!0);break}Oe+=B.decode(Re,{stream:!0});let Be=Oe.split(`
|
|
605
|
+
`);Oe=Be.pop();let Ct=!1;for(let un of Be){let Wt=un.trim();if(Wt){if(Wt==="data: [DONE]"){Ct=!0;break}if(Wt.startsWith("data: ")){let zt;try{zt=JSON.parse(Wt.substring(6))}catch{continue}if(zt.error)throw new Error(`NVIDIA Stream Error: ${zt.error.message||JSON.stringify(zt.error)}`);try{let ke=zt.usage;ke&&(U={totalTokenCount:ke.total_tokens||ke.prompt_tokens+ke.completion_tokens,promptTokenCount:ke.prompt_tokens||0,candidatesTokenCount:ke.completion_tokens||0,cachedContentTokenCount:ke.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(ke.completion_tokens_details?.reasoning_tokens||0)+(ke.completion_tokens_details?.thoughts_tokens||0)},ye=!0);let oe=zt.choices?.[0]?.delta?.reasoning||zt.choices?.[0]?.delta?.reasoning_content||"",le=zt.choices?.[0]?.delta?.content||"";oe&&(q.push({text:oe,thought:!0}),ye=!0),le&&(q.push({text:le}),ye=!0)}catch{}}}}if((Ct||Date.now()-K>=350)&&ye&&(yield{candidates:q.length>0?[{content:{parts:[...q]}}]:[],usageMetadata:U},Q=!0,q=[],K=Date.now(),ye=!1),Ct)break}break}catch(We){if(Q||ne>=fe)throw We;await new Promise(L=>setTimeout(L,3500))}}},Ur=async function*(e,t){let n=[],s=null,o=!1,l=null,u=i=>{if(n.push(i),s){let c=s;s=null,c()}},a=t.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let p=`https://buildapi.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,h=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,g=!1,m=null,b=async()=>{try{let c=await(await Promise.any([p,h].map(async w=>{let M=await fetch(w);if(!M.ok)throw new Error(`HTTP ${M.status}`);return M}))).json();if(c&&c.queues&&c.queues[0]&&typeof c.queues[0].queueDepth=="number"){let w=c.queues[0].queueDepth;g||u({value:{type:"status",content:`Queue ${w||1}`},done:!1})}}catch{}};process.env.NVIDIA_BASE_URL||(b(),m=setInterval(b,5e3)),(async()=>{try{let i=e[Symbol.asyncIterator]();for(;;){let{value:c,done:w}=await i.next();if(w)break;g=!0,m&&(clearInterval(m),m=null),u({value:c,done:!1})}o=!0,u(null)}catch(i){if(l=i,m&&(clearInterval(m),m=null),s){let c=s;s=null,c()}}})();try{for(;;){if(l)throw l;if(n.length>0){let i=n.shift();if(i===null&&o)break;yield i.value}else{if(o)break;await new Promise(i=>{s=i})}}}finally{m&&(clearInterval(m),m=null)}};var Zo=async function*(e,t,n,s,o,l,u,a,p=1,h=null){let g=[];s&&g.push({role:"system",content:[{type:"text",text:s}]});for(let A of n){let I=A.role==="user"?"user":"assistant",W=[];if(Array.isArray(A.parts)){for(let $ of A.parts)if($.text)W.push({type:"text",text:$.text});else if($.inlineData&&u){let v=$.inlineData.mimeType,ne=$.inlineData.data;v.startsWith("image/")?W.push({type:"image_url",image_url:{url:`data:${v};base64,${ne}`}}):W.push({type:"file",file:{filename:$.filename||"file",file_data:`data:${v};base64,${ne}`}})}}else{let $=A.text||"";$&&W.push({type:"text",text:$})}g.push({role:I,content:W.length===1&&W[0].type==="text"?W[0].text:W})}let m={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},b=["free","nitro","floor","exacto"],i=t,c=null,w=null;if(t.includes(":")){let A=t.split(":");if(A.length>1){let I=A[A.length-1].toLowerCase().trim();(I==="flex"||I==="priority")&&(w=I,A.pop())}if(A.length>1){let I=A[A.length-1].toLowerCase().trim();if(!b.includes(I)){let W=A.pop().trim();W&&(c={only:[W],allow_fallbacks:!1})}}i=A.join(":").trim()}let M=`${e.slice(-5)}${h||""}${o}${i}${w||""}${c?JSON.stringify(c):""}`,x=await zo(M),_={model:i,messages:g,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:x};w&&(_.service_tier=w),c&&(_.provider=c);let O=Ve("OpenRouter",t,o),E=O!==null?O:m[o];E&&E!=="none"&&(O!==null||o!=="Fast")&&(_.reasoning_effort=E);let S=await tt("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://fluxflow-cli.onrender.com/","X-Title":"FluxFlow CLI","X-OpenRouter-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(_),signal:a});if(!S.ok){let A=await S.json().catch(()=>({})),I=A.error?.metadata?.raw||A.error?.message||(typeof A.error=="string"?A.error:"")||S.statusText||"Unknown error";throw new Error(`OpenRouter Error (${S.status}): ${I}`)}let R=S.body.getReader(),P=new TextDecoder,k="",d=[],C=null,f=Date.now(),r=!1;for(;;){let{done:A,value:I}=await R.read();if(A){r&&(d.length>0||C)&&(yield{candidates:d.length>0?[{content:{parts:d}}]:[],usageMetadata:C});break}k+=P.decode(I,{stream:!0});let W=k.split(`
|
|
606
|
+
`);k=W.pop();for(let $ of W){let v=$.trim();if(!v||!v.startsWith("data: "))continue;let ne=!1;if(v==="data: [DONE]")ne=!0;else try{let fe=JSON.parse(v.substring(6));if(fe.error){let Me=fe.error.metadata?.raw||fe.error.message||JSON.stringify(fe.error);throw new Error(`OpenRouter Stream Error: ${Me}`)}let Q=fe.choices?.[0]?.delta,ue=fe.usage;if(fe.choices?.[0]?.finish_reason&&(ne=!0),ue&&(C={totalTokenCount:ue.total_tokens||(ue.prompt_tokens||0)+(ue.completion_tokens||0),promptTokenCount:ue.prompt_tokens||0,candidatesTokenCount:ue.completion_tokens||0,cachedContentTokenCount:ue.prompt_tokens_details?.cached_tokens||ue.prompt_tokens_details?.cache_read_input_tokens||ue.cache_read_input_tokens||0,thoughtsTokenCount:ue.completion_tokens_details?.reasoning_tokens||0},r=!0),Q){let Me=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(We=>We.text).join(""):null);Me&&(d.push({text:Me,thought:!0}),r=!0),Q.content&&(d.push({text:Q.content}),r=!0)}}catch(fe){if(fe.message&&fe.message.startsWith("OpenRouter Stream Error:"))throw fe}if((ne||Date.now()-f>=150)&&r&&(yield{candidates:d.length>0?[{content:{parts:[...d]}}]:[],usageMetadata:C},d=[],f=Date.now(),r=!1),ne)break}}};import{Ollama as La}from"ollama";var Qs=async function*(e,t,n,s,o,l,u,a,p=1,h="Cloud"){let g=[];s&&g.push({role:"system",content:s});for(let k of n){let d=k.role==="user"?"user":"assistant",C="",f=[];if(Array.isArray(k.parts)){C=k.parts.map(r=>r.text||"").filter(Boolean).join(`
|
|
607
|
+
`);for(let r of k.parts){let A=r.inlineData||r.inline_data;A&&A.data&&f.push(A.data)}}else C=k.text||"";if(C||f.length>0){let r={role:d,content:C};f.length>0&&(r.images=f),g.push(r)}}let m=h==="Local"||!e||e==="LOCAL",i={host:m?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!m&&e&&(i.headers={Authorization:"Bearer "+e});let c=new La(i),w=[],M=null,x=Date.now(),_=!1,O=Ve("Ollama",t,o),E={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},S=O!==null?O==="false"||O===!1?!1:O==="true"||O===!0?!0:O:E[o]!==void 0?E[o]:!0,R={model:t,messages:g,stream:!0,think:S,keep_alive:"10m",options:{temperature:p}},P=await c.chat(R);for await(let k of P){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(k.message?.thinking&&(w.push({text:k.message.thinking,thought:!0}),_=!0),k.message?.content&&(w.push({text:k.message.content}),_=!0),k.done){let d=k.prompt_cached_count||0;if(!d&&k.prompt_eval_count){let C=k.prompt_eval_duration||0;C>0&&C<5e7&&(d=k.prompt_eval_count)}M={totalTokenCount:(k.prompt_eval_count||0)+(k.eval_count||0),promptTokenCount:k.prompt_eval_count||0,candidatesTokenCount:k.eval_count||0,cachedContentTokenCount:d,thoughtsTokenCount:0},_=!0}(k.done||Date.now()-x>=150&&_)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:M},w=[],x=Date.now(),_=!1)}_&&(w.length>0||M)&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:M})};var es=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f="";if(Array.isArray(d.parts))for(let r of d.parts)r.text&&(f+=(f?`
|
|
608
|
+
`:"")+r.text);else f=d.text||"";h.push({role:C,content:f})}let g=Ve("InferX",t,o),b=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i=t&&t.toLowerCase().includes("qwen3.8-27b")&&g===null,c=t&&(t.toLowerCase().includes("qwen3.8-27b")||t.toLowerCase().includes("qwen3.6-35b-a3b-fp8")),w={model:t,messages:h.filter(d=>d.content&&String(d.content).trim().length>0),stream:!0,stream_options:{include_usage:!0},temperature:p};!i&&b&&(w.stream_options={include_usage:!0},w.reasoning_effort=b);let M=await tt("https://model.inferx.net/endpoints/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(w),signal:a});if(!M.ok){let d=await M.text().catch(()=>""),C="";try{let f=JSON.parse(d);C=f.error?.message||f.error?.detail||f.message||f.detail||(typeof f.error=="string"?f.error:"")||(d&&d!=="{}"?d:"")}catch{C=d}throw(!C||C==="{}")&&(C=M.statusText||"Unknown error"),new Error(`InferX Error (${M.status}): ${C}`)}let x=M.body.getReader(),_=new TextDecoder,O="",E=[],S=null,R=Date.now(),P=!1,k=!0;for(;;){let{done:d,value:C}=await x.read();if(d){P&&(E.length>0||S)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:S});break}O+=_.decode(C,{stream:!0});let f=O.split(`
|
|
609
|
+
`);O=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,v=W.usage;if(v&&(S={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},P=!0),$){let ne=$.reasoning||$.reasoning_content||null;if(ne&&(E.push({text:ne,thought:!0}),P=!0),$.content){let fe=$.content;c&&k&&fe.length>0&&(fe="<think>"+fe,k=!1),E.push({text:fe}),P=!0}}}catch{}if((I||Date.now()-R>=150||S)&&P&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:S},E=[],R=Date.now(),P=!1),I)break}Date.now()-R>=150&&P&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:S},E=[],R=Date.now(),P=!1)}};var ts=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let R of n){let P=R.role==="user"?"user":"assistant",k=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)k.push({type:"text",text:d.text});else if(d.inlineData&&u){let C=d.inlineData.mimeType,f=d.inlineData.data;C.startsWith("image/")&&k.push({type:"image_url",image_url:{url:`data:${C};base64,${f}`}})}}else{let d=R.text||"";d&&k.push({type:"text",text:d})}h.push({role:P,content:k.length===1&&k[0].type==="text"?k[0].text:k})}let g=Ve("SenseNova",t,o),b=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&(i.reasoning_effort=b);let c=await tt("https://token.sensenova.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`SenseNova Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),M=new TextDecoder,x="",_=[],O=null,E=Date.now(),S=!1;for(;;){let{done:R,value:P}=await w.read();if(R){S&&(_.length>0||O)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:O});break}x+=M.decode(P,{stream:!0});let k=x.split(`
|
|
610
|
+
`);x=k.pop();for(let d of k){let C=d.trim();if(!C||!C.startsWith("data: "))continue;let f=!1;if(C==="data: [DONE]")f=!0;else try{let r=JSON.parse(C.substring(6)),A=r.choices?.[0]?.delta,I=r.usage;if(I&&(O={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},S=!0),A){let W=A.reasoning||A.reasoning_content||null;W&&(_.push({text:W,thought:!0}),S=!0),A.content&&(_.push({text:A.content}),S=!0)}}catch{}if((f||Date.now()-E>=150||O)&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1),f)break}Date.now()-E>=150&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1)}};var ns=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let R of n){let P=R.role==="user"?"user":"assistant",k=[];if(Array.isArray(R.parts)){for(let d of R.parts)if(d.text)k.push({type:"text",text:d.text});else if(d.inlineData&&u){let C=d.inlineData.mimeType,f=d.inlineData.data;C.startsWith("image/")&&k.push({type:"image_url",image_url:{url:`data:${C};base64,${f}`}})}}else{let d=R.text||"";d&&k.push({type:"text",text:d})}h.push({role:P,content:k.length===1&&k[0].type==="text"?k[0].text:k})}let g=Ve("AIHubMix",t,o),b=g!==null?g:{Fast:"minimal",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&(i.reasoning_effort=b);let c=await tt("https://aihubmix.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:a});if(!c.ok){let R=await c.json().catch(()=>({}));throw new Error(`AIHubMix Error (${c.status}): ${R.error?.message||c.statusText}`)}let w=c.body.getReader(),M=new TextDecoder,x="",_=[],O=null,E=Date.now(),S=!1;for(;;){let{done:R,value:P}=await w.read();if(R){S&&(_.length>0||O)&&(yield{candidates:_.length>0?[{content:{parts:_}}]:[],usageMetadata:O});break}x+=M.decode(P,{stream:!0});let k=x.split(`
|
|
611
|
+
`);x=k.pop();for(let d of k){let C=d.trim();if(!C||!C.startsWith("data: "))continue;let f=!1;if(C==="data: [DONE]")f=!0;else try{let r=JSON.parse(C.substring(6)),A=r.choices?.[0]?.delta,I=r.usage;if(r.choices?.[0]?.finish_reason&&(f=!0),I&&(O={totalTokenCount:I.total_tokens||(I.prompt_tokens||0)+(I.completion_tokens||0),promptTokenCount:I.prompt_tokens||0,candidatesTokenCount:I.completion_tokens||0,cachedContentTokenCount:I.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:I.completion_tokens_details?.reasoning_tokens||I.reasoning_tokens||0},S=!0),A){let W=A.reasoning_content||null;W&&(_.push({text:W,thought:!0}),S=!0),A.content&&(_.push({text:A.content}),S=!0)}}catch{}if((f||Date.now()-E>=150)&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1),f)break}Date.now()-E>=150&&S&&(yield{candidates:_.length>0?[{content:{parts:[..._]}}]:[],usageMetadata:O},_=[],E=Date.now(),S=!1)}};var os=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let S of n){let R=S.role==="user"?"user":"assistant",P=[];if(Array.isArray(S.parts)){for(let k of S.parts)if(k.text)P.push({type:"text",text:k.text});else if(k.inlineData&&u){let d=k.inlineData.mimeType,C=k.inlineData.data;d.startsWith("image/")&&P.push({type:"image_url",image_url:{url:`data:${d};base64,${C}`}})}}else{let k=S.text||"";k&&P.push({type:"text",text:k})}h.push({role:R,content:P.length===1&&P[0].type==="text"?P[0].text:P})}let g=Ve("Poolside",t,o),m=g!==null?g===!1||g==="false"||g==="none"||g==="Fast":o==="Fast",b={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};m?b.chat_template_kwargs={enable_thinking:!1}:g!==null&&typeof g=="object"?b.chat_template_kwargs=g:b.chat_template_kwargs={enable_thinking:!0};let i=await tt("https://inference.poolside.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(b),signal:a});if(!i.ok){let S=await i.json().catch(()=>({}));throw new Error(`Poolside Error (${i.status}): ${S.error?.message||i.statusText}`)}let c=i.body.getReader(),w=new TextDecoder,M="",x=[],_=null,O=Date.now(),E=!1;for(;;){let{done:S,value:R}=await c.read();if(S){E&&(x.length>0||_)&&(yield{candidates:x.length>0?[{content:{parts:x}}]:[],usageMetadata:_});break}M+=w.decode(R,{stream:!0});let P=M.split(`
|
|
612
|
+
`);M=P.pop();for(let k of P){let d=k.trim();if(!d||!d.startsWith("data: "))continue;let C=!1;if(d==="data: [DONE]")C=!0;else try{let f=JSON.parse(d.substring(6)),r=f.choices?.[0]?.delta,A=f.usage;if(f.choices?.[0]?.finish_reason&&(C=!0),A&&(_={totalTokenCount:A.total_tokens||(A.prompt_tokens||0)+(A.completion_tokens||0),promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||A.reasoning_tokens||0},E=!0),r){let I=r.reasoning_content||r.reasoning||null;I&&(x.push({text:I,thought:!0}),E=!0),r.content&&(x.push({text:r.content}),E=!0)}}catch{}if((C||Date.now()-O>=150)&&E&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],O=Date.now(),E=!1),C)break}Date.now()-O>=150&&E&&(yield{candidates:x.length>0?[{content:{parts:[...x]}}]:[],usageMetadata:_},x=[],O=Date.now(),E=!1)}};var ss=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:{url:`data:${A};base64,${I}`}})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}h.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let g=Ve("9router",t,o)||Ve("9Router",t,o),b=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&b!=="none"&&(g!==null||o!=="Fast")&&(i.reasoning_effort=b);let c=process.env["9ROUTER_URL"]||process.env.NINEROUTER_URL||"http://127.0.0.1:20128/v1/chat/completions",w={"Content-Type":"application/json"},M=e&&e!=="LOCAL"?e:process.env["9ROUTER_API_KEY"]||"dummy-key";w.Authorization=`Bearer ${M}`;let x=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!x.ok){let d=await x.json().catch(()=>({}));throw new Error(`9router Error (${x.status}): ${d.error?.message||x.statusText}`)}let _=x.body.getReader(),O=new TextDecoder,E="",S=[],R=null,P=Date.now(),k=!1;for(;;){let{done:d,value:C}=await _.read();if(d){k&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}E+=O.decode(C,{stream:!0});let f=E.split(`
|
|
613
|
+
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,v=W.usage;if(W.choices?.[0]?.finish_reason&&(I=!0),v&&(R={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},k=!0),$){let ne=$.reasoning_content||$.reasoning||$.thinking||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>typeof fe=="string"?fe:fe?.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),k=!0),$.content&&(S.push({text:$.content}),k=!0)}}catch{}if((I||Date.now()-P>=150)&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1),I)break}Date.now()-P>=150&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1)}};var is=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:{url:`data:${A};base64,${I}`}})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}h.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let g=Ve("ExpLabs",t,o),b=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&(i.reasoning_effort=b);let c=process.env.EXPLABS_URL||process.env.EXPERIENTIALLABS_URL||"https://api.experientiallabs.ai/v1/chat/completions",w={"Content-Type":"application/json"},M=e||process.env.EXPLABS_API_KEY||process.env.EXPERIENTIALLABS_API_KEY||"";w.Authorization=`Bearer ${M}`;let x=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!x.ok){let d=await x.json().catch(()=>({}));throw new Error(`Experiential Labs Error (${x.status}): ${d.error?.message||d.message||x.statusText}`)}let _=x.body.getReader(),O=new TextDecoder,E="",S=[],R=null,P=Date.now(),k=!1;for(;;){let{done:d,value:C}=await _.read();if(d){k&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}E+=O.decode(C,{stream:!0});let f=E.split(`
|
|
614
|
+
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,v=W.usage;if(v&&(R={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},k=!0),$){let ne=$.reasoning_content||$.reasoning||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),k=!0),$.content&&(S.push({text:$.content}),k=!0)}}catch{}if((I||Date.now()-P>=150)&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1),I)break}Date.now()-P>=150&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1)}};var Zs=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:{url:`data:${A};base64,${I}`}})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}h.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let g=Ve("TokenHarbor",t,o),b=g!==null?g:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&(i.reasoning_effort=b);let c=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},M=e||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";w.Authorization=`Bearer ${M}`;let x=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!x.ok){let d=await x.json().catch(()=>({}));throw new Error(`Token Harbor Error (${x.status}): ${d.error?.message||d.message||x.statusText}`)}let _=x.body.getReader(),O=new TextDecoder,E="",S=[],R=null,P=Date.now(),k=!1;for(;;){let{done:d,value:C}=await _.read();if(d){k&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}E+=O.decode(C,{stream:!0});let f=E.split(`
|
|
615
|
+
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,v=W.usage;if(v&&(R={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},k=!0),$){let ne=$.reasoning_content||$.reasoning||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),k=!0),$.content&&(S.push({text:$.content}),k=!0)}}catch{}if((I||Date.now()-P>=150)&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1),I)break}Date.now()-P>=150&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1)}};var ei=async function*(e,t,n,s,o,l,u,a,p=1){let h=[];s&&h.push({role:"system",content:s});for(let d of n){let C=d.role==="user"?"user":"assistant",f=[];if(Array.isArray(d.parts)){for(let r of d.parts)if(r.text)f.push({type:"text",text:r.text});else if(r.inlineData&&u){let A=r.inlineData.mimeType,I=r.inlineData.data;A.startsWith("image/")&&f.push({type:"image_url",image_url:{url:`data:${A};base64,${I}`}})}}else{let r=d.text||"";r&&f.push({type:"text",text:r})}h.push({role:C,content:f.length===1&&f[0].type==="text"?f[0].text:f})}let g=Ve("APInex",t,o),b=g!==null?g:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[o],i={model:t,messages:h,stream:!0,stream_options:{include_usage:!0},temperature:p};b&&(i.reasoning_effort=b);let c=process.env.APINEX_URL||"https://api.apinex.bond/v1/chat/completions",w={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},M=e||process.env.APINEX_API_KEY||"";w.Authorization=`Bearer ${M}`;let x=await tt(c,{method:"POST",headers:w,body:JSON.stringify(i),signal:a});if(!x.ok){let d=await x.json().catch(()=>({}));throw new Error(`APInex Error (${x.status}): ${d.error?.message||d.message||x.statusText}`)}let _=x.body.getReader(),O=new TextDecoder,E="",S=[],R=null,P=Date.now(),k=!1;for(;;){let{done:d,value:C}=await _.read();if(d){k&&(S.length>0||R)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:R});break}E+=O.decode(C,{stream:!0});let f=E.split(`
|
|
616
|
+
`);E=f.pop();for(let r of f){let A=r.trim();if(!A||!A.startsWith("data: "))continue;let I=!1;if(A==="data: [DONE]")I=!0;else try{let W=JSON.parse(A.substring(6)),$=W.choices?.[0]?.delta,v=W.usage;if(v&&(R={totalTokenCount:v.total_tokens||(v.prompt_tokens||0)+(v.completion_tokens||0),promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||v.reasoning_tokens||0},k=!0),$){let ne=$.reasoning_content||$.reasoning||null;!ne&&Array.isArray($.reasoning_details)&&$.reasoning_details.length>0&&(ne=$.reasoning_details.map(fe=>fe.text||"").filter(Boolean).join("")),ne&&(S.push({text:ne,thought:!0}),k=!0),$.content&&(S.push({text:$.content}),k=!0)}}catch{}if((I||Date.now()-P>=150)&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1),I)break}Date.now()-P>=150&&k&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:R},S=[],P=Date.now(),k=!1)}};var Pa=/```[\s\S]*?```/g,$a=/```[\s\S]*$/g,Na=/`[^`]+`/g,Fa=/^\|.*\|$/gm,Ba=/^[^\w]+|[^\w]+$/g,Ua=/[^a-z0-9]/gi,bo=/\[\s*tool:(?:functions\.)?([a-z0-9_]+)\s*\(/gi,Wa=/\[\s*(?:tool:(?:functions\.)?|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Ha=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Gn=/["']/g,Wr=/\\/g,Ga=/<\|channel>thought/gi,ja=/<channel\|>/gi,Va=e=>typeof e!="string"?e:e.replace(Ga,"<think>").replace(ja,"</think>"),df=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\]|$)/i,Ka=(e,t,n=1)=>{let s=t>0?e[t-1]:"",o=t+n<e.length?e[t+n]:"";return s==="`"&&o==="`"},Ya=e=>{let t=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,n;for(;(n=t.exec(e))!==null;)if(!Ka(e,n.index,n[0].length))return{index:n.index,length:n[0].length};return{index:-1,length:0}},ti=e=>{if(!e||typeof e!="string")return null;let t=e.match(/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i);if(!t)return null;let n=t.index+t[0].length,s=e.substring(n),o=Ya(s);if(o.index!==-1){let l=n+o.index+o.length;return{fullBlock:e.substring(0,l),innerContent:s.substring(0,o.index),remainingText:e.substring(l)}}return{fullBlock:e,innerContent:s,remainingText:""}},qt=e=>{if(!e||typeof e!="string")return e;let t=ti(e);return t?t.remainingText.trimStart():e};var qr=/`[^`]*`/g,zr=/`[^`]*$/,Hr=/<\|\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,qa=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Gr=/<\|\s*tool_calls_section_begin\s*\|>/gi,jr=/<\|\s*tool_calls_section_end\s*\|>/gi,za=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi;var Vr=e=>!e||typeof e!="string"?e:e.replace(/(```[\s\S]*?```|`[^`]*`)|(<(?:\w+)(?:[^>]*)>\r?\n?|\r?\n?<\/\w+(?:[^>]*)>)/gi,(t,n)=>n||""),Jr=e=>{if(!e||typeof e!="string")return e;let t=ko(e);if(!t||t.length===0)return e;let n=t[t.length-1];if(!n.fullMatch)return e;let s=e.lastIndexOf(n.fullMatch);if(s===-1)return e;let o=s+n.fullMatch.length;return e.substring(0,o).trimEnd()},oi=null,rs={},jn={key:null,value:null},Yt=e=>e&&e.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Clicked|Dragged|Scrolled|Typed|Pressed Key|Recaptured Screen|Created|Read Skill|Read Documentation|Searched Documentation|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Execution Error|Loop Detected|Contacting Ancestors)\b/ig,(t,n,s,o,l)=>`${n||""}${s}${o||""} \x1B[95m${l}\x1B[0m`),Ja=async(e,t=8,n=1e3,s=8e3,o=null)=>{let l=0;for(;;){if(o?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await e()}catch(u){if(o?.aborted||u?.name==="AbortError"||u?.message==="Subagent task was cancelled."||(l++,l>=t))throw u;let a=Math.min(n*Math.pow(2,l-1),s);await new Promise((p,h)=>{let g=setTimeout(p,a);o&&o.addEventListener("abort",()=>{clearTimeout(g),h(new DOMException("The user aborted a request.","AbortError"))})})}}},bt=!1;var Xa=e=>{let t=e.filter(o=>(o.role==="user"||o.role==="agent"||o.role==="system")&&o.role!=="think"&&!o.isVisualFeedback&&!o.isMeta&&!o.isTerminalRecord&&!(o.text&&o.text.includes("[TERMINAL_RECORD]"))&&!String(o.id).startsWith("welcome")).map((o,l,u)=>{let a=o.fullText||o.text||"";if(o.role==="user"&&l<u.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let p=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(p!==-1){let g=a.substring(0,p).lastIndexOf("[SYSTEM METADATA]");g!==-1?a=a.substring(g).trim():a=a.substring(p).trim()}}else{let p=a.lastIndexOf("[USER]"),h=a.lastIndexOf("[USER PROMPT]");p!==-1?a=a.substring(p+6).trim():h!==-1&&(a=a.substring(h).trim())}return{...o,text:a}}),n=[],s=0;for(;s<t.length;){let o=t[s];if(o.role==="user")n.push(o),s++;else{let l=[];for(;s<t.length&&t[s].role!=="user";)l.push(t[s]),s++;let u=[],a=[],p=!1,h=()=>{u.length>0&&(n.push({role:"agent",text:"combined"}),u=[]),a.length>0&&(n.push({role:"system",text:"combined"}),a=[]),p=!1};l.forEach(g=>{let m=g.role==="system"&&(g.text?.startsWith("[TOOL RESULT]")||g.text?.startsWith("SUCCESS:")||g.text?.startsWith("ERROR:")||g.fullText?.startsWith("[TOOL RESULT]")||g.fullText?.startsWith("SUCCESS:")||g.fullText?.startsWith("ERROR:")),b=g.fullText||g.text||"",i=b.trim();if(!(!i&&!g.binaryPart)){if(m)a.push(i);else if(g.role==="agent"){!p&&a.length>0&&h();let c=b.endsWith(`
|
|
617
617
|
`),w=i.toLowerCase().includes("tool:functions.")||i.toLowerCase().includes("agent:generalist.");u.push(i),w&&c?p=!0:p=!1}}}),h()}}return n.length},Qa=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ff=()=>{bt=!0},uf=()=>bt,ni={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",goal:"Planning",Goal:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"},Vn=(e,t)=>{try{let n=re(t),s=e.toLowerCase().replace(/_/g,"");if(s==="invokesync"||s==="invoke")return n.title||(n.task?n.task.substring(0,30):null);if(s==="getprogress"||s==="cancel"||s==="steer"||s==="steersubagent")return n.id||n.taskId;let o=n.path||n.targetFile||n.TargetFile||n.directory;return o?te.basename(o.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},si=e=>e?new Yr({apiKey:e}):oi,gf=async(e,t,n,s,o={})=>{let{onStatus:a,onMemoryUpdated:p,onBackgroundIncrement:h}=o,{profile:g,thinkingLevel:m,mode:b,janitorModel:i,chatId:c,systemSettings:w,sessionStats:M,aiProvider:x="Google",apiKey:_}=e,O=process.env.NVIDIA_BASE_URL||x==="Ollama"||x==="InferX"||x==="SenseNova"||x==="AIHubMix"||x==="Poolside"||x==="9router"||x==="ExpLabs"||x==="ExperientialLabs"?!1:w?.memory!==!1,S=At(Wn,[]).map(L=>`- [${L.id}]: ${L.memory}`).join(`
|
|
618
|
-
`),
|
|
618
|
+
`),R=s.slice(0,-1).filter(L=>L.text&&!L.text.includes("[TOOL RESULT]")&&!L.text.includes("OBSERVATION:")&&!L.text.startsWith("[TERMINAL_RECORD]")&&!L.isTerminalRecord&&!L.isMeta&&!L.isLogo&&!String(L.id).startsWith("welcome")&&!String(L.id).startsWith("logo")).slice(-14).map(L=>{let B=qt(Qa(L.text)).replace(/\[tool:(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(K,ye)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ye.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
|
|
619
619
|
`).replace(/\n\n/g,`
|
|
620
620
|
`).replace(/\\n\\n/g,"").trim(),Oe=L.role==="user"?8192:32768,q=B.substring(0,Oe);B.length>Oe&&(q+=`
|
|
621
621
|
... (truncated) ...`);let U=L.role==="user"?q.startsWith("[USER]")?"":"[USER]: ":q.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:L.role==="user"?"user":"model",parts:[{text:`${U}${q}`}]}}),P=s.filter(L=>L.role==="user").length===1,k=t.includes("[TITLE-UPDATE]"),d=Math.random()<.8,C=P||k||d,f=qt(n).trim(),r=gr(S,O,C),A=`${f.replace(/\[tool:(?:functions\.)?.*?\]/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;A.length>32768&&(A+=`
|
|
622
622
|
... (truncated) ...`);let I=t.replace(/\[Prompted on:.*?\]/g,"").trim();A=A.replace(/\r?\n\r?\n/g,`
|
|
623
623
|
`).replace(/\n\n/g,`
|
|
624
|
-
`).replace(/\\n\\n/g,"").trim();let W=new Date,
|
|
624
|
+
`).replace(/\\n\\n/g,"").trim();let W=new Date,v=`[METADATA] Current date and Time: ${`${W.getFullYear()}-${W.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(W.getDate()).padStart(2,"0")}, ${W.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
625
625
|
|
|
626
626
|
[USER]: ${I.substring(0,8192)}
|
|
627
627
|
${I.length>8192?`... (truncated) ...
|
|
628
628
|
|
|
629
629
|
`:""}
|
|
630
|
-
[AGENT (current turn)]: ${A}`;
|
|
630
|
+
[AGENT (current turn)]: ${A}`;R.push({role:"user",parts:[{text:v}]});let ne=await Ts("NVIDIA"),Q=(await ro()).quotas?.providerTiers?.NVIDIA==="Free",ue="",Me=0,We=O?12:-1;for(;Me<=We;)try{if(!await wi("background",e))return;let L="",B=null,Oe=!1,q=x;try{let ye=new Promise((ke,oe)=>setTimeout(()=>oe(new Error("JANITOR_TIMEOUT")),1e4)),Ae=x==="Google"&&Me>=0&&Me<6&&ne&&Q,Re=x==="DeepSeek"&&Me<4&&ne&&Q;Oe=Ae||Re,q=Oe?"NVIDIA":x;let Be=(async()=>{if(x==="OpenRouter"){let ke=pe("janitor_open_router"),le=Zo(_,ke,R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),Rt=await le.next();return{iterator:le,firstResult:Rt}}else if(x==="DeepSeek"&&!Oe){let oe=Jo(_,pe("deepseek_fast_fallback"),R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="Mistral"&&!Oe){let oe=Xo(_,pe("mistral_janitor_fallback"),R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="NVIDIA"||Oe){let oe=Qo(Oe?ne:_,pe("nvidia_janitor_fallback"),R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="InferX"){let oe=es(_,targetModel||pe("inferx_fallback")||"deepseek-v4-flash",R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="SenseNova"){let oe=ts(_,targetModel||pe("sensenova_fallback")||"sensenova-6.8-flash-lite",R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="AIHubMix"){let oe=ns(_,targetModel||pe("aihubmix_fallback")||"gpt-4o-mini",R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="Poolside"){let oe=os(_,targetModel||pe("poolside_fallback")||"poolside/laguna-s-2.1",R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="9router"||x==="9Router"){let oe=ss(_,targetModel||pe("9router_fallback")||"z-ai/glm-5.3-flash",R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else if(x==="ExpLabs"||x==="ExperientialLabs"){let oe=is(_,targetModel||pe("explabs_fallback")||"deepseek-v4-pro-0813",R,r,"Fast",b,!1,null,.7)[Symbol.asyncIterator](),le=await oe.next();return{iterator:oe,firstResult:le}}else{let le=(await si(_).models.generateContentStream({model:i||(Me===We?pe("janitor_default"):pe("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:r,temperature:.7,safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}}}))[Symbol.asyncIterator](),Rt=await le.next();return{iterator:le,firstResult:Rt}}})();if(process.stdout.isTTY){let le=(await Es())[c]?.name||"",Rt=le&&!le.startsWith("flow-")&&!le.startsWith("Session ")?le:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Rt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Rt}\x07`)}let{iterator:Ct,firstResult:un}=await Promise.race([Be,ye]),{value:Wt,done:zt}=un;if(!zt&&Wt){let ke=Wt.candidates?.[0]?.content?.parts,oe=ke?q==="Google"?ke[1]?.text||ke[0]?.text||"":ke.filter(le=>le.text&&!le.thought).map(le=>le.text).join(""):typeof Wt.text=="function"?Wt.text():"";oe&&(L+=oe),B=Wt.usageMetadata;for await(let le of{[Symbol.asyncIterator]:()=>Ct}){let Rt=le.candidates?.[0]?.content?.parts,Zn=Rt?q==="Google"?Rt[1]?.text||Rt[0]?.text||"":Rt.filter(Tn=>Tn.text&&!Tn.thought).map(Tn=>Tn.text).join(""):typeof le.text=="function"?le.text():"";Zn&&(L+=Zn),B=le.usageMetadata}}}catch(ye){throw ye}if(L){if(ue=L,B){let ye=B.totalTokenCount||0,Ae=B.cachedContentTokenCount||0,Re=(B.candidatesTokenCount||0)+(q==="Google"&&B.thoughtsTokenCount||0),Be=Oe?pe("nvidia_janitor_fallback"):q==="DeepSeek"?pe("deepseek_fast_fallback"):q==="ExpLabs"||q==="ExperientialLabs"?pe("explabs_fallback")||"deepseek-v4-pro-0813":q==="OpenRouter"?pe("janitor_open_router"):i||(Me===We?pe("janitor_default"):pe("gemma_janitor_fallback_google"));await Bt("tokens",ye,q,Be),Ae>0&&await Bt("cachedTokens",Ae,q,Be),Re>0&&await Bt("candidateTokens",Re,q,Be),Do({provider:q,model:Be,prompt:B.promptTokenCount||0,cached:Ae,output:Re,reasoning:B.thoughtsTokenCount||0})}}else throw new Error("No synthesis generated by Janitor.");h&&(h(),await Et("background"));let U=ko(ue),K=!1;for(let ye of U){let Ae=ye.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Ae)&&(K=!0);let Re={chatId:c,sessionId:c,history:s},Be=await yo(Ae,ye.args,Re);Ae.toLowerCase()==="memory"&&(ye.args.includes("action='user'")||ye.args.includes('action="user"'))&&!Be.startsWith("ERROR")&&(p&&p(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(un=>setTimeout(un,3e3)))}if(!K)try{let ye=At(Wn,[]);if(ye.length>0){let Ae=[];for(let Re of ye)Re.score===void 0&&(Re.score=.5),Re.score*=.99995,Re.score<.05&&(Re.score=0),Re.score=Math.round(Re.score*1e5)/1e5,Re.score>0&&Ae.push(Re);Jn(Wn,Ae)}}catch{}break}catch(L){Me++;let B=new Date().toLocaleString(),Oe=L instanceof Error?(()=>{try{return JSON.parse(JSON.parse(L.message).error.message).error.message}catch{return String(L)}})():String(L);await new Promise(K=>setTimeout(K,1e3));let q=te.join(Mn,"janitor");if(Ge.existsSync(q)||Ge.mkdirSync(q,{recursive:!0}),Ge.appendFileSync(te.join(q,"error.log"),`ERROR [Attempt ${Me}/${We+1}] [${B}]: ${Oe}
|
|
631
631
|
|
|
632
632
|
`),Me>We)break;let U=Math.min(750*Math.pow(2,Me-1),5e3);await new Promise(K=>setTimeout(K,U))}if(Me){let L=te.join(Mn,"janitor");Ge.appendFileSync(te.join(L,"error.log"),`-----------------------------------------------------------------------------
|
|
633
633
|
|
|
634
|
-
`)}if(process.stdout.isTTY)try{let Oe=(await Es())[c]?.name||"",q=Oe&&!Oe.startsWith("flow-")&&!Oe.startsWith("Session ")?Oe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${q}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${q}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Za=e=>{let t=qt(e),n=As?t:t.replace(qr,o=>" ".repeat(o.length)).replace(zr,o=>" ".repeat(o.length));bo.lastIndex=0;let s;for(;(s=bo.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,u=null,a=!1,p=!1;for(let h=o;h<n.length;h++){let g=t[h];if(!u&&(g==='"'||g==="'"||g==="`")?(u=g,a=!1):u&&g===u&&!a&&(u=null),!u&&(g==="("?l++:g===")"&&l--,l===0)){let m=h+1;for(;m<n.length&&/\s/.test(n[m]);)m++;if(m<n.length&&n[m]==="]"){p=!0,bo.lastIndex=m+1;break}}g==="\\"?a=!a:a=!1}if(!p)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Xr=(e,t=!0)=>{let n=bo;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let u=e.substring(o,l.index);s+=t&&o===0?qt(u):u;let a=l.index+l[0].length-1,p=0,h=null,g=-1;for(let m=a;m<e.length;m++){let b=e[m];if(h){if(b===h){let i=0;for(let c=m-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(h=null)}}else if(b==='"'||b==="'"||b==="`")h=b;else if(b==="(")p++;else if(b===")"&&(p--,p===0)){let i=m+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+l[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},el=(e,t,n)=>{let s=bo;s.lastIndex=0;let o="",l=0,u;for(;(u=s.exec(e))!==null;){let a=e.substring(l,u.index);o+=a.replace(t,n);let p=u.index+u[0].length-1,h=0,g=null,m=-1;for(let b=p;b<e.length;b++){let i=e[b];if(g){if(i===g){let c=0;for(let w=b-1;w>=0&&e[w]==="\\";w--)c++;c%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")h++;else if(i===")"&&(h--,h===0)){let c=b+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){m=c;break}}}if(m!==-1)o+=e.substring(u.index,m+1),l=m+1,s.lastIndex=l;else{o+=e.substring(u.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Kr=e=>Xr(e,!0),tl=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Hr.lastIndex=0;let s=e.replace(Hr,(o,l,u)=>{let a="";try{let g=JSON.parse(u.trim());g&&typeof g=="object"&&(a=Object.entries(g).map(([b,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${b}=${JSON.stringify(c)}`}).join(", "))}catch{let m=[],b=qa;b.lastIndex=0;let i;for(;(i=b.exec(u))!==null;){let c=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();m.push(`${c}=${JSON.stringify(w)}`)}m.length>0?a=m.join(", "):a=u.trim()}let p=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[p]||n(l)}(${a})]`});return Gr.lastIndex=0,jr.lastIndex=0,s=s.replace(Gr,""),s=s.replace(jr,""),s},nl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,ol=/^['"`]?\s*\.\.\.\s*['"`]?$/,wn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||ol.test(t)},ko=e=>{if(!e)return[];let t=tl(e),n=qt(t),s=[],o=As?n:n.replace(qr,a=>" ".repeat(a.length)).replace(zr,a=>" ".repeat(a.length)),l=Wa;l.lastIndex=0;let u;for(;(u=l.exec(o))!==null;){let a=u[1],p=u.index+u[0].length-1,h=0,g=null,m=-1,b=-1;for(let i=p;i<o.length;i++){let c=n[i];if(g){if(c===g){let w=0;for(let M=i-1;M>=0&&n[M]==="\\";M--)w++;w%2===0&&(g=null)}}else if(c==='"'||c==="'"||c==="`")g=c;else if(c==="(")h++;else if(c===")"&&(h--,h===0)){b=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){m=w;break}}}if(m!==-1){let i=n.substring(p+1,b),c=n.substring(u.index,m+1),w=re(i);wn(w.path)||wn(w.query)||wn(w.url)||wn(w.keyword)||wn(w.command)||wn(w.method)||wn(w.title)||wn(w.task)||wn(w.id)||nl.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=m+1}}return s},hf=(e,t={})=>{if(!e)return null;if(rs=t,oi=new Yr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},as=async(e,t,n,s,o="Fast",l=.75,u="agent")=>Ja(async()=>{let{aiProvider:a="Google",apiKey:p,mode:h}=e,g="",m=null,b=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,w=setInterval(()=>{bt&&(i.abort(),clearInterval(w))},100);try{let M;a==="Ollama"?M=Qs(p,t,b,s,o,h,ft(t),c,l,e.systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?M=Zo(p,t,b,s,o,h,ft(t),c,l):a==="DeepSeek"?M=Jo(p,t,b,s,o,h,ft(t),c,l):a==="Mistral"?M=Xo(p,t,b,s,o,h,ft(t),c,l):a==="NVIDIA"?M=Qo(p,t,b,s,o,h,ft(t),c,l):a==="InferX"?M=es(p,t,b,s,o,h,ft(t),c,l):a==="SenseNova"?M=ts(p,t,b,s,o,h,ft(t),c,l):a==="AIHubMix"?M=ns(p,t,b,s,o,h,ft(t),c,l):a==="Poolside"?M=os(p,t,b,s,o,h,ft(t),c,l):a==="9router"||a==="9Router"?M=ss(p,t,b,s,o,h,ft(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?M=is(p,t,b,s,o,h,ft(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?M=Zs(p,t,b,s,o,h,ft(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?M=ei(p,t,b,s,o,h,ft(t),c,l):M=await si(p).models.generateContentStream({model:t,contents:b,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let O=(t||"").toLowerCase(),E=O.includes("gemma-4")||O.startsWith("gemma"),S=O.includes("gemini-3");if(E||S)return E?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Qe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:O.includes("pro")?Qe.LOW:Qe.MINIMAL,Low:Qe.LOW,Medium:Qe.MEDIUM,Standard:Qe.MEDIUM,High:Qe.HIGH,xHigh:Qe.HIGH}[o]||Qe.MEDIUM};{let
|
|
634
|
+
`)}if(process.stdout.isTTY)try{let Oe=(await Es())[c]?.name||"",q=Oe&&!Oe.startsWith("flow-")&&!Oe.startsWith("Session ")?Oe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${q}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${q}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Za=e=>{let t=qt(e),n=As?t:t.replace(qr,o=>" ".repeat(o.length)).replace(zr,o=>" ".repeat(o.length));bo.lastIndex=0;let s;for(;(s=bo.exec(n))!==null;){let o=s.index+s[0].length-1,l=0,u=null,a=!1,p=!1;for(let h=o;h<n.length;h++){let g=t[h];if(!u&&(g==='"'||g==="'"||g==="`")?(u=g,a=!1):u&&g===u&&!a&&(u=null),!u&&(g==="("?l++:g===")"&&l--,l===0)){let m=h+1;for(;m<n.length&&/\s/.test(n[m]);)m++;if(m<n.length&&n[m]==="]"){p=!0,bo.lastIndex=m+1;break}}g==="\\"?a=!a:a=!1}if(!p)return{inside:!0,toolName:s[1],startIndex:s.index,args:t.substring(s.index+s[0].length)}}return{inside:!1}},Xr=(e,t=!0)=>{let n=bo;n.lastIndex=0;let s="",o=0,l;for(;(l=n.exec(e))!==null;){let u=e.substring(o,l.index);s+=t&&o===0?qt(u):u;let a=l.index+l[0].length-1,p=0,h=null,g=-1;for(let m=a;m<e.length;m++){let b=e[m];if(h){if(b===h){let i=0;for(let c=m-1;c>=0&&e[c]==="\\";c--)i++;i%2===0&&(h=null)}}else if(b==='"'||b==="'"||b==="`")h=b;else if(b==="(")p++;else if(b===")"&&(p--,p===0)){let i=m+1;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="]"){g=i;break}}}if(g!==-1)s+="[tool:functions."+l[1]+"()]",o=g+1,n.lastIndex=o;else{s+="[tool:functions."+l[1]+"(",o=e.length;break}}return o<e.length&&(s+=t&&o===0?qt(e.substring(o)):e.substring(o)),s},el=(e,t,n)=>{let s=bo;s.lastIndex=0;let o="",l=0,u;for(;(u=s.exec(e))!==null;){let a=e.substring(l,u.index);o+=a.replace(t,n);let p=u.index+u[0].length-1,h=0,g=null,m=-1;for(let b=p;b<e.length;b++){let i=e[b];if(g){if(i===g){let c=0;for(let w=b-1;w>=0&&e[w]==="\\";w--)c++;c%2===0&&(g=null)}}else if(i==='"'||i==="'"||i==="`")g=i;else if(i==="(")h++;else if(i===")"&&(h--,h===0)){let c=b+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){m=c;break}}}if(m!==-1)o+=e.substring(u.index,m+1),l=m+1,s.lastIndex=l;else{o+=e.substring(u.index),l=e.length;break}}return l<e.length&&(o+=e.substring(l).replace(t,n)),o},Kr=e=>Xr(e,!0),tl=e=>{if(!e)return e;let t={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",goal:"Goal",askuser:"AskUser",ask:"AskUser"},n=o=>o.split("_").map(l=>l.charAt(0).toUpperCase()+l.slice(1)).join("");Hr.lastIndex=0;let s=e.replace(Hr,(o,l,u)=>{let a="";try{let g=JSON.parse(u.trim());g&&typeof g=="object"&&(a=Object.entries(g).map(([b,i])=>{let c=typeof i=="string"?i:JSON.stringify(i);return`${b}=${JSON.stringify(c)}`}).join(", "))}catch{let m=[],b=qa;b.lastIndex=0;let i;for(;(i=b.exec(u))!==null;){let c=i[1],w=i[2]!==void 0?i[2]:i[0].split(":").slice(1).join(":").trim();m.push(`${c}=${JSON.stringify(w)}`)}m.length>0?a=m.join(", "):a=u.trim()}let p=l.toLowerCase().replace(/_/g,"");return`[tool:functions.${t[p]||n(l)}(${a})]`});return Gr.lastIndex=0,jr.lastIndex=0,s=s.replace(Gr,""),s=s.replace(jr,""),s},nl=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,ol=/^['"`]?\s*\.\.\.\s*['"`]?$/,wn=e=>{if(e==null)return!1;let t=String(e).trim();return t==="..."||t==="\u2026"||ol.test(t)},ko=e=>{if(!e)return[];let t=tl(e),n=qt(t),s=[],o=As?n:n.replace(qr,a=>" ".repeat(a.length)).replace(zr,a=>" ".repeat(a.length)),l=Wa;l.lastIndex=0;let u;for(;(u=l.exec(o))!==null;){let a=u[1],p=u.index+u[0].length-1,h=0,g=null,m=-1,b=-1;for(let i=p;i<o.length;i++){let c=n[i];if(g){if(c===g){let w=0;for(let M=i-1;M>=0&&n[M]==="\\";M--)w++;w%2===0&&(g=null)}}else if(c==='"'||c==="'"||c==="`")g=c;else if(c==="(")h++;else if(c===")"&&(h--,h===0)){b=i;let w=i+1;for(;w<o.length&&/\s/.test(o[w]);)w++;if(w<o.length&&o[w]==="]"){m=w;break}}}if(m!==-1){let i=n.substring(p+1,b),c=n.substring(u.index,m+1),w=re(i);wn(w.path)||wn(w.query)||wn(w.url)||wn(w.keyword)||wn(w.command)||wn(w.method)||wn(w.title)||wn(w.task)||wn(w.id)||nl.test(i)||s.push({fullMatch:c,toolName:a.trim(),args:i.trim()}),l.lastIndex=m+1}}return s},hf=(e,t={})=>{if(!e)return null;if(rs=t,oi=new Yr({apiKey:e}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let n=globalThis.fetch;globalThis.fetch=async(...s)=>{try{let o=await n(...s);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}catch(o){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),o}}}},as=async(e,t,n,s,o="Fast",l=.75,u="agent")=>Ja(async()=>{let{aiProvider:a="Google",apiKey:p,mode:h}=e,g="",m=null,b=typeof n=="string"?[{role:"user",parts:[{text:n}]}]:n,i=new AbortController,c=i.signal,w=setInterval(()=>{bt&&(i.abort(),clearInterval(w))},100);try{let M;a==="Ollama"?M=Qs(p,t,b,s,o,h,ft(t),c,l,e.systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?M=Zo(p,t,b,s,o,h,ft(t),c,l):a==="DeepSeek"?M=Jo(p,t,b,s,o,h,ft(t),c,l):a==="Mistral"?M=Xo(p,t,b,s,o,h,ft(t),c,l):a==="NVIDIA"?M=Qo(p,t,b,s,o,h,ft(t),c,l):a==="InferX"?M=es(p,t,b,s,o,h,ft(t),c,l):a==="SenseNova"?M=ts(p,t,b,s,o,h,ft(t),c,l):a==="AIHubMix"?M=ns(p,t,b,s,o,h,ft(t),c,l):a==="Poolside"?M=os(p,t,b,s,o,h,ft(t),c,l):a==="9router"||a==="9Router"?M=ss(p,t,b,s,o,h,ft(t),c,l):a==="ExpLabs"||a==="ExperientialLabs"?M=is(p,t,b,s,o,h,ft(t),c,l):a==="TokenHarbor"||a==="Token Harbor"||a==="tokenharbor"||a==="token_harbor"||a==="thk"?M=Zs(p,t,b,s,o,h,ft(t),c,l):a==="APInex"||a==="apinex"||a==="apx"?M=ei(p,t,b,s,o,h,ft(t),c,l):M=await si(p).models.generateContentStream({model:t,contents:b,config:{systemInstruction:s,temperature:l,thinkingConfig:(()=>{let O=(t||"").toLowerCase(),E=O.includes("gemma-4")||O.startsWith("gemma"),S=O.includes("gemini-3");if(E||S)return E?o.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Qe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:O.includes("pro")?Qe.LOW:Qe.MINIMAL,Low:Qe.LOW,Medium:Qe.MEDIUM,Standard:Qe.MEDIUM,High:Qe.HIGH,xHigh:Qe.HIGH}[o]||Qe.MEDIUM};{let R={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[o]||2048;return R===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:R}}})()}},{signal:c});for await(let x of M){if(bt)throw new Error("Subagent task was cancelled.");if(e?.taskId&&typeof Kt<"u"){let E=Kt.find(S=>S.id===e.taskId);if(E&&E.status==="cancelled")throw new Error("Subagent task was cancelled.")}let _="";if(x.candidates?.[0]?.content?.parts)for(let E of x.candidates[0].content.parts)E.text&&!E.thought&&(g+=E.text,_+=E.text);let O=_?_s(_):0;e&&typeof e.onTokenChunk=="function"&&e.onTokenChunk(_,O),x.usageMetadata&&(m=x.usageMetadata)}}finally{clearInterval(w)}if(m){let M=m.totalTokenCount||0,x=m.cachedContentTokenCount||0,_=(m.candidatesTokenCount||0)+(a==="Google"&&m.thoughtsTokenCount||0);await Bt("tokens",M,a,t),x>0&&await Bt("cachedTokens",x,a,t),_>0&&await Bt("candidateTokens",_,a,t),Do({provider:a,model:t,prompt:m.promptTokenCount||0,cached:x,output:_,reasoning:m.thoughtsTokenCount||0}),e&&typeof e.onUsage=="function"&&e.onUsage({totalTokenCount:M,cachedContentTokenCount:x,candidatesTokenCount:_})}return await Et("agent",a),{text:g,usageMetadata:m}}),sl=async(e,t,n=null)=>{n=n||At(vo,{});try{let{aiProvider:s="Google"}=t;if(Object.values(n).flat().length<=5)return;let l=Object.keys(n).filter(b=>b!==e&&Array.isArray(n[b])&&n[b].length>2);if(l.length===0)return;let u=`You are a silent background process for the FluxFlow CLI Agent.
|
|
635
635
|
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
636
636
|
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
637
637
|
|
|
@@ -657,7 +657,7 @@ ${c}
|
|
|
657
657
|
${c}
|
|
658
658
|
|
|
659
659
|
`}let p=0,h=5,g=!1,m=pe("gemma_janitor_fallback_google");for(s==="OpenRouter"&&(m=pe("janitor_open_router")),s==="DeepSeek"&&(m=pe("deepseek_level_1")),s==="Mistral"&&(m=pe("mistral_level_1")),s==="NVIDIA"&&(m=pe("nvidia_janitor_fallback")),s==="InferX"&&(m=pe("inferx_fallback")),s==="SenseNova"&&(m=pe("sensenova_fallback")),s==="AIHubMix"&&(m=pe("aihubmix_fallback")),s==="Poolside"&&(m=pe("poolside_fallback")),(s==="9router"||s==="9Router")&&(m=pe("9router_fallback"));p<=h&&!g;){p++;try{let i=(await as(t,m,u,null,"Fast",.75,"background")).text||"",c=ko(i);if(c.length===0)throw new Error("No tool calls detected in synthesis response");for(let w of c){let M=w.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(M)&&await yo(M,w.args,{chatId:e})}g=!0}catch(b){if(p>=h)throw new Error(`Failed after ${h} attempts. Last error: ${b.message}`)}}}catch(s){let o=s instanceof Error?(()=>{try{return JSON.parse(JSON.parse(s.message).error.message).error.message}catch{return String(s)}})():String(s),l=te.join(Mn,"janitor");Ge.existsSync(l)||Ge.mkdirSync(l,{recursive:!0}),Ge.appendFileSync(te.join(l,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${o}
|
|
660
|
-
`)}},mf=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=te.join(
|
|
660
|
+
`)}},mf=async(e,t,n=!1)=>{let{chatId:s,aiProvider:o="Google"}=e,l=te.join(Ro,"chat-summaries.json"),u=i=>i.filter(c=>(c.role==="user"||c.role==="agent"||c.role==="system")&&c.role!=="think"&&!c.isVisualFeedback&&!c.isMeta&&!c.isTerminalRecord&&!(c.text&&c.text.includes("[TERMINAL_RECORD]"))&&!String(c.id).startsWith("welcome")).map(c=>{let w=c.fullText||c.text||"",M=c.role==="system"||w.startsWith("[TOOL RESULT]:")||c.text&&c.text.startsWith("[TOOL RESULT]:"),x=w;return M&&(w.includes("[TOOL RESULT]:")||c.text&&c.text.includes("[TOOL RESULT]:"))?x="[TOOL RESULT]: ...truncated for summary":x=x.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${M?"TOOL":c.role==="agent"?"AGENT":"USER"}]: ${x}`}).join(`
|
|
661
661
|
|
|
662
662
|
`),a=async(i,c)=>{let w="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",M=c?`Here is the previous summary:
|
|
663
663
|
${c}
|
|
@@ -668,9 +668,9 @@ ${i}
|
|
|
668
668
|
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
669
669
|
${i}
|
|
670
670
|
|
|
671
|
-
Provide a consolidated summary of the entire session.`,x=pe("gemma_janitor_fallback_google");o==="OpenRouter"&&(x=pe("janitor_open_router")),o==="DeepSeek"&&(x=pe("deepseek_level_1")),o==="Mistral"&&(x=pe("mistral_level_1")),o==="NVIDIA"&&(x=pe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(x=pe("inferx_fallback")),o==="SenseNova"&&(x=pe("sensenova_fallback")),o==="AIHubMix"&&(x=pe("aihubmix_fallback")),o==="Poolside"&&(x=pe("poolside_fallback")),(o==="9router"||o==="9Router")&&(x=pe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(x=pe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(x=pe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let _=0,O=!1,E=null;for(;_<=3&&!O;){_++;try{E=await as(e,x,M,w,"Fast"),O=!0}catch{if(_>3){if(o==="Google")try{let
|
|
671
|
+
Provide a consolidated summary of the entire session.`,x=pe("gemma_janitor_fallback_google");o==="OpenRouter"&&(x=pe("janitor_open_router")),o==="DeepSeek"&&(x=pe("deepseek_level_1")),o==="Mistral"&&(x=pe("mistral_level_1")),o==="NVIDIA"&&(x=pe("nvidia_chat_summarizer_fallback")),o==="InferX"&&(x=pe("inferx_fallback")),o==="SenseNova"&&(x=pe("sensenova_fallback")),o==="AIHubMix"&&(x=pe("aihubmix_fallback")),o==="Poolside"&&(x=pe("poolside_fallback")),(o==="9router"||o==="9Router")&&(x=pe("9router_fallback")),(o==="ExpLabs"||o==="ExperientialLabs")&&(x=pe("explabs_fallback")||"deepseek-v4-pro-0813"),(o==="TokenHarbor"||o==="Token Harbor"||o==="tokenharbor"||o==="token_harbor"||o==="thk")&&(x=pe("tokenharbor_fallback")||"deepseek-v4.1-flash:free");let _=0,O=!1,E=null;for(;_<=3&&!O;){_++;try{E=await as(e,x,M,w,"Fast"),O=!0}catch{if(_>3){if(o==="Google")try{let R=pe("general_fallback");return(await as(e,R,M,w,"Fast")).text||""}catch{return""}return""}}}return E&&E.text||""},p=u(t),h=At(l,{}),g=h[s]||{summary:"",historyLength:0};typeof g=="string"&&(g={summary:g,historyLength:0});let m=g.summary||"",b=await a(p,m);if(b){g.summary=b;let i=Xa(t);return n?g.historyLength=(g.historyLength||0)+i:g.historyLength=i,h[s]=g,Jn(l,h),b}return null},pf=e=>{try{let t=te.join(Ro,"chat-summaries.json");if(Ge.existsSync(t)){let n=At(t,{});n[e]&&(delete n[e],Jn(t,n))}}catch{}},yf=async function*(e,t,n,s,o){let{profile:l,thinkingLevel:u,mode:a,janitorModel:p,chatId:h,isPlayground:g,systemSettings:m,sessionStats:b,aiProvider:i="Google",apiTier:c,wildcardTooling:w,wildercardTooling:M}=n,x=ft(e);if(!oi&&i==="Google")throw new Error("AI not initialized");let _=process.env.NVIDIA_BASE_URL||n?.aiProvider==="Ollama"||n?.aiProvider==="InferX"||n?.aiProvider==="SenseNova"||n?.aiProvider==="AIHubMix"||n?.aiProvider==="Poolside"||n?.aiProvider==="9router"||n?.aiProvider==="ExpLabs"||n?.aiProvider==="ExperientialLabs"||n?.aiProvider==="TokenHarbor"||n?.aiProvider==="Token Harbor"||n?.aiProvider==="tokenharbor"||n?.aiProvider==="token_harbor"||n?.aiProvider==="thk"||n?.aiProvider==="APInex"||n?.aiProvider==="apinex"||n?.aiProvider==="apx"?!1:m?.memory!==!1,O=t[t.length-1].text,E=te.join(Ro,"chat-summaries.json"),S=!1,R=t.filter(f=>f.role==="user").length===1,P=O.includes("[TITLE-UPDATE]"),k=R||P,d=O.replace(/\[TITLE-UPDATE\]/g,"").trim();d=d.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await Oo.startTransaction(h,d),m?.advanceRollback&&await ao.takeInitialSnapshot(h),bt=!1;let C=null;try{let f=new AbortController;C=setInterval(()=>{bt&&(f.abort(),C&&(clearInterval(C),C=null))},400);let r=[...t.slice(0,-1)];{let Pe=At(E,{})[h]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let Jt=0,Ze=[];for(let Ie=0;Ie<r.length;Ie++){let it=r[Ie];(it.role==="user"||it.role==="agent"||it.role==="system")&&!String(it.id).startsWith("welcome")&&!it.isMeta&&Jt++,Jt>Pe.historyLength&&Ze.push(it)}r=Ze}}r=r.map(H=>{if(H.role==="user"&&H.text){let Pe=H.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...H,text:Pe[1].trim()}}return{...H}});let A=process.env.HIGH_CONTEXT,I=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,v={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[m?.contextLength]||256e3;if(A&&A!=="false"){let H=parseInt(A,10);!isNaN(H)&&H>=0&&H<=1e6&&(v=H)}if((i==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||i==="Mistral")&&(v=126e3),i==="Google"&&e?.includes("gemma")&&I&&(v=16e3),(b?.tokens||0)>v){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(R&&_){let H=At(vo,{});Object.values(H).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await sl(h,n,H))}let ne=At(vo,{}),fe=At(ks,{}),Q=Object.entries(ne).filter(([H])=>H!==h).flatMap(([H,Pe])=>Pe),Me=[...Object.entries(fe).filter(([H])=>H!==h).slice(-20).map(([H,Pe])=>`[Chat Summary]: ${Pe}`),...Q].map(H=>`- ${H}`).join(`
|
|
672
672
|
`),L=At(Wn,[]).map(H=>`- ${H.memory}`).join(`
|
|
673
|
-
`),B=(b?.tokens||0)>=1e4,Oe=fr(Me,L,_,B),q=new Date,U=q.getFullYear(),K=q.toLocaleString("en-US",{month:"short"}).toUpperCase(),ye=String(q.getDate()).padStart(2,"0"),Ae=q.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),
|
|
673
|
+
`),B=(b?.tokens||0)>=1e4,Oe=fr(Me,L,_,B),q=new Date,U=q.getFullYear(),K=q.toLocaleString("en-US",{month:"short"}).toUpperCase(),ye=String(q.getDate()).padStart(2,"0"),Ae=q.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Re=`${U}-${K}-${ye}, ${Ae}`,Be=`${Ae}`,Ct=[".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"],un=H=>{try{return Ge.readdirSync(H,{withFileTypes:!0})}catch{return[]}},Wt=(H,Pe={value:0},Jt=1)=>{if(Pe.value>6200||Jt>7)return Pe.value;let Ze=un(H);for(let Ie of Ze){if(Pe.value>6200)break;Ct.includes(Ie.name)||Ie.name.startsWith(".")||Ie.isDirectory()&&(Pe.value++,Wt(te.join(H,Ie.name),Pe,Jt+1))}return Pe.value},zt=(H,Pe)=>m?.indentationTree!==!1?zs(H,Pe,1,un,Ct):Xs(H,Pe,"",1,un,Ct),ke=Wt(process.cwd()),oe=10;ke>3072||ke>2304?oe=1:ke>1536?oe=2:ke>768?oe=3:ke>384?oe=5:ke>192?oe=6:ke>96?oe=7:(ke>48||ke>24)&&(oe=9);let le=At(ws,{}),Rt=le[h],Zn=Rt?Rt!==process.cwd():!1;le[h]=process.cwd(),Jn(ws,le);let Tn=At(E,{}),Zt=Tn[h]||{summary:"",historyLength:0};typeof Zt=="string"&&(Zt={summary:Zt,historyLength:0});let Qr=t.filter(H=>(H.role==="user"||H.role==="agent"||H.role==="system")&&!String(H.id).startsWith("welcome")&&!H.isMeta).length;Zt.historyLength&&Qr<Zt.historyLength&&(Zt.summary="",Zt.historyLength=0,Tn[h]=Zt,Jn(E,Tn));let wo=typeof Zt=="object"?Zt.summary||"":Zt||"",ii=r.length>0;ii&&wo&&r[0]&&(r[0].role==="user"||r[0].role==="system")&&(r[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(r[0].text=`[SYSTEM METADATA]
|
|
674
674
|
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
675
675
|
${wo}
|
|
676
676
|
|
|
@@ -694,7 +694,7 @@ Cursor Line: ${pt.cursor_line}
|
|
|
694
694
|
... [truncated] ...
|
|
695
695
|
`+Ze.slice(-128)),gn+=`Current Selection: "${Ze}"
|
|
696
696
|
`}if(pt.manual_edits){let Ie=pt.manual_edits.split(`
|
|
697
|
-
`),it=[],nt=null;for(let G of Ie)G.trim()&&(G.startsWith(" Line ")?nt&&nt.edits.push(G):(nt={path:G.endsWith(":")?G.slice(0,-1):G,edits:[]},it.push(nt)));for(let G of it)G.edits.length>80&&(G.edits=G.edits.slice(-80)),G.originalEditsCount=G.edits.length;let rt=(G,je)=>je.reduce((
|
|
697
|
+
`),it=[],nt=null;for(let G of Ie)G.trim()&&(G.startsWith(" Line ")?nt&&nt.edits.push(G):(nt={path:G.endsWith(":")?G.slice(0,-1):G,edits:[]},it.push(nt)));for(let G of it)G.edits.length>80&&(G.edits=G.edits.slice(-80)),G.originalEditsCount=G.edits.length;let rt=(G,je)=>je.reduce((ve,ut)=>{let vt=pt.file_focused&&(ut.path===pt.file_focused||te.resolve(process.cwd(),ut.path)===te.resolve(pt.file_focused))?Math.ceil(G*1.2):G;return ve+Math.min(ut.edits.length,vt)},0),we=80;if(rt(80,it)>300){let G=!1;for(let je=80;je>=10;je--)if(rt(je,it)<=300){we=je,G=!0;break}G||(we=10)}let qe=[...it];if(we===10&&rt(10,qe)>500)for(;qe.length>0&&rt(10,qe)>500;){let G=0,je=qe[0].originalEditsCount;for(let ve=1;ve<qe.length;ve++)qe[ve].originalEditsCount<je&&(je=qe[ve].originalEditsCount,G=ve);qe.splice(G,1)}for(let G of qe){let ve=pt.file_focused&&(G.path===pt.file_focused||te.resolve(process.cwd(),G.path)===te.resolve(pt.file_focused))?Math.ceil(we*1.2):we;G.edits.length>ve&&(G.edits=G.edits.slice(-ve))}for(let G of qe){let je=`${G.path}:
|
|
698
698
|
${G.edits.join(`
|
|
699
699
|
`)}`;for(;G.edits.length>0&&je.length>4*768;)G.edits.shift(),je=`${G.path}:
|
|
700
700
|
${G.edits.join(`
|
|
@@ -710,10 +710,10 @@ ${pt.diagnostics}
|
|
|
710
710
|
`),(d.toLowerCase().includes("lint")||d.toLowerCase().includes("warning"))&&pt.warnings&&(gn+=`
|
|
711
711
|
**Lint Warnings**:
|
|
712
712
|
${pt.warnings}
|
|
713
|
-
`)}let li=d.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ci=/(?:\\)?@\[([^\]]+)\]/g,cs,ds=[];for(ci.lastIndex=0;(cs=ci.exec(li))!==null;){let H=cs[0].startsWith("\\");ds.push({tag:cs[1],isEscaped:H})}let fs=[],To=null;for(let H=0;H<ds.length;H++){let{tag:Pe,isEscaped:Jt}=ds[H];if(!Jt)try{let Ze=Pe.trim().replace(/^["']|["']$/g,""),Ie=/[:#]L?(\d+)(?:-L?(\d+))?$/i,it=Ze.match(Ie),nt=Ze,rt=null,we=null;it&&(rt=parseInt(it[1],10),we=it[2]?parseInt(it[2],10):rt,nt=Ze.slice(0,it.index));let qe=te.resolve(process.cwd(),nt);if(Ge.existsSync(qe)&&Ge.statSync(qe).isFile()){let G=nt.toLowerCase(),je=G.endsWith(".pdf"),
|
|
713
|
+
`)}let li=d.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),ci=/(?:\\)?@\[([^\]]+)\]/g,cs,ds=[];for(ci.lastIndex=0;(cs=ci.exec(li))!==null;){let H=cs[0].startsWith("\\");ds.push({tag:cs[1],isEscaped:H})}let fs=[],To=null;for(let H=0;H<ds.length;H++){let{tag:Pe,isEscaped:Jt}=ds[H];if(!Jt)try{let Ze=Pe.trim().replace(/^["']|["']$/g,""),Ie=/[:#]L?(\d+)(?:-L?(\d+))?$/i,it=Ze.match(Ie),nt=Ze,rt=null,we=null;it&&(rt=parseInt(it[1],10),we=it[2]?parseInt(it[2],10):rt,nt=Ze.slice(0,it.index));let qe=te.resolve(process.cwd(),nt);if(Ge.existsSync(qe)&&Ge.statSync(qe).isFile()){let G=nt.toLowerCase(),je=G.endsWith(".pdf"),ve=G.endsWith(".docx")||G.endsWith(".doc")||G.endsWith(".ppt")||G.endsWith(".pptx")||G.endsWith(".xls")||G.endsWith(".xlsx"),ut=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(G),_n=ut||je||ve,vt=i==="Google"||ft(e);if(_n&&!vt){let Ot=`\u2718 Unsupported Modality: ${te.basename(nt)}`,ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let Te=[Ot],Je=Math.max(...Te.map(hn=>hn.length)),En=Math.min(Je+4,ze),Pn=Te.map(hn=>`${hn.padEnd(En-2).substring(0,En-2)}`).join(`
|
|
714
714
|
`);yield{type:"visual_feedback",content:Yt(`${Pn}
|
|
715
715
|
`)};continue}if(rt===null&&!_n){let Ot=0;try{Ot=Ge.readFileSync(qe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Ot>300){let ze=`\u21B7 Skipped (Too Large): ${te.basename(nt)}`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let Je=Math.min(ze.length+4,Te),En=ze.padEnd(Je-2).substring(0,Je-2);yield{type:"visual_feedback",content:Yt(`${En}
|
|
716
|
-
`)};continue}}let ln=rt!==null?rt:1,An=we!==null?we:rt!==null?rt:ln+299;An-ln>300&&(An=ln+300);let eo=`path=${JSON.stringify(nt)}, startLine=${ln}, endLine=${An}`,tn=await
|
|
716
|
+
`)};continue}}let ln=rt!==null?rt:1,An=we!==null?we:rt!==null?rt:ln+299;An-ln>300&&(An=ln+300);let eo=`path=${JSON.stringify(nt)}, startLine=${ln}, endLine=${An}`,tn=await Ri(eo,{isMultiModal:vt}),yt=!1,et="",Dt=null;if(typeof tn=="string"?tn.trim().startsWith("ERROR")?yt=!0:et=tn:tn&&typeof tn=="object"&&tn.binaryPart?(Dt=tn.binaryPart,et=tn.text||""):yt=!0,!yt){let Ot="";if(ut?(Ot=`\u2714 Processed: ${te.basename(nt)}`,To=Dt):je||ve?(Ot=`\u2714 Auto-Analysed: ${te.basename(nt)}`,To=Dt):(Ot=`\u2714 Auto-Read: ${te.basename(nt)}`,fs.push(et)),Ot){let ze=115;process.stdout.isTTY&&(ze=process.stdout.columns-5||120);let Te=[Ot],Je=Math.max(...Te.map(hn=>hn.length)),En=Math.min(Je+4,ze),Pn=Te.map(hn=>`${hn.padEnd(En-2).substring(0,En-2)}`).join(`
|
|
717
717
|
`);yield{type:"visual_feedback",content:Yt(`${Pn}
|
|
718
718
|
`)}}}}}catch{}}let us="";fs.length>0&&(us=`
|
|
719
719
|
[Tagged File Contents] Auto Read User Tagged files by System, No need to re-read
|
|
@@ -721,18 +721,17 @@ ${pt.warnings}
|
|
|
721
721
|
|
|
722
722
|
`)+`
|
|
723
723
|
[Tagged File Contents]
|
|
724
|
-
`);let di=li.replace(/\\(@\[[^\]]+\])/g,"$1"),fi=w||M?`You cannot execute tools
|
|
725
|
-
Instead output the exact string you WOULD have produced
|
|
724
|
+
`);let di=li.replace(/\\(@\[[^\]]+\])/g,"$1"),fi=w||M?`You cannot execute tools. Instead output the string in chat you WOULD have produced to call
|
|
726
725
|
${M?`tool string format [tool:ToolName(arg="value")]
|
|
727
726
|
`:""}`:"",ea=process.env.forcedReasoning||!1,ui=u!=="Fast"&&(i==="Mistral"&&!Io(e)||u!=="High"&&i==="Google")?`${i==="Mistral"&&!Io(e)||e.toLowerCase().startsWith("gemma")||ea?`[system] strictly follow thinking policy as high priority. do not start a response without <think>...</think> [/system]
|
|
728
727
|
`:""}`:"",So="",gi=!!m?.autoExcludeMetadata,ta=!!(gn||us||fi||ls||Oe||ui||Zn||m?.dynamicDirAwareness||m?.autoTruncateResults||_);gi&&!ta?So=di.trim():So=`[System Metadata]
|
|
729
|
-
Time: ${gi?Be:
|
|
730
|
-
WARNING: CWD Changed from previous: "${
|
|
728
|
+
Time: ${gi?Be:Re}${m?.dynamicDirAwareness?ai:""}${Zn?`
|
|
729
|
+
WARNING: CWD Changed from previous: "${Rt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
731
730
|
`:""}${Oe}${gn}
|
|
732
731
|
[/Metadata]
|
|
733
732
|
${ls}${ui}${us}${fi}[user prompt] ${di.trim()} [/user prompt]`.trim();let hi={role:"user",text:So};To&&(hi.binaryPart=To),r.forEach(H=>{H.text&&H.role==="agent"&&(H.text=qt(H.text))}),r.push(hi),ls&&t[t.length-1]?.id&&(yield{type:"summary_injected",content:{id:t[t.length-1].id,text:So}});let en=null,Sn=a==="Flux"?50:15;Sn=a.toLowerCase().includes("cu")?75:Sn;let na=Math.floor(Sn/2),mi=0,rn=16;yield{type:"status",content:"Connecting"},bt=!1;let gs=[],_o=!1,pi=!1;for(let H=0;H<=Sn;H++){let Pe=Math.floor(Sn*.95);if(H>=Pe&&mi<Pe&&typeof n?.onAskUser=="function"){mi=Pe;try{let me="Agent has been running for a long time. Do you want to continue execution?",_e=[{id:"continue",label:"Continue",description:"Add few more steps"},{id:"cancel",label:"Cancel",description:"Stop extending and finish current turn limit"}],ee=await n.onAskUser(me,_e);ee&&(ee.toLowerCase().includes("continue")||ee==="Continue")&&(Sn+=na)}catch{}}let Jt=await Ss("agent",n);if(!Jt.allowed)throw new Error(Jt.reason||`Budget Exhausted for Provider (${i||"Agent"})`);let Ze=[];if(_o=!1,a==="ICU"||a==="FluxCU")try{yield{type:"status",content:"Capturing Screen"},await new Promise(ee=>setTimeout(ee,1e3));let{captureGriddedScreenshot:me}=await import("./screen_grid-DR34XH4Z.js"),_e=await me();if(_e&&_e.base64){let ee="[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]",Lt={inlineData:{mimeType:_e.mimeType,data:_e.base64}},Mt=m?.imageHistoryCU||"Standard",St=Mt==="Low"?1:Mt==="Extended"?5:3,Xt=r.filter(Ye=>Array.isArray(Ye.parts)&&Ye.parts.some(Pt=>Pt.inlineData));if(Xt.length>=St){let Ye=Xt.length-St+1;for(let Pt=0;Pt<Ye;Pt++){let _t=Xt[Pt];Array.isArray(_t.parts)&&(_t.parts=_t.parts.filter(kt=>!kt.inlineData))}}if(r.length>0&&r[r.length-1].role==="user"){let Ye=r[r.length-1];typeof Ye.text=="string"&&(Ye.text+=`
|
|
734
733
|
|
|
735
|
-
${ee}`,Array.isArray(Ye.parts)||(Ye.parts=[{text:Ye.text}]),Ye.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(m?.compression===0&&(b?.tokens||0)>
|
|
734
|
+
${ee}`,Array.isArray(Ye.parts)||(Ye.parts=[{text:Ye.text}]),Ye.parts.push(Lt))}else r.push({role:"user",text:ee,parts:[{text:ee},Lt]})}}catch(me){console.error("Vision screenshot capture error:",me)}if(m?.compression===0&&(b?.tokens||0)>v&&(r=Ci(r,6)),H>0?yield{type:"status",content:"Working"}:yield{type:"status",content:"Connecting"},bt){try{let{clearPendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js");me()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
736
735
|
|
|
737
736
|
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:me}=await import("./subagent_state-LZCOZSUJ.js"),_e=me();if(_e&&_e.length>0){let ee=_e.join(`
|
|
738
737
|
|
|
@@ -744,9 +743,9 @@ ${ee}`:r.push({role:"user",text:ee}),yield{type:"status",content:"Subagent Updat
|
|
|
744
743
|
[question] ${me.replace("/btw","").trim()} [/question]`:r.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
|
|
745
744
|
[question] ${me.replace("/btw","").trim()} [/question]`}):r.length>0&&r[r.length-1].role==="user"?r[r.length-1].text+=`
|
|
746
745
|
|
|
747
|
-
[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ie,it=!1,nt=1,rt=1,we="",qe=null,an=null,G=null,je=0,
|
|
746
|
+
[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`:r.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${me.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${me.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ie,it=!1,nt=1,rt=1,we="",qe=null,an=null,G=null,je=0,ve=[],ut=0,_n=!1,vt=!1,ln=!1,An=!1,eo=!0,tn=0,yt="",et="",Dt=!1,Ot=!1,ze=!0,Te=e,Je="";for(;nt<=rn&&rt<=rn&&!it&&!bt;){let me=!1;try{we="",eo&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},eo=!1,rt===1&&(yt=""));let _e=D=>{if(!D||!D.includes("[tool:"))return D;let Y="",N=ti(D);N&&(Y=N.fullBlock,D=N.remainingText),D=D.replace(za,(ce,se)=>se.includes("[tool:")?se.trim():ce);let V="",X=0;for(;X<D.length;){let ce=D.indexOf("[tool:",X);if(ce===-1){V+=Vr(D.substring(X));break}let se=D.substring(X,ce);V+=Vr(se);let ht=-1,F=null,Z=0;for(let Ee=ce;Ee<D.length;Ee++){let y=D[Ee];if(F){if(y===F){let He=0;for(let xe=Ee-1;xe>=0&&D[xe]==="\\";xe--)He++;He%2===0&&(F=null)}}else if(y==='"'||y==="'"||y==="`")F=y;else if(y==="(")Z++;else if(y===")")Z--;else if(y==="]"&&Z<=0){ht=Ee;break}}if(ht===-1){V+=D.substring(ce);break}V+=D.substring(ce,ht+1),X=ht+1}return(m?.keepReasoningContext?Y:"")+V},ee=r.filter(D=>(D.role==="user"||D.role==="agent"||D.role==="system")&&!String(D.id).startsWith("welcome")&&!D.isMeta&&!D.isTerminalRecord&&!(D.text&&D.text.startsWith("[TERMINAL_RECORD]"))).map((D,Y,N)=>{let V=D.text||"";_||(V=V.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(V=_e(V),V=V.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),V=V.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let X=[];return Array.isArray(D.parts)&&D.parts.length>0?X=D.parts.map(ce=>{if(ce.text){let se=ce.text;return _||(se=se.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),D.role==="agent"&&(se=_e(se),se=se.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),se=se.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:se}}return ce}):X=[{text:V}],D.binaryPart&&ft(Te)&&N.slice(Y+1).filter(se=>se.role==="user"&&!se.text?.startsWith("[TOOL RESULT]")).length<=2&&X.push(D.binaryPart),{role:D.role==="user"||D.role==="system"?"user":"model",parts:X}});for(let D=0;D<ee.length;D++){let Y=ee[D],N=Y.parts?.[0]?.text||"";if(Y.role==="model"&&/\[tool:/i.test(N)){let V=-1;for(let X=D+1;X<ee.length;X++){let ce=ee[X],se=ce.parts?.[0]?.text||"";if(ce.role==="user"&&se.startsWith("[TOOL RESULT]")){V=X;break}}if(V!==-1&&V!==D+1){let[X]=ee.splice(V,1);ee.splice(D+1,0,X)}}}for(let D=ee.length-2;D>=0;D--){let Y=ee[D],N=ee[D+1];Y.role==="user"&&N.role==="user"&&(N.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ee.splice(D,1)}let Lt=[];for(let D=0;D<ee.length;D++){let Y=ee[D];if(Lt.length===0)Lt.push(Y);else{let N=Lt[Lt.length-1];N.role===Y.role?(N.parts[0].text+=`
|
|
748
747
|
|
|
749
|
-
`+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&N.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Te=e;let Mt=`${h}|${i}|${a}|${u}|${Te}|${JSON.stringify(l)}|${!!m?.dynamicDirAwareness}|${!!m?.subAgents}`,St=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(St=!1),St)Je=jn.value;else{let D=i==="Mistral"?!!Io(Te):!(Te||"gemma").toLowerCase().startsWith("gemma");Je=ur(l,((Te||"gemma").toLowerCase().startsWith("gemma"),u),a,m,_,
|
|
748
|
+
`+(Y.parts?.[0]?.text||""),Y.parts?.length>1&&N.parts.push(...Y.parts.slice(1))):Lt.push(Y)}}ee.length=0,ee.push(...Lt),Te=e;let Mt=`${h}|${i}|${a}|${u}|${Te}|${JSON.stringify(l)}|${!!m?.dynamicDirAwareness}|${!!m?.subAgents}`,St=jn.key===Mt&&jn.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(St=!1),St)Je=jn.value;else{let D=i==="Mistral"?!!Io(Te):!(Te||"gemma").toLowerCase().startsWith("gemma");Je=ur(l,((Te||"gemma").toLowerCase().startsWith("gemma"),u),a,m,_,R,i,i==="Google"?!0:x,D,h,!!m?.keepReasoningContext,Te),m?.dynamicDirAwareness||(Je+=`
|
|
750
749
|
${ai.replace(`
|
|
751
750
|
**Directory Structure**`,`
|
|
752
751
|
-- Directory Structure --`)}`),jn.key=Mt,jn.value=Je}let Ye=ee[ee.length-1];if(qo()&H>0){await new Promise(N=>setTimeout(N,2500)),yield{type:"status",content:"Verifying"};let D=await Hn(),Y=D?D.diagnostics:null;Y&&Ye&&Ye.role==="user"&&Ye.parts?.[0]?.text&&(Ye.parts[0].text+=`
|
|
@@ -756,19 +755,19 @@ ${Y} [/ERROR]`),yield{type:"status",content:"Working"}}let Pt=i==="Mistral"||i==
|
|
|
756
755
|
`;for(let V of D.modifiedFiles)Y+=`* ${V} (modified)
|
|
757
756
|
`;for(let V of D.deletedFiles)Y+=`* ${V} (deleted)
|
|
758
757
|
`;Y+="[/system]",Ye.parts[0].text+=Y;let N=-1;for(let V=r.length-1;V>=0;V--)if(r[V].role==="user"&&r[V].text?.startsWith("[TOOL RESULT]")){N=V;break}N!==-1&&(r[N].text+=Y)}}catch{}let _t=Math.floor(Sn*.99),kt=H+1;kt>=_t&&Ye&&Ye.parts?.[0]&&(Ye.parts[0].text+=`
|
|
759
|
-
[system] WARNING, Turn Limit Impending: Step ${kt}/${Sn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{f.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),f.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Ie=Qs(n.apiKey,Te,gt,Je,u,a,x,f.signal,1,m?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Ie=Zo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1,h);else if(i==="DeepSeek")Ie=Jo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="Mistral")Ie=Xo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1,h);else if(i==="NVIDIA"){let D=Qo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);Ie=Ur(D,Te)}else if(i==="InferX")Ie=es(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="SenseNova")Ie=ts(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="AIHubMix")Ie=ns(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="Poolside")Ie=os(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="9router"||i==="9Router")Ie=ss(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Ie=is(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Ie=Zs(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Ie=ei(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else{let Y=si(n?.apiKey).models.generateContentStream({model:Te||"gemini-3-flash-preview",contents:gt,config:{systemInstruction:Je,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let N=Ve("Google",Te||"gemini-3-flash-preview",u);if(N!==null){if(typeof N=="object")return N;if(N===!1||N==="false"||N==="none"||N===0||N==="0")return{includeThoughts:!1};if(typeof N=="number")return{includeThoughts:!0,thinkingBudget:N};if(typeof N=="string"){let se=N.toLowerCase();if(se==="minimal")return{includeThoughts:!0,thinkingLevel:Qe.MINIMAL};if(se==="low")return{includeThoughts:!0,thinkingLevel:Qe.LOW};if(se==="medium")return{includeThoughts:!0,thinkingLevel:Qe.MEDIUM};if(se==="high")return{includeThoughts:!0,thinkingLevel:Qe.HIGH};let ht=Number(N);if(!isNaN(ht))return{includeThoughts:!0,thinkingBudget:ht}}}let V=(Te||"").toLowerCase(),X=V.includes("gemma-4")||V.startsWith("gemma"),ce=V.includes("gemini-3");if(X||ce)return X?u.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Qe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:V.includes("pro")?Qe.LOW:Qe.MINIMAL,Low:Qe.LOW,Medium:Qe.MEDIUM,Standard:Qe.MEDIUM,High:Qe.HIGH,xHigh:Qe.HIGH}[u]||Qe.MEDIUM};{let se={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[u]||2048;return se===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:se}}})()}},{signal:f.signal});Ie=await Promise.race([Y,It])}we="",qe=null,G=null,
|
|
758
|
+
[system] WARNING, Turn Limit Impending: Step ${kt}/${Sn}. Wrap up quickly/prompt user to continue. [/system]`);let It=new Promise((D,Y)=>{f.signal.aborted&&Y(new DOMException("The user aborted a request.","AbortError")),f.signal.addEventListener("abort",()=>{Y(new DOMException("The user aborted a request.","AbortError"))})});It.catch(()=>{});let gt=ee;if(i==="Ollama")Ie=Qs(n.apiKey,Te,gt,Je,u,a,x,f.signal,1,m?.ollamaEndpoint||"Cloud");else if(i==="OpenRouter")Ie=Zo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1,h);else if(i==="DeepSeek")Ie=Jo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="Mistral")Ie=Xo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1,h);else if(i==="NVIDIA"){let D=Qo(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);Ie=Ur(D,Te)}else if(i==="InferX")Ie=es(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="SenseNova")Ie=ts(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="AIHubMix")Ie=ns(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="Poolside")Ie=os(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="9router"||i==="9Router")Ie=ss(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="ExpLabs"||i==="ExperientialLabs")Ie=is(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="TokenHarbor"||i==="Token Harbor"||i==="tokenharbor"||i==="token_harbor"||i==="thk")Ie=Zs(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else if(i==="APInex"||i==="apinex"||i==="apx")Ie=ei(n.apiKey,Te,gt,Je,u,a,x,f.signal,1);else{let Y=si(n?.apiKey).models.generateContentStream({model:Te||"gemini-3-flash-preview",contents:gt,config:{systemInstruction:Je,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:Ln.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Ln.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let N=Ve("Google",Te||"gemini-3-flash-preview",u);if(N!==null){if(typeof N=="object")return N;if(N===!1||N==="false"||N==="none"||N===0||N==="0")return{includeThoughts:!1};if(typeof N=="number")return{includeThoughts:!0,thinkingBudget:N};if(typeof N=="string"){let se=N.toLowerCase();if(se==="minimal")return{includeThoughts:!0,thinkingLevel:Qe.MINIMAL};if(se==="low")return{includeThoughts:!0,thinkingLevel:Qe.LOW};if(se==="medium")return{includeThoughts:!0,thinkingLevel:Qe.MEDIUM};if(se==="high")return{includeThoughts:!0,thinkingLevel:Qe.HIGH};let ht=Number(N);if(!isNaN(ht))return{includeThoughts:!0,thinkingBudget:ht}}}let V=(Te||"").toLowerCase(),X=V.includes("gemma-4")||V.startsWith("gemma"),ce=V.includes("gemini-3");if(X||ce)return X?u.toLowerCase()!=="high"?{includeThoughts:!1,thinkingLevel:Qe.MINIMAL}:{includeThoughts:!0,thinkingLevel:Qe.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:V.includes("pro")?Qe.LOW:Qe.MINIMAL,Low:Qe.LOW,Medium:Qe.MEDIUM,Standard:Qe.MEDIUM,High:Qe.HIGH,xHigh:Qe.HIGH}[u]||Qe.MEDIUM};{let se={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[u]||2048;return se===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:se}}})()}},{signal:f.signal});Ie=await Promise.race([Y,It])}we="",qe=null,G=null,ve=[],ut=0,yield{type:"model_update",content:null},et="",Dt=yt.length>0;let cn="",hs=Date.now(),Nn=async function*(){if(i==="Google"&&cn){let D=no(cn);for(let Y of D)yield Y;cn="",hs=Date.now()}},yi=!0,Fn="",Kn=!1,wt=null,xi=!1,Yn=!1,qn=!1,Ao=!1,Cn=!1,to=D=>{let Y=0;for(;Y+2<D.length;)D[Y]==="`"&&D[Y+1]==="`"&&D[Y+2]==="`"?(Ao=!Ao,Y+=3):Y++},bi=D=>{if(!D)return;let Y=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,N;for(;(N=Y.exec(D))!==null;){let V=N[0].toLowerCase();V.startsWith("</")||V.startsWith("[/")||V==="<channel|>"?Cn=!1:Cn=!0}},ia={tool:{startPrefix:"[tool",fullPrefix:"[tool:",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},no=D=>{let Y=[],N=D,V=X=>{if(!X)return;if(!xi){Y.push({type:"text",content:X}),to(X),bi(X);return}let ce=/(?:<(\/?)(?:think|thought|thoughts)[^>]*>|\[(\/?)(?:think|thought|thoughts)\]|<\/?channel\|?>|<\|channel>thought)/gi,se=0,ht;for(;(ht=ce.exec(X))!==null;){let Z=X.substring(se,ht.index);if(Z)if(to(Z),Cn)Y.push({type:"text",content:Z});else{let He=Z.replace(/[^\n]/g,"");He&&Y.push({type:"text",content:He})}let Ee=ht[0];to(Ee);let y=Ee.toLowerCase();y.startsWith("</")||y.startsWith("[/")||y==="<channel|>"?Cn=!1:Cn=!0,Y.push({type:"text",content:Ee}),se=ce.lastIndex}let F=X.substring(se);if(F)if(to(F),Cn)Y.push({type:"text",content:F});else{let Z=F.replace(/[^\n]/g,"");Z&&Y.push({type:"text",content:Z})}};for(;N.length>0;)if(Kn){let X=Fn+N,ce=ia[wt];if(ce){let F=!1;if(X.length<ce.startPrefix.length?ce.startPrefix.startsWith(X)||(F=!0):X.startsWith(ce.startPrefix)?X.length>=ce.fullPrefix.length&&!X.startsWith(ce.fullPrefix)&&(F=!0):F=!0,F){V(X),Fn="",Kn=!1,wt=null,Yn=!1,qn=!1,N="";break}}let se=-1,ht=ce?ce.endTag:"]";if(wt==="tool"||wt==="agent"){let F=0,Z=null,Ee=0,y=!1;for(let He=0;He<X.length;He++){let xe=X[He];if(Z){if(xe===Z){let J=0;for(let $t=He-1;$t>=0&&X[$t]==="\\";$t--)J++;J%2===0&&(Z=null)}}else if(xe==='"'||xe==="'"||xe==="`")Z=xe;else if(xe==="(")F++,y=!0;else if(xe===")")F--;else if(xe==="[")Ee++;else if(xe==="]"){if(y&&F===0&&Ee===1){se=He;break}Ee--}}}else se=X.indexOf(ht);if(se!==-1){let F=ht.length,Z=X.substring(0,se+F);wt?.startsWith("kimi")||Y.push({type:"text",content:Z}),to(Z),bi(Z),(wt==="tool"||wt==="agent"||wt?.startsWith("kimi"))&&!Yn&&!qn&&(xi=!0),Yn=!1,qn=!1,Fn="",Kn=!1,wt=null,N=X.substring(se+F)}else{let F=wt?.startsWith("kimi")?8192:512;X.length>F?(V(X),Fn="",Kn=!1,wt=null,Yn=!1,qn=!1):Fn=X,N="";break}}else{let X=N.indexOf("[tool"),ce=N.indexOf("[agent"),se=N.indexOf("[[END]]"),ht=N.indexOf("<|tool_calls_section_begin|>"),F=N.indexOf("<|tool_call_begin|>"),Z=[{type:"tool",idx:X,start:"[tool",end:"]"},{type:"agent",idx:ce,start:"[agent",end:"]"},{type:"end",idx:se,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:ht,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:F,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(Ee=>Ee.idx!==-1).sort((Ee,y)=>Ee.idx-y.idx);if(Z.length>0){let Ee=Z[0],y=N.substring(0,Ee.idx);Ee.idx>0&&V(y);let He=Ee.idx>0?N[Ee.idx-1]:"";Yn=Ao||He==="`",qn=Cn,Kn=!0,wt=Ee.type,Fn="",N=N.substring(Ee.idx)}else{let Ee=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],y=-1;for(let He of Ee){for(let xe=He.length-1;xe>0;xe--)if(N.endsWith(He.substring(0,xe))){y=N.length-xe;let J=Ee.indexOf(He);J===0?wt="tool":J===1?wt="agent":J===2?wt="end":J===3?wt="kimi_section":wt="kimi_call";break}if(y!==-1)break}if(y!==-1){if(y>0){let xe=N.substring(0,y);V(xe)}let He=y>0?N[y-1]:"";Yn=Ao||He==="`",qn=Cn,Kn=!0,Fn=N.substring(y),N=""}else{V(N);break}}}return Y},ra=Ie[Symbol.asyncIterator]();for(;;){let{value:D,done:Y}=await Promise.race([ra.next(),It]);if(Y)break;if(D&&D.type==="status"){yield D;continue}let N="",V=D.candidates?.[0]?.content?.parts;if(V&&V.length>0)for(let ce of V){let se=typeof ce.text=="string"?ce.text:ce.text?parseChunkText(ce.text):"";ce.thought?se&&(me||(N+="<think>",me=!0),N+=se):se&&(me&&(N+="</think>",me=!1),N+=se)}else D.text&&me&&(N+="</think>",me=!1);N=Va(N);let X=N?_s(N):0;if(n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(N,X),yi&&(yield{type:"status",content:"Thinking"},yi=!1),bt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
760
759
|
|
|
761
|
-
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(N){if(Dt){if(et+=N,et.length>=64){let F=0,Z=Math.min(yt.length,et.length);for(let y=Z;y>=10;y--)if(yt.endsWith(et.substring(0,y))){F=y;break}let Ee=et.substring(F);if(Ee){let He=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?Ee.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ee.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(He)if(we+=He,i==="Google")cn+=He;else{yield*Nn();let xe=no(He);for(let J of xe)yield J}}Dt=!1,et=""}continue}else if(we+=N,i==="Google")cn+=N;else{yield*Nn();let F=no(N);for(let Z of F)yield Z}let ce=Za(we);if(ce.inside){Ot=!0,G||(G=Date.now());let Z={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ce.toolName]||ce.toolName,Ee=ce.args||"",y=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(Z)){let xe=re(Ee),J=xe.path||xe.targetFile||xe.TargetFile||xe.directory,$t=xe.keyword,Bn=xe.title||xe.task,
|
|
762
|
-
`).length;Ke=xt,!Ce&&!z&&xt>800?Xe=Math.min(50,xt):Xe=Math.min(de,xt)}}catch{}let Le=(T||"").toLowerCase(),mt=Le.endsWith(".pdf"),Fe=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),ot=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);mt||Fe?J=`${T.length>0?"\u2714":"\u2718"} ${T?`Analyzed: ${te.basename(T)}`:"Analyzed: File Not Found"}`:ot?J=`${T.length>0?"\u2714":"\u2718"} ${T?`Processed: ${te.basename(T)}`:"Processed: File Not Found"}`:J=`${Ke!=="..."?"\u2714":"\u2718"} Read: ${T?`${te.basename(T)} \u2192 ${Ke!=="..."?`Lines ${ae} - ${Xe} of ${Ke}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let T=y==="list_files"?"List":"Browsed",j=re(F.args).path||null,ie=re(F.args).recurse||1;J=`${j?"\u2714":"\u2718"} ${T}: ${j?`${j==="."?`./${ie>1?"*":""}`:`${j.replaceAll("\\","/")}${ie>1?`${j.endsWith("/")?"*":"/*"}`:`${j.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let T=y==="write_file"?"Created":"Edited",j=re(F.args),ie=j.path||null,be=Object.entries(j).some(([Ue,De])=>Ue.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";J=`${ie?"\u2714":"\u2718"} ${T}${be} ${ie?ie.replaceAll("\\","/"):"No File Changes"}`}else if(y==="write_pdf"){let T=re(F.args).path||null;J=`${T?"\u2714":"\u2718"} Generated: ${T.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let T=re(F.args).path||null;J=`${T?"\u2714":"\u2718"} Generated: ${T.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let T=re(F.args).path;J=`${T?"\u2714":"\u2718"} Indexed: ${T.replaceAll("\\","/")?""+T:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")J="";else if(y.toLowerCase()==="generate_image"){let{path:T,outputPath:j,output:ie}=re(F.args);J=`\u2714 Generated: ${T||j||ie||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let T=Vn(y,F.args);J=`\u2714 Called Generalist${T?`: ${T}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let T=Vn(y,F.args);J=`\u2714 Started Generalist${T?`: ${T}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let T=Vn(y,F.args);J=`\u2714 Checked${T?`: ${T}`:""}`}else if(y==="cancel"){let T=Vn(y,F.args);J=`\u{1F6C7} Cancelled${T?`: ${T}`:""}`}else if(y==="steer"||y==="Steer"){let T=Vn(y,F.args);J=`\u2714 Steered${T?`: ${T}`:""}`}else if(y==="EmergencyRollback"){let{method:T}=re(F.args);J=T==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:T,timeout:j}=re(F.args),ie=parseFloat(j||T)||0;ie||(ie=120);let ge=De=>{if(De>=60){let Ce=Math.floor(De/60),z=De%60;return`${Ce}m${z>0?` ${z}s`:""}`}return`${De}s`},be=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];J=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ge(ie)}`}else y==="Answer"||y==="answer"?J="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?J="":J=`Executed: ${F.toolName}`;if(yield*Nn(),y==="exec_command"){let{command:T}=re(F.args);if(T&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let j=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ie=te.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=z=>{let ae=[],de="",Ke=null;for(let Xe=0;Xe<z.length;Xe++){let he=z[Xe];Ke?(he===Ke&&(Ke=null),de+=he):he==='"'||he==="'"?(Ke=he,de+=he):he==="&"&&z[Xe+1]==="&"||he==="|"&&z[Xe+1]==="|"?(de.trim()&&(ae.push(de.trim()),de=""),Xe++):he===";"||he==="|"||he==="&"?de.trim()&&(ae.push(de.trim()),de=""):de+=he}return de.trim()&&ae.push(de.trim()),ae},be=z=>{let ae=[],de="",Ke=null;for(let Xe=0;Xe<z.length;Xe++){let he=z[Xe];Ke?(he===Ke&&(Ke=null),de+=he):he==='"'||he==="'"?(Ke=he,de+=he):/\s/.test(he)?de&&(ae.push(de),de=""):de+=he}return de&&ae.push(de),ae},Ue=z=>{let ae=z.replace(/^['"]|['"]$/g,"").trim();return!ae||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ae)?!1:j.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Ke=ae.match(/[a-zA-Z]:[\\\/]/i);return Ke&&Ke[0].toLowerCase()!==ie}return de.test(ae)})};if(ge(T).some(z=>{let ae=be(z);if(ae.length===0)return!1;let de=ae[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let Xe=!1;return ae.some(he=>{let Tt=he.replace(/^['"]|['"]$/g,"");if(Tt===">"||Tt===">>"||Tt==="<")return Xe=!0,!1;if(Tt.startsWith(">")||Tt.startsWith("<")){let Le=Tt.replace(/^[><]+/,"");return Ue(Le)}return Xe?(Xe=!1,Ue(he)):!1})}return ae.some(Xe=>Ue(Xe))})){let z='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(T||"No Command"),yield{type:"exec_start"},await new Promise(ae=>setTimeout(ae,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${z}`),await new Promise(ae=>setTimeout(ae,50)),n.onExecEnd&&n.onExecEnd(),
|
|
760
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(N){if(Dt){if(et+=N,et.length>=64){let F=0,Z=Math.min(yt.length,et.length);for(let y=Z;y>=10;y--)if(yt.endsWith(et.substring(0,y))){F=y;break}let Ee=et.substring(F);if(Ee){let He=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?Ee.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ee.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(He)if(we+=He,i==="Google")cn+=He;else{yield*Nn();let xe=no(He);for(let J of xe)yield J}}Dt=!1,et=""}continue}else if(we+=N,i==="Google")cn+=N;else{yield*Nn();let F=no(N);for(let Z of F)yield Z}let ce=Za(we);if(ce.inside){Ot=!0,G||(G=Date.now());let Z={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[ce.toolName]||ce.toolName,Ee=ce.args||"",y=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map","invoke","invoke_sync","get_progress","await","answer"].includes(Z)){let xe=re(Ee),J=xe.path||xe.targetFile||xe.TargetFile||xe.directory,$t=xe.keyword,Bn=xe.title||xe.task,Rn=xe.id||xe.taskId,$e=xe.timeout||xe.time;if($t!=null)y=String($t).replace(Gn,"");else if(J)y=te.basename(String(J).replace(Gn,"").replace(Wr,"/"));else if(Bn&&(Z==="invoke"||Z==="invoke_sync"))y=String(Bn).replace(Gn,"").substring(0,30);else if(Rn&&Z==="get_progress")y=String(Rn).replace(Gn,"");else if($e&&Z==="await"){let Nt=parseFloat(String($e).replace(Gn,""));isNaN(Nt)?y=String($e).replace(Gn,""):(Nt<5&&(Nt=5),Nt>120&&(Nt=120),y=(mn=>{if(mn>=60){let ps=Math.floor(mn/60),zn=mn%60;return`${ps}m${zn>0?` ${zn}s`:""}`}return`${mn}s`})(Nt))}else{let Nt=Ee.match(Ha);if(Nt){let Ht=Nt[1].replace(Gn,"");Z==="invoke"||Z==="invoke_sync"||Z==="get_progress"?y=Ht.substring(0,30):y=Z==="search_keyword"||Z==="file_map"?Ht:te.basename(Ht.replace(Wr,"/"))}}}let He=`${ni[Z]||Z}${y?` ${y}`:""}`;if((Z!==qe||y!==an)&&(qe=Z,an=y,yield{type:"status",content:`${He}`},process.stdout.isTTY)){let J={WebSearch:"Searching",web_search:"Searching",WebScrape:"Reading",web_scrape:"Reading",ReadFile:"Reading",read_file:"Reading",ReadFolder:"Reading",read_folder:"Reading",WriteFile:"Writing",write_file:"Writing",UpdateFile:"Editing",update_file:"Editing",WritePdf:"Creating",write_pdf:"Creating",WriteDocx:"Creating",write_docx:"Creating",SearchKeyword:"Searching",search_keyword:"Searching",CodeSearch:"Searching",code_search:"Searching",Run:"Executing",Ask:"User Input Required",AskUser:"User Input Required",Memory:"Updating Memory",GenerateImage:"Generating",InvokeSync:"Sub-Agent Working",invoke_sync:"Sub-Agent Working",Invoke:"Working",invoke:"Working",GetProgress:"Checking Progress",get_progress:"Checking Progress",Cancel:"Stopping Generalist",cancel:"Stopping Generalist",Await:"Waiting",await:"Waiting",EmergencyRollback:"Rolling the Ball",Answer:"Answering Sub-Agent",answer:"Answering Sub-Agent",Steer:"Steering Sub-Agent",steer:"Steering Sub-Agent",Click:"Clicking",click:"Clicking",Drag:"Dragging",drag:"Dragging",Scroll:"Scrolling",scroll:"Scrolling",KeyboardTyping:"Typing",keyboard_typing:"Typing",KeyPress:"Pressing Key",key_press:"Pressing Key",RecaptureScreen:"Recapturing Screen",recapture_screen:"Recapturing Screen"}[Z]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(we.length-tn>150){tn=we.length;let F=Xr(we,!1),Z=ti(F),Ee=Z?(Z.innerContent||"").trim():"",y=Ee.split(/[.!?]\s+/),He=new Set(y),xe=y.length>10?(y.length-He.size)/y.length:0,J=Ee.split(/\s+/).filter(Ne=>Ne.length>0).length,$t=.6,Bn=.8,Rn=!1;if(i.toLowerCase().includes("google")&&(Te||"").toLowerCase().startsWith("gemma")){let T={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[u?.toLowerCase()]||2500;Rn=J>T}if(xe>$t||Rn){yield{type:"status",content:`${xe>$t?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},vt=!0,await new Promise(T=>setTimeout(T,3e3));break}let Ht=Kr(we).trim().split(/[.!?]\s+/),mn=new Set(Ht);if((Ht.length>10?(Ht.length-mn.size)/Ht.length:0)>Bn){yield{type:"status",content:"Response Loop Detected. Re-centering..."},vt=!1,An=!0,await new Promise(Ne=>setTimeout(Ne,3e3));break}let zn=F.replace(Pa,"").replace($a,"").replace(Na,"").replace(Fa,""),Ft=zn.toLowerCase().split(/\s+/).map(Ne=>Ne.replace(Ba,"")).filter(Ne=>Ne.length>0),pn=!1;if(Ft.length>=10)for(let Ne=1;Ne<=15;Ne++){let T=Math.max(3,Math.ceil(10/Ne));if(Ft.length<Ne*T)continue;let j=Ft.slice(Ft.length-Ne),ie=j.join(" ");if(Ne>1&&ie===j.slice(0,Math.floor(Ne/2)).join(" ").repeat(2).trim())continue;let ge=!0;for(let be=1;be<T;be++)if(Ft.slice(Ft.length-Ne*(be+1),Ft.length-Ne*be).join(" ")!==ie){ge=!1;break}if(ge){pn=!0;break}}if(!pn){let Ne=zn.toLowerCase().replace(Ua,"");if(Ne.length>=20)for(let T=1;T<=10;T++){let j=Math.max(5,Math.ceil(16/T));if(Ne.length<T*j)continue;let ie=Ne.substring(Ne.length-T),ge=!0;for(let be=1;be<j;be++)if(Ne.substring(Ne.length-T*(be+1),Ne.length-T*be)!==ie){ge=!1;break}if(ge){pn=!0;break}}}if(pn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},vt=!1,ln=!0,await new Promise(Ne=>setTimeout(Ne,3e3));break}}let se=qt(we),ht=ko(se);for(;ht.length>ut;){yield*Nn();let F=ht[ut],Z=Date.now(),y={Ask:"ask",AskUser:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",CodeSearch:"search_keyword",code_search:"search_keyword",Code_Search:"search_keyword",codesearch:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image",todo:"todo",Todo:"todo",goal:"todo",Goal:"todo",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Await:"await",await:"await",AwaitSubagent:"await",awaitSubagent:"await",Answer:"answer",answer:"answer",AnswerSubagent:"answer",answerSubagent:"answer",Steer:"steer",steer:"steer",SteerSubagent:"steer",steerSubagent:"steer",Cancel:"cancel",cancel:"cancel",Click:"click",click:"click",Drag:"drag",drag:"drag",Scroll:"scroll",scroll:"scroll",KeyboardTyping:"keyboard_typing",keyboard_typing:"keyboard_typing",KeyPress:"key_press",key_press:"key_press",RecaptureScreen:"recapture_screen",recapture_screen:"recapture_screen",EmergencyRollback:"EmergencyRollback"}[F.toolName]||F.toolName,He=ni[y]||F.toolName,xe=Vn(y,F.args);yield{type:"status",content:`${He}${xe?` ${xe}`:""}`};let J="";if(y==="click"){let T=re(F.args);J=`\u2714 Clicked: ${T.intendedClickText?`${T.intendedClickText}`:""}`}else if(y==="drag"){let T=re(F.args);J=`\u2714 Dragged: Cell ${T.fromGridId||""} \u2192 Cell ${T.toGridId||""}`}else if(y==="scroll"){let T=re(F.args);J=`\u2714 Scrolled: ${T.direction||"down"} (${T.amount||1})`}else if(y==="keyboard_typing"){let T=re(F.args);J=`\u2714 Typed: ${T.text?`"${T.text.length>20?T.text.substring(0,20)+"...":T.text}"`:""}`}else if(y==="key_press")J=`\u2714 Pressed Key: ${re(F.args).key||""}`;else if(y==="recapture_screen")J="\u2714 Recaptured Screen";else if(y==="web_search"){let{query:T,limit:j=10,aiMode:ie=!1}=re(F.args);J=`${T?"\u2714":"\u2718"} ${ie?"AI Search":"Searched"}: ${T?`${T}`:"No Search Query"}${ie===!1&&T?` \u2192 ${j}`:""}`}else if(y==="web_scrape"){let T=re(F.args).url||null;J=`${T?"\u2714":"\u2718"} Visited: ${T||"No Source"}`}else if(y==="view_file"){let{path:T,StartLine:j,EndLine:ie,start_line:ge,end_line:be,startLine:Ue,endLine:De}=re(F.args),Ce=j||ge||Ue,z=ie||be||De,ae=parseInt(Ce)||1,de=parseInt(z)||(Ce?ae+800:800),Ke="...",Xe=de,he=(T||"").trim().toLowerCase().replaceAll("\\","/");if(he.startsWith("#skill"))he.startsWith("#skill/global/fluxflow")||he.startsWith("#skills/global/fluxflow")||he.includes("#skill/fluxflow")||he.includes("#skills/fluxflow")?J="\u2714 Read Documentation":J=`\u2714 Read Skill: ${te.basename(T.replaceAll("\\","/"))}`;else{try{let Se=te.resolve(process.cwd(),T);if(Ge.existsSync(Se)){let xt=Ge.readFileSync(Se,"utf8").split(`
|
|
761
|
+
`).length;Ke=xt,!Ce&&!z&&xt>800?Xe=Math.min(50,xt):Xe=Math.min(de,xt)}}catch{}let Le=(T||"").toLowerCase(),mt=Le.endsWith(".pdf"),Fe=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),ot=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);mt||Fe?J=`${T.length>0?"\u2714":"\u2718"} ${T?`Analyzed: ${te.basename(T)}`:"Analyzed: File Not Found"}`:ot?J=`${T.length>0?"\u2714":"\u2718"} ${T?`Processed: ${te.basename(T)}`:"Processed: File Not Found"}`:J=`${Ke!=="..."?"\u2714":"\u2718"} Read: ${T?`${te.basename(T)} \u2192 ${Ke!=="..."?`Lines ${ae} - ${Xe} of ${Ke}`:"File Not Found"}`:"File Not Found"}`}}else if(y==="list_files"||y==="read_folder"){let T=y==="list_files"?"List":"Browsed",j=re(F.args).path||null,ie=re(F.args).recurse||1;J=`${j?"\u2714":"\u2718"} ${T}: ${j?`${j==="."?`./${ie>1?"*":""}`:`${j.replaceAll("\\","/")}${ie>1?`${j.endsWith("/")?"*":"/*"}`:`${j.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(y==="write_file"||y==="update_file"){let T=y==="write_file"?"Created":"Edited",j=re(F.args),ie=j.path||null,be=Object.entries(j).some(([Ue,De])=>Ue.startsWith("searchContent")&&typeof De=="string"&&De.startsWith("^LINE:"))?"\u1361":":";J=`${ie?"\u2714":"\u2718"} ${T}${be} ${ie?ie.replaceAll("\\","/"):"No File Changes"}`}else if(y==="write_pdf"){let T=re(F.args).path||null;J=`${T?"\u2714":"\u2718"} Generated: ${T.replaceAll("\\","/")||"No PDF Generated"}`}else if(y==="write_docx"){let T=re(F.args).path||null;J=`${T?"\u2714":"\u2718"} Generated: ${T.replaceAll("\\","/")||"No Docx Generated"}`}else if(y==="file_map"){let T=re(F.args).path;J=`${T?"\u2714":"\u2718"} Indexed: ${T.replaceAll("\\","/")?""+T:"File Not Found"}`}else if(y.toLowerCase()==="search_keyword"||y.toLowerCase()==="todo")J="";else if(y.toLowerCase()==="generate_image"){let{path:T,outputPath:j,output:ie}=re(F.args);J=`\u2714 Generated: ${T||j||ie||"generated_image.png"}`}else if(y==="invoke_sync"||y==="InvokeSync"){let T=Vn(y,F.args);J=`\u2714 Called Generalist${T?`: ${T}`:""}`}else if(y==="Invoke"||y==="InvokeAsync"||y==="invoke"){let T=Vn(y,F.args);J=`\u2714 Started Generalist${T?`: ${T}`:""}`}else if(y==="get_progress"||y==="GetProgress"){let T=Vn(y,F.args);J=`\u2714 Checked${T?`: ${T}`:""}`}else if(y==="cancel"){let T=Vn(y,F.args);J=`\u{1F6C7} Cancelled${T?`: ${T}`:""}`}else if(y==="steer"||y==="Steer"){let T=Vn(y,F.args);J=`\u2714 Steered${T?`: ${T}`:""}`}else if(y==="EmergencyRollback"){let{method:T}=re(F.args);J=T==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(y==="await"||y==="Await"){let{time:T,timeout:j}=re(F.args),ie=parseFloat(j||T)||0;ie||(ie=120);let ge=De=>{if(De>=60){let Ce=Math.floor(De/60),z=De%60;return`${Ce}m${z>0?` ${z}s`:""}`}return`${De}s`},be=["Aligning Moon Phase","Contemplating Existence","Staring At Void","Delaying Professionally","Negotiating With Electrons","Touching Grass (virtually)","Panicking Softly","Rethinking Career Choices","Loading Cat Videos","Summoning Braincell #2","Pretending To Be Busy","Waiting For Motivation DLC","Rotating Internal Screaming","Downloading More RAM","Feeding The Hamsters","Gaslighting Scheduler","Performing Dramatic Pause","Buffering Social Energy","Calculating Regret","Reading Terms And Conditions","Becoming Sentient Briefly","Contacting Ancestors"];J=`\u2714 ${be[Math.floor(Math.random()*be.length)]} \u2192 ${ge(ie)}`}else y==="Answer"||y==="answer"?J="\u2714 Resolved Sub-Agent Query":y==="exec_command"||y==="ask"?J="":J=`Executed: ${F.toolName}`;if(yield*Nn(),y==="exec_command"){let{command:T}=re(F.args);if(T&&n.systemSettings&&n.systemSettings.allowExternalAccess===!1){let j=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ie=te.resolve(process.cwd()).substring(0,3).toLowerCase(),ge=z=>{let ae=[],de="",Ke=null;for(let Xe=0;Xe<z.length;Xe++){let he=z[Xe];Ke?(he===Ke&&(Ke=null),de+=he):he==='"'||he==="'"?(Ke=he,de+=he):he==="&"&&z[Xe+1]==="&"||he==="|"&&z[Xe+1]==="|"?(de.trim()&&(ae.push(de.trim()),de=""),Xe++):he===";"||he==="|"||he==="&"?de.trim()&&(ae.push(de.trim()),de=""):de+=he}return de.trim()&&ae.push(de.trim()),ae},be=z=>{let ae=[],de="",Ke=null;for(let Xe=0;Xe<z.length;Xe++){let he=z[Xe];Ke?(he===Ke&&(Ke=null),de+=he):he==='"'||he==="'"?(Ke=he,de+=he):/\s/.test(he)?de&&(ae.push(de),de=""):de+=he}return de&&ae.push(de),ae},Ue=z=>{let ae=z.replace(/^['"]|['"]$/g,"").trim();return!ae||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(ae)?!1:j.some(de=>{if(de.source==="[a-zA-Z]:[\\\\\\/]"){let Ke=ae.match(/[a-zA-Z]:[\\\/]/i);return Ke&&Ke[0].toLowerCase()!==ie}return de.test(ae)})};if(ge(T).some(z=>{let ae=be(z);if(ae.length===0)return!1;let de=ae[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(de)){let Xe=!1;return ae.some(he=>{let Tt=he.replace(/^['"]|['"]$/g,"");if(Tt===">"||Tt===">>"||Tt==="<")return Xe=!0,!1;if(Tt.startsWith(">")||Tt.startsWith("<")){let Le=Tt.replace(/^[><]+/,"");return Ue(Le)}return Xe?(Xe=!1,Ue(he)):!1})}return ae.some(Xe=>Ue(Xe))})){let z='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';n.onExecStart&&n.onExecStart(T||"No Command"),yield{type:"exec_start"},await new Promise(ae=>setTimeout(ae,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${z}`),await new Promise(ae=>setTimeout(ae,50)),n.onExecEnd&&n.onExecEnd(),ve.push({role:"user",text:`[TOOL RESULT]: ERROR: ${z}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${z}`},ut++;continue}}n.onExecStart&&n.onExecStart(T||"No Command"),yield{type:"exec_start"}}let $t=re(F.args),Bn=$t.path||$t.targetPath||null;if(Bn){let T=n.systemSettings&&n.systemSettings.allowExternalAccess===!1,j=te.resolve(Bn),ie=te.resolve(process.cwd());if(T&&!j.startsWith(ie)){let ge="Access Denied. You are not allowed to access files outside the current workspace.";if(y==="write_file"||y==="update_file"){let Ue=`\u2718 ${y==="write_file"?"Write Canceled":"Edit Canceled"}: ${$t.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Ce=Math.min(Ue.length+4,De),z=`${Ue.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
763
762
|
`:""}${z}
|
|
764
|
-
`)},ze=!1}
|
|
763
|
+
`)},ze=!1}ve.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ge}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ge}`},ut++;continue}}if(n.onToolApproval&&(y==="write_file"||y==="update_file"||y==="exec_command")){let j=n.systemSettings||{},ie=j.autoExec,ge=null,be=!1,Ue=!1,De=!1;if(y==="exec_command"){let{command:Le}=re(F.args),mt=(Le||"").trim(),Fe=(Gt,xt)=>{if(!xt)return!1;let nn=xt.split(",").map(jt=>jt.trim().toLowerCase()).filter(Boolean),at=Gt.toLowerCase();return nn.some(jt=>at.startsWith(jt))},ot=Fe(mt,j.alwaysAskCommands),Se=Fe(mt,j.autoApproveCommands);if(Ue=Fe(mt,j.autoDisallowCommands),ot?be=!0:(Se||j.autoApproveGit&&/^git\s+commit\b/i.test(mt))&&(ge="allow"),!be&&!ge){if(j.networkAccess===!1){let xt=mt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),at=xt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),jt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),lt=!1;jt.has(at)&&(lt=!0);let st=vn=>xt.slice(1).some(yn=>vn.includes(yn)),ct=vn=>{let yn=xt.findIndex(xn=>vn.includes(xn)),Un=xt.findIndex(xn=>["run","exec","test"].includes(xn));return yn!==-1&&!(Un!==-1&&Un<yn)};at==="git"&&st(["clone","pull","push","fetch"])&&(lt=!0),at==="go"&&st(["get","install"])&&(lt=!0),at==="npm"&&ct(["install","i","update","add"])&&(lt=!0),at==="yarn"&&ct(["add","install","upgrade"])&&(lt=!0),at==="pnpm"&&ct(["add","install","update"])&&(lt=!0),at==="bun"&&ct(["add","install","update"])&&(lt=!0),at==="deno"&&st(["install","add"])&&(lt=!0),at==="pip"&&st(["install","download"])&&(lt=!0),at==="pip3"&&st(["install","download"])&&(lt=!0),at==="cargo"&&st(["install","add"])&&(lt=!0),["bash","sh","zsh","fish"].includes(at)&&st(["-c"])&&(lt=!0),at==="cmd"&&st(["/c"])&&(lt=!0),lt&&(ge="deny",De=!0)}!ge&&Ue&&(ge="deny")}!be&&!ge&&ie&&(ge="allow")}else ie&&(ge="allow");let Ce=ge,z="";ge==="deny"&&(De?z="network":Ue?z="settings":z="prohibited");let ae=!1,de="",Ke=[],Xe=0,he=!1,Tt="";if(!Ce){if(y==="write_file"||y==="update_file")try{let Fe=re(F.args),{path:ot}=Fe;if(ot){let Se=te.resolve(process.cwd(),ot),Gt=st=>st?st.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ct=>ct.toUpperCase()):"",xt=Gt(Se),nn="",at=!1,jt=await Hn(),lt=Gt(jt?.file_focused);if(jt&<===xt&&jt.full_content?(nn=jt.full_content,at=!0):Ge.existsSync(Se)&&(nn=Ge.readFileSync(Se,"utf8"),at=!0),de=nn,await Oo.recordFileChange(Se,nn),at){let st=nn;if(y==="write_file"){let ct=Fe.content||Fe.newContent||"";st=ct.endsWith(`
|
|
765
764
|
`)?ct:ct+`
|
|
766
|
-
`,Tt=st}else{let{patchPairs:ct,allowMultiple:
|
|
765
|
+
`,Tt=st}else{let{patchPairs:ct,allowMultiple:vn,error:yn}=Ti(Fe);if(yn){let Qt=`[TOOL RESULT]: ERROR: ${yn}`;ve.push({role:"user",text:Qt}),await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:Qt,toolName:y},ut++;continue}let Un=Fe.allowMultiple!==void 0?Fe.allowMultiple===!0||String(Fe.allowMultiple).toLowerCase()==="true":vn;Xe=ct.length;let xn=Si(nn,ct,{allowMultiple:Un});st=xn.content,Tt=st,Ke=xn.results;let Eo=Ke.filter(Qt=>Qt.success),ys=Ke.filter(Qt=>!Qt.success);if(Eo.length===0){let Qt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${te.basename(Se)}].
|
|
767
766
|
${ys.map(Co=>` \u2022 ${Co.error}`).join(`
|
|
768
767
|
`)}`,so=`\u2714 Edited: ${te.basename(Se.replaceAll("\\","/"))}`,dt=115;process.stdout.isTTY&&(dt=process.stdout.columns-5||120);let Vt=Math.min(so.length+4,dt),io=`${so.padEnd(Vt-2).substring(0,Vt-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
769
|
-
`:""}${io}`)},ze=!1,
|
|
768
|
+
`:""}${io}`)},ze=!1,ve.push({role:"user",text:Qt}),await Et("toolFailure"),n.onToolResult&&n.onToolResult("failure",y),yield{type:"tool_result",content:Qt,toolName:y},ut++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${te.basename(Se)}`},qs(Se,nn,st),ae=!0,await new Promise(ct=>setTimeout(ct,50))}else if(y==="write_file"){let st=Fe.content||Fe.newContent||"",ct=st.endsWith(`
|
|
770
769
|
`)?st:st+`
|
|
771
|
-
`;Tt=ct,Ge.existsSync(Se)||(he=!0,Ge.mkdirSync(te.dirname(Se),{recursive:!0}),Ge.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${te.basename(Se)}`},qs(Se,"",ct),ae=!0,await new Promise(
|
|
770
|
+
`;Tt=ct,Ge.existsSync(Se)||(he=!0,Ge.mkdirSync(te.dirname(Se),{recursive:!0}),Ge.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${te.basename(Se)}`},qs(Se,"",ct),ae=!0,await new Promise(vn=>setTimeout(vn,50))}}}catch(Fe){console.error("Simulation/Diff Error:",Fe)}let Le=null;Ys(Fe=>{Le=Fe});let mt=n.onToolApproval;if(Ce=await new Promise(async Fe=>{let ot=setInterval(()=>{Le&&(rs.onIDEApproval&&rs.onIDEApproval(Le),clearInterval(ot),Fe(Le))},100);try{let Se=await mt(y,F.args);clearInterval(ot),Fe(Se)}catch{clearInterval(ot),Fe("deny")}}),Ys(null),y==="write_file"||y==="update_file"){let{path:Fe}=re(F.args);if(Fe){let ot=te.resolve(process.cwd(),Fe);if(Fr(ot,Ce),Ce==="deny"&&he&&Ge.existsSync(ot))try{Ge.unlinkSync(ot)}catch{}}}Ce==="deny"&&(z="user")}if(Ce==="allow"&&ae&&qo()){let{path:Le}=re(F.args),mt=te.resolve(process.cwd(),Le),Fe=dt=>dt?te.resolve(dt).replace(/\\/g,"/").toLowerCase():"",ot=await Hn(),Se="";if(ot&&ot.file_focused&&Fe(ot.file_focused)===Fe(mt)&&ot.full_content&&(Se=ot.full_content),!Se&&Ge.existsSync(mt)){let dt=Ge.readFileSync(mt,"utf8");dt&&(Se=dt)}!Se&&Tt&&(Se=Tt),(Se||he)&&Ge.writeFileSync(mt,Se,"utf8");let Gt=Se.split(/\r?\n/),xt=Gt.length,nn=Buffer.byteLength(Se,"utf8"),at="";de&&(at=`Old File contents:
|
|
772
771
|
${de.split(/\r?\n/).map((Vt,io)=>`${io+1} | ${Vt}`).join(`
|
|
773
772
|
`)}
|
|
774
773
|
|
|
@@ -797,11 +796,11 @@ ${bs}`}lt=`SUCCESS: File [${Le}] saved via IDE Companion (May have user edits).
|
|
|
797
796
|
${Co}- Content Preview:
|
|
798
797
|
|
|
799
798
|
${xs}`}let st=y==="write_file"?"Created":"Edited",ct=re(F.args),yn=Object.entries(ct).some(([dt,Vt])=>dt.startsWith("searchContent")&&typeof Vt=="string"&&Vt.startsWith("^LINE:"))?"\u1361":":",Un=`${Le?"\u2714":"\u2718"} ${st}${yn} ${Le?Le.replaceAll("\\","/"):"No File Changes"}`,xn=115;process.stdout.isTTY&&(xn=process.stdout.columns-5||120);let Eo=Math.min(Un.length+4,xn),ys=`${Un.padEnd(Eo-2).substring(0,Eo-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
800
|
-
`:""}${ys}`)},ze=!1;let Qt=Date.now();je=Qt,yield{type:"tool_time",content:Qt-Z};let so=`[TOOL RESULT]: ${lt}`;
|
|
799
|
+
`:""}${ys}`)},ze=!1;let Qt=Date.now();je=Qt,yield{type:"tool_time",content:Qt-Z};let so=`[TOOL RESULT]: ${lt}`;ve.push({role:"user",text:so}),_n=!0,await Et("toolSuccess"),n.onToolResult&&n.onToolResult("success",y),yield{type:"tool_result",content:lt,aiContent:so,toolName:y},ut++;continue}if(Ce==="deny"){let Le=`Permission Denied: Prohibited ${y==="exec_command"?"Command":"file edit"}.`;if(z==="user"?Le="Permission Denied by User":z==="settings"?Le="Permission Denied by User Policy":z==="network"?Le="Permission Denied: Sandbox Network Access Disabled by User Policy.":z==="prohibited"&&y==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),y==="write_file"||y==="update_file"){let Fe=`\u2718 ${y==="write_file"?"Write Cancelled":"Edit Denied"}: ${re(F.args).path.replaceAll("\\","/")||"..."}`,ot=115;process.stdout.isTTY&&(ot=process.stdout.columns-5||120);let Se=Math.min(Fe.length+4,ot),Gt=`${Fe.padEnd(Se-2).substring(0,Se-2)}`,xt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
801
800
|
`:""}${Gt}
|
|
802
|
-
`)},ze=!1}y==="exec_command"&&(await new Promise(mt=>setTimeout(mt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Le}`),await new Promise(mt=>setTimeout(mt,50)),n.onExecEnd&&n.onExecEnd()),
|
|
801
|
+
`)},ze=!1}y==="exec_command"&&(await new Promise(mt=>setTimeout(mt,50)),n.onExecChunk&&n.onExecChunk(`ERROR: ${Le}`),await new Promise(mt=>setTimeout(mt,50)),n.onExecEnd&&n.onExecEnd()),ve.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await Et("toolDenied"),n.onToolResult&&n.onToolResult("denied",y),ut++;continue}}if(J){let T=115;process.stdout.isTTY&&(T=process.stdout.columns-5||120);let j=await s(),ie=!1;j&&(ie=j.trim().length>0);let ge=Math.min(J.length+4,T),be=`${J.padEnd(ge-2).substring(0,ge-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
803
802
|
`:""}${be}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`${ie?"":`
|
|
804
|
-
`}`}`)},ze=!1}if(je>0){let T=Date.now()-je,j=Math.max(0,1e3-T);j>0&&await new Promise(ie=>setTimeout(ie,j))}let
|
|
803
|
+
`}`}`)},ze=!1}if(je>0){let T=Date.now()-je,j=Math.max(0,1e3-T);j>0&&await new Promise(ie=>setTimeout(ie,j))}let Rn={chatId:h,history:t,onChunk:T=>n.onExecChunk?n.onExecChunk(T):null,onAskUser:n.onAskUser,systemSettings:n.systemSettings,mode:a,isMultiModal:ft(Te),onVisualFeedback:n.onVisualFeedback,onSubagentUpdate:n.onSubagentUpdate,onTokenChunk:n.onTokenChunk,modelName:Te,aiProvider:n.aiProvider,apiKey:n.apiKey,onUsage:n.onUsage};if(y==="write_file"||y==="update_file")try{let{path:T}=re(F.args);if(T){let j=te.resolve(process.cwd(),T),ie=await Hn();ie&&ie.file_focused===j&&ie.full_content&&(Rn.forcedContent=ie.full_content)}}catch{}Ze.push(y);let $e=await yo(y,F.args,Rn);if((y==="write_file"||y==="update_file")&&$e.startsWith("SUCCESS")){let{path:T}=re(F.args);if(T){let j=te.resolve(process.cwd(),T);Nr(j)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Nt=Date.now();je=Nt,yield{type:"tool_time",content:Nt-Z},G=Nt;let Ht=null;if(typeof $e=="object"&&$e.binaryPart&&(Ht=$e.binaryPart,$e=$e.text),y==="search_keyword"){let{keyword:T,path:j}=re(F.args),ie=typeof $e=="string"&&$e.startsWith("[GLOB]");ie&&($e=$e.slice(6).trimStart());let ge=typeof $e=="string"&&$e.startsWith("[DIR]");ge&&($e=$e.slice(5).trimStart());let be=0;if($e){let he=$e.match(/Found (\d+) match/i);he&&(be=parseInt(he[1]))}let Ue=(j||"").trim().toLowerCase().replaceAll("\\","/"),De=Ue==="#doc"||Ue==="#docs"||Ue==="#documentation"||Ue.includes("#skill/global/fluxflow")||Ue.includes("#skill/fluxflow")||Ue.includes("#skills/fluxflow")||Ue.includes("#skills/global/fluxflow"),Ce,z=115;process.stdout.isTTY&&(z=process.stdout.columns-5||120);let ae=Math.max(10,(z+5)/3),de=Math.max(10,(z+5)/4);if(De)Ce=`${T?"\u2714":"\u2718"} Searched Documentation`;else{let he=j?j.replace(/[\/\\]+$/,""):null,Tt=he&&he!=="."?`"${ie?j:ge?`${he}/*`:he}"`:"./",Le=Tt.length>de?`${Tt.slice(0,de)}...`:Tt;Ce=`${T?"\u2714":"\u2718"} Searched: "${T?T.length>z/2?`${T.slice(0,ae)}...`:T:""}" in ${Le.replaceAll("\\","/")} \u2192 ${be} Match${be===1?"":"es"}`}let Ke=Math.min(Ce.length+4,z),Xe=`${Ce.padEnd(Ke-2).substring(0,Ke-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
805
804
|
`:""}${Xe}
|
|
806
805
|
`)},ze=!1}if(y==="EmergencyRollback"){let{method:T}=re(F.args);if(T==="forceRevert"){let j=0;if($e){let ae=$e.match(/Total\s*:\s*(\d+)/i);ae&&(j=parseInt(ae[1]))}let ge=$e&&$e.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${j} file${j===1?"":"s"} processed`,be=115;process.stdout.isTTY&&(be=process.stdout.columns-5||120);let Ue=await s(),De=!1;Ue&&(De=Ue.trim().length>0);let Ce=Math.min(ge.length+4,be),z=`${ge.padEnd(Ce-2).substring(0,Ce-2)}`;yield{type:"visual_feedback",content:Yt(`${ze?`
|
|
807
806
|
`:""}${z}${De?"":`
|
|
@@ -816,9 +815,9 @@ ${xs}`}let st=y==="write_file"?"Created":"Edited",ct=re(F.args),yn=Object.entrie
|
|
|
816
815
|
`));let pn;if(Ft.startsWith("[[SAME]]")){let j=Ft.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ie=j.filter(be=>be.startsWith("SUCCESS:")||be.trim().startsWith("- Stats:"));pn=`[TOOL RESULT]: ${ie.length>0?ie.join(`
|
|
817
816
|
`):j.slice(0,2).join(`
|
|
818
817
|
`)}
|
|
819
|
-
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else pn=`[TOOL RESULT]: ${Ft}`;
|
|
818
|
+
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else pn=`[TOOL RESULT]: ${Ft}`;ve.push({role:"user",text:pn,binaryPart:Ht}),_n=!0;let Ne=`[TOOL RESULT]: ${$e.replaceAll(`[[VERIFIED]]
|
|
820
819
|
`,"").replaceAll(`
|
|
821
|
-
[[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Ne=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ne,aiContent:pn,binaryPart:Ht,toolName:y},y==="memory"&&$e.includes("SUCCESS")&&(yield{type:"memory_updated"}),ut++}if(i==="Google"&&cn&&Date.now()-hs>=150){yield*Nn();let F=no(cn);for(let Z of F)yield Z;cn="",hs=Date.now()}}D.usageMetadata&&(en=D.usageMetadata),en&&(yield{type:"liveTokens",content:en.totalTokenCount})}if(me&&(me=!1,Dt?et+="</think>":(we+="</think>",i==="Google"?cn+="</think>":yield{type:"text",content:"</think>"})),Dt&&et.length>0){let D=0,Y=Math.min(yt.length,et.length);for(let V=Y;V>0;V--)if(yt.endsWith(et.substring(0,V))){D=V;break}let N=et.substring(D);if(N){let X=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(X)if(we+=X,i==="Google")cn+=X;else{yield*Nn();let ce=no(X);for(let se of ce)yield se}}Dt=!1,et=""}if(yield*Nn(),bt)break;let oo=(we||"").trim(),aa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(oo.toLowerCase())||/\[\[END\]\]/i.test(oo.toLowerCase()),la=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(oo.toLowerCase()),ca=
|
|
820
|
+
[[/VERIFIED]]`,"")||""}`;(y==="view_file"||y==="web_scrape"||y==="file_map")&&(Ne=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ne,aiContent:pn,binaryPart:Ht,toolName:y},y==="memory"&&$e.includes("SUCCESS")&&(yield{type:"memory_updated"}),ut++}if(i==="Google"&&cn&&Date.now()-hs>=150){yield*Nn();let F=no(cn);for(let Z of F)yield Z;cn="",hs=Date.now()}}D.usageMetadata&&(en=D.usageMetadata),en&&(yield{type:"liveTokens",content:en.totalTokenCount})}if(me&&(me=!1,Dt?et+="</think>":(we+="</think>",i==="Google"?cn+="</think>":yield{type:"text",content:"</think>"})),Dt&&et.length>0){let D=0,Y=Math.min(yt.length,et.length);for(let V=Y;V>0;V--)if(yt.endsWith(et.substring(0,V))){D=V;break}let N=et.substring(D);if(N){let X=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):N.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(X)if(we+=X,i==="Google")cn+=X;else{yield*Nn();let ce=no(X);for(let se of ce)yield se}}Dt=!1,et=""}if(yield*Nn(),bt)break;let oo=(we||"").trim(),aa=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(oo.toLowerCase())||/\[\[END\]\]/i.test(oo.toLowerCase()),la=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(oo.toLowerCase()),ca=ve.length>0||qe!==null,ms=qt(oo).trim(),da=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ms),fa=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ms.trim()),ua=/[.!?}"'`’“”]$|```$/s.test(ms)||fa||da;!aa&&!la&&!ca&&oo.length>0,it=!0,await Et("agent",i)}catch(_e){if(bt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
822
821
|
|
|
823
822
|
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(_e).includes("Incomplete JSON segment at the end")){me&&(me=!1,Dt?et+="</think>":(we+="</think>",yield{type:"text",content:"</think>"})),it=!0,await Et("agent",i);break}if(me&&(me=!1,Dt?et+="</think>":we+="</think>"),Dt&&et.length>0){let Pt=0,_t=Math.min(yt.length,et.length);for(let It=_t;It>0;It--)if(yt.endsWith(et.substring(0,It))){Pt=It;break}let kt=et.substring(Pt);if(kt){let gt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(yt)?kt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):kt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");gt&&(we+=gt)}Dt=!1,et=""}let ee=_e instanceof Error?(()=>{try{return JSON.parse(JSON.parse(_e.message).error.message).error.message}catch{return String(_e)}})():String(_e),Lt=new Date().toLocaleString(),Mt=te.join(Mn,"agent");Ge.existsSync(Mt)||Ge.mkdirSync(Mt,{recursive:!0}),Ge.appendFileSync(te.join(Mt,"error.log"),`ERROR [${Lt}]: ${ee}
|
|
824
823
|
|
|
@@ -829,11 +828,11 @@ ${xs}`}let st=y==="write_file"?"Created":"Edited",ct=re(F.args),yn=Object.entrie
|
|
|
829
828
|
- no repetition: do not repeat any text already written
|
|
830
829
|
- no re-think: do not restart or open <think> if reasoning already started. continue the thinking and close thinking block </think> before chat output
|
|
831
830
|
- mid-tool safety: if cutoff was mid-tool call, restart that tool call from start
|
|
832
|
-
- stealth: do not mention/apologize for cutoff [/system]`;
|
|
831
|
+
- stealth: do not mention/apologize for cutoff [/system]`;ve.length>0?ve.forEach((kt,It)=>{It===ve.length-1?r.push({...kt,text:`${kt.text}
|
|
833
832
|
|
|
834
833
|
${_t}`}):r.push(kt)}):r.push({role:"user",text:_t}),yt+=we}for(let _t=Pt/1e3;_t>0&&!bt;_t--)yield{type:"status",content:`Error Occured. Recovering Stream (${rt}/${rn}) [Retrying in ${_t.toFixed(0)}s]...`},await new Promise(kt=>setTimeout(kt,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${rn} times)
|
|
835
834
|
Error log can be found in \`/export logs\``);else if(nt<=rn){nt++,rt=1,yt="";let Pt=Math.min(1e3*Math.pow(2,nt-1),32e3),_t=.8+Math.random()*.4,kt=Math.round(Pt*_t);eo=!0,yield{type:"status",content:`Trying to reach ${e} (${nt}/${rn}) [Retrying in ${(kt/1e3).toFixed(0)}s]`};for(let It=kt/1e3;It>0&&!bt;It--)yield{type:"status",content:`Trying to reach ${e} (${nt}/${rn}) [Retrying in ${It.toFixed(0)}s]`},await new Promise(gt=>setTimeout(gt,1e3));yield{type:"status",content:`Trying to reach ${e}`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${rn} times)
|
|
836
|
-
Error log can be found in \`/export logs\``)}}if(en){let me=en.totalTokenCount||0,_e=en.cachedContentTokenCount||0,ee=(en.candidatesTokenCount||0)+(i==="Google"&&en.thoughtsTokenCount||0);await Bt("tokens",me,i,Te),_e>0&&await Bt("cachedTokens",_e,i,Te),ee>0&&await Bt("candidateTokens",ee,i,Te),Do({provider:i,model:Te,prompt:en.promptTokenCount||0,cached:_e,output:ee,reasoning:en.thoughtsTokenCount||0}),yield{type:"usage",content:en}}we=Jr(we),gs.push(we);let En=qt(we),Pn=Kr(we),hn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,rl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),al=ut>0;yield{type:"status",content:"Thinking"};let oa=el(we,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(hn||
|
|
835
|
+
Error log can be found in \`/export logs\``)}}if(en){let me=en.totalTokenCount||0,_e=en.cachedContentTokenCount||0,ee=(en.candidatesTokenCount||0)+(i==="Google"&&en.thoughtsTokenCount||0);await Bt("tokens",me,i,Te),_e>0&&await Bt("cachedTokens",_e,i,Te),ee>0&&await Bt("candidateTokens",ee,i,Te),Do({provider:i,model:Te,prompt:en.promptTokenCount||0,cached:_e,output:ee,reasoning:en.thoughtsTokenCount||0}),yield{type:"usage",content:en}}we=Jr(we),gs.push(we);let En=qt(we),Pn=Kr(we),hn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(Pn.toLowerCase())||/\[\[END\]\]/i.test(Pn.toLowerCase())||!0,rl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(Pn.toLowerCase()),al=ut>0;yield{type:"status",content:"Thinking"};let oa=el(we,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),$n=(hn||ve.length===0)&&!vt&&!ln&&!An;if($n=ve.length===0?$n:!1,$n=Ot||_o?!1:$n,we&&we.trim().endsWith('")]')&&ve.length===0&&($n=!1),$n){pi=!0;let me=gs.join(`
|
|
837
836
|
`),_e=qt(me).trim();yield{type:"interactive_turn_finished",data:{agentText:d,fullAgentTextRaw:me,history:[...r],needTitle:k}},r.length>0&&r[r.length-1].role==="agent"?r[r.length-1].text=_e:r.push({role:"agent",text:_e}),r.forEach(ee=>{if(ee.role==="user"&&ee.text&&(ee.text=ee.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ee.text=ee.text.replaceAll(`
|
|
838
837
|
|
|
839
838
|
[system] user question. resolve this specific query within '[ANSWER] ... [/ANSWER]' concisely, naturally [/system]
|
|
@@ -842,15 +841,15 @@ Error log can be found in \`/export logs\``)}}if(en){let me=en.totalTokenCount||
|
|
|
842
841
|
`,"").replaceAll(`[system] **strictly follow thinking policy as high priority. do not start a response without <think>...</think>** [/system]
|
|
843
842
|
`,"").replaceAll(/\n\[system\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/system\]/g,""),ee.text=ee.text.replaceAll(/\n\[system\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/system\]/g,""),(i==="Mistral"||i==="Google"&&e?.toLowerCase().startsWith("gemma"))&&ee.text.startsWith("[TOOL RESULT]"))){let Mt=`
|
|
844
843
|
[system] Tool result received. Analyze output and proceed with your turn [/system]`,St=`
|
|
845
|
-
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ee.text=ee.text.replaceAll(St,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if($n)break;let sa=oa.trim()||"*Working...*";if(r.push({role:"agent",text:sa}),
|
|
844
|
+
[system] Tool result received. Analyze output and proceed with your turn. **strictly follow thinking policy. do not start a response without <think>...</think>** [/system]`;ee.text=ee.text.replaceAll(St,"").replaceAll(Mt,"").trim()}}),yield{type:"status",content:"[end]"}}if($n)break;let sa=oa.trim()||"*Working...*";if(r.push({role:"agent",text:sa}),ve.length>0||_n){if(ve.length>0){let me=ve.map(Xt=>Xt.text).join(`
|
|
846
845
|
|
|
847
|
-
`),Lt=(qt(we).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Mt=
|
|
846
|
+
`),Lt=(qt(we).replace(/\[{1,2}tool:[\s\S]*?\)\s*\]{1,2}/gi,"").match(/\[tool:/gi)||[]).length,Mt=ve.length+Lt;if(ve.length<Mt){me+=`
|
|
848
847
|
|
|
849
|
-
[system] Only ${
|
|
848
|
+
[system] Only ${ve.length} out of ${Mt} attempted tool calls were executed. Verify proper structure compliance & try failed calls again [/system]`;let Xt=Mt-ve.length;for(let Ye=0;Ye<Xt;Ye++)await Et("toolFailure")}let St=ve.find(Xt=>Xt.binaryPart)?.binaryPart||null;r.push({role:"user",text:me,binaryPart:St})}}else if(!bt){let _e=(we.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/i,"").match(/\[tool:/gi)||[]).length;_o||Ot||_e>0?(r.push({role:"user",text:`[system] Failed to execute ${_e} tool${_e>1?"s":""}. Verify proper structure compliance & try again [/system]`}),await Et("toolFailure"),yield{type:"visual_feedback",content:`
|
|
850
849
|
${Yt("\u2718 Execution Error")}
|
|
851
850
|
`}):(yield{type:"visual_feedback",content:`
|
|
852
851
|
${Yt("\u2718 Loop Detected")}
|
|
853
|
-
`},r.push({role:"user",text:`[system] ${ln&&!
|
|
852
|
+
`},r.push({role:"user",text:`[system] ${ln&&!vt?"Stuttering Detected by Internal System. Re-calibrate your response & proceed.":`${vt?" Over Thinking":" Loop"} Detected by Internal System${vt?" for current Effort Level":""}. ${vt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/system]`})),vt=!1,ln=!1,An=!1}m?.advanceRollback&&await ao.recordTurnDelta(h,H+1,Ze),_o=ut>0||_n}if(!pi&&!bt){let H="\u2726 Turn safety limit reached. Stopping execution.";yield{type:"text",content:`
|
|
854
853
|
|
|
855
854
|
${H}
|
|
856
855
|
`};let Pe=(gs.join(`
|
|
@@ -864,15 +863,14 @@ CAUSE: ${f.cause?.stack||f.cause}`:""}
|
|
|
864
863
|
----------------------------------------------------------------------
|
|
865
864
|
|
|
866
865
|
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${I}`}}finally{C&&(clearInterval(C),C=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await Oo.commitTransaction(),m?.advanceRollback&&await ao.cleanup(h),await Hn()}yield{type:"status",content:null}},xf=async(e,t,n=null,s=null,o=50,l=null,u=!1)=>{let a=await ro(),p={...a,...t},h=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,g=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,m=new Date,b=`${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(":","-")}`,c=(C=>{if(!C)return null;let f=C.toLowerCase();return f==="google"?"Google":f==="deepseek"?"DeepSeek":f==="openrouter"?"OpenRouter":f==="nvidia"?"NVIDIA":f==="mistral"?"Mistral":f==="ollama"?"Ollama":f==="inferx"?"InferX":f==="sensenova"?"SenseNova":f==="poolside"?"Poolside":f==="9router"||f==="9Router"?"9router":f==="aihubmix"||f==="aihub"?"AIHubMix":f==="explabs"||f==="experientiallabs"||f==="experimentallabs"?"ExpLabs":f==="tokenharbor"||f==="token harbor"||f==="token_harbor"||f==="thk"?"TokenHarbor":f==="apinex"||f==="apx"?"APInex":null})(g),w=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentModel:null,M=p?.systemSettings?.CustomSubAgent?p?.systemSettings?.SubAgentProvider:null,x=null;if(w==="ENV"?(x=h,h&&c&&(p.aiProvider=c)):w&&w!=="Default"?(x=w,M&&(p.aiProvider=M)):h&&c&&(p.aiProvider=c),p.aiProvider){let C=await Ts(p.aiProvider);C&&(p.apiKey=C)}let _=C=>{if(!C||typeof C!="string")return{allowed:!0};let f=[/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 r of f)if(r.test(C))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${r.source}"`};return{allowed:!0}},O=n||x||t?.modelName||t?.activeModel||a.activeModel,E=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",S=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
867
|
-
|
|
866
|
+
To use tools in chat output the format [tool:ToolName(arg1="value1")] \u2190 mandatory
|
|
868
867
|
Tool Rules:
|
|
869
|
-
- Mandatorily JSON escape literal sequences
|
|
868
|
+
- Mandatorily JSON escape literal sequences, backslash: \\\\, newLine: \\ n
|
|
870
869
|
- Same file, multiple edits? ONE PatchFile (\u226415 blocks)
|
|
871
870
|
- Need text or huge file? CodeSearch > Full Read
|
|
872
871
|
- Avoid unnecessary large file chunk reads
|
|
873
|
-
- Dont hallucinate tool results
|
|
872
|
+
- Dont hallucinate tool results
|
|
874
873
|
- Stuck on syntax error? Tell user > waste time
|
|
875
|
-
- ONLY valid tools defined below are allowed
|
|
876
874
|
|
|
877
875
|
# Provided Tools
|
|
878
876
|
**Communication Tools**
|
|
@@ -889,7 +887,7 @@ ${u?"- AskMain(question=string). Communicate with PARENT/MAIN AGENT. When clarif
|
|
|
889
887
|
- ReadFile(path=string, startLine?=int, endLine?=int)
|
|
890
888
|
- PatchFile(path=string, allowMultiple?=bool, searchContent1="string match OR ^LINE:start..end$", newContent1=string, ...MAX15). Small searchString. Line Anchors: ^LINE:...$ syntax, must for large blocks & escape sequences
|
|
891
889
|
- WriteFile(path=string, content=string). Creates/Overwrites. File Exist? PatchFile > WriteFile
|
|
892
|
-
- Run(command=string). Runs ${E==="Windows"?Ai()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),
|
|
890
|
+
- Run(command=string). Runs ${E==="Windows"?Ai()?"powershell":"windows CMD":"bash"} command. Destructive command \u2192 Ask user`.trim(),R=`=== START SYSTEM PROMPT ===
|
|
893
891
|
Identity: FluxFlow subagent helping the main Agent
|
|
894
892
|
Your task is: "${e}"
|
|
895
893
|
|
|
@@ -903,9 +901,9 @@ CWD: ${process.cwd()}
|
|
|
903
901
|
${S.trimEnd()}
|
|
904
902
|
|
|
905
903
|
Current Time: ${b}
|
|
906
|
-
=== END SYSTEM PROMPT ===`,P=[{role:"user",text:`Complete this task: ${e}`}],k=0,d="";for(;k<o;){let C=await Ss("subagent",p);if(!C.allowed)throw new Error(C.reason||`Budget Exhausted for Provider (${p?.aiProvider||"Subagent"})`);if(bt){if(t?.taskId&&typeof Kt<"u"){let L=Kt.find(B=>B.id===t.taskId);L&&(L.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let L=Kt.find(B=>B.id===t.taskId);if(L&&L.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let f=P.map(L=>({role:L.role==="user"?"user":"model",parts:[{text:L.text}]}));l&&l(`[Subagent Turn ${k+1}]...`);let r=["Fast","Low","Medium","High"],A=process.env.SUBAGENT_THINKING,I=r.includes(A)?A:"Low",$=(await as(p,O,f,
|
|
907
|
-
${
|
|
908
|
-
`),P.push({role:"agent",text:
|
|
904
|
+
=== END SYSTEM PROMPT ===`,P=[{role:"user",text:`Complete this task: ${e}`}],k=0,d="";for(;k<o;){let C=await Ss("subagent",p);if(!C.allowed)throw new Error(C.reason||`Budget Exhausted for Provider (${p?.aiProvider||"Subagent"})`);if(bt){if(t?.taskId&&typeof Kt<"u"){let L=Kt.find(B=>B.id===t.taskId);L&&(L.status="cancelled")}throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let L=Kt.find(B=>B.id===t.taskId);if(L&&L.status==="cancelled")throw l&&l("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let f=P.map(L=>({role:L.role==="user"?"user":"model",parts:[{text:L.text}]}));l&&l(`[Subagent Turn ${k+1}]...`);let r=["Fast","Low","Medium","High"],A=process.env.SUBAGENT_THINKING,I=r.includes(A)?A:"Low",$=(await as(p,O,f,R,I)).text||"",v=Jr(qt($).trim());d=v,l&&l(`[Subagent Response]
|
|
905
|
+
${v}
|
|
906
|
+
`),P.push({role:"agent",text:v});let ne=ko(v);if(ne.length===0)break;let fe=ne.filter(L=>L.toolName.toLowerCase()==="askmain"||L.toolName.toLowerCase()==="ask_main"),Q=!1,ue="";for(let L of ne){if(bt){if(t?.taskId&&typeof Kt<"u"){let U=Kt.find(K=>K.id===t.taskId);U&&(U.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(t?.taskId&&typeof Kt<"u"){let U=Kt.find(K=>K.id===t.taskId);if(U&&U.status==="cancelled")throw new Error("Subagent task was cancelled.")}let B=L.toolName.toLowerCase();if(B==="askuser"&&(B="ask"),B==="askmain"||B==="ask_main"){if(Q)continue;Q=!0;let U="";if(fe.length===1?U=re(fe[0].args).question||fe[0].args:U=fe.map((K,ye)=>{let Ae=re(K.args);return`Q${ye+1}: ${Ae.question||K.args}`}).join(`
|
|
909
907
|
`),t.onAskMain){l&&l(`[Executing Tool] AskMain("${U}")...`);let K=await t.onAskMain(U);l&&l(`[Tool Result]
|
|
910
908
|
Answer from Main Agent: ${K}
|
|
911
909
|
`),ue+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${K}
|
|
@@ -918,13 +916,13 @@ Answer from Main Agent: ${K}
|
|
|
918
916
|
`;continue}if(B==="exec_command"||B==="execcommand"||B==="run"){let U=re(L.args).command||"",K=_(U);if(!K.allowed){let ye=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${K.reason}`;l&&l(`[Blocked Command] ${U} - ${K.reason}
|
|
919
917
|
`),ue+=`${ye}
|
|
920
918
|
|
|
921
|
-
`;continue}}let q="";if(B==="web_search"||B==="websearch")q=`\u2714 \x1B[95mSearched\x1B[0m: ${re(L.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")q=`\u2714 \x1B[95mScraped\x1B[0m: ${re(L.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let U=re(L.args),K=U.keyword||"",ye=U.path||"";q=`${K?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${K||"No Query"}${ye?` \u2192 ${ye.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")q=`\u2714 \x1B[95mRead\x1B[0m: ${(re(L.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let U=re(L.args).path||null,K=re(L.args).recurse||0;q=`${U?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${U?`${U.replaceAll("\\","/")}${K>0?`${U.endsWith("/")?`*${K}`:`/*${K}`}`:`${U.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let U=re(L.args).path||null;q=`${U?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${U?`${U.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"){let U=re(L.args),K=U.path||null,Ae=Object.entries(U).some(([
|
|
919
|
+
`;continue}}let q="";if(B==="web_search"||B==="websearch")q=`\u2714 \x1B[95mSearched\x1B[0m: ${re(L.args).query||""}`;else if(B==="web_scrape"||B==="webscrape")q=`\u2714 \x1B[95mScraped\x1B[0m: ${re(L.args).url||""}`;else if(B==="search_keyword"||B==="searchkeyword"||B==="codesearch"||B==="code_search"){let U=re(L.args),K=U.keyword||"",ye=U.path||"";q=`${K?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${K||"No Query"}${ye?` \u2192 ${ye.replaceAll("\\","/")}`:""}`}else if(B==="view_file"||B==="viewfile"||B==="readfile")q=`\u2714 \x1B[95mRead\x1B[0m: ${(re(L.args).path||"").replaceAll("\\","/")}`;else if(B==="list_files"||B==="read_folder"||B==="readfolder"){let U=re(L.args).path||null,K=re(L.args).recurse||0;q=`${U?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${U?`${U.replaceAll("\\","/")}${K>0?`${U.endsWith("/")?`*${K}`:`/*${K}`}`:`${U.endsWith("/")?"":"/"}`}`:""}`}else if(B==="write_file"||B==="writefile"){let U=re(L.args).path||null;q=`${U?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${U?`${U.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="update_file"||B==="updatefile"||B==="patchfile"||B==="patch_file"){let U=re(L.args),K=U.path||null,Ae=Object.entries(U).some(([Re,Be])=>Re.startsWith("searchContent")&&typeof Be=="string"&&Be.startsWith("^LINE:"))?"\u1361":":";q=`${K?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m${Ae} ${K?`${K.replaceAll("\\","/")}`:"No File Changes"}`}else if(B==="exec_command"||B==="execcommand"||B==="run"){let U=re(L.args).command||null;q=`${U?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${U?U.slice(0,100)+(U.length>100?"...":""):"No Command"}`}else if(B==="file_map"||B==="filemap"){let U=re(L.args).path||"";q=`${U?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${U?`${U.replaceAll("\\","/")}`:"File Not Found"}`}else if(B==="await"){let{time:U}=re(L.args),K=parseFloat(U)||0;K<10&&(K=10),K>180&&(K=180),q=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(Ae=>{if(Ae>=60){let Re=Math.floor(Ae/60),Be=Ae%60;return`${Re}m${Be>0?` ${Be}s`:""}`}return`${Ae}s`})(K)}`}else{let U=ni[B]||L.toolName,K=Vn(B,L.args);q=`\u2714 \x1B[95m${U}\x1B[0m${K?`: ${K}`:""}`}t.onVisualFeedback&&q&&t.onVisualFeedback(q),l&&l(`[Executing Tool] ${L.toolName}(${L.args})...`);try{let U=await yo(L.toolName,L.args,{...t,mode:"Flux"});if(l&&l(`[Tool Result]
|
|
922
920
|
${U}
|
|
923
921
|
`),ue+=`[TOOL RESULT for ${L.toolName}]: ${U}
|
|
924
922
|
|
|
925
923
|
`,await Et("toolSuccess"),B==="patchfile"||B==="update_file"||B==="updatefile"||B==="patch_file"){if(U){let K=U.split(`
|
|
926
|
-
`),ye=0,Ae=0,
|
|
927
|
-
`)){if(Be.includes("Old File contents:")){
|
|
924
|
+
`),ye=0,Ae=0,Re=!1;for(let Be of K){if(Be.includes("[DIFF_START]")){Re=!0;continue}if(Be.includes("[DIFF_END]")){Re=!1;continue}Re&&(/^\+\d+/.test(Be)?ye++:/^\-\d+/.test(Be)&&Ae++)}(ye>0||Ae>0)&&(await Bt("linesAdded",ye),await Bt("linesRemoved",Ae))}}else if((B==="writefile"||B==="write_file")&&U){let K=U.match(/- Stats: \[(\d+) lines/),ye=K?parseInt(K[1]):0,Ae=0;if(U.includes("Old File contents:")){let Re=!1;for(let Be of U.split(`
|
|
925
|
+
`)){if(Be.includes("Old File contents:")){Re=!0;continue}Re&&(Be.trim()===""?Re=!1:/^\d+ \|/.test(Be)&&Ae++)}}(ye>0||Ae>0)&&(await Bt("linesAdded",ye),await Bt("linesRemoved",Ae))}}catch(U){let K=`ERROR: Execution failed for [${L.toolName}]: ${U.message}`;l&&l(`[Tool Error] ${K}
|
|
928
926
|
`),ue+=`${K}
|
|
929
927
|
|
|
930
928
|
`,await Et("toolFailure")}}let Me="";if(t?.taskId&&typeof Kt<"u"){let L=Kt.find(B=>B.id===t.taskId);if(L&&L.pendingSteerMessages&&L.pendingSteerMessages.length>0){let B=[...L.pendingSteerMessages];L.pendingSteerMessages=[];for(let Oe of B)Me+=`
|