fluxflow-cli 4.8.3 → 4.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{b as pr}from"./chunk-LXTPAZBK.js";import{e as Ot,g as zt,i as Oi,j as Di,k as Li,l as Pi,m as Fi}from"./chunk-S27ZX6SS.js";import{c as Et,d as vo,g as he,h as tn}from"./chunk-4C4RG42K.js";import{a as fr,b as Ii,c as oe,d as me}from"./chunk-SIINYZWE.js";import{a as Rt,c as Ln,d as hn,e as Ts,f as Ao,g as Mo,j as Ft,k as en,l as Pn,m as Kn,n as ln,o as gn,p as co,q as ur,r as Yn,s as uo}from"./chunk-4TZKD2XR.js";import{a as Qe,c as Rs}from"./chunk-56EJGQU3.js";import{c as Ni,d as Ui,e as Yo}from"./chunk-GPHO47JC.js";import Yt from"dotenv";import{GoogleGenAI as pl,ThinkingLevel as pt,HarmBlockThreshold as eo,HarmCategory as to}from"@google/genai";import{execSync as Wi}from"child_process";import{spawn as mr}from"child_process";var L=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let i=t,p=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),m=u.trim(),g=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(g&&u.startsWith(`
1
+ import{b as pr}from"./chunk-LXTPAZBK.js";import{e as Ot,g as zt,i as Oi,j as Di,k as Li,l as Pi,m as Fi}from"./chunk-S27ZX6SS.js";import{c as Et,d as vo,g as ge,h as tn}from"./chunk-4C4RG42K.js";import{a as fr,b as Ii,c as oe,d as he}from"./chunk-SIINYZWE.js";import{a as Rt,c as Ln,d as hn,e as Ts,f as Ao,g as Mo,j as Ft,k as en,l as Pn,m as Kn,n as ln,o as gn,p as co,q as ur,r as Yn,s as uo}from"./chunk-4TZKD2XR.js";import{a as Qe,c as Rs}from"./chunk-56EJGQU3.js";import{c as Ni,d as Ui,e as Yo}from"./chunk-GPHO47JC.js";import Yt from"dotenv";import{GoogleGenAI as pl,ThinkingLevel as pt,HarmBlockThreshold as eo,HarmCategory as to}from"@google/genai";import{execSync as Wi}from"child_process";import{spawn as mr}from"child_process";var L=e=>{let n={};if(!e)return n;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let o=e.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let a=e[t];t++;let i=t,p=-1,d=t;for(;d<e.length;){let l=e.indexOf(a,d);if(l===-1)break;let f=0;for(let y=l-1;y>=0&&e[y]==="\\";y--)f++;if(f%2!==0){d=l+1;continue}let u=e.substring(l+1),m=u.trim(),g=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(g&&u.startsWith(`
2
2
  `)){let y=m.split(`
3
3
  `)[0];if(!y.includes("=")&&!y.includes(")")){d=l+1;continue}}if(g){p=l;break}d=l+1}p!==-1?(r=e.substring(i,p),t=p+1):(r=e.substring(i),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(l,f)=>{switch(f){case"n":return`
4
4
  `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return f===a?a:f}})}else if(t<e.length&&e[t]==="["){let a=0,i=null,p=t,d=-1;for(let c=t;c<e.length;c++){let l=e[c];if(i&&l===i){let f=0;for(let u=c-1;u>=0&&e[u]==="\\";u--)f++;f%2===0&&(i=null)}else!i&&(l==='"'||l==="'"||l==="`")&&(i=l);if(!i&&(l==="["?a++:l==="]"&&a--,a===0)){d=c;break}}if(d!==-1){r=e.substring(p,d+1),t=d+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(p),t=e.length}else{let a=e.substring(t),i=a.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(i){let p=i.index;r=a.substring(0,p).trim(),t+=p}else r=a.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),n[s]=r}return n};var Es=null;try{let e=await import("node-pty");Es=e.default||e}catch{}var Md=!!Es,_s=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),hr=e=>{if(!e)return"";let n=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,a,i=d=>{for(let c=0;c<d.length;c++){let l=d[c];if(l===`
@@ -594,12 +594,12 @@ ${Gi(n,t)}
594
594
  === END SYSTEM PROMPT ===${e?`
595
595
 
596
596
  -- current saved user memories --
597
- ${e}`:""}`.trim();import vt from"fs-extra";import Ms from"path";import{nanoid as Hl}from"nanoid";import mt from"fs-extra";import cn from"path";mt.ensureDirSync(Kn);var yn=null;async function jl(e,n){try{if(e.type==="create")await mt.pathExists(e.filePath)&&(await mt.chmod(e.filePath,438).catch(()=>{}),await mt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=cn.join(Kn,n.chatId,e.backupFile);if(await mt.pathExists(t)){let o=oe(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${cn.basename(e.filePath)}`);let s=Ii(o.data);await mt.pathExists(e.filePath)&&await mt.chmod(e.filePath,438).catch(()=>{}),await mt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${cn.basename(e.filePath)}: ${t.message}`)}}async function Gl(e,n,t=7){let o=0;for(;o<t;)try{return await jl(e,n),!0}catch{if(o++,o>=t)return!1;let r=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,r))}return!1}var Ar=null,ht={async startTransaction(e,n){Ar=e,yn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},me(co,yn)},async recordFileChange(e,n=null){try{if(!yn){if(Ar){let a=oe(ln,[]),i=[...a].reverse().find(p=>p.chatId===Ar);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await mt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=cn.basename(e);l=`${i.id}_${f}.bak`;let u=cn.join(Kn,i.chatId);await mt.ensureDir(u);let m=cn.join(u,l),g=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);g!==null?me(m,{data:fr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),me(ln,a)}}return}if(yn.changes.some(a=>a.filePath===e))return;let s=await mt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=cn.basename(e);r=`${yn.id}_${a}.bak`;let i=cn.join(Kn,yn.chatId);await mt.ensureDir(i);let p=cn.join(i,r),d=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);d!==null?me(p,{data:fr(d)}):(s="create",r=null)}yn.changes.push({filePath:e,type:s,backupFile:r}),me(co,yn)}catch{}},async commitTransaction(){if(yn)try{let e=oe(ln,[]);if(e.push(yn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await mt.remove(cn.join(Kn,n.chatId,t.backupFile)).catch(()=>{})}me(ln,e),await mt.remove(co).catch(()=>{})}catch{}finally{yn=null}},async recoverCrashedTransaction(){try{if(await mt.pathExists(co)){let e=oe(co,null);if(e?.changes?.length>0){let n=oe(ln,[]);n.some(t=>t.id===e.id)||(n.push(e),me(ln,n))}await mt.remove(co).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=oe(ln,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,r=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of r){for(let i of[...a.changes].reverse())await Gl(i,a);for(let i of a.changes)if(i.backupFile){let p=cn.join(Kn,a.chatId,i.backupFile);await mt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),me(ln,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return oe(ln,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await mt.remove(cn.join(Kn,e));let n=oe(ln,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&me(ln,t)}catch{}}};var ba=Promise.resolve(),vs=e=>{let n=ba.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return ba=n.catch(()=>{}),n},fo=async()=>{await vt.ensureDir(Mo);let e={};if(await vt.pathExists(Ao))try{e=oe(Ao,{})}catch{e={}}for(let n in e){let t=Ms.join(Mo,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(vt.existsSync(t))try{return oe(t,[])}catch{return[]}return[]},set:o=>{try{me(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Ku=async(e,n,t)=>vs(async()=>{await vt.ensureDir(Mo);let o=await fo(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await tn()).systemSettings?.preserveThinking===!1&&(r=r.filter(h=>h.role!=="think"))}catch{}let a=y=>{if(!y)return;let h=typeof y=="string"?y:y.text||y.content||"";if(!h||typeof h!="string")return;let x=h.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!x)return;let w=x.split(/\s+/),T;return w.length>7?T=w.slice(0,7).join(" ")+"...":x.length>45?T=x.substring(0,45).trimEnd()+"...":T=x,T},i,p=r.filter(y=>y.role==="user"),d=p[0],c=p[p.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.5&&l?i=l:i=s.prompt:i=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),m=Ms.join(Mo,`${e}.json`);me(m,r),o[e]={name:u,prompt:i||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};me(Ao,g)}),Sa=async(e,n)=>vs(async()=>{let t=await fo();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};me(Ao,o)}),ql=async e=>vs(async()=>{let n=await fo();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(me(Ao,t),await vt.pathExists(Yn))try{let a=oe(Yn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));me(Yn,i)}}catch{}let o=oe(en,{});o[e]&&(delete o[e],me(en,o));let s=oe(Pn,{});s[e]&&(delete s[e],me(Pn,s)),await ht.deleteChatBackups(e);let r=Ms.join(Mo,`${e}.json`);if(await vt.pathExists(r))try{await vt.remove(r)}catch{}return n}),Yu=()=>`flow-${Hl(6)}`,Vu=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await fo(),o=Date.now(),s=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&o-i.updatedAt>s&&(await ql(a),r++)}return r},zl=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],r=o[1]||"",a=o[2]||"",i=s.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),c,l,f;if(i[0]>1e3)c=i[0],l=i[1],f=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(f=i[0],l=i[1]):i[1]>12?(f=i[1],l=i[0]):d?(f=i[0],l=i[1]):(l=i[0],f=i[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,m=0,g=0;if(r){let h=r.split(":").map(Number);u=h[0]||0,m=h[1]||0,g=h[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(c,l-1,f,u,m,g);return isNaN(y.getTime())?null:y.getTime()},Kl=async e=>{try{if(!await vt.pathExists(e))return;let n=await vt.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
597
+ ${e}`:""}`.trim();import vt from"fs-extra";import Ms from"path";import{nanoid as Hl}from"nanoid";import mt from"fs-extra";import cn from"path";mt.ensureDirSync(Kn);var yn=null;async function jl(e,n){try{if(e.type==="create")await mt.pathExists(e.filePath)&&(await mt.chmod(e.filePath,438).catch(()=>{}),await mt.remove(e.filePath));else if(e.type==="update"){if(!e.backupFile)return;let t=cn.join(Kn,n.chatId,e.backupFile);if(await mt.pathExists(t)){let o=oe(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${cn.basename(e.filePath)}`);let s=Ii(o.data);await mt.pathExists(e.filePath)&&await mt.chmod(e.filePath,438).catch(()=>{}),await mt.writeFile(e.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${cn.basename(e.filePath)}: ${t.message}`)}}async function Gl(e,n,t=7){let o=0;for(;o<t;)try{return await jl(e,n),!0}catch{if(o++,o>=t)return!1;let r=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(a=>setTimeout(a,r))}return!1}var Ar=null,ht={async startTransaction(e,n){Ar=e,yn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:n.trim(),changes:[],reverted:!1},he(co,yn)},async recordFileChange(e,n=null){try{if(!yn){if(Ar){let a=oe(ln,[]),i=[...a].reverse().find(p=>p.chatId===Ar);if(i){if(i.changes.some(f=>f.filePath===e))return;let c=await mt.pathExists(e)||n?"update":"create",l=null;if(c==="update"){let f=cn.basename(e);l=`${i.id}_${f}.bak`;let u=cn.join(Kn,i.chatId);await mt.ensureDir(u);let m=cn.join(u,l),g=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);g!==null?he(m,{data:fr(g)}):(c="create",l=null)}i.changes.push({filePath:e,type:c,backupFile:l}),he(ln,a)}}return}if(yn.changes.some(a=>a.filePath===e))return;let s=await mt.pathExists(e)||n?"update":"create",r=null;if(s==="update"){let a=cn.basename(e);r=`${yn.id}_${a}.bak`;let i=cn.join(Kn,yn.chatId);await mt.ensureDir(i);let p=cn.join(i,r),d=n!==null?n:await mt.readFile(e,"utf8").catch(()=>null);d!==null?he(p,{data:fr(d)}):(s="create",r=null)}yn.changes.push({filePath:e,type:s,backupFile:r}),he(co,yn)}catch{}},async commitTransaction(){if(yn)try{let e=oe(ln,[]);if(e.push(yn),e.length>512e3){let n=e.shift();if(n.changes)for(let t of n.changes)t.backupFile&&await mt.remove(cn.join(Kn,n.chatId,t.backupFile)).catch(()=>{})}he(ln,e),await mt.remove(co).catch(()=>{})}catch{}finally{yn=null}},async recoverCrashedTransaction(){try{if(await mt.pathExists(co)){let e=oe(co,null);if(e?.changes?.length>0){let n=oe(ln,[]);n.some(t=>t.id===e.id)||(n.push(e),he(ln,n))}await mt.remove(co).catch(()=>{})}}catch{}},async rollbackToBefore(e){let n=oe(ln,null);if(!n)throw new Error("No transaction ledger found.");let t=n.findIndex(a=>a.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let o=n[t].chatId,s=n[t].prompt,r=n.slice(t).filter(a=>a.chatId===o&&!a.reverted).reverse();for(let a of r){for(let i of[...a.changes].reverse())await Gl(i,a);for(let i of a.changes)if(i.backupFile){let p=cn.join(Kn,a.chatId,i.backupFile);await mt.remove(p).catch(()=>{})}n=n.filter(i=>i.id!==a.id),he(ln,n)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(e){try{return oe(ln,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{await mt.remove(cn.join(Kn,e));let n=oe(ln,[]),t=n.filter(o=>o.chatId!==e);n.length!==t.length&&he(ln,t)}catch{}}};var ba=Promise.resolve(),vs=e=>{let n=ba.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return ba=n.catch(()=>{}),n},fo=async()=>{await vt.ensureDir(Mo);let e={};if(await vt.pathExists(Ao))try{e=oe(Ao,{})}catch{e={}}for(let n in e){let t=Ms.join(Mo,`${n}.json`);Object.defineProperty(e[n],"messages",{get:()=>{if(vt.existsSync(t))try{return oe(t,[])}catch{return[]}return[]},set:o=>{try{he(t,o)}catch{}},enumerable:!1,configurable:!0})}return e},Ku=async(e,n,t)=>vs(async()=>{await vt.ensureDir(Mo);let o=await fo(),s=o[e],r=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await tn()).systemSettings?.preserveThinking===!1&&(r=r.filter(h=>h.role!=="think"))}catch{}let a=y=>{if(!y)return;let h=typeof y=="string"?y:y.text||y.content||"";if(!h||typeof h!="string")return;let x=h.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!x)return;let w=x.split(/\s+/),T;return w.length>7?T=w.slice(0,7).join(" ")+"...":x.length>45?T=x.substring(0,45).trimEnd()+"...":T=x,T},i,p=r.filter(y=>y.role==="user"),d=p[0],c=p[p.length-1],l=a(c),f=a(d);s&&s.prompt?Math.random()<.3&&l?i=l:i=s.prompt:i=f||l;let u=n||(s?s.name:`Session ${e.slice(-6)}`),m=Ms.join(Mo,`${e}.json`);he(m,r),o[e]={name:u,prompt:i||void 0,updatedAt:Date.now()};let g={};for(let y in o)g[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};he(Ao,g)}),Sa=async(e,n)=>vs(async()=>{let t=await fo();t[e]?(t[e].name=n,t[e].updatedAt=Date.now()):t[e]={name:n,updatedAt:Date.now()};let o={};for(let s in t)o[s]={name:t[s].name,prompt:t[s].prompt||void 0,updatedAt:t[s].updatedAt};he(Ao,o)}),ql=async e=>vs(async()=>{let n=await fo();delete n[e];let t={};for(let a in n)t[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};if(he(Ao,t),await vt.pathExists(Yn))try{let a=oe(Yn,[]);if(Array.isArray(a)){let i=a.filter(p=>Object.keys(p)[0]!==String(e));he(Yn,i)}}catch{}let o=oe(en,{});o[e]&&(delete o[e],he(en,o));let s=oe(Pn,{});s[e]&&(delete s[e],he(Pn,s)),await ht.deleteChatBackups(e);let r=Ms.join(Mo,`${e}.json`);if(await vt.pathExists(r))try{await vt.remove(r)}catch{}return n}),Yu=()=>`flow-${Hl(6)}`,Vu=async e=>{if(!e||e==="Never")return;let n=parseInt(e);if(isNaN(n))return;let t=await fo(),o=Date.now(),s=n*24*60*60*1e3,r=0;for(let a in t){let i=t[a];i.updatedAt&&o-i.updatedAt>s&&(await ql(a),r++)}return r},zl=e=>{let n=e.replace(/[\[\]]/g,"").trim(),t=new Date(n);if(!isNaN(t.getTime()))return t.getTime();let o=n.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],r=o[1]||"",a=o[2]||"",i=s.split(/[-\/.]/).map(Number);if(i.length!==3)return null;let p="en";try{p=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let d=!/^en[-_]?us$|^en$/.test(p?.toLowerCase()),c,l,f;if(i[0]>1e3)c=i[0],l=i[1],f=i[2];else if(i[2]>1e3)c=i[2],i[0]>12?(f=i[0],l=i[1]):i[1]>12?(f=i[1],l=i[0]):d?(f=i[0],l=i[1]):(l=i[0],f=i[1]);else return null;if(l<1||l>12||f<1||f>31)return null;let u=0,m=0,g=0;if(r){let h=r.split(":").map(Number);u=h[0]||0,m=h[1]||0,g=h[2]||0,a.toLowerCase()==="pm"&&u<12?u+=12:a.toLowerCase()==="am"&&u===12&&(u=0)}let y=new Date(c,l-1,f,u,m,g);return isNaN(y.getTime())?null:y.getTime()},Kl=async e=>{try{if(!await vt.pathExists(e))return;let n=await vt.readFile(e,"utf8");if(!n.trim())return;let t=n.split(`
598
598
  `),o=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)r.test(l)?(s&&o.push(s),s={header:l,body:[]}):s?s.body.push(l):o.push({header:l,body:[]});s&&o.push(s);let a=10080*60*1e3,i=Date.now(),p=[],d=/(\d{1,4}[-\/.]\d{1,4}[-\/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let l of o){if(r.test(l.header)){let m=l.header.match(d);if(m){let g=zl(m[1]);if(g&&i-g>a)continue}}let u=l.header+(l.body.length>0?`
599
599
  `+l.body.join(`
600
600
  `):"");p.push(u)}let c=p.join(`
601
601
  `).trim();c?await vt.writeFile(e,c+`
602
- `,"utf8"):await vt.writeFile(e,"","utf8")}catch{}},Xu=async e=>{try{if(!await vt.pathExists(e))return;let n=async t=>{let o=await vt.readdir(t);for(let s of o){let r=Ms.join(t,s);(await vt.stat(r)).isDirectory()?(await n(r),(await vt.readdir(r)).length===0&&await vt.remove(r)):s.endsWith(".log")&&await Kl(r)}};await n(e)}catch{}},ka=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var Ju=async(e,n,t)=>vs(async()=>{let o=oe(Yn,[]);Array.isArray(o)||(o=[]);let s={total:n,context:t},r=o.findIndex(a=>Object.keys(a)[0]===String(e));r!==-1?o[r]={[String(e)]:s}:o.push({[String(e)]:s}),me(Yn,o)}),Qu=async e=>{try{if(!await vt.pathExists(Yn))return{total:0,context:0};let n=oe(Yn,[]);if(!Array.isArray(n))return{total:0,context:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?t[String(e)]:{total:0,context:0}}catch{return{total:0,context:0}}};import Ea from"puppeteer";import _a from"fs";import Ca from"path";import Ta from"os";import es from"path";import Oo from"fs";import{createRequire as Yl}from"module";import{fileURLToPath as Vl}from"url";var Xl=Yl(import.meta.url),Ra=es.dirname(Vl(import.meta.url));function po(){let e=Ta.platform(),n=Ta.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=es.resolve(Ra,"..","..",".puppeteerrc.cjs");if(Oo.existsSync(r)||(r=es.resolve(Ra,"..",".puppeteerrc.cjs")),!Oo.existsSync(r))return{};try{let a=Xl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=es.join(i,"chrome",`${t}-${p}`,s,o);if(Oo.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!Oo.existsSync(l))return null;try{let f=Oo.readdirSync(l),u=[];for(let m of f){let g=es.join(l,m),y;try{y=Oo.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(m.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let m of u)if(m.includes(p)){let g=d(m);if(g)return g}}for(let m of u)if(!p||!m.includes(p)){let g=d(m);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var Mr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=L(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
602
+ `,"utf8"):await vt.writeFile(e,"","utf8")}catch{}},Xu=async e=>{try{if(!await vt.pathExists(e))return;let n=async t=>{let o=await vt.readdir(t);for(let s of o){let r=Ms.join(t,s);(await vt.stat(r)).isDirectory()?(await n(r),(await vt.readdir(r)).length===0&&await vt.remove(r)):s.endsWith(".log")&&await Kl(r)}};await n(e)}catch{}},ka=(e,n=4)=>{if(e.length<=1)return e;let t=e[0],o=e.slice(1),s=n*2,r=o.slice(s);return[t,...r]};var Ju=async(e,n,t,o=0)=>vs(async()=>{let s=oe(Yn,[]);Array.isArray(s)||(s=[]);let r={total:n,context:t,cached:o},a=s.findIndex(i=>Object.keys(i)[0]===String(e));a!==-1?s[a]={[String(e)]:r}:s.push({[String(e)]:r}),he(Yn,s)}),Qu=async e=>{try{if(!await vt.pathExists(Yn))return{total:0,context:0,cached:0};let n=oe(Yn,[]);if(!Array.isArray(n))return{total:0,context:0,cached:0};let t=n.find(o=>Object.keys(o)[0]===String(e));return t?{total:0,context:0,cached:0,...t[String(e)]}:{total:0,context:0,cached:0}}catch{return{total:0,context:0,cached:0}}};import Ea from"puppeteer";import _a from"fs";import Ca from"path";import Ta from"os";import es from"path";import Oo from"fs";import{createRequire as Yl}from"module";import{fileURLToPath as Vl}from"url";var Xl=Yl(import.meta.url),Ra=es.dirname(Vl(import.meta.url));function po(){let e=Ta.platform(),n=Ta.arch(),t="",o="",s="";if(e==="win32")t=n==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(e==="darwin"){t=n==="arm64"?"mac_arm":"mac";let a=n==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${a}`}else if(e==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let r=es.resolve(Ra,"..","..",".puppeteerrc.cjs");if(Oo.existsSync(r)||(r=es.resolve(Ra,"..",".puppeteerrc.cjs")),!Oo.existsSync(r))return{};try{let a=Xl(r),i=a.cacheDirectory,p=a.chrome?.version;if(i){if(process.env.PUPPETEER_CACHE_DIR=i,p){let l=es.join(i,"chrome",`${t}-${p}`,s,o);if(Oo.existsSync(l))return{executablePath:l,cacheDirectory:i}}let d=l=>{if(!Oo.existsSync(l))return null;try{let f=Oo.readdirSync(l),u=[];for(let m of f){let g=es.join(l,m),y;try{y=Oo.statSync(g)}catch{continue}if(y.isDirectory())u.push(g);else if(m.toLowerCase()===o.toLowerCase()&&(!p||g.includes(p)))return g}if(p){for(let m of u)if(m.includes(p)){let g=d(m);if(g)return g}}for(let m of u)if(!p||!m.includes(p)){let g=d(m);if(g)return g}}catch{}return null},c=d(i);if(c)return{executablePath:c,cacheDirectory:i}}}catch{}return{}}var Mr=async e=>{let{query:n,limit:t=5,aiMode:o=!1}=L(e);if(!n)return'ERROR: Missing "query" argument for web_search.';let s=3,r=null;if(o){let a=`Query: ${n}
603
603
 
604
604
  RESPONSE RULES:
605
605
  - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
@@ -649,7 +649,7 @@ ${u}`}catch(p){if(r=p,i&&await i.close(),_a.writeFileSync(Ca.join(hn,"web_tools"
649
649
 
650
650
  ${m}${u.length>5e4?`
651
651
 
652
- [TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let p=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var ec=4*(1024*2),Ir=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),m=e.match(u);return m?m[1].trim():null},o=t("action"),s=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),p=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=oe(en,{});c[d]||(c[d]=[]),c[d].push(r),me(en,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=oe(Ft,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,m=ec,g=c.reduce((w,T)=>w+(T.memory?.length||0),0);for(;c.length>0&&g+u.length>m;){let w=c.shift();g-=w.memory?.length||0}let y=t("score"),h=y?parseFloat(y):.5,x={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(h)?.5:h)};return c.push(x),me(Ft,c),`SUCCESS: Memory added with ID [${x.id}] and score [${x.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=p||i,f=a||r;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(h=>h.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let m=new Date,g=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,me(Ft,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(m=>m.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(me(Ft,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var Or=async(e,n={})=>{let t=L(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Sa(o,t),`SUCCESS: Chat title updated to [${t}] for session [${o}].`}catch(s){return`ERROR: Failed to update chat title: ${s instanceof Error?s.message:String(s)}`}};import dn from"fs";import $n from"path";var tc=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let s="",r=t.match(/^name:\s*(.+)$/m);return r&&(s=r[1].trim().replace(/^["']|["']$/g,"")),s?{name:s}:null},nc=e=>{let n=[];if(!e||!dn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=dn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=$n.join(o,a.name),p=a.name.toLowerCase();a.isFile()?p==="skill.md"&&n.push(i):a.isDirectory()&&(s===0?(p==="skills"||p===".skills"||p==="skill"||p===".skill")&&t(i,s+1):t(i,s+1))}}catch{}};return t(e,0),n},oc=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,o,s)=>{let r=o.split(`
652
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(i){if(s=i,a&&await a.close(),r<o){let p=Math.pow(2,r)*1e3;await new Promise(d=>setTimeout(d,p))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var ec=4*(1024*2),Ir=async(e,n={})=>{let t=c=>{let l=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),f=e.match(l);if(f)return f[2].trim();let u=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),m=e.match(u);return m?m[1].trim():null},o=t("action"),s=t("method"),r=t("content"),a=t("content-new"),i=t("content-old"),p=t("id"),d=t("chat-id")||n.chatId||n.sessionId||"default-session";if(o==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=oe(en,{});c[d]||(c[d]=[]),c[d].push(r),he(en,c);let l=c[d].reduce((f,u)=>f+u.length,0);return`SUCCESS: Temporary context saved for session [${d}]. (Size: ${l} chars)`}if(o==="user"){let c=oe(Ft,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let l=new Date,f=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,u=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${f}]`,m=ec,g=c.reduce((w,T)=>w+(T.memory?.length||0),0);for(;c.length>0&&g+u.length>m;){let w=c.shift();g-=w.memory?.length||0}let y=t("score"),h=y?parseFloat(y):.5,x={id:`mem-${Date.now().toString(36)}`,memory:u,score:Math.min(2,isNaN(h)?.5:h)};return c.push(x),he(Ft,c),`SUCCESS: Memory added with ID [${x.id}] and score [${x.score}]. (Vault Size: ${g+u.length} chars)`}if(s==="update"){let l=p||i,f=a||r;if(!l||!f)return"ERROR: Missing 'id' or content for update.";let u=c.findIndex(h=>h.id===l);if(u===-1)return`ERROR: Memory ID [${l}] not found.`;let m=new Date,g=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=f.includes("[Saved on:")?f:`${f.trim()} [Saved on: ${g}]`;return c[u].memory=y,he(Ft,c),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=p||r;if(!l)return"ERROR: Missing 'id' for deletion.";let f=c.length,u=c.filter(m=>m.id!==l);return u.length===f?`ERROR: Memory ID [${l}] not found.`:(he(Ft,u),`SUCCESS: Memory [${l}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${o}] for memory tool.`};var Or=async(e,n={})=>{let t=L(e).title,o=n.chatId||n.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Sa(o,t),`SUCCESS: Chat title updated to [${t}] for session [${o}].`}catch(s){return`ERROR: Failed to update chat title: ${s instanceof Error?s.message:String(s)}`}};import dn from"fs";import $n from"path";var tc=e=>{if(!e)return null;let n=e.match(/^\s*---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?([\s\S]*)$/);if(!n)return null;let t=n[1];if((n[2]||"").trim().length===0)return null;let s="",r=t.match(/^name:\s*(.+)$/m);return r&&(s=r[1].trim().replace(/^["']|["']$/g,"")),s?{name:s}:null},nc=e=>{let n=[];if(!e||!dn.existsSync(e))return n;let t=(o,s=0)=>{if(!(s>5))try{let r=dn.readdirSync(o,{withFileTypes:!0});for(let a of r){let i=$n.join(o,a.name),p=a.name.toLowerCase();a.isFile()?p==="skill.md"&&n.push(i):a.isDirectory()&&(s===0?(p==="skills"||p===".skills"||p==="skill"||p===".skill")&&t(i,s+1):t(i,s+1))}}catch{}};return t(e,0),n},oc=e=>e.replace(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/,(n,t,o,s)=>{let r=o.split(`
653
653
  `),a=[],i=!1;for(let p of r){if(/^\s*description\s*:/i.test(p)){i=!0;continue}if(i){if(/^\s+/.test(p))continue;i=!1}a.push(p)}return`${t}${a.join(`
654
654
  `)}${s}`}),sc=(e,n)=>{let t=[$n.join(e,"references"),$n.join(e,"reference"),e],o=n.toLowerCase().endsWith(".md")?n.toLowerCase():`${n.toLowerCase()}.md`,s=n.toLowerCase();for(let r of t)if(dn.existsSync(r)&&dn.statSync(r).isDirectory())try{let a=dn.readdirSync(r);for(let i of a){let p=i.toLowerCase();if(p===o||p===s){let d=$n.join(r,i);if(dn.statSync(d).isFile())return d}}}catch{}return null},ts=async(e,n={})=>{let{path:t,StartLine:o,EndLine:s,start_line:r,end_line:a,startLine:i,endLine:p}=L(e),d=parseInt(o||r||i),c=parseInt(s||a||p),l=!isNaN(d),f=!isNaN(c),u=d||1,m=c||(d?d+800:800);if(!t)return'ERROR: Missing "path" argument for ReadFile.';if(t.trim().toLowerCase().startsWith("#skill")){let h=t.trim().replace(/\\/g,"/").replace(/^#skills?\/?/i,"").split("/").filter(Boolean),x=h[0]?.toLowerCase();if(x!=="global"&&x!=="project")return`ERROR: Invalid skill scope '${x||""}'. Expected 'global' or 'project'.`;let w=h[1];if(!w)return`ERROR: Missing skill name in path [${t}].`;let T=h[2]?.toLowerCase()==="references"||h[2]?.toLowerCase()==="reference",$=T?h.slice(3).join("/"):null,R=x==="global"?Rt:process.cwd(),S=nc(R),k=null;for(let C of S)try{let M=dn.readFileSync(C,"utf8"),O=tc(M),D=$n.basename($n.dirname(C)).toLowerCase();if(O?.name&&O.name.toLowerCase()===w.toLowerCase()||D===w.toLowerCase()||C.toLowerCase()===$n.join(R,"skill.md").toLowerCase()&&w.toLowerCase()==="skill"){k=C;break}}catch{}if(!k)return`No '${w}' exist in given scope.`;let _=$n.dirname(k),E=k,b=!0;if(T){if(!$)return`ERROR: Missing reference file name in path [${t}].`;let C=sc(_,$);if(!C)return`No such reference exist for skill '${w}'`;E=C,b=!1}try{let C=dn.readFileSync(E,"utf8");C.startsWith("\uFEFF")&&(C=C.slice(1)),C=C.replace(/\r\n/g,`
655
655
  `).replace(/\r/g,`
@@ -813,7 +813,7 @@ ${i.map(p=>`- ${p}`).join(`
813
813
  `;for(let M of T){C+=`${M.path}
814
814
  `;for(let O of M.matches)C+=` ${O.line}: ${O.content}
815
815
  `;C+=`
816
- `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Da from"fs-extra";import qr from"path";var _c=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let i=a;for(let p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([i,...t,p])}return e}catch{return e}},zr=async(e,n={})=>{let t=L(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],i=o.toLowerCase();if(a.some(d=>i.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await tn();if(!await Li(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Pi()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,m={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(r){let O=r.replace(/\s+/g,"");O==="16:9"?(g=1024,y=576):O==="9:16"?(g=576,y=1024):O==="4:3"?(g=1024,y=768):O==="3:4"?(g=768,y=1024):O==="1:1"&&(g=1024,y=1024)}let h=Math.floor(Math.random()*1e7),w=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${m}&width=${g}&height=${y}&seed=${h}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,T=await fetch(w,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!T.ok){let O=T.status,D="";try{D=await T.text()}catch{}return O===402||D.includes("Insufficient balance")||D.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${O}]: ${D||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let O=await T.json();return O.status===402||O.error&&O.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${O.error?.message||JSON.stringify(O)}`}let R=await T.arrayBuffer(),S=Buffer.from(R),k={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:r||"1:1",Seed:String(h)};S=_c(S,k);let _=qr.resolve(process.cwd(),s);await Da.ensureDir(qr.dirname(_)),await ht.recordFileChange(_),await Da.writeFile(_,S),await Fi(d);let E=qr.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:C}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var rs=async(e,n={})=>{let t=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(a);return i?i[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=oe(en,{}),a=oe(Pn,{});return a[o]=s,delete r[o],me(Pn,a),me(en,r),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Fo=async(e,n={})=>{let o=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=oe(Ft,[]),r=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(me(Ft,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),p=i?i.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${p}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${r}`}};import Yr from"fs-extra";import wo from"path";import{createRequire as Ac}from"module";import yo from"fs-extra";import Kr from"path";import Cc from"https";var La={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"};async function $c(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Kr.join(uo,e);return await yo.ensureDir(uo),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Cc.get(t,a,i=>{if([301,302,307,308].includes(i.statusCode)&&i.headers.location){let d=i.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}$c(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=yo.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{yo.existsSync(o)&&yo.unlink(o,()=>{}),r(i)})})}function Gp(e){let n=Kr.join(uo,e);return yo.existsSync(n)}async function Hp(e){let n=Kr.join(uo,e);yo.existsSync(n)&&await yo.unlink(n)}var Na=Ac(import.meta.url),Pa=Na("web-tree-sitter"),Fa=!1,Ua=new Set(["class_declaration","function_declaration","method_definition","arrow_function","function_expression","if_statement","else_clause","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_statement","try_statement","catch_clause","variable_declarator","export_statement","lexical_declaration","variable_declaration","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","assignment_expression","pair","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]),Ba=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function bn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function Wa(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${bn(o.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let o=e.childForFieldName("condition");return`${n.split("_")[0]} (${o?bn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
816
+ `}return C.trimEnd()}catch(g){return`ERROR: ${g.message}`}};import Da from"fs-extra";import qr from"path";var _c=(e,n={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],o=[];for(let a=0;a<256;a++){let i=a;for(let p=0;p<8;p++)i&1?i=3988292384^i>>>1:i=i>>>1;o[a]=i}let s=a=>{let i=4294967295;for(let p=0;p<a.length;p++)i=o[(i^a[p])&255]^i>>>8;return(i^4294967295)>>>0},r=(a,i)=>{let p=Buffer.from(a,"ascii"),d=Buffer.from(i,"utf-8"),c=p.length+1+d.length,l=Buffer.alloc(8+c+4);l.writeUInt32BE(c,0),l.write("tEXt",4,"ascii"),p.copy(l,8),l[8+p.length]=0,d.copy(l,8+p.length+1);let f=s(l.subarray(4,8+c));return l.writeUInt32BE(f,8+c),l};for(let[a,i]of Object.entries(n))i!=null&&t.push(r(a,String(i)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let i=e.subarray(0,33),p=e.subarray(33);return Buffer.concat([i,...t,p])}return e}catch{return e}},zr=async(e,n={})=>{let t=L(e),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let a=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],i=o.toLowerCase();if(a.some(d=>i.includes(d)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let d=await tn();if(!await Li(d))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Pi()).nextResetMin||60}m).`;let l=d.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},f=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,m={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",g=1024,y=1024;if(r){let O=r.replace(/\s+/g,"");O==="16:9"?(g=1024,y=576):O==="9:16"?(g=576,y=1024):O==="4:3"?(g=1024,y=768):O==="3:4"?(g=768,y=1024):O==="1:1"&&(g=1024,y=1024)}let h=Math.floor(Math.random()*1e7),w=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${m}&width=${g}&height=${y}&seed=${h}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,T=await fetch(w,{method:"GET",headers:{Authorization:`Bearer ${f}`}});if(!T.ok){let O=T.status,D="";try{D=await T.text()}catch{}return O===402||D.includes("Insufficient balance")||D.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${O}]: ${D||"Unknown API Error"}`}if((T.headers.get("content-type")||"").includes("application/json")){let O=await T.json();return O.status===402||O.error&&O.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${O.error?.message||JSON.stringify(O)}`}let R=await T.arrayBuffer(),S=Buffer.from(R),k={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:r||"1:1",Seed:String(h)};S=_c(S,k);let _=qr.resolve(process.cwd(),s);await Da.ensureDir(qr.dirname(_)),await ht.recordFileChange(_),await Da.writeFile(_,S),await Fi(d);let E=qr.extname(s).toLowerCase(),C={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[E]||"image/png";return n.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:C}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(d){return`ERROR: Failed during image generation: ${d instanceof Error?d.message:String(d)}`}};var rs=async(e,n={})=>{let t=r=>{let a=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),i=e.match(a);return i?i[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=oe(en,{}),a=oe(Pn,{});return a[o]=s,delete r[o],he(Pn,a),he(en,r),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to save summary for chat [${o}]: ${a}`}};var Fo=async(e,n={})=>{let o=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=e.match(r);return a?a[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=oe(Ft,[]),r=!1,a=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===o?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&a.push(c);if(he(Ft,a),!r)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let i=a.find(c=>c.id===o),p=i?i.score.toFixed(2):"deleted (score <= 0)",d=s.length-a.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${p}.${d>0?` Purged ${d} decayed memories.`:""}`}catch(s){let r=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${r}`}};import Yr from"fs-extra";import wo from"path";import{createRequire as Ac}from"module";import yo from"fs-extra";import Kr from"path";import Cc from"https";var La={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"};async function $c(e,n=null){let t=n||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,o=Kr.join(uo,e);return await yo.ensureDir(uo),new Promise((s,r)=>{let a={headers:{"User-Agent":"FluxFlow-Agent"}};Cc.get(t,a,i=>{if([301,302,307,308].includes(i.statusCode)&&i.headers.location){let d=i.headers.location;if(!d.startsWith("http")){let c=new URL(t);d=`${c.protocol}//${c.host}${d}`}$c(e,d).then(s).catch(r);return}if(i.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${i.statusCode}`));return}let p=yo.createWriteStream(o);i.pipe(p),p.on("finish",()=>{p.close(),s()})}).on("error",i=>{yo.existsSync(o)&&yo.unlink(o,()=>{}),r(i)})})}function Gp(e){let n=Kr.join(uo,e);return yo.existsSync(n)}async function Hp(e){let n=Kr.join(uo,e);yo.existsSync(n)&&await yo.unlink(n)}var Na=Ac(import.meta.url),Pa=Na("web-tree-sitter"),Fa=!1,Ua=new Set(["class_declaration","function_declaration","method_definition","arrow_function","function_expression","if_statement","else_clause","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_statement","try_statement","catch_clause","variable_declarator","export_statement","lexical_declaration","variable_declaration","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","assignment_expression","pair","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]),Ba=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function bn(e,n=50){if(!e)return"";let t=e.replace(/\s+/g," ").trim();return t.length>n?t.substring(0,n-3)+"...":t}function Wa(e){let n=e.type;if(n==="if_statement"){let o=e.childForFieldName("condition");return o?`if (${bn(o.text,40)})`:"if"}if(n==="else_clause")return"else";if(n==="while_statement"||n==="do_statement"){let o=e.childForFieldName("condition");return`${n.split("_")[0]} (${o?bn(o.text,40):""})`}if(n==="for_statement"||n==="for_in_statement"||n==="for_of_statement"){let s=e.text.split(`
817
817
  `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${bn(s[1],40)})`:"for"}if(n==="switch_statement"){let o=e.childForFieldName("value");return`switch (${o?bn(o.text,40):""})`}if(n==="try_statement")return"try";if(n==="catch_clause")return"catch";if(n==="element"||n==="script_element"||n==="style_element"||n==="jsx_element"||n==="jsx_self_closing_element"){let o=e.childForFieldName("opening_element")||e.childForFieldName("start_tag")||e.children.find(r=>r.type==="start_tag")||e,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(r=>r.type==="tag_name");return s?`<${bn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(n))return bn(e.text.split(`
818
818
  `)[0],60);if(n==="pair"){let o=e.childForFieldName("key");return o?bn(o.text.replace(/["']/g,""),40):null}if(n==="assignment_expression"){let o=e.childForFieldName("left");return o?`${bn(o.text,30)} = ...`:null}if(n==="variable_declarator"){let o=e.childForFieldName("name")||e.children.find(s=>["identifier","object_pattern","array_pattern"].includes(s.type));return o?bn(o.text,40):null}let t=e.childForFieldName("name")||e.childForFieldName("declarator")||e.children.find(o=>["identifier","type_identifier","field_identifier","property_identifier","shorthand_property_identifier"].includes(o.type));if(t){if(t.type.includes("declarator")){let o=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(o)return bn(o.text,40)}return bn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(n)){let o=e.parent;for(;o&&o.type!=="program";){let s=Wa(o);if(s)return s;if(!Ba.has(o.type))break;o=o.parent}}return null}function Mc(e){let n=[];function t(o){for(let s of o.children)Ua.has(s.type)?n.push(s):t(s)}return t(e),n}function vc(e){return e.replace(/_([a-z])/g,n=>n[1].toUpperCase())}function ja(e,n=0,t=!0,o="",s=null,r=12){let a=e.type,i=Wa(e),p=Ua.has(a)||n===0,d=Mc(e),c=p&&n>0&&(Ba.has(a)&&d.length>0||i!==null&&i===s&&d.length>0),l="",f=o,u=n,m=s;if(p&&!c){let g=e.startPosition.row+1,y=e.endPosition.row+1,h=vc(a),x=i?`${h} [${i}]`:h;n===0?(l+=`\u{1F4C1} ROOT (Lines: ${g}-${y})
819
819
  `,f=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${x} (Lines: ${g}-${y})
@@ -830,14 +830,14 @@ Stack: ${a.stack}`:"";return`ERROR: Failed to map file: ${i}${p}`}};import Qn fr
830
830
  ${l}`}return`SUCCESS: TASK LIST CREATED (${u} total)
831
831
  ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=d(o);await ht.recordFileChange(i),Qn.appendFileSync(i,l,"utf8");let f=Qn.readFileSync(i,"utf8"),u=f.split(/\r?\n/).map(h=>h.trim()),m=u.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=u.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${g} completed, ${m-g} left, ${y} added)
832
832
  ${f}`}if(t==="get"){if(!Qn.existsSync(i))return"TODO GET: No task list found for this session.";let l=Qn.readFileSync(i,"utf8"),f=0;if(s){let h=c(l,s);h.markedCount>0&&(l=h.content,f=h.markedCount,await ht.recordFileChange(i),Qn.writeFileSync(i,l,"utf8"))}let u=l.split(/\r?\n/).map(h=>h.trim()),m=u.filter(h=>h.startsWith("- [ ]")||h.startsWith("- [x]")||h.startsWith("- [X]")).length,g=u.filter(h=>h.startsWith("- [x]")||h.startsWith("- [X]")).length;return`${f>0?`SUCCESS: ${f} TASK(S) MARKED DONE`:"TODO GET"}: ${g} Completed, ${m-g} left
833
- ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Xr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-O2P2GKC7.js"),o=L(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
834
- `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-O2P2GKC7.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
835
- `)}return`ERROR: Subagent execution failed: ${d.message}`}};var Ha=async(e,n={})=>{let{runSubagent:t}=await import("./ai-O2P2GKC7.js"),o=L(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let h=i.trim();h.startsWith("[")&&h.endsWith("]")&&(h=h.substring(1,h.length-1)),p=h.split(",").map(x=>x.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((h,x)=>{c=h,l=x}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:h=>{h&&u.pendingSteerMessages.push(h)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},m={chunks:[],totalWords:0};Qe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async h=>{let x=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,w=null,T=new Promise(S=>{w=S}),$={id:x,question:h,answered:!1,answer:null,askedAt:Date.now(),_resolve:w};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${h}"
833
+ ${l}`}return`ERROR: Unknown method "${t}". Use create, append, or get.`}catch(l){return`ERROR: Todo tool failure: ${l instanceof Error?l.message:String(l)}`}};var Xr=async(e,n={})=>{let{runSubagent:t}=await import("./ai-MNMJ5SVM.js"),o=L(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let i=null;if(a)try{let d=a.trim();d.startsWith("[")&&d.endsWith("]")&&(d=d.substring(1,d.length-1)),i=d.split(",").map(c=>c.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let p=o.title||s.substring(0,30);try{n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p}`);let d=await t(s,n,r,i,50);return n.onVisualFeedback&&n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} [COMPLETED]
834
+ `),d}catch(d){let{isTerminationSignaled:c}=await import("./ai-MNMJ5SVM.js"),l=d.message==="Subagent task was cancelled by user."||c();if(n.onVisualFeedback){let f=l?"[CANCELLED]":"[FAILED]";n.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${p} ${f}
835
+ `)}return`ERROR: Subagent execution failed: ${d.message}`}};var Ha=async(e,n={})=>{let{runSubagent:t}=await import("./ai-MNMJ5SVM.js"),o=L(e),s=o.task||o.instruction||o.prompt,r=o.model||null,a=o.title||null,i=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let p=null;if(i)try{let h=i.trim();h.startsWith("[")&&h.endsWith("]")&&(h=h.substring(1,h.length-1)),p=h.split(",").map(x=>x.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,c=null,l=null,f=new Promise((h,x)=>{c=h,l=x}),u={id:d,title:a||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:h=>{h&&u.pendingSteerMessages.push(h)},completionPromise:f,_resolveCompletion:c,_rejectCompletion:l,progress:[]},m={chunks:[],totalWords:0};Qe.push(u),n.onSubagentUpdate&&n.onSubagentUpdate();let g=[],y={...n,taskId:d,onAskMain:async h=>{let x=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,w=null,T=new Promise(S=>{w=S}),$={id:x,question:h,answered:!1,answer:null,askedAt:Date.now(),_resolve:w};return u.questions.push($),u.status="waiting",n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" is WAITING FOR YOUR INPUT: "${h}"
836
836
  Respond using tool: [tool:functions.Answer(id="${d}", answer="...")]
837
837
  [/SYSTEM]`),await T},onVisualFeedback:h=>{u.lastChunkTime=Date.now();let x=h.replace(/\x1b\[[0-9;]*m/g,""),w=x.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);w?u.currentTool=w[1].trim():u.currentTool=x,n.onSubagentUpdate&&n.onSubagentUpdate()},onTokenChunk:(h,x)=>{let w=Date.now();if(u.lastChunkTime=w,u.currentTool="Thinking",typeof x=="number"&&x>0){m.totalWords+=x,m.chunks.push({time:w,words:x});let T=w-400;if(m.chunks=m.chunks.filter($=>$.time>=T),m.chunks.length>0){let $=m.chunks.reduce((k,_)=>k+_.words,0),R=m.chunks[0].time,S=Math.max(.4,(w-R)/1e3);u.wps=Math.round($/S*10)/10}}n.onSubagentUpdate&&n.onSubagentUpdate()}};return t(s,y,r,p,50,h=>{if(u.status==="cancelled")return;if(h.startsWith("[Subagent Turn")&&g.length>0&&(u.progress.push([...g]),g=[]),h.includes("[Executing Tool]")){let w=h.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);w&&(!u.currentTool||u.currentTool==="Thinking")&&(u.currentTool=w[1])}let x=h;if(x.startsWith("[Tool Result]")){let w=x.split(`
838
838
  `);w.length>5&&(x=w.slice(0,4).join(`
839
839
  `)+`
840
- ... [Content/Diff Truncated from Logs] ...`)}g.push(x),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(h=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(h);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=h,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(h)}).catch(async h=>{let{isTerminationSignaled:x}=await import("./ai-O2P2GKC7.js");if(h.message==="Subagent task was cancelled."||u.status==="cancelled"||x()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${h.message}`),u.progress.push([...g]),u.status="failed",u.error=h.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${h.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(h)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Jr=async(e,n={})=>{let o=L(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Qe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
840
+ ... [Content/Diff Truncated from Logs] ...`)}g.push(x),n.onSubagentUpdate&&n.onSubagentUpdate()},!0).then(h=>{if(u.status==="cancelled"){u._resolveCompletion&&u._resolveCompletion(h);return}g.length>0&&(u.progress.push([...g]),g=[]),u.status="completed",u.finalAnswer=h,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) has FINISHED. Call GetProgress(id="${d}") to see the final result. [/SYSTEM]`),u._resolveCompletion&&u._resolveCompletion(h)}).catch(async h=>{let{isTerminationSignaled:x}=await import("./ai-MNMJ5SVM.js");if(h.message==="Subagent task was cancelled."||u.status==="cancelled"||x()){u.status="cancelled",g.push("[SUBAGENT CANCELLED] Task was cancelled."),u.progress.push([...g]),n.onSubagentUpdate&&n.onSubagentUpdate(),u._resolveCompletion&&u._resolveCompletion(null);return}g.push(`[SUBAGENT FAILURE] Error: ${h.message}`),u.progress.push([...g]),u.status="failed",u.error=h.message,n.onSubagentUpdate&&n.onSubagentUpdate(),Rs(`[SYSTEM] Background subagent "${u.title}" (id: ${d}) FAILED with error: ${h.message}. [/SYSTEM]`),u._rejectCompletion&&u._rejectCompletion(h)}),`SUCCESS: Background subagent started. Task ID: ${d}`};var Jr=async(e,n={})=>{let o=L(e).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=Qe.find(i=>i.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let r=`Subagent Task Status: ${s.status.toUpperCase()}
841
841
  `;if(r+=`Title: ${s.title}
842
842
  `,r+=`Task: ${s.task}
843
843
  `,s.startedAt){let i=Math.floor((Date.now()-s.startedAt)/1e3);r+=`Elapsed Time: ${i}s
@@ -862,7 +862,7 @@ ${s.finalAnswer}
862
862
  `),r.replace(/\r\n/g,`
863
863
  `).replace(/\n{3,}/g,`
864
864
 
865
- `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var qa=async(e,n={})=>{let o=L(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Qe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import bt from"fs-extra";import _t from"path";var Ic=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function as(e,n=e){let t={},o=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Ic.includes(s.name))continue;let r=_t.join(e,s.name),a=_t.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await as(r,n);Object.assign(t,i)}else{let i=await bt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function za(e,n){await bt.ensureDir(e);for(let t of Object.keys(n)){let o=_t.join(process.cwd(),t),s=_t.join(e,t);await bt.ensureDir(_t.dirname(s)),await bt.copyFile(o,s).catch(()=>{})}}async function Qr(e,n,t=null,o=null){if(!await bt.pathExists(e))return;o||(o=e);let s=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=_t.join(e,r.name),i=_t.join(n,r.name);if(r.isDirectory())await Qr(a,i,t,o);else{let p=_t.relative(o,a).replace(/\\/g,"/"),d=await bt.pathExists(i);d&&await bt.chmod(i,438).catch(()=>{}),await bt.ensureDir(_t.dirname(i));let c=await bt.copyFile(a,i).then(()=>!0).catch(()=>!1);await bt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Zn={async takeInitialSnapshot(e){try{let n=_t.join(Ln,"snapshots",e);await bt.remove(n).catch(()=>{}),await bt.ensureDir(n);let t=await as(process.cwd());await za(_t.join(n,"initial"),t);let o=oe(gn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},me(gn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=oe(gn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await as(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=_t.join(Ln,"snapshots",e,`turn_${n}`);await za(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,me(gn,o)}catch{}},async getCheckpoints(e){try{let t=oe(gn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=oe(gn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=_t.join(Ln,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await as(process.cwd());for(let c of Object.keys(p)){let l=_t.join(process.cwd(),c);await bt.chmod(l,438).catch(()=>{}),await bt.remove(l).catch(()=>{})}let d=_t.join(a,"initial");await Qr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=_t.join(a,l.id);if(await Qr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let m=_t.join(process.cwd(),u);await bt.chmod(m,438).catch(()=>{}),await bt.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await as(process.cwd()),me(gn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=oe(gn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=_t.join(Ln,"snapshots",e);await bt.remove(n).catch(()=>{});let t=oe(gn,{});t[e]&&(delete t[e],me(gn,t))}catch{}}};var Zr=async(e,n={})=>{let t=L(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Zn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
865
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var qa=async(e,n={})=>{let o=L(e).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Qe.find(r=>r.id===o);return s?s.status==="completed"||s.status==="failed"?`INFO: Subagent task with ID [${o}] has already finished with status [${s.status.toUpperCase()}].`:s.status==="cancelled"?`INFO: Subagent task with ID [${o}] is already cancelled.`:(s.status="cancelled",n.onSubagentUpdate&&n.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import bt from"fs-extra";import _t from"path";var Ic=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function as(e,n=e){let t={},o=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Ic.includes(s.name))continue;let r=_t.join(e,s.name),a=_t.relative(n,r).replace(/\\/g,"/");if(s.isDirectory()){let i=await as(r,n);Object.assign(t,i)}else{let i=await bt.stat(r).catch(()=>null);i&&(t[a]={size:i.size,mtime:i.mtimeMs})}}return t}async function za(e,n){await bt.ensureDir(e);for(let t of Object.keys(n)){let o=_t.join(process.cwd(),t),s=_t.join(e,t);await bt.ensureDir(_t.dirname(s)),await bt.copyFile(o,s).catch(()=>{})}}async function Qr(e,n,t=null,o=null){if(!await bt.pathExists(e))return;o||(o=e);let s=await bt.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let r of s){let a=_t.join(e,r.name),i=_t.join(n,r.name);if(r.isDirectory())await Qr(a,i,t,o);else{let p=_t.relative(o,a).replace(/\\/g,"/"),d=await bt.pathExists(i);d&&await bt.chmod(i,438).catch(()=>{}),await bt.ensureDir(_t.dirname(i));let c=await bt.copyFile(a,i).then(()=>!0).catch(()=>!1);await bt.chmod(i,438).catch(()=>{}),t&&(c?d?t.replaced++:t.restored++:t.failed.push(p))}}}var Zn={async takeInitialSnapshot(e){try{let n=_t.join(Ln,"snapshots",e);await bt.remove(n).catch(()=>{}),await bt.ensureDir(n);let t=await as(process.cwd());await za(_t.join(n,"initial"),t);let o=oe(gn,{});o[e]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},he(gn,o)}catch{}},async recordTurnDelta(e,n,t=[]){try{let o=oe(gn,{}),s=o[e];if(!s)return;let r=s.currentManifest||s.initialManifest,a=await as(process.cwd()),i=[],p=[],d=[];for(let[l,f]of Object.entries(a)){let u=r[l];u?(u.size!==f.size||u.mtime!==f.mtime)&&p.push(l):i.push(l)}for(let l of Object.keys(r))a[l]||d.push(l);let c=[...i,...p];if(c.length>0||d.length>0){let l={};for(let u of c)l[u]=a[u];let f=_t.join(Ln,"snapshots",e,`turn_${n}`);await za(f,l)}s.checkpoints.push({id:`turn_${n}`,timestamp:new Date().toISOString(),newFiles:i,modifiedFiles:p,deletedFiles:d,toolsUsed:t}),s.currentManifest=a,he(gn,o)}catch{}},async getCheckpoints(e){try{let t=oe(gn,{})[e];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(e,n){try{let t=oe(gn,{}),o=t[e];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],r=s.findIndex(c=>c.id===n);if(r===-1)throw new Error(`Checkpoint [${n}] not found.`);let a=_t.join(Ln,"snapshots",e),i={restored:0,replaced:0,failed:[]},p=await as(process.cwd());for(let c of Object.keys(p)){let l=_t.join(process.cwd(),c);await bt.chmod(l,438).catch(()=>{}),await bt.remove(l).catch(()=>{})}let d=_t.join(a,"initial");await Qr(d,process.cwd(),i,d);for(let c=1;c<=r;c++){let l=s[c],f=_t.join(a,l.id);if(await Qr(f,process.cwd(),i,f),l.deletedFiles&&l.deletedFiles.length>0)for(let u of l.deletedFiles){let m=_t.join(process.cwd(),u);await bt.chmod(m,438).catch(()=>{}),await bt.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,r+1),o.currentManifest=await as(process.cwd()),he(gn,t),{checkpointId:n,stats:i}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(e){try{let t=oe(gn,{})[e];if(!t||!t.checkpoints||t.checkpoints.length===0)return{newFiles:[],modifiedFiles:[],deletedFiles:[]};let o=t.checkpoints[t.checkpoints.length-1];return{newFiles:o.newFiles||[],modifiedFiles:o.modifiedFiles||[],deletedFiles:o.deletedFiles||[]}}catch{return{newFiles:[],modifiedFiles:[],deletedFiles:[]}}},async cleanup(e){try{let n=_t.join(Ln,"snapshots",e);await bt.remove(n).catch(()=>{});let t=oe(gn,{});t[e]&&(delete t[e],he(gn,t))}catch{}}};var Zr=async(e,n={})=>{let t=L(e),o=t.method,s=t.id,r=n.chatId;if(!n.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!r)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let i=await Zn.getCheckpoints(r);if(i.length===0)return"No checkpoints available.";let p={write_file:"WriteFile",update_file:"PatchFile",view_file:"ReadFile",read_folder:"ReadFolder",exec_command:"Run",web_search:"WebSearch",web_scrape:"WebScrape",search_keyword:"SearchKeyword",CodeSearch:"SearchKeyword",code_search:"SearchKeyword",write_pdf:"WritePDF",write_docx:"WriteDoc",generate_image:"GenerateImage",file_map:"FileMap",todo:"Todo",goal:"Goal",Goal:"Goal",await:"Await",ask:"AskUser",ask_user:"AskUser",AskUser:"AskUser",askuser:"AskUser",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},d=l=>p[l]||p[l.toLowerCase()]||l,c=`Available checkpoints for rollback:
866
866
 
867
867
  `;for(let l of i)if(l.id==="initial")c+=`--- Initial State (id: initial) ---
868
868
  Tools Used: User Prompted for task
@@ -895,7 +895,8 @@ ${l[3]} ${r}FluxFlow ${f("v"+e)}${p}
895
895
  ${l[4]}
896
896
  ${l[5]} ${a}See /help for additional commands.${p}
897
897
  ${l[6]} ${f(o)}
898
- ${l[7]}`};import{WebSocket as js}from"ws";var Kt=null,Bo=!1,qc="ws://localhost:56832",ci=[],Wo=null,di=null,tl="2.0.0",og=e=>{tl=e,nl()},ui=e=>{di=e},nl=()=>{if(Kt||Bo)return;Bo=!0;let e=new js(qc);e.on("open",()=>{for(Kt=e,Bo=!1,Kt.send(JSON.stringify({command:"version",version:tl,pid:process.pid,ppid:process.ppid}));ci.length>0;)Kt.send(JSON.stringify(ci.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Wo?(Wo(t.data),Wo=null):t.command==="securityResponse"&&di&&di(t.result)}catch{}}),e.on("error",()=>{Bo=!1,Kt=null}),e.on("close",()=>{Bo=!1,Kt=null})},Gs=e=>{Kt&&Kt.readyState===js.OPEN?Kt.send(JSON.stringify(e)):(ci.push(e),Bo||nl())},Hs=()=>Kt!==null&&Kt.readyState===js.OPEN,sg=e=>{Gs({command:"status",status:e})},xo=()=>new Promise(e=>{if(!Kt||Kt.readyState!==js.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Wo=e,Kt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Wo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Wo=null)},1e3)}),ol=e=>{Gs({command:"open",filePath:e})},fi=(e,n,t)=>{Gs({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sl=(e,n)=>{Gs({command:"closeDiff",filePath:e,result:n})};import rl from"path";import zc from"fs";var Kc=e=>{try{return zc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},pi=(e,n,t=1,o=Kc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${rl.basename(e)}/ (>100 files)
898
+ ${l[7]}
899
+ `};import{WebSocket as js}from"ws";var Kt=null,Bo=!1,qc="ws://localhost:56832",ci=[],Wo=null,di=null,tl="2.0.0",og=e=>{tl=e,nl()},ui=e=>{di=e},nl=()=>{if(Kt||Bo)return;Bo=!0;let e=new js(qc);e.on("open",()=>{for(Kt=e,Bo=!1,Kt.send(JSON.stringify({command:"version",version:tl,pid:process.pid,ppid:process.ppid}));ci.length>0;)Kt.send(JSON.stringify(ci.shift()))}),e.on("message",n=>{try{let t=JSON.parse(n.toString());t.command==="contextResponse"&&Wo?(Wo(t.data),Wo=null):t.command==="securityResponse"&&di&&di(t.result)}catch{}}),e.on("error",()=>{Bo=!1,Kt=null}),e.on("close",()=>{Bo=!1,Kt=null})},Gs=e=>{Kt&&Kt.readyState===js.OPEN?Kt.send(JSON.stringify(e)):(ci.push(e),Bo||nl())},Hs=()=>Kt!==null&&Kt.readyState===js.OPEN,sg=e=>{Gs({command:"status",status:e})},xo=()=>new Promise(e=>{if(!Kt||Kt.readyState!==js.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Wo=e,Kt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Wo===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Wo=null)},1e3)}),ol=e=>{Gs({command:"open",filePath:e})},fi=(e,n,t)=>{Gs({command:"showDiff",filePath:e,originalContent:n,modifiedContent:t})},sl=(e,n)=>{Gs({command:"closeDiff",filePath:e,result:n})};import rl from"path";import zc from"fs";var Kc=e=>{try{return zc.readdirSync(e,{withFileTypes:!0})}catch{return[]}},pi=(e,n,t=1,o=Kc,s=[],r=null)=>{let a=r||o(e),i=" ".repeat(t-1);if(a.length>100)return`${i}${rl.basename(e)}/ (>100 files)
899
900
  `;let p="",d=s,c=a.filter(m=>!d.includes(m.name)&&!m.name.startsWith(".")),l=a.filter(m=>d.includes(m.name)||m.name.startsWith(".")).map(m=>m.name).sort();l.length>0&&(p+=`${i}[ignored: ${l.map(m=>m+"/").join(", ")}]
900
901
  `);let f=c.filter(m=>m.isDirectory()).sort((m,g)=>m.name.localeCompare(g.name)),u=c.filter(m=>!m.isDirectory()).map(m=>m.name).sort();for(let m of f){let g=rl.join(e,m.name);if(t>n)p+=`${i}${m.name}/ (max depth)
901
902
  `;else{let y=o(g);y.length>80?p+=`${i}${m.name}/ (>80 files)
@@ -910,7 +911,7 @@ ${l[7]}`};import{WebSocket as js}from"ws";var Kt=null,Bo=!1,qc="ws://localhost:5
910
911
  `}),p};import"@google/genai";var gt=async(e,n,t=5,o=1e3)=>{let s=n?.signal;for(let a=0;a<t;a++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let i=await fetch(e,n);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.ok||i.status!==429&&i.status<500)return i}catch(i){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i.name==="AbortError"||s?.aborted||a===t-1)throw i}s?await new Promise((i,p)=>{let d=setTimeout(()=>{s.removeEventListener("abort",c),i()},Math.min(24e3,o*Math.pow(2,a))),c=()=>{clearTimeout(d),p(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",c)}):await new Promise(i=>setTimeout(i,Math.min(24e3,o*Math.pow(2,a))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let r=await fetch(e,n);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),r};async function qs(e){let n=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(t).slice(0,16)].map(o=>o.toString(16).padStart(2,"0")).join("")}var Bn=e=>typeof e!="string"?e:e.replace(/<\|channel>thought/gi,"<think>").replace(/<channel\|>/gi,"</think>");var zs=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let w of t){let T=w.role==="user"?"user":"assistant",$=[];if(Array.isArray(w.parts)){for(let R of w.parts)if(R.text)$.push({type:"text",text:R.text});else if(R.inlineData&&a){let S=R.inlineData.mimeType,k=R.inlineData.data;S.startsWith("image/")&&$.push({type:"image_url",image_url:{url:`data:${S};base64,${k}`}})}}else{let R=w.text||"";R&&$.push({type:"text",text:R})}d.push({role:T,content:$.length===1&&$[0].type==="text"?$[0].text:$})}let c={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p};if(s!=="Fast"){let w={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};c.reasoning_effort=w[s]||"high",c.extra_body={thinking:{type:"enabled"}}}else c.extra_body={thinking:{type:"disabled"}};let l=await gt("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:i});if(!l.ok){let w=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${w.error?.message||l.statusText}`)}let f=l.body.getReader(),u=new TextDecoder,m="",g=[],y=null,h=Date.now(),x=!1;for(;;){let{done:w,value:T}=await f.read();if(w){x&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:y});break}m+=u.decode(T,{stream:!0});let $=m.split(`
911
912
  `);m=$.pop();for(let R of $){let S=R.trim();if(!S||!S.startsWith("data: "))continue;let k=!1;if(S==="data: [DONE]")k=!0;else try{let _=JSON.parse(S.substring(6)),E=_.choices?.[0]?.delta,b=_.usage;if(_.choices?.[0]?.finish_reason&&(k=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},x=!0),E){let C=E.reasoning_content||null;C&&(g.push({text:C,thought:!0}),x=!0),E.content&&(g.push({text:E.content}),x=!0)}}catch{}if((k||Date.now()-h>=150)&&x&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),x=!1),k)break}Date.now()-h>=150&&x&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),x=!1)}};var Ks=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let _=k.role==="user"?"user":"assistant",E=[];if(Array.isArray(k.parts)){for(let b of k.parts)if(b.text)E.push({type:"text",text:b.text});else if(b.inlineData&&a){let C=b.inlineData.mimeType,M=b.inlineData.data;C.startsWith("image/")&&E.push({type:"image_url",image_url:`data:${C};base64,${M}`})}}else{let b=k.text||"";b&&E.push({type:"text",text:b})}E.length>0&&c.push({role:_,content:E.length===1&&E[0].type==="text"?E[0].text:E})}let l={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},f=`${e.slice(-5)}${d||""}${s}${n}`,u=await qs(f),m={model:n,messages:c,stream:!0,temperature:p,prompt_cache_key:u};s&&s!=="Fast"&&vo(n)&&(m.reasoning_effort=l[s]||"high");let g=await gt("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:i});if(!g.ok){let k=await g.text().catch(()=>""),_=g.statusText;try{let E=JSON.parse(k);_=E.error?.message||E.message||JSON.stringify(E.detail||E)}catch{k&&(_=k)}throw new Error(`Mistral Error (${g.status}): ${JSON.stringify(_)}`)}let y=g.body.getReader(),h=new TextDecoder,x="",w=[],T=null,$=Date.now(),R=!1,S=k=>k?typeof k=="string"?Bn(k):Array.isArray(k)?k.map(S).filter(Boolean).join(""):typeof k=="object"&&k!==null?typeof k.text=="string"?Bn(k.text):typeof k.content=="string"?Bn(k.content):typeof k.thinking=="string"?Bn(k.thinking):typeof k.reasoning_content=="string"?Bn(k.reasoning_content):typeof k.reasoning=="string"?Bn(k.reasoning):typeof k.value=="string"?Bn(k.value):k.text?S(k.text):k.content?S(k.content):k.thinking?S(k.thinking):k.reasoning_content?S(k.reasoning_content):k.reasoning?S(k.reasoning):k.value?S(k.value):"":Bn(String(k)):"";for(;;){let{done:k,value:_}=await y.read();if(k){R&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}x+=h.decode(_,{stream:!0});let E=x.split(`
912
913
  `);x=E.pop();for(let b of E){let C=b.trim();if(!C||!C.startsWith("data: "))continue;let M=!1;if(C==="data: [DONE]")M=!0;else try{let O=JSON.parse(C.substring(6)),D=O.choices?.[0]?.delta,B=O.usage;if(O.choices?.[0]?.finish_reason&&(M=!0),B&&(T={totalTokenCount:B.total_tokens||(B.prompt_tokens||0)+(B.completion_tokens||0),promptTokenCount:B.prompt_tokens||0,candidatesTokenCount:B.completion_tokens||0,cachedContentTokenCount:B.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:B.completion_tokens_details?.reasoning_tokens||0},R=!0),D){let H=D.thinking||D.reasoning_content||D.reasoning,Q=S(H);Q&&(w.push({text:Q,thought:!0}),R=!0);let V=D.content||(!D.thinking&&!D.reasoning_content&&!D.reasoning?D.text:null);if(V)if(Array.isArray(V))for(let F of V)if(typeof F=="object"&&F!==null){let W=F.type==="thinking"||F.type==="reasoning"||!!F.thought,ee=S(F);ee&&(w.push({text:ee,...W?{thought:!0}:{}}),R=!0)}else{let W=S(F);W&&(w.push({text:W}),R=!0)}else if(typeof V=="object"&&V!==null){let F=V.type==="thinking"||V.type==="reasoning"||!!V.thought,W=S(V);W&&(w.push({text:W,...F?{thought:!0}:{}}),R=!0)}else{let F=S(V);F&&(w.push({text:F}),R=!0)}}}catch{}if((M||Date.now()-$>=150)&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1),M)break}Date.now()-$>=150&&R&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],$=Date.now(),R=!1)}};var Ys=async function*(e,n,t,o,s,r,a=!1,i,p=1){let d=[];o&&d.push({role:"system",content:o}),t.forEach(ee=>{let Me=ee.role==="model"?"assistant":"user",I=[];Array.isArray(ee.parts)&&ee.parts.forEach(U=>{if(U.text)I.push({type:"text",text:U.text});else if(U.inlineData&&a){let X=U.inlineData.mimeType,te=U.inlineData.data;X.startsWith("image/")&&Et(n)&&I.push({type:"image_url",image_url:{url:`data:${X};base64,${te}`}})}}),d.push({role:Me,content:I.length===1&&I[0].type==="text"?I[0].text:I})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",f=l!=="Fast",u=n.includes("kimi"),m=n.includes("gemma"),g=n.includes("deepseek"),y=n.includes("glm"),h=n.includes("mistral"),x=n.includes("minimax"),w=n.includes("gpt"),T=n.includes("qwen"),$=n.includes("nemotron"),R=n.includes("llama-3"),S=n.includes("seed"),k=n.includes("poolside"),_=n.includes("thinkingmachines")||n.includes("muse"),E=R,b=null,C={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},M={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},O={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},D=x||g||k||_?16384:32768;D=process.env.NVIDIA_BASE_URL?1024:D,D=b?1024:D;let B={model:n,messages:d,max_tokens:D,stream:!0,stream_options:{include_usage:!0},temperature:p,...w&&{thinking:C[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||E||b))if(u)B.chat_template_kwargs={thinking:f};else if(m)B.chat_template_kwargs={enable_thinking:f};else if(g)if(f){let ee=l==="High"?"max":"high";B.chat_template_kwargs={thinking:!0,reasoning_effort:ee}}else B.chat_template_kwargs={thinking:!1};else y?B.chat_template_kwargs={enable_thinking:f,clear_thinking:!f}:h?B.reasoning_effort=f?"high":"none":x&&n.includes("minimax-m3")?B.chat_template_kwargs={thinking_mode:f?"enabled":"disabled"}:T?B.chat_template_kwargs={enable_thinking:f}:$?l==="High"?B.chat_template_kwargs={enable_thinking:!0}:l==="Standard"?B.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}:B.chat_template_kwargs={enable_thinking:!1}:S?f&&(B.extra_body={thinking_budget:parseInt(M[l]??"4096")}):k?B.chat_template_kwargs={enable_thinking:f}:_&&(B.reasoning_effort=O[l]||"medium");let H=0,Q=6,V=!1,F=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",W=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:e;for(F.endsWith("/chat/completions")||(F=F.replace(/\/+$/,"")+"/chat/completions");H<Q;){H++;try{let ee=await gt(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${W}`},body:JSON.stringify(B),signal:i});if(!ee.ok){let Ze=await ee.text().catch(()=>""),ct=ee.statusText;try{let yt=JSON.parse(Ze);ct=yt.error?.message||yt.message||JSON.stringify(yt.detail||yt)}catch{Ze&&(ct=Ze)}let He=new Error(`NVIDIA API Error (${ee.status}): ${ct}`);throw He.status=ee.status,He}let Me=ee.body.getReader(),I=new TextDecoder,U="",X=[],te=null,We=Date.now(),Ne=!1;for(;;){let{done:Ze,value:ct}=await Me.read();if(Ze){Ne&&(X.length>0||te)&&(yield{candidates:X.length>0?[{content:{parts:X}}]:[],usageMetadata:te},V=!0);break}U+=I.decode(ct,{stream:!0});let He=U.split(`
913
- `);U=He.pop();let yt=!1;for(let To of He){let St=To.trim();if(St){if(St==="data: [DONE]"){yt=!0;break}if(St.startsWith("data: ")){let Ke;try{Ke=JSON.parse(St.substring(6))}catch{continue}if(Ke.error)throw new Error(`NVIDIA Stream Error: ${Ke.error.message||JSON.stringify(Ke.error)}`);try{let Ct=Ke.usage;Ct&&(te={totalTokenCount:Ct.total_tokens||Ct.prompt_tokens+Ct.completion_tokens,promptTokenCount:Ct.prompt_tokens||0,candidatesTokenCount:Ct.completion_tokens||0,cachedContentTokenCount:Ct.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Ct.completion_tokens_details?.reasoning_tokens||0)+(Ct.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let Ye=Ke.choices?.[0]?.delta?.reasoning||Ke.choices?.[0]?.delta?.reasoning_content||"",we=Ke.choices?.[0]?.delta?.content||"";Ye&&(X.push({text:Ye,thought:!0}),Ne=!0),we&&(X.push({text:we}),Ne=!0)}catch{}}}}if((yt||Date.now()-We>=350)&&Ne&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:te},V=!0,X=[],We=Date.now(),Ne=!1),yt)break}break}catch(ee){if(V||H>=Q)throw ee;await new Promise(Me=>setTimeout(Me,3500))}}},il=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let m=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${m||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:m}=await f.next();if(m)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}};var Vs=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o}]});for(let b of t){let C=b.role==="user"?"user":"assistant",M=[];if(Array.isArray(b.parts)){for(let O of b.parts)if(O.text)M.push({type:"text",text:O.text});else if(O.inlineData&&a){let D=O.inlineData.mimeType,B=O.inlineData.data;D.startsWith("image/")?M.push({type:"image_url",image_url:{url:`data:${D};base64,${B}`}}):M.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${D};base64,${B}`}})}}else{let O=b.text||"";O&&M.push({type:"text",text:O})}c.push({role:C,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=["free","nitro","floor","exact","extended","beta","online"],u=n,m=null;if(n.includes(":")){let b=n.split(":"),C=b[b.length-1].toLowerCase().trim();if(f.includes(C))u=n.trim();else{let M=b.pop().trim();u=b.join(":").trim(),M&&(m={order:[M],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${u}${m?JSON.stringify(m):""}`,y=await qs(g),h={model:u,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};m&&(h.provider=m);let x=l[s];x&&s!=="Fast"&&(h.reasoning_effort=x);let w=await gt("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(h),signal:i});if(!w.ok){let b=await w.json().catch(()=>({})),C=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||w.statusText||"Unknown error";throw new Error(`OpenRouter Error (${w.status}): ${C}`)}let T=w.body.getReader(),$=new TextDecoder,R="",S=[],k=null,_=Date.now(),E=!1;for(;;){let{done:b,value:C}=await T.read();if(b){E&&(S.length>0||k)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:k});break}R+=$.decode(C,{stream:!0});let M=R.split(`
914
+ `);U=He.pop();let yt=!1;for(let To of He){let St=To.trim();if(St){if(St==="data: [DONE]"){yt=!0;break}if(St.startsWith("data: ")){let Ke;try{Ke=JSON.parse(St.substring(6))}catch{continue}if(Ke.error)throw new Error(`NVIDIA Stream Error: ${Ke.error.message||JSON.stringify(Ke.error)}`);try{let Ct=Ke.usage;Ct&&(te={totalTokenCount:Ct.total_tokens||Ct.prompt_tokens+Ct.completion_tokens,promptTokenCount:Ct.prompt_tokens||0,candidatesTokenCount:Ct.completion_tokens||0,cachedContentTokenCount:Ct.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Ct.completion_tokens_details?.reasoning_tokens||0)+(Ct.completion_tokens_details?.thoughts_tokens||0)},Ne=!0);let Ye=Ke.choices?.[0]?.delta?.reasoning||Ke.choices?.[0]?.delta?.reasoning_content||"",xe=Ke.choices?.[0]?.delta?.content||"";Ye&&(X.push({text:Ye,thought:!0}),Ne=!0),xe&&(X.push({text:xe}),Ne=!0)}catch{}}}}if((yt||Date.now()-We>=350)&&Ne&&(yield{candidates:X.length>0?[{content:{parts:[...X]}}]:[],usageMetadata:te},V=!0,X=[],We=Date.now(),Ne=!1),yt)break}break}catch(ee){if(V||H>=Q)throw ee;await new Promise(Me=>setTimeout(Me,3500))}}},il=async function*(e,n){let t=[],o=null,s=!1,r=null,a=f=>{if(t.push(f),o){let u=o;o=null,u()}},i=n.split("/").pop();i=i.replace("llama-3.3","llama-3_3");let p=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${i}`,d=!1,c=null,l=async()=>{try{let f=await fetch(p);if(f.ok){let u=await f.json();if(u&&u.queues&&u.queues[0]&&typeof u.queues[0].queueDepth=="number"){let m=u.queues[0].queueDepth;d||a({value:{type:"status",content:`Queue ${m||1}`},done:!1})}}}catch{}};process.env.NVIDIA_BASE_URL||(l(),c=setInterval(l,5e3)),(async()=>{try{let f=e[Symbol.asyncIterator]();for(;;){let{value:u,done:m}=await f.next();if(m)break;d=!0,c&&(clearInterval(c),c=null),a({value:u,done:!1})}s=!0,a(null)}catch(f){if(r=f,c&&(clearInterval(c),c=null),o){let u=o;o=null,u()}}})();try{for(;;){if(r)throw r;if(t.length>0){let f=t.shift();if(f===null&&s)break;yield f.value}else{if(s)break;await new Promise(f=>{o=f})}}}finally{c&&(clearInterval(c),c=null)}};var Vs=async function*(e,n,t,o,s,r,a,i,p=1,d=null){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o}]});for(let b of t){let C=b.role==="user"?"user":"assistant",M=[];if(Array.isArray(b.parts)){for(let O of b.parts)if(O.text)M.push({type:"text",text:O.text});else if(O.inlineData&&a){let D=O.inlineData.mimeType,B=O.inlineData.data;D.startsWith("image/")?M.push({type:"image_url",image_url:{url:`data:${D};base64,${B}`}}):M.push({type:"file",file:{filename:O.filename||"file",file_data:`data:${D};base64,${B}`}})}}else{let O=b.text||"";O&&M.push({type:"text",text:O})}c.push({role:C,content:M.length===1&&M[0].type==="text"?M[0].text:M})}let l={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},f=["free","nitro","floor","exact","extended","beta","online"],u=n,m=null;if(n.includes(":")){let b=n.split(":"),C=b[b.length-1].toLowerCase().trim();if(f.includes(C))u=n.trim();else{let M=b.pop().trim();u=b.join(":").trim(),M&&(m={order:[M],allow_fallbacks:!1})}}let g=`${e.slice(-5)}${d||""}${s}${u}${m?JSON.stringify(m):""}`,y=await qs(g),h={model:u,messages:c,stream:!0,temperature:p,cache_control:{type:"ephemeral"},session_id:y};m&&(h.provider=m);let x=l[s];x&&s!=="Fast"&&(h.reasoning_effort=x);let w=await gt("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(h),signal:i});if(!w.ok){let b=await w.json().catch(()=>({})),C=b.error?.metadata?.raw||b.error?.message||(typeof b.error=="string"?b.error:"")||w.statusText||"Unknown error";throw new Error(`OpenRouter Error (${w.status}): ${C}`)}let T=w.body.getReader(),$=new TextDecoder,R="",S=[],k=null,_=Date.now(),E=!1;for(;;){let{done:b,value:C}=await T.read();if(b){E&&(S.length>0||k)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:k});break}R+=$.decode(C,{stream:!0});let M=R.split(`
914
915
  `);R=M.pop();for(let O of M){let D=O.trim();if(!D||!D.startsWith("data: "))continue;let B=!1;if(D==="data: [DONE]")B=!0;else try{let H=JSON.parse(D.substring(6));if(H.error){let F=H.error.metadata?.raw||H.error.message||JSON.stringify(H.error);throw new Error(`OpenRouter Stream Error: ${F}`)}let Q=H.choices?.[0]?.delta,V=H.usage;if(H.choices?.[0]?.finish_reason&&(B=!0),V&&(k={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||V.prompt_tokens_details?.cache_read_input_tokens||V.cache_read_input_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},E=!0),Q){let F=Q.reasoning||(Q.reasoning_details?Q.reasoning_details.map(W=>W.text).join(""):null);F&&(S.push({text:F,thought:!0}),E=!0),Q.content&&(S.push({text:Q.content}),E=!0)}}catch(H){if(H.message&&H.message.startsWith("OpenRouter Stream Error:"))throw H}if((B||Date.now()-_>=150)&&E&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:k},S=[],_=Date.now(),E=!1),B)break}}};import{Ollama as Xc}from"ollama";var gi=async function*(e,n,t,o,s,r,a,i,p=1,d="Cloud"){let c=[];o&&c.push({role:"system",content:o});for(let S of t){let k=S.role==="user"?"user":"assistant",_="",E=[];if(Array.isArray(S.parts)){_=S.parts.map(b=>b.text||"").filter(Boolean).join(`
915
916
  `);for(let b of S.parts){let C=b.inlineData||b.inline_data;C&&C.data&&E.push(C.data)}}else _=S.text||"";if(_||E.length>0){let b={role:k,content:_};E.length>0&&(b.images=E),c.push(b)}}let l=d==="Local"||!e||e==="LOCAL",u={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&e&&(u.headers={Authorization:"Bearer "+e});let m=new Xc(u),g=[],y=null,h=Date.now(),x=!1,w={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},T=w[s]!==void 0?w[s]:!0,$={model:n,messages:c,stream:!0,think:T,keep_alive:"10m",options:{temperature:p}},R=await m.chat($);for await(let S of R){if(i?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(S.message?.thinking&&(g.push({text:S.message.thinking,thought:!0}),x=!0),S.message?.content&&(g.push({text:S.message.content}),x=!0),S.done){let k=S.prompt_cached_count||0;if(!k&&S.prompt_eval_count){let _=S.prompt_eval_duration||0;_>0&&_<5e7&&(k=S.prompt_eval_count)}y={totalTokenCount:(S.prompt_eval_count||0)+(S.eval_count||0),promptTokenCount:S.prompt_eval_count||0,candidatesTokenCount:S.eval_count||0,cachedContentTokenCount:k,thoughtsTokenCount:0},x=!0}(S.done||Date.now()-h>=150&&x)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y},g=[],h=Date.now(),x=!1)}x&&(g.length>0||y)&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:y})};var Xs=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let T of t){let $=T.role==="user"?"user":"assistant",R=[];if(Array.isArray(T.parts)){for(let S of T.parts)if(S.text)R.push({type:"text",text:S.text});else if(S.inlineData&&a){let k=S.inlineData.mimeType,_=S.inlineData.data;k.startsWith("image/")&&R.push({type:"image_url",image_url:{url:`data:${k};base64,${_}`}})}}else{let S=T.text||"";S&&R.push({type:"text",text:S})}d.push({role:$,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let c={Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},temperature:p,max_completion_tokens:32768};c[s]&&(l.reasoning_effort=c[s]);let f=await gt("https://crof.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:i});if(!f.ok){let T=await f.json().catch(()=>({}));throw new Error(`CrofAI Error (${f.status}): ${T.error?.message||f.statusText}`)}let u=f.body.getReader(),m=new TextDecoder,g="",y=[],h=null,x=Date.now(),w=!1;for(;;){let{done:T,value:$}=await u.read();if(T){w&&(y.length>0||h)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:h});break}g+=m.decode($,{stream:!0});let R=g.split(`
916
917
  `);g=R.pop();for(let S of R){let k=S.trim();if(!k||!k.startsWith("data: "))continue;let _=!1;if(k==="data: [DONE]")_=!0;else try{let E=JSON.parse(k.substring(6)),b=E.choices?.[0]?.delta,C=E.usage;if(E.choices?.[0]?.finish_reason&&(_=!0),C&&(h={totalTokenCount:C.total_tokens||(C.prompt_tokens||0)+(C.completion_tokens||0),promptTokenCount:C.prompt_tokens||0,candidatesTokenCount:C.completion_tokens||0,cachedContentTokenCount:C.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:C.completion_tokens_details?.reasoning_tokens||C.reasoning_tokens||0},w=!0),b){let M=b.reasoning_content||null;M&&(y.push({text:M,thought:!0}),w=!0),b.content&&(y.push({text:b.content}),w=!0)}}catch{}if((_||Date.now()-x>=150)&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],x=Date.now(),w=!1),_)break}Date.now()-x>=150&&w&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:h},y=[],x=Date.now(),w=!1)}};var Js=async function*(e,n,t,o,s,r,a,i,p=1){let d=[];o&&d.push({role:"system",content:o});for(let S of t){let k=S.role==="user"?"user":"assistant",_="";if(Array.isArray(S.parts))for(let E of S.parts)E.text&&(_+=(_?`
@@ -933,7 +934,7 @@ ${l[7]}`};import{WebSocket as js}from"ws";var Kt=null,Bo=!1,qc="ws://localhost:5
933
934
  ${O.length>8192?`... (truncated) ...
934
935
 
935
936
  `:""}
936
- [AGENT (current turn)]: ${M}`;R.push({role:"user",parts:[{text:H}]});let Q=await pr("NVIDIA"),F=(await tn()).quotas?.providerTiers?.NVIDIA==="Free",W="",ee=0,Me=w?12:-1;for(;ee<=Me;)try{if(!await Di("background",e))return;let I="",U=null,X=!1,te=h;try{let Ze=new Promise((Ye,we)=>setTimeout(()=>we(new Error("JANITOR_TIMEOUT")),1e4)),ct=h==="Google"&&ee>=0&&ee<6&&Q&&F,He=h==="DeepSeek"&&ee<4&&Q&&F;X=ct||He,te=X?"NVIDIA":h;let yt=(async()=>{if(h==="OpenRouter"){let Ye=he("janitor_open_router"),ce=Vs(x,Ye,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),nt=await ce.next();return{iterator:ce,firstResult:nt}}else if(h==="DeepSeek"&&!X){let we=zs(x,he("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="Mistral"&&!X){let we=Ks(x,he("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="NVIDIA"||X){let we=Ys(X?Q:x,he("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="CrofAI"){let we=Xs(x,targetModel||he("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="InferX"){let we=Js(x,targetModel||he("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="SenseNova"){let we=Qs(x,targetModel||he("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="AIHubMix"){let we=Zs(x,targetModel||he("aihubmix_fallback")||"gpt-4o-mini",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="Poolside"){let we=er(x,targetModel||he("poolside_fallback")||"poolside/laguna-s-2.1",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else if(h==="9router"||h==="9Router"){let we=tr(x,targetModel||he("9router_fallback")||"z-ai/glm-5.3-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await we.next();return{iterator:we,firstResult:ce}}else{let ce=(await bi(x).models.generateContentStream({model:u||(ee===Me?he("janitor_default"):he("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:to.HARM_CATEGORY_HARASSMENT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_HATE_SPEECH,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:eo.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:pt.MINIMAL}}}))[Symbol.asyncIterator](),nt=await ce.next();return{iterator:ce,firstResult:nt}}})();if(process.stdout.isTTY){let ce=(await fo())[m]?.name||"",nt=ce&&!ce.startsWith("flow-")&&!ce.startsWith("Session ")?ce:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${nt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${nt}\x07`)}let{iterator:To,firstResult:St}=await Promise.race([yt,Ze]),{value:Ke,done:Ct}=St;if(!Ct&&Ke){let Ye=Ke.candidates?.[0]?.content?.parts,we=Ye?te==="Google"?Ye[1]?.text||Ye[0]?.text||"":Ye.filter(ce=>ce.text&&!ce.thought).map(ce=>ce.text).join(""):typeof Ke.text=="function"?Ke.text():"";we&&(I+=we),U=Ke.usageMetadata;for await(let ce of{[Symbol.asyncIterator]:()=>To}){let nt=ce.candidates?.[0]?.content?.parts,ys=nt?te==="Google"?nt[1]?.text||nt[0]?.text||"":nt.filter(An=>An.text&&!An.thought).map(An=>An.text).join(""):typeof ce.text=="function"?ce.text():"";ys&&(I+=ys),U=ce.usageMetadata}}}catch(Ze){throw Ze}if(I){if(W=I,U){let Ze=U.totalTokenCount||0,ct=U.cachedContentTokenCount||0,He=(U.candidatesTokenCount||0)+(U.thoughtsTokenCount||0),yt=X?he("nvidia_janitor_fallback"):te==="DeepSeek"?he("deepseek_fast_fallback"):te==="OpenRouter"?he("janitor_open_router"):u||(ee===Me?he("janitor_default"):he("gemma_janitor_fallback_google"));await zt("tokens",Ze,te,yt),ct>0&&await zt("cachedTokens",ct,te,yt),He>0&&await zt("candidateTokens",He,te,yt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let We=sr(W),Ne=!1;for(let Ze of We){let ct=Ze.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ct)&&(Ne=!0);let He={chatId:m,sessionId:m,history:o},yt=await ms(ct,Ze.args,He);ct.toLowerCase()==="memory"&&(Ze.args.includes("action='user'")||Ze.args.includes('action="user"'))&&!yt.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(St=>setTimeout(St,3e3)))}if(!Ne)try{let Ze=oe(Ft,[]);if(Ze.length>0){let ct=[];for(let He of Ze)He.score===void 0&&(He.score=.5),He.score*=.99995,He.score<.05&&(He.score=0),He.score=Math.round(He.score*1e5)/1e5,He.score>0&&ct.push(He);me(Ft,ct)}}catch{}break}catch(I){ee++;let U=new Date().toLocaleString(),X=I instanceof Error?(()=>{try{return JSON.parse(JSON.parse(I.message).error.message).error.message}catch{return String(I)}})():String(I);await new Promise(Ne=>setTimeout(Ne,1e3));let te=Z.join(hn,"janitor");if(Fe.existsSync(te)||Fe.mkdirSync(te,{recursive:!0}),Fe.appendFileSync(Z.join(te,"error.log"),`ERROR [Attempt ${ee}/${Me+1}] [${U}]: ${X}
937
+ [AGENT (current turn)]: ${M}`;R.push({role:"user",parts:[{text:H}]});let Q=await pr("NVIDIA"),F=(await tn()).quotas?.providerTiers?.NVIDIA==="Free",W="",ee=0,Me=w?12:-1;for(;ee<=Me;)try{if(!await Di("background",e))return;let I="",U=null,X=!1,te=h;try{let Ze=new Promise((Ye,xe)=>setTimeout(()=>xe(new Error("JANITOR_TIMEOUT")),1e4)),ct=h==="Google"&&ee>=0&&ee<6&&Q&&F,He=h==="DeepSeek"&&ee<4&&Q&&F;X=ct||He,te=X?"NVIDIA":h;let yt=(async()=>{if(h==="OpenRouter"){let Ye=ge("janitor_open_router"),ce=Vs(x,Ye,R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),nt=await ce.next();return{iterator:ce,firstResult:nt}}else if(h==="DeepSeek"&&!X){let xe=zs(x,ge("deepseek_fast_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="Mistral"&&!X){let xe=Ks(x,ge("mistral_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="NVIDIA"||X){let xe=Ys(X?Q:x,ge("nvidia_janitor_fallback"),R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="CrofAI"){let xe=Xs(x,targetModel||ge("crofai_fallback")||"deepseek-v4-flash-0731",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="InferX"){let xe=Js(x,targetModel||ge("inferx_fallback")||"deepseek-v4-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="SenseNova"){let xe=Qs(x,targetModel||ge("sensenova_fallback")||"sensenova-6.8-flash-lite",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="AIHubMix"){let xe=Zs(x,targetModel||ge("aihubmix_fallback")||"gpt-4o-mini",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="Poolside"){let xe=er(x,targetModel||ge("poolside_fallback")||"poolside/laguna-s-2.1",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else if(h==="9router"||h==="9Router"){let xe=tr(x,targetModel||ge("9router_fallback")||"z-ai/glm-5.3-flash",R,C,"Fast",f,!1,null,.7)[Symbol.asyncIterator](),ce=await xe.next();return{iterator:xe,firstResult:ce}}else{let ce=(await bi(x).models.generateContentStream({model:u||(ee===Me?ge("janitor_default"):ge("gemma_janitor_fallback_google")),contents:R,config:{systemInstruction:C,temperature:.7,safetySettings:[{category:to.HARM_CATEGORY_HARASSMENT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_HATE_SPEECH,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:eo.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:pt.MINIMAL}}}))[Symbol.asyncIterator](),nt=await ce.next();return{iterator:ce,firstResult:nt}}})();if(process.stdout.isTTY){let ce=(await fo())[m]?.name||"",nt=ce&&!ce.startsWith("flow-")&&!ce.startsWith("Session ")?ce:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${nt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${nt}\x07`)}let{iterator:To,firstResult:St}=await Promise.race([yt,Ze]),{value:Ke,done:Ct}=St;if(!Ct&&Ke){let Ye=Ke.candidates?.[0]?.content?.parts,xe=Ye?te==="Google"?Ye[1]?.text||Ye[0]?.text||"":Ye.filter(ce=>ce.text&&!ce.thought).map(ce=>ce.text).join(""):typeof Ke.text=="function"?Ke.text():"";xe&&(I+=xe),U=Ke.usageMetadata;for await(let ce of{[Symbol.asyncIterator]:()=>To}){let nt=ce.candidates?.[0]?.content?.parts,ys=nt?te==="Google"?nt[1]?.text||nt[0]?.text||"":nt.filter(An=>An.text&&!An.thought).map(An=>An.text).join(""):typeof ce.text=="function"?ce.text():"";ys&&(I+=ys),U=ce.usageMetadata}}}catch(Ze){throw Ze}if(I){if(W=I,U){let Ze=U.totalTokenCount||0,ct=U.cachedContentTokenCount||0,He=(U.candidatesTokenCount||0)+(U.thoughtsTokenCount||0),yt=X?ge("nvidia_janitor_fallback"):te==="DeepSeek"?ge("deepseek_fast_fallback"):te==="OpenRouter"?ge("janitor_open_router"):u||(ee===Me?ge("janitor_default"):ge("gemma_janitor_fallback_google"));await zt("tokens",Ze,te,yt),ct>0&&await zt("cachedTokens",ct,te,yt),He>0&&await zt("candidateTokens",He,te,yt)}}else throw new Error("No synthesis generated by Janitor.");d&&(d(),await Ot("background"));let We=sr(W),Ne=!1;for(let Ze of We){let ct=Ze.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(ct)&&(Ne=!0);let He={chatId:m,sessionId:m,history:o},yt=await ms(ct,Ze.args,He);ct.toLowerCase()==="memory"&&(Ze.args.includes("action='user'")||Ze.args.includes('action="user"'))&&!yt.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(St=>setTimeout(St,3e3)))}if(!Ne)try{let Ze=oe(Ft,[]);if(Ze.length>0){let ct=[];for(let He of Ze)He.score===void 0&&(He.score=.5),He.score*=.99995,He.score<.05&&(He.score=0),He.score=Math.round(He.score*1e5)/1e5,He.score>0&&ct.push(He);he(Ft,ct)}}catch{}break}catch(I){ee++;let U=new Date().toLocaleString(),X=I instanceof Error?(()=>{try{return JSON.parse(JSON.parse(I.message).error.message).error.message}catch{return String(I)}})():String(I);await new Promise(Ne=>setTimeout(Ne,1e3));let te=Z.join(hn,"janitor");if(Fe.existsSync(te)||Fe.mkdirSync(te,{recursive:!0}),Fe.appendFileSync(Z.join(te,"error.log"),`ERROR [Attempt ${ee}/${Me+1}] [${U}]: ${X}
937
938
 
938
939
  `),ee>Me)break;let We=Math.min(750*Math.pow(2,ee-1),5e3);await new Promise(Ne=>setTimeout(Ne,We))}if(ee){let I=Z.join(hn,"janitor");Fe.appendFileSync(Z.join(I,"error.log"),`-----------------------------------------------------------------------------
939
940
 
@@ -962,7 +963,7 @@ ${m}
962
963
  `):a+=`-- Individual Memories:
963
964
  ${m}
964
965
 
965
- `}let p=0,d=5,c=!1,l=he("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=he("janitor_open_router")),o==="DeepSeek"&&(l=he("deepseek_level_1")),o==="Mistral"&&(l=he("mistral_level_1")),o==="NVIDIA"&&(l=he("nvidia_janitor_fallback")),o==="CrofAI"&&(l=he("crofai_fallback")),o==="InferX"&&(l=he("inferx_fallback")),o==="SenseNova"&&(l=he("sensenova_fallback")),o==="AIHubMix"&&(l=he("aihubmix_fallback")),o==="Poolside"&&(l=he("poolside_fallback")),(o==="9router"||o==="9Router")&&(l=he("9router_fallback"));p<=d&&!c;){p++;try{let u=(await or(n,l,a,null,"Fast",.75,"background")).text||"",m=sr(u);if(m.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of m){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ms(y,g.args,{chatId:e})}c=!0}catch(f){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=Z.join(hn,"janitor");Fe.existsSync(r)||Fe.mkdirSync(r,{recursive:!0}),Fe.appendFileSync(Z.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
966
+ `}let p=0,d=5,c=!1,l=ge("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=ge("janitor_open_router")),o==="DeepSeek"&&(l=ge("deepseek_level_1")),o==="Mistral"&&(l=ge("mistral_level_1")),o==="NVIDIA"&&(l=ge("nvidia_janitor_fallback")),o==="CrofAI"&&(l=ge("crofai_fallback")),o==="InferX"&&(l=ge("inferx_fallback")),o==="SenseNova"&&(l=ge("sensenova_fallback")),o==="AIHubMix"&&(l=ge("aihubmix_fallback")),o==="Poolside"&&(l=ge("poolside_fallback")),(o==="9router"||o==="9Router")&&(l=ge("9router_fallback"));p<=d&&!c;){p++;try{let u=(await or(n,l,a,null,"Fast",.75,"background")).text||"",m=sr(u);if(m.length===0)throw new Error("No tool calls detected in synthesis response");for(let g of m){let y=g.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ms(y,g.args,{chatId:e})}c=!0}catch(f){if(p>=d)throw new Error(`Failed after ${d} attempts. Last error: ${f.message}`)}}}catch(o){let s=o instanceof Error?(()=>{try{return JSON.parse(JSON.parse(o.message).error.message).error.message}catch{return String(o)}})():String(o),r=Z.join(hn,"janitor");Fe.existsSync(r)||Fe.mkdirSync(r,{recursive:!0}),Fe.appendFileSync(Z.join(r,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
966
967
  `)}},Sd=async(e,n,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=e,r=Z.join(Ts,"chat-summaries.json"),a=u=>u.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&m.role!=="think"&&!m.isVisualFeedback&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.includes("[TERMINAL_RECORD]"))&&!String(m.id).startsWith("welcome")).map(m=>{let g=m.fullText||m.text||"",y=m.role==="system"||g.startsWith("[TOOL RESULT]:")||m.text&&m.text.startsWith("[TOOL RESULT]:"),h=g;return y&&(g.includes("[TOOL RESULT]:")||m.text&&m.text.includes("[TOOL RESULT]:"))?h="[TOOL RESULT]: ...truncated for summary":h=h.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":m.role==="agent"?"AGENT":"USER"}]: ${h}`}).join(`
967
968
 
968
969
  `),i=async(u,m)=>{let g="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.",y=m?`Here is the previous summary:
@@ -974,9 +975,9 @@ ${u}
974
975
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
975
976
  ${u}
976
977
 
977
- Provide a consolidated summary of the entire session.`,h=he("gemma_janitor_fallback_google");s==="OpenRouter"&&(h=he("janitor_open_router")),s==="DeepSeek"&&(h=he("deepseek_level_1")),s==="Mistral"&&(h=he("mistral_level_1")),s==="NVIDIA"&&(h=he("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(h=he("crofai_fallback")),s==="InferX"&&(h=he("inferx_fallback")),s==="SenseNova"&&(h=he("sensenova_fallback")),s==="AIHubMix"&&(h=he("aihubmix_fallback")),s==="Poolside"&&(h=he("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=he("9router_fallback"));let x=0,w=!1,T=null;for(;x<=3&&!w;){x++;try{T=await or(e,h,y,g,"Fast"),w=!0}catch{if(x>3){if(s==="Google")try{let R=he("general_fallback");return(await or(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=oe(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=pd(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,me(r,d),f}return null},My=e=>{try{let n=Z.join(Ts,"chat-summaries.json");if(Fe.existsSync(n)){let t=oe(n,{});t[e]&&(delete t[e],me(n,t))}}catch{}},vy=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:m,wildcardTooling:g}=t,y=Et(e);if(!xi&&u==="Google")throw new Error("AI not initialized");let h=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"?!1:l?.memory!==!1,x=n[n.length-1].text,w=Z.join(Ts,"chat-summaries.json"),T=!1,$=n.filter(E=>E.role==="user").length===1,R=x.includes("[TITLE-UPDATE]"),S=$||R,k=x.replace(/\[TITLE-UPDATE\]/g,"").trim();k=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(d,k),l?.advanceRollback&&await Zn.takeInitialSnapshot(d),It=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{It&&(E.abort(),_&&(clearInterval(_),_=null))},400);let b=[...n.slice(0,-1)];{let Pe=oe(w,{})[d]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let sn=0,Ee=[];for(let ot=0;ot<b.length;ot++){let qe=b[ot];(qe.role==="user"||qe.role==="agent"||qe.role==="system")&&!String(qe.id).startsWith("welcome")&&!qe.isMeta&&sn++,sn>Pe.historyLength&&Ee.push(qe)}b=Ee}}b=b.map(z=>{if(z.role==="user"&&z.text){let Pe=z.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...z,text:Pe[1].trim()}}return{...z}});let C=process.env.HIGH_CONTEXT,M=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,O=255e3,D=26e4;if(C&&C!=="false"){let z=parseInt(C,10);!isNaN(z)&&z>=0&&z<=1e6&&(D=z,O=Math.round(z*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(O=122e3,D=126e3),u==="Google"&&e?.includes("gemma")&&M&&(O=14e3,D=16e3),(u==="Ollama"||u==="9router"||u==="9Router")&&(f?.tokens||0)>O){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(u!=="Ollama"&&u!=="9router"&&u!=="9Router"&&(f?.tokens||0)>O&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Sd(t,b,!0)&&(b=[],T=!0)),$&&h){let z=oe(en,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await bd(d,t,z))}let B=oe(en,{}),H=oe(Pn,{}),Q=Object.entries(B).filter(([z])=>z!==d).flatMap(([z,Pe])=>Pe),F=[...Object.entries(H).filter(([z])=>z!==d).slice(-20).map(([z,Pe])=>`[Chat Summary]: ${Pe}`),...Q].map(z=>`- ${z}`).join(`
978
+ Provide a consolidated summary of the entire session.`,h=ge("gemma_janitor_fallback_google");s==="OpenRouter"&&(h=ge("janitor_open_router")),s==="DeepSeek"&&(h=ge("deepseek_level_1")),s==="Mistral"&&(h=ge("mistral_level_1")),s==="NVIDIA"&&(h=ge("nvidia_chat_summarizer_fallback")),s==="CrofAI"&&(h=ge("crofai_fallback")),s==="InferX"&&(h=ge("inferx_fallback")),s==="SenseNova"&&(h=ge("sensenova_fallback")),s==="AIHubMix"&&(h=ge("aihubmix_fallback")),s==="Poolside"&&(h=ge("poolside_fallback")),(s==="9router"||s==="9Router")&&(h=ge("9router_fallback"));let x=0,w=!1,T=null;for(;x<=3&&!w;){x++;try{T=await or(e,h,y,g,"Fast"),w=!0}catch{if(x>3){if(s==="Google")try{let R=ge("general_fallback");return(await or(e,R,y,g,"Fast")).text||""}catch{return""}return""}}}return T&&T.text||""},p=a(n),d=oe(r,{}),c=d[o]||{summary:"",historyLength:0};typeof c=="string"&&(c={summary:c,historyLength:0});let l=c.summary||"",f=await i(p,l);if(f){c.summary=f;let u=pd(n);return t?c.historyLength=(c.historyLength||0)+u:c.historyLength=u,d[o]=c,he(r,d),f}return null},My=e=>{try{let n=Z.join(Ts,"chat-summaries.json");if(Fe.existsSync(n)){let t=oe(n,{});t[e]&&(delete t[e],he(n,t))}}catch{}},vy=async function*(e,n,t,o,s){let{profile:r,thinkingLevel:a,mode:i,janitorModel:p,chatId:d,isPlayground:c,systemSettings:l,sessionStats:f,aiProvider:u="Google",apiTier:m,wildcardTooling:g}=t,y=Et(e);if(!xi&&u==="Google")throw new Error("AI not initialized");let h=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"||t?.aiProvider==="CrofAI"||t?.aiProvider==="InferX"||t?.aiProvider==="SenseNova"||t?.aiProvider==="AIHubMix"||t?.aiProvider==="Poolside"||t?.aiProvider==="9router"?!1:l?.memory!==!1,x=n[n.length-1].text,w=Z.join(Ts,"chat-summaries.json"),T=!1,$=n.filter(E=>E.role==="user").length===1,R=x.includes("[TITLE-UPDATE]"),S=$||R,k=x.replace(/\[TITLE-UPDATE\]/g,"").trim();k=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ht.startTransaction(d,k),l?.advanceRollback&&await Zn.takeInitialSnapshot(d),It=!1;let _=null;try{let E=new AbortController;_=setInterval(()=>{It&&(E.abort(),_&&(clearInterval(_),_=null))},400);let b=[...n.slice(0,-1)];{let Pe=oe(w,{})[d]||{summary:"",historyLength:0};if(Pe.summary&&Pe.historyLength>0){let sn=0,Ee=[];for(let ot=0;ot<b.length;ot++){let qe=b[ot];(qe.role==="user"||qe.role==="agent"||qe.role==="system")&&!String(qe.id).startsWith("welcome")&&!qe.isMeta&&sn++,sn>Pe.historyLength&&Ee.push(qe)}b=Ee}}b=b.map(z=>{if(z.role==="user"&&z.text){let Pe=z.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Pe)return{...z,text:Pe[1].trim()}}return{...z}});let C=process.env.HIGH_CONTEXT,M=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1,O=255e3,D=26e4;if(C&&C!=="false"){let z=parseInt(C,10);!isNaN(z)&&z>=0&&z<=1e6&&(D=z,O=Math.round(z*.85))}if((u==="NVIDIA"&&(e?.includes("gpt")||e?.includes("qwen")||e?.includes("medium")||e.includes("muse"))||u==="Mistral")&&(O=122e3,D=126e3),u==="Google"&&e?.includes("gemma")&&M&&(O=14e3,D=16e3),(u==="Ollama"||u==="9router"||u==="9Router")&&(f?.tokens||0)>O){yield{type:"text",content:"\u2726 Maximum Context Limit Reached. Start a new chat."};return}if(u!=="Ollama"&&u!=="9router"&&u!=="9Router"&&(f?.tokens||0)>O&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await Sd(t,b,!0)&&(b=[],T=!0)),$&&h){let z=oe(en,{});Object.values(z).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await bd(d,t,z))}let B=oe(en,{}),H=oe(Pn,{}),Q=Object.entries(B).filter(([z])=>z!==d).flatMap(([z,Pe])=>Pe),F=[...Object.entries(H).filter(([z])=>z!==d).slice(-20).map(([z,Pe])=>`[Chat Summary]: ${Pe}`),...Q].map(z=>`- ${z}`).join(`
978
979
  `),ee=oe(Ft,[]).map(z=>`- ${z.memory}`).join(`
979
- `),Me=(f?.tokens||0)>=1e4,I=ya(F,ee,h,Me),U=new Date,X=U.getFullYear(),te=U.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(U.getDate()).padStart(2,"0"),Ne=U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ze=`${X}-${te}-${We}, ${Ne}`,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"],He=z=>{try{return Fe.readdirSync(z,{withFileTypes:!0})}catch{return[]}},yt=(z,Pe={value:0},sn=1)=>{if(Pe.value>6200||sn>7)return Pe.value;let Ee=He(z);for(let ot of Ee){if(Pe.value>6200)break;ct.includes(ot.name)||ot.name.startsWith(".")||ot.isDirectory()&&(Pe.value++,yt(Z.join(z,ot.name),Pe,sn+1))}return Pe.value},To=(z,Pe)=>l?.indentationTree!==!1?pi(z,Pe,1,He,ct):hi(z,Pe,"",1,He,ct),St=yt(process.cwd()),Ke=10;St>3072||St>2304?Ke=1:St>1536?Ke=2:St>768?Ke=3:St>384?Ke=5:St>192?Ke=6:St>96?Ke=7:(St>48||St>24)&&(Ke=9);let Ct=oe(ur,{}),Ye=Ct[d],we=Ye?Ye!==process.cwd():!1;Ct[d]=process.cwd(),me(ur,Ct);let ce=oe(w,{}),nt=ce[d]||{summary:"",historyLength:0};typeof nt=="string"&&(nt={summary:nt,historyLength:0});let ys=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;nt.historyLength&&ys<nt.historyLength&&(nt.summary="",nt.historyLength=0,ce[d]=nt,me(w,ce));let An=typeof nt=="object"?nt.summary||"":nt||"",Si=b.length>0;Si&&An&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
980
+ `),Me=(f?.tokens||0)>=1e4,I=ya(F,ee,h,Me),U=new Date,X=U.getFullYear(),te=U.toLocaleString("en-US",{month:"short"}).toUpperCase(),We=String(U.getDate()).padStart(2,"0"),Ne=U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ze=`${X}-${te}-${We}, ${Ne}`,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"],He=z=>{try{return Fe.readdirSync(z,{withFileTypes:!0})}catch{return[]}},yt=(z,Pe={value:0},sn=1)=>{if(Pe.value>6200||sn>7)return Pe.value;let Ee=He(z);for(let ot of Ee){if(Pe.value>6200)break;ct.includes(ot.name)||ot.name.startsWith(".")||ot.isDirectory()&&(Pe.value++,yt(Z.join(z,ot.name),Pe,sn+1))}return Pe.value},To=(z,Pe)=>l?.indentationTree!==!1?pi(z,Pe,1,He,ct):hi(z,Pe,"",1,He,ct),St=yt(process.cwd()),Ke=10;St>3072||St>2304?Ke=1:St>1536?Ke=2:St>768?Ke=3:St>384?Ke=5:St>192?Ke=6:St>96?Ke=7:(St>48||St>24)&&(Ke=9);let Ct=oe(ur,{}),Ye=Ct[d],xe=Ye?Ye!==process.cwd():!1;Ct[d]=process.cwd(),he(ur,Ct);let ce=oe(w,{}),nt=ce[d]||{summary:"",historyLength:0};typeof nt=="string"&&(nt={summary:nt,historyLength:0});let ys=n.filter(z=>(z.role==="user"||z.role==="agent"||z.role==="system")&&!String(z.id).startsWith("welcome")&&!z.isMeta).length;nt.historyLength&&ys<nt.historyLength&&(nt.summary="",nt.historyLength=0,ce[d]=nt,he(w,ce));let An=typeof nt=="object"?nt.summary||"":nt||"",Si=b.length>0;Si&&An&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
980
981
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
981
982
  ${An}
982
983
 
@@ -1029,7 +1030,7 @@ ${kt.warnings}
1029
1030
  `);let wl=Ei.replace(/\\(@\[[^\]]+\])/g,"$1"),xl=g?`You cannot execute tools
1030
1031
  Instead, output in chat the exact string you WOULD have produced & wait for system response
1031
1032
  `:"",bl=process.env.forcedReasoning||!1,$i=`[System Metadata]
1032
- Time: ${Ze}${l?.dynamicDirAwareness?Ri:""}${we?`
1033
+ Time: ${Ze}${l?.dynamicDirAwareness?Ri:""}${xe?`
1033
1034
  WARNING: CWD Changed from previous: "${Ye}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
1034
1035
  `:""}${I}${jn}
1035
1036
  [/Metadata]
@@ -1049,7 +1050,7 @@ ${ue}`:b.push({role:"user",text:ue}),yield{type:"status",content:"Subagent Updat
1049
1050
  [question] ${de.replace("/btw","").trim()} [/question]`:b.push({role:"user",text:`[system] User question. Resolve this specific query within '[ANSWER]...[/ANSWER]' concisely, naturally [/system]
1050
1051
  [question] ${de.replace("/btw","").trim()} [/question]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
1051
1052
 
1052
- [STEERING HINT from USER, HIGH PRIORITY] ${de.trim().toUpperCase()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, HIGH PRIORITY] ${de.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${de.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,ot=!1,qe=1,et=1,pe="",Ut=null,tt=null,rn=null,K=0,ne=[],ze=0,fn=!1,Bt=!1,kn=!1,vn=!1,no=!0,bs=0,it="",Ve="",Wt=!1,oo=!1,je=!0,be=e,Xe="";for(;qe<=Sn&&et<=Sn&&!ot&&!It;){let de=!1;try{pe="",no&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},no=!1,et===1&&(it=""));let Se=N=>{if(!N||!N.includes("[tool:"))return N;let ie="",G=yi(N);G&&(ie=G.fullBlock,N=G.remainingText),N=N.replace(ud,(ge,_e)=>_e.includes("[tool:")?_e.trim():ge);let q="",ke=0;for(;ke<N.length;){let ge=N.indexOf("[tool:",ke);if(ge===-1){q+=ul(N.substring(ke));break}let _e=N.substring(ke,ge);q+=ul(_e);let st=-1,j=null,se=0;for(let Ue=ge;Ue<N.length;Ue++){let A=N[Ue];if(j){if(A===j){let Be=0;for(let ve=Ue-1;ve>=0&&N[ve]==="\\";ve--)Be++;Be%2===0&&(j=null)}}else if(A==='"'||A==="'"||A==="`")j=A;else if(A==="(")se++;else if(A===")")se--;else if(A==="]"&&se<=0){st=Ue;break}}if(st===-1){q+=N.substring(ge);break}q+=N.substring(ge,st+1),ke=st+1}return ie+q},ue=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,ie,G)=>{let q=N.text||"";h||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(q=Se(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ke=[];return Array.isArray(N.parts)&&N.parts.length>0?ke=N.parts.map(ge=>{if(ge.text){let _e=ge.text;return h||(_e=_e.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(_e=Se(_e),_e=_e.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),_e=_e.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:_e}}return ge}):ke=[{text:q}],N.binaryPart&&Et(be)&&G.slice(ie+1).filter(_e=>_e.role==="user"&&!_e.text?.startsWith("[TOOL RESULT]")).length<=2&&ke.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:ke}});for(let N=0;N<ue.length;N++){let ie=ue[N],G=ie.parts?.[0]?.text||"";if(ie.role==="model"&&/\[tool:/i.test(G)){let q=-1;for(let ke=N+1;ke<ue.length;ke++){let ge=ue[ke],_e=ge.parts?.[0]?.text||"";if(ge.role==="user"&&_e.startsWith("[TOOL RESULT]")){q=ke;break}}if(q!==-1&&q!==N+1){let[ke]=ue.splice(q,1);ue.splice(N+1,0,ke)}}}for(let N=ue.length-2;N>=0;N--){let ie=ue[N],G=ue[N+1];ie.role==="user"&&G.role==="user"&&(G.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ue.splice(N,1)}let at=[];for(let N=0;N<ue.length;N++){let ie=ue[N];if(at.length===0)at.push(ie);else{let G=at[at.length-1];G.role===ie.role?(G.parts[0].text+=`
1053
+ [STEERING HINT from USER, High Priority] ${de.trim()} [/STEERING HINT]`:b.push({role:"user",text:`[STEERING HINT from USER, High Priority] ${de.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${de.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Ee,ot=!1,qe=1,et=1,pe="",Ut=null,tt=null,rn=null,K=0,ne=[],ze=0,fn=!1,Bt=!1,kn=!1,vn=!1,no=!0,bs=0,it="",Ve="",Wt=!1,oo=!1,je=!0,be=e,Xe="";for(;qe<=Sn&&et<=Sn&&!ot&&!It;){let de=!1;try{pe="",no&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},no=!1,et===1&&(it=""));let Se=N=>{if(!N||!N.includes("[tool:"))return N;let ie="",G=yi(N);G&&(ie=G.fullBlock,N=G.remainingText),N=N.replace(ud,(ye,_e)=>_e.includes("[tool:")?_e.trim():ye);let q="",ke=0;for(;ke<N.length;){let ye=N.indexOf("[tool:",ke);if(ye===-1){q+=ul(N.substring(ke));break}let _e=N.substring(ke,ye);q+=ul(_e);let st=-1,j=null,se=0;for(let Ue=ye;Ue<N.length;Ue++){let A=N[Ue];if(j){if(A===j){let Be=0;for(let ve=Ue-1;ve>=0&&N[ve]==="\\";ve--)Be++;Be%2===0&&(j=null)}}else if(A==='"'||A==="'"||A==="`")j=A;else if(A==="(")se++;else if(A===")")se--;else if(A==="]"&&se<=0){st=Ue;break}}if(st===-1){q+=N.substring(ye);break}q+=N.substring(ye,st+1),ke=st+1}return ie+q},ue=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,ie,G)=>{let q=N.text||"";h||(q=q.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(q=Se(q),q=q.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),q=q.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let ke=[];return Array.isArray(N.parts)&&N.parts.length>0?ke=N.parts.map(ye=>{if(ye.text){let _e=ye.text;return h||(_e=_e.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(_e=Se(_e),_e=_e.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),_e=_e.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*")),{text:_e}}return ye}):ke=[{text:q}],N.binaryPart&&Et(be)&&G.slice(ie+1).filter(_e=>_e.role==="user"&&!_e.text?.startsWith("[TOOL RESULT]")).length<=2&&ke.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:ke}});for(let N=0;N<ue.length;N++){let ie=ue[N],G=ie.parts?.[0]?.text||"";if(ie.role==="model"&&/\[tool:/i.test(G)){let q=-1;for(let ke=N+1;ke<ue.length;ke++){let ye=ue[ke],_e=ye.parts?.[0]?.text||"";if(ye.role==="user"&&_e.startsWith("[TOOL RESULT]")){q=ke;break}}if(q!==-1&&q!==N+1){let[ke]=ue.splice(q,1);ue.splice(N+1,0,ke)}}}for(let N=ue.length-2;N>=0;N--){let ie=ue[N],G=ue[N+1];ie.role==="user"&&G.role==="user"&&(G.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ue.splice(N,1)}let at=[];for(let N=0;N<ue.length;N++){let ie=ue[N];if(at.length===0)at.push(ie);else{let G=at[at.length-1];G.role===ie.role?(G.parts[0].text+=`
1053
1054
 
1054
1055
  `+(ie.parts?.[0]?.text||""),ie.parts?.length>1&&G.parts.push(...ie.parts.slice(1))):at.push(ie)}}ue.length=0,ue.push(...at),be=e;let jt=`${d}|${u}|${i}|${a}|${be}|${JSON.stringify(r)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`,Vt=So.key===jt&&So.value;if((process.env.I_HAVE_TOO_MUCH_MONEY==="true"||process.env.I_HAVE_TOO_MUCH_MONEY===!0)&&(Vt=!1),Vt)Xe=So.value;else{let N=u==="Mistral"?!!vo(be):!(be||"gemma").toLowerCase().startsWith("gemma");Xe=wa(r,((be||"gemma").toLowerCase().startsWith("gemma"),a),i,l,h,$,u,u==="Google"?!0:y,N,d),l?.dynamicDirAwareness||(Xe+=`
1055
1056
  ${Ri.replace(`
@@ -1061,19 +1062,19 @@ ${ie} [/ERROR]`),yield{type:"status",content:"Working"}}let qn=u==="Mistral"||u=
1061
1062
  `;for(let q of N.modifiedFiles)ie+=`* ${q} (modified)
1062
1063
  `;for(let q of N.deletedFiles)ie+=`* ${q} (deleted)
1063
1064
  `;ie+="[/system]",Dt.parts[0].text+=ie;let G=-1;for(let q=b.length-1;q>=0;q--)if(b[q].role==="user"&&b[q].text?.startsWith("[TOOL RESULT]")){G=q;break}G!==-1&&(b[G].text+=ie)}}catch{}let an=Math.floor(jo*(i==="Flux"?.98:.8)),Lt=z+1;Lt>=an&&Dt&&Dt.parts?.[0]&&(Dt.parts[0].text+=`
1064
- [system] WARNING, Turn Limit Impending: Step ${Lt}/${jo}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((N,ie)=>{E.signal.aborted&&ie(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ie(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let $t=ue;if(u==="Ollama")Ee=gi(t.apiKey,be,$t,Xe,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Ee=Vs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Ee=zs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="Mistral")Ee=Ks(t.apiKey,be,$t,Xe,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let N=Ys(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);Ee=il(N,be)}else if(u==="CrofAI")Ee=Xs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="InferX")Ee=Js(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="SenseNova")Ee=Qs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="AIHubMix")Ee=Zs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="Poolside")Ee=er(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="9router"||u==="9Router")Ee=tr(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else{let ie=bi(t?.apiKey).models.generateContentStream({model:be||"gemini-3-flash-preview",contents:$t,config:{systemInstruction:Xe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:to.HARM_CATEGORY_HARASSMENT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_HATE_SPEECH,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:eo.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let G=(be||"").toLowerCase(),q=G.includes("gemma-4")||G.startsWith("gemma"),ke=G.includes("gemini-3");if(q||ke)return q?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:pt.MINIMAL}:{includeThoughts:!0,thinkingLevel:pt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:G.includes("pro")?pt.LOW:pt.MINIMAL,Low:pt.LOW,Medium:pt.MEDIUM,Standard:pt.MEDIUM,High:pt.HIGH,xHigh:pt.HIGH}[a]||pt.MEDIUM};{let ge={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ge===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ge}}})()}},{signal:E.signal});Ee=await Promise.race([ie,Pt])}pe="",Ut=null,rn=null,ne=[],ze=0,yield{type:"model_update",content:null},Ve="",Wt=it.length>0;let Tn="",lr=Date.now(),io=async function*(){if(u==="Google"&&Tn){let N=Ho(Tn);for(let ie of N)yield ie;Tn="",lr=Date.now()}},vi=!0,ao="",Ro=!1,Gt=null,Tl={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Ho=N=>{let ie=[],G=N;for(;G.length>0;)if(Ro){let q=ao+G,ke=Tl[Gt];if(ke){let st=!1;if(q.length<ke.startPrefix.length?ke.startPrefix.startsWith(q)||(st=!0):q.startsWith(ke.startPrefix)?q.length>=ke.fullPrefix.length&&!q.startsWith(ke.fullPrefix)&&(st=!0):st=!0,st){ie.push({type:"text",content:q}),ao="",Ro=!1,Gt=null,G="";break}}let ge=-1,_e=ke?ke.endTag:"]";if(Gt==="tool"||Gt==="agent"){let st=0,j=null,se=0,Ue=!1;for(let A=0;A<q.length;A++){let Be=q[A];if(j){if(Be===j){let ve=0;for(let J=A-1;J>=0&&q[J]==="\\";J--)ve++;ve%2===0&&(j=null)}}else if(Be==='"'||Be==="'"||Be==="`")j=Be;else if(Be==="(")st++,Ue=!0;else if(Be===")")st--;else if(Be==="[")se++;else if(Be==="]"){if(Ue&&st===0&&se===1){ge=A;break}se--}}}else ge=q.indexOf(_e);if(ge!==-1){let st=_e.length;if(!Gt?.startsWith("kimi")){let j=q.substring(0,ge+st);ie.push({type:"text",content:j})}ao="",Ro=!1,Gt=null,G=q.substring(ge+st)}else{let st=Gt?.startsWith("kimi")?8192:512;q.length>st?(ie.push({type:"text",content:q}),ao="",Ro=!1,Gt=null):ao=q,G="";break}}else{let q=G.indexOf("[tool"),ke=G.indexOf("[agent"),ge=G.indexOf("[[END]]"),_e=G.indexOf("<|tool_calls_section_begin|>"),st=G.indexOf("<|tool_call_begin|>"),j=[{type:"tool",idx:q,start:"[tool",end:"]"},{type:"agent",idx:ke,start:"[agent",end:"]"},{type:"end",idx:ge,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:_e,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:st,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(se=>se.idx!==-1).sort((se,Ue)=>se.idx-Ue.idx);if(j.length>0){let se=j[0];se.idx>0&&ie.push({type:"text",content:G.substring(0,se.idx)}),Ro=!0,Gt=se.type,ao="",G=G.substring(se.idx)}else{let se=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ue=-1;for(let A of se){for(let Be=A.length-1;Be>0;Be--)if(G.endsWith(A.substring(0,Be))){Ue=G.length-Be;let ve=se.indexOf(A);ve===0?Gt="tool":ve===1?Gt="agent":ve===2?Gt="end":ve===3?Gt="kimi_section":Gt="kimi_call";break}if(Ue!==-1)break}if(Ue!==-1)Ue>0&&ie.push({type:"text",content:G.substring(0,Ue)}),Ro=!0,ao=G.substring(Ue),G="";else{ie.push({type:"text",content:G});break}}}return ie},Rl=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ie}=await Promise.race([Rl.next(),Pt]);if(ie)break;if(N&&N.type==="status"){yield N;continue}let G="",q=N.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let ge of q){let _e=typeof ge.text=="string"?ge.text:ge.text?parseChunkText(ge.text):"";ge.thought?_e&&(de||(G+="<think>",de=!0),G+=_e):_e&&(de&&(G+="</think>",de=!1),G+=_e)}else N.text&&de&&(G+="</think>",de=!1);G=ad(G);let ke=G?G.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(G,ke),vi&&(yield{type:"status",content:"Thinking"},vi=!1),It){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1065
+ [system] WARNING, Turn Limit Impending: Step ${Lt}/${jo}. Wrap up quickly/prompt user to continue. [/system]`);let Pt=new Promise((N,ie)=>{E.signal.aborted&&ie(new DOMException("The user aborted a request.","AbortError")),E.signal.addEventListener("abort",()=>{ie(new DOMException("The user aborted a request.","AbortError"))})});Pt.catch(()=>{});let $t=ue;if(u==="Ollama")Ee=gi(t.apiKey,be,$t,Xe,a,i,y,E.signal,1,l?.ollamaEndpoint||"Cloud");else if(u==="OpenRouter")Ee=Vs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1,d);else if(u==="DeepSeek")Ee=zs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="Mistral")Ee=Ks(t.apiKey,be,$t,Xe,a,i,y,E.signal,1,d);else if(u==="NVIDIA"){let N=Ys(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);Ee=il(N,be)}else if(u==="CrofAI")Ee=Xs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="InferX")Ee=Js(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="SenseNova")Ee=Qs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="AIHubMix")Ee=Zs(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="Poolside")Ee=er(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else if(u==="9router"||u==="9Router")Ee=tr(t.apiKey,be,$t,Xe,a,i,y,E.signal,1);else{let ie=bi(t?.apiKey).models.generateContentStream({model:be||"gemini-3-flash-preview",contents:$t,config:{systemInstruction:Xe,mediaResolution:"MEDIA_RESOLUTION_HIGH",safetySettings:[{category:to.HARM_CATEGORY_HARASSMENT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_HATE_SPEECH,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:eo.BLOCK_NONE},{category:to.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:eo.BLOCK_NONE}],temperature:1.05,thinkingConfig:(()=>{let G=(be||"").toLowerCase(),q=G.includes("gemma-4")||G.startsWith("gemma"),ke=G.includes("gemini-3");if(q||ke)return q?a.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:pt.MINIMAL}:{includeThoughts:!0,thinkingLevel:pt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:G.includes("pro")?pt.LOW:pt.MINIMAL,Low:pt.LOW,Medium:pt.MEDIUM,Standard:pt.MEDIUM,High:pt.HIGH,xHigh:pt.HIGH}[a]||pt.MEDIUM};{let ye={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[a]||2048;return ye===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:ye}}})()}},{signal:E.signal});Ee=await Promise.race([ie,Pt])}pe="",Ut=null,rn=null,ne=[],ze=0,yield{type:"model_update",content:null},Ve="",Wt=it.length>0;let Tn="",lr=Date.now(),io=async function*(){if(u==="Google"&&Tn){let N=Ho(Tn);for(let ie of N)yield ie;Tn="",lr=Date.now()}},vi=!0,ao="",Ro=!1,Gt=null,Tl={tool:{startPrefix:"[tool",fullPrefix:"[tool:functions.",endTag:"]"},agent:{startPrefix:"[agent",fullPrefix:"[agent:generalist.",endTag:"]"},end:{startPrefix:"[[END]]",fullPrefix:"[[END]]",endTag:"[[END]]"},kimi_section:{startPrefix:"<|tool_calls_section_begin|>",fullPrefix:"<|tool_calls_section_begin|>",endTag:"<|tool_calls_section_end|>"},kimi_call:{startPrefix:"<|tool_call_begin|>",fullPrefix:"<|tool_call_begin|>",endTag:"<|tool_call_end|>"}},Ho=N=>{let ie=[],G=N;for(;G.length>0;)if(Ro){let q=ao+G,ke=Tl[Gt];if(ke){let st=!1;if(q.length<ke.startPrefix.length?ke.startPrefix.startsWith(q)||(st=!0):q.startsWith(ke.startPrefix)?q.length>=ke.fullPrefix.length&&!q.startsWith(ke.fullPrefix)&&(st=!0):st=!0,st){ie.push({type:"text",content:q}),ao="",Ro=!1,Gt=null,G="";break}}let ye=-1,_e=ke?ke.endTag:"]";if(Gt==="tool"||Gt==="agent"){let st=0,j=null,se=0,Ue=!1;for(let A=0;A<q.length;A++){let Be=q[A];if(j){if(Be===j){let ve=0;for(let J=A-1;J>=0&&q[J]==="\\";J--)ve++;ve%2===0&&(j=null)}}else if(Be==='"'||Be==="'"||Be==="`")j=Be;else if(Be==="(")st++,Ue=!0;else if(Be===")")st--;else if(Be==="[")se++;else if(Be==="]"){if(Ue&&st===0&&se===1){ye=A;break}se--}}}else ye=q.indexOf(_e);if(ye!==-1){let st=_e.length;if(!Gt?.startsWith("kimi")){let j=q.substring(0,ye+st);ie.push({type:"text",content:j})}ao="",Ro=!1,Gt=null,G=q.substring(ye+st)}else{let st=Gt?.startsWith("kimi")?8192:512;q.length>st?(ie.push({type:"text",content:q}),ao="",Ro=!1,Gt=null):ao=q,G="";break}}else{let q=G.indexOf("[tool"),ke=G.indexOf("[agent"),ye=G.indexOf("[[END]]"),_e=G.indexOf("<|tool_calls_section_begin|>"),st=G.indexOf("<|tool_call_begin|>"),j=[{type:"tool",idx:q,start:"[tool",end:"]"},{type:"agent",idx:ke,start:"[agent",end:"]"},{type:"end",idx:ye,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:_e,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:st,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(se=>se.idx!==-1).sort((se,Ue)=>se.idx-Ue.idx);if(j.length>0){let se=j[0];se.idx>0&&ie.push({type:"text",content:G.substring(0,se.idx)}),Ro=!0,Gt=se.type,ao="",G=G.substring(se.idx)}else{let se=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ue=-1;for(let A of se){for(let Be=A.length-1;Be>0;Be--)if(G.endsWith(A.substring(0,Be))){Ue=G.length-Be;let ve=se.indexOf(A);ve===0?Gt="tool":ve===1?Gt="agent":ve===2?Gt="end":ve===3?Gt="kimi_section":Gt="kimi_call";break}if(Ue!==-1)break}if(Ue!==-1)Ue>0&&ie.push({type:"text",content:G.substring(0,Ue)}),Ro=!0,ao=G.substring(Ue),G="";else{ie.push({type:"text",content:G});break}}}return ie},Rl=Ee[Symbol.asyncIterator]();for(;;){let{value:N,done:ie}=await Promise.race([Rl.next(),Pt]);if(ie)break;if(N&&N.type==="status"){yield N;continue}let G="",q=N.candidates?.[0]?.content?.parts;if(q&&q.length>0)for(let ye of q){let _e=typeof ye.text=="string"?ye.text:ye.text?parseChunkText(ye.text):"";ye.thought?_e&&(de||(G+="<think>",de=!0),G+=_e):_e&&(de&&(G+="</think>",de=!1),G+=_e)}else N.text&&de&&(G+="</think>",de=!1);G=ad(G);let ke=G?G.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(G,ke),vi&&(yield{type:"status",content:"Thinking"},vi=!1),It){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1065
1066
 
1066
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(G){if(Wt){if(Ve+=G,Ve.length>=64){let j=0,se=Math.min(it.length,Ve.length);for(let A=se;A>=10;A--)if(it.endsWith(Ve.substring(0,A))){j=A;break}let Ue=Ve.substring(j);if(Ue){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(pe+=Be,u==="Google")Tn+=Be;else{yield*io();let ve=Ho(Be);for(let J of ve)yield J}}Wt=!1,Ve=""}continue}else if(pe+=G,u==="Google")Tn+=G;else{yield*io();let j=Ho(G);for(let se of j)yield se}let ge=hd(pe);if(ge.inside){oo=!0,rn||(rn=Date.now());let se={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"}[ge.toolName]||ge.toolName,Ue=ge.args||"",A=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(se)){let ve=L(Ue),J=ve.path||ve.targetFile||ve.TargetFile||ve.directory,Rn=ve.keyword,lo=ve.title||ve.task,zn=ve.id||ve.taskId,Ce=ve.timeout||ve.time;if(Rn!=null)A=String(Rn).replace(bo,"");else if(J)A=Z.basename(String(J).replace(bo,"").replace(al,"/"));else if(lo&&(se==="invoke"||se==="invoke_sync"))A=String(lo).replace(bo,"").substring(0,30);else if(zn&&se==="get_progress")A=String(zn).replace(bo,"");else if(Ce&&se==="await"){let Ht=parseFloat(String(Ce).replace(bo,""));isNaN(Ht)?A=String(Ce).replace(bo,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),A=(In=>{if(In>=60){let dr=Math.floor(In/60),Eo=In%60;return`${dr}m${Eo>0?` ${Eo}s`:""}`}return`${In}s`})(Ht))}else{let Ht=Ue.match(sd);if(Ht){let Xt=Ht[1].replace(bo,"");se==="invoke"||se==="invoke_sync"||se==="get_progress"?A=Xt.substring(0,30):A=se==="search_keyword"||se==="file_map"?Xt:Z.basename(Xt.replace(al,"/"))}}}let Be=`${wi[se]||se}${A?` ${A}`:""}`;if((se!==Ut||A!==tt)&&(Ut=se,tt=A,yield{type:"status",content:`${Be}`},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"}[se]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(pe.length-bs>150){bs=pe.length;let j=gl(pe,!1),se=yi(j),Ue=se?(se.innerContent||"").trim():"",A=Ue.split(/[.!?]\s+/),Be=new Set(A),ve=A.length>10?(A.length-Be.size)/A.length:0,J=Ue.split(/\s+/).filter(Ie=>Ie.length>0).length,Rn=.6,lo=.8,zn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((be||"").toLowerCase().startsWith("gemma")||(be||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;zn=J>v}if(ve>Rn||zn){yield{type:"status",content:`${ve>Rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Xt=fl(pe).trim().split(/[.!?]\s+/),In=new Set(Xt);if((Xt.length>10?(Xt.length-In.size)/Xt.length:0)>lo){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,vn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}let Eo=j.replace(Jc,"").replace(Qc,"").replace(Zc,"").replace(ed,""),qt=Eo.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(td,"")).filter(Ie=>Ie.length>0),On=!1;if(qt.length>=10)for(let Ie=1;Ie<=15;Ie++){let v=Math.max(3,Math.ceil(10/Ie));if(qt.length<Ie*v)continue;let Y=qt.slice(qt.length-Ie),ae=Y.join(" ");if(Ie>1&&ae===Y.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let xe=!0;for(let Te=1;Te<v;Te++)if(qt.slice(qt.length-Ie*(Te+1),qt.length-Ie*Te).join(" ")!==ae){xe=!1;break}if(xe){On=!0;break}}if(!On){let Ie=Eo.toLowerCase().replace(nd,"");if(Ie.length>=20)for(let v=1;v<=10;v++){let Y=Math.max(5,Math.ceil(16/v));if(Ie.length<v*Y)continue;let ae=Ie.substring(Ie.length-v),xe=!0;for(let Te=1;Te<Y;Te++)if(Ie.substring(Ie.length-v*(Te+1),Ie.length-v*Te)!==ae){xe=!1;break}if(xe){On=!0;break}}}if(On){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,kn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let _e=on(pe),st=sr(_e);for(;st.length>ze;){yield*io();let j=st[ze],se=Date.now(),A={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"}[j.toolName]||j.toolName,Be=wi[A]||j.toolName,ve=ko(A,j.args);yield{type:"status",content:`${Be}${ve?` ${ve}`:""}`};let J="";if(A==="click"){let v=L(j.args);J=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(A==="drag"){let v=L(j.args);J=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(A==="scroll"){let v=L(j.args);J=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(A==="keyboard_typing"){let v=L(j.args);J=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(A==="key_press")J=`\u2714 Pressed Key: ${L(j.args).key||""}`;else if(A==="recapture_screen")J="\u2714 Recaptured Screen";else if(A==="web_search"){let{query:v,limit:Y=10,aiMode:ae=!1}=L(j.args);J=`${v?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${ae===!1&&v?` \u2192 ${Y}`:""}`}else if(A==="web_scrape"){let v=L(j.args).url||null;J=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(A==="view_file"){let{path:v,StartLine:Y,EndLine:ae,start_line:xe,end_line:Te,startLine:Ge,endLine:De}=L(j.args),Re=Y||xe||Ge,re=ae||Te||De,fe=parseInt(Re)||1,le=parseInt(re)||(Re?fe+800:800),$e="...",Je=le,Ae=(v||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")?J="\u2714 Read Documentation":J=`\u2714 Read Skill: ${Z.basename(v.replaceAll("\\","/"))}`;else{try{let ye=Z.resolve(process.cwd(),v);if(Fe.existsSync(ye)){let Tt=Fe.readFileSync(ye,"utf8").split(`
1067
- `).length;$e=Tt,!Re&&!re&&Tt>800?Je=Math.min(50,Tt):Je=Math.min(le,Tt)}}catch{}let Le=(v||"").toLowerCase(),wt=Le.endsWith(".pdf"),Oe=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),rt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);wt||Oe?J=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${Z.basename(v)}`:"Analyzed: File Not Found"}`:rt?J=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${Z.basename(v)}`:"Processed: File Not Found"}`:J=`${$e!=="..."?"\u2714":"\u2718"} Read: ${v?`${Z.basename(v)} \u2192 ${$e!=="..."?`Lines ${fe} - ${Je} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(A==="list_files"||A==="read_folder"){let v=A==="list_files"?"List":"Browsed",Y=L(j.args).path||null,ae=L(j.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${v}: ${Y?`${Y==="."?`./${ae>1?"*":""}`:`${Y.replaceAll("\\","/")}${ae>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(A==="write_file"||A==="update_file"){let v=A==="write_file"?"Created":"Edited",Y=L(j.args).path||null;J=`${Y?"\u2714":"\u2718"} ${v}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(A==="write_pdf"){let v=L(j.args).path||null;J=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(A==="write_docx"){let v=L(j.args).path||null;J=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(A==="file_map"){let v=L(j.args).path;J=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(A.toLowerCase()==="search_keyword"||A.toLowerCase()==="todo")J="";else if(A.toLowerCase()==="generate_image"){let{path:v,outputPath:Y,output:ae}=L(j.args);J=`\u2714 Generated: ${v||Y||ae||"generated_image.png"}`}else if(A==="invoke_sync"||A==="InvokeSync"){let v=ko(A,j.args);J=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(A==="Invoke"||A==="InvokeAsync"||A==="invoke"){let v=ko(A,j.args);J=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(A==="get_progress"||A==="GetProgress"){let v=ko(A,j.args);J=`\u2714 Checked${v?`: ${v}`:""}`}else if(A==="cancel"){let v=ko(A,j.args);J=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(A==="steer"||A==="Steer"){let v=ko(A,j.args);J=`\u2714 Steered${v?`: ${v}`:""}`}else if(A==="EmergencyRollback"){let{method:v}=L(j.args);J=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(A==="await"||A==="Await"){let{time:v,timeout:Y}=L(j.args),ae=parseFloat(Y||v)||0;ae||(ae=120);let xe=De=>{if(De>=60){let Re=Math.floor(De/60),re=De%60;return`${Re}m${re>0?` ${re}s`:""}`}return`${De}s`},Te=["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 ${Te[Math.floor(Math.random()*Te.length)]} \u2192 ${xe(ae)}`}else A==="Answer"||A==="answer"?J="\u2714 Resolved Sub-Agent Query":A==="exec_command"||A==="ask"?J="":J=`Executed: ${j.toolName}`;if(yield*io(),A==="exec_command"){let{command:v}=L(j.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Z.resolve(process.cwd()).substring(0,3).toLowerCase(),xe=re=>{let fe=[],le="",$e=null;for(let Je=0;Je<re.length;Je++){let Ae=re[Je];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):Ae==="&"&&re[Je+1]==="&"||Ae==="|"&&re[Je+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Je++):Ae===";"||Ae==="|"||Ae==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=Ae}return le.trim()&&fe.push(le.trim()),fe},Te=re=>{let fe=[],le="",$e=null;for(let Je=0;Je<re.length;Je++){let Ae=re[Je];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):/\s/.test(Ae)?le&&(fe.push(le),le=""):le+=Ae}return le&&fe.push(le),fe},Ge=re=>{let fe=re.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:Y.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let $e=fe.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==ae}return le.test(fe)})};if(xe(v).some(re=>{let fe=Te(re);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Je=!1;return fe.some(Ae=>{let Jt=Ae.replace(/^['"]|['"]$/g,"");if(Jt===">"||Jt===">>"||Jt==="<")return Je=!0,!1;if(Jt.startsWith(">")||Jt.startsWith("<")){let Le=Jt.replace(/^[><]+/,"");return Ge(Le)}return Je?(Je=!1,Ge(Ae)):!1})}return fe.some(Je=>Ge(Je))})){let re='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${re}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${re}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${re}`},ze++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let Rn=L(j.args),lo=Rn.path||Rn.targetPath||null;if(lo){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=Z.resolve(lo),ae=Z.resolve(process.cwd());if(v&&!Y.startsWith(ae)){let xe="Access Denied. You are not allowed to access files outside the current workspace.";if(A==="write_file"||A==="update_file"){let Ge=`\u2718 ${A==="write_file"?"Write Canceled":"Edit Canceled"}: ${Rn.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Re=Math.min(Ge.length+4,De),re=`${Ge.padEnd(Re-2).substring(0,Re-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1067
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(G){if(Wt){if(Ve+=G,Ve.length>=64){let j=0,se=Math.min(it.length,Ve.length);for(let A=se;A>=10;A--)if(it.endsWith(Ve.substring(0,A))){j=A;break}let Ue=Ve.substring(j);if(Ue){let Be=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ue.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(Be)if(pe+=Be,u==="Google")Tn+=Be;else{yield*io();let ve=Ho(Be);for(let J of ve)yield J}}Wt=!1,Ve=""}continue}else if(pe+=G,u==="Google")Tn+=G;else{yield*io();let j=Ho(G);for(let se of j)yield se}let ye=hd(pe);if(ye.inside){oo=!0,rn||(rn=Date.now());let se={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"}[ye.toolName]||ye.toolName,Ue=ye.args||"",A=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(se)){let ve=L(Ue),J=ve.path||ve.targetFile||ve.TargetFile||ve.directory,Rn=ve.keyword,lo=ve.title||ve.task,zn=ve.id||ve.taskId,Ce=ve.timeout||ve.time;if(Rn!=null)A=String(Rn).replace(bo,"");else if(J)A=Z.basename(String(J).replace(bo,"").replace(al,"/"));else if(lo&&(se==="invoke"||se==="invoke_sync"))A=String(lo).replace(bo,"").substring(0,30);else if(zn&&se==="get_progress")A=String(zn).replace(bo,"");else if(Ce&&se==="await"){let Ht=parseFloat(String(Ce).replace(bo,""));isNaN(Ht)?A=String(Ce).replace(bo,""):(Ht<5&&(Ht=5),Ht>120&&(Ht=120),A=(In=>{if(In>=60){let dr=Math.floor(In/60),Eo=In%60;return`${dr}m${Eo>0?` ${Eo}s`:""}`}return`${In}s`})(Ht))}else{let Ht=Ue.match(sd);if(Ht){let Xt=Ht[1].replace(bo,"");se==="invoke"||se==="invoke_sync"||se==="get_progress"?A=Xt.substring(0,30):A=se==="search_keyword"||se==="file_map"?Xt:Z.basename(Xt.replace(al,"/"))}}}let Be=`${wi[se]||se}${A?` ${A}`:""}`;if((se!==Ut||A!==tt)&&(Ut=se,tt=A,yield{type:"status",content:`${Be}`},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"}[se]||"Working";process.stdout.write(`\x1B]0;${J}...\x07`)}}if(pe.length-bs>150){bs=pe.length;let j=gl(pe,!1),se=yi(j),Ue=se?(se.innerContent||"").trim():"",A=Ue.split(/[.!?]\s+/),Be=new Set(A),ve=A.length>10?(A.length-Be.size)/A.length:0,J=Ue.split(/\s+/).filter(Ie=>Ie.length>0).length,Rn=.6,lo=.8,zn=!1;if((u.toLowerCase().includes("google")||u.toLowerCase().includes("mistral"))&&((be||"").toLowerCase().startsWith("gemma")||(be||"").toLowerCase().includes("stral"))){let v={low:256,medium:1024,high:8192,max:16384,xhigh:16384}[a?.toLowerCase()]||2500;zn=J>v}if(ve>Rn||zn){yield{type:"status",content:`${ve>Rn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Bt=!0,await new Promise(v=>setTimeout(v,3e3));break}let Xt=fl(pe).trim().split(/[.!?]\s+/),In=new Set(Xt);if((Xt.length>10?(Xt.length-In.size)/Xt.length:0)>lo){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Bt=!1,vn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}let Eo=j.replace(Jc,"").replace(Qc,"").replace(Zc,"").replace(ed,""),qt=Eo.toLowerCase().split(/\s+/).map(Ie=>Ie.replace(td,"")).filter(Ie=>Ie.length>0),On=!1;if(qt.length>=10)for(let Ie=1;Ie<=15;Ie++){let v=Math.max(3,Math.ceil(10/Ie));if(qt.length<Ie*v)continue;let Y=qt.slice(qt.length-Ie),ae=Y.join(" ");if(Ie>1&&ae===Y.slice(0,Math.floor(Ie/2)).join(" ").repeat(2).trim())continue;let me=!0;for(let Te=1;Te<v;Te++)if(qt.slice(qt.length-Ie*(Te+1),qt.length-Ie*Te).join(" ")!==ae){me=!1;break}if(me){On=!0;break}}if(!On){let Ie=Eo.toLowerCase().replace(nd,"");if(Ie.length>=20)for(let v=1;v<=10;v++){let Y=Math.max(5,Math.ceil(16/v));if(Ie.length<v*Y)continue;let ae=Ie.substring(Ie.length-v),me=!0;for(let Te=1;Te<Y;Te++)if(Ie.substring(Ie.length-v*(Te+1),Ie.length-v*Te)!==ae){me=!1;break}if(me){On=!0;break}}}if(On){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Bt=!1,kn=!0,await new Promise(Ie=>setTimeout(Ie,3e3));break}}let _e=on(pe),st=sr(_e);for(;st.length>ze;){yield*io();let j=st[ze],se=Date.now(),A={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"}[j.toolName]||j.toolName,Be=wi[A]||j.toolName,ve=ko(A,j.args);yield{type:"status",content:`${Be}${ve?` ${ve}`:""}`};let J="";if(A==="click"){let v=L(j.args);J=`\u2714 Clicked: ${v.intendedClickText?`${v.intendedClickText}`:""}`}else if(A==="drag"){let v=L(j.args);J=`\u2714 Dragged: Cell ${v.fromGridId||""} \u2192 Cell ${v.toGridId||""}`}else if(A==="scroll"){let v=L(j.args);J=`\u2714 Scrolled: ${v.direction||"down"} (${v.amount||1})`}else if(A==="keyboard_typing"){let v=L(j.args);J=`\u2714 Typed: ${v.text?`"${v.text.length>20?v.text.substring(0,20)+"...":v.text}"`:""}`}else if(A==="key_press")J=`\u2714 Pressed Key: ${L(j.args).key||""}`;else if(A==="recapture_screen")J="\u2714 Recaptured Screen";else if(A==="web_search"){let{query:v,limit:Y=10,aiMode:ae=!1}=L(j.args);J=`${v?"\u2714":"\u2718"} ${ae?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${ae===!1&&v?` \u2192 ${Y}`:""}`}else if(A==="web_scrape"){let v=L(j.args).url||null;J=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(A==="view_file"){let{path:v,StartLine:Y,EndLine:ae,start_line:me,end_line:Te,startLine:Ge,endLine:De}=L(j.args),Re=Y||me||Ge,re=ae||Te||De,fe=parseInt(Re)||1,le=parseInt(re)||(Re?fe+800:800),$e="...",Je=le,Ae=(v||"").trim().toLowerCase().replaceAll("\\","/");if(Ae.startsWith("#skill"))Ae.startsWith("#skill/global/fluxflow")||Ae.startsWith("#skills/global/fluxflow")?J="\u2714 Read Documentation":J=`\u2714 Read Skill: ${Z.basename(v.replaceAll("\\","/"))}`;else{try{let we=Z.resolve(process.cwd(),v);if(Fe.existsSync(we)){let Tt=Fe.readFileSync(we,"utf8").split(`
1068
+ `).length;$e=Tt,!Re&&!re&&Tt>800?Je=Math.min(50,Tt):Je=Math.min(le,Tt)}}catch{}let Le=(v||"").toLowerCase(),wt=Le.endsWith(".pdf"),Oe=Le.endsWith(".docx")||Le.endsWith(".doc")||Le.endsWith(".ppt")||Le.endsWith(".pptx")||Le.endsWith(".xls")||Le.endsWith(".xlsx"),rt=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(Le);wt||Oe?J=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${Z.basename(v)}`:"Analyzed: File Not Found"}`:rt?J=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${Z.basename(v)}`:"Processed: File Not Found"}`:J=`${$e!=="..."?"\u2714":"\u2718"} Read: ${v?`${Z.basename(v)} \u2192 ${$e!=="..."?`Lines ${fe} - ${Je} of ${$e}`:"File Not Found"}`:"File Not Found"}`}}else if(A==="list_files"||A==="read_folder"){let v=A==="list_files"?"List":"Browsed",Y=L(j.args).path||null,ae=L(j.args).recurse||1;J=`${Y?"\u2714":"\u2718"} ${v}: ${Y?`${Y==="."?`./${ae>1?"*":""}`:`${Y.replaceAll("\\","/")}${ae>1?`${Y.endsWith("/")?"*":"/*"}`:`${Y.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(A==="write_file"||A==="update_file"){let v=A==="write_file"?"Created":"Edited",Y=L(j.args).path||null;J=`${Y?"\u2714":"\u2718"} ${v}: ${Y.replaceAll("\\","/")||"No File Changes"}`}else if(A==="write_pdf"){let v=L(j.args).path||null;J=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(A==="write_docx"){let v=L(j.args).path||null;J=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(A==="file_map"){let v=L(j.args).path;J=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(A.toLowerCase()==="search_keyword"||A.toLowerCase()==="todo")J="";else if(A.toLowerCase()==="generate_image"){let{path:v,outputPath:Y,output:ae}=L(j.args);J=`\u2714 Generated: ${v||Y||ae||"generated_image.png"}`}else if(A==="invoke_sync"||A==="InvokeSync"){let v=ko(A,j.args);J=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(A==="Invoke"||A==="InvokeAsync"||A==="invoke"){let v=ko(A,j.args);J=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(A==="get_progress"||A==="GetProgress"){let v=ko(A,j.args);J=`\u2714 Checked${v?`: ${v}`:""}`}else if(A==="cancel"){let v=ko(A,j.args);J=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(A==="steer"||A==="Steer"){let v=ko(A,j.args);J=`\u2714 Steered${v?`: ${v}`:""}`}else if(A==="EmergencyRollback"){let{method:v}=L(j.args);J=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(A==="await"||A==="Await"){let{time:v,timeout:Y}=L(j.args),ae=parseFloat(Y||v)||0;ae||(ae=120);let me=De=>{if(De>=60){let Re=Math.floor(De/60),re=De%60;return`${Re}m${re>0?` ${re}s`:""}`}return`${De}s`},Te=["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 ${Te[Math.floor(Math.random()*Te.length)]} \u2192 ${me(ae)}`}else A==="Answer"||A==="answer"?J="\u2714 Resolved Sub-Agent Query":A==="exec_command"||A==="ask"?J="":J=`Executed: ${j.toolName}`;if(yield*io(),A==="exec_command"){let{command:v}=L(j.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Y=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ae=Z.resolve(process.cwd()).substring(0,3).toLowerCase(),me=re=>{let fe=[],le="",$e=null;for(let Je=0;Je<re.length;Je++){let Ae=re[Je];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):Ae==="&"&&re[Je+1]==="&"||Ae==="|"&&re[Je+1]==="|"?(le.trim()&&(fe.push(le.trim()),le=""),Je++):Ae===";"||Ae==="|"||Ae==="&"?le.trim()&&(fe.push(le.trim()),le=""):le+=Ae}return le.trim()&&fe.push(le.trim()),fe},Te=re=>{let fe=[],le="",$e=null;for(let Je=0;Je<re.length;Je++){let Ae=re[Je];$e?(Ae===$e&&($e=null),le+=Ae):Ae==='"'||Ae==="'"?($e=Ae,le+=Ae):/\s/.test(Ae)?le&&(fe.push(le),le=""):le+=Ae}return le&&fe.push(le),fe},Ge=re=>{let fe=re.replace(/^['"]|['"]$/g,"").trim();return!fe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(fe)?!1:Y.some(le=>{if(le.source==="[a-zA-Z]:[\\\\\\/]"){let $e=fe.match(/[a-zA-Z]:[\\\/]/i);return $e&&$e[0].toLowerCase()!==ae}return le.test(fe)})};if(me(v).some(re=>{let fe=Te(re);if(fe.length===0)return!1;let le=fe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(le)){let Je=!1;return fe.some(Ae=>{let Jt=Ae.replace(/^['"]|['"]$/g,"");if(Jt===">"||Jt===">>"||Jt==="<")return Je=!0,!1;if(Jt.startsWith(">")||Jt.startsWith("<")){let Le=Jt.replace(/^[><]+/,"");return Ge(Le)}return Je?(Je=!1,Ge(Ae)):!1})}return fe.some(Je=>Ge(Je))})){let re='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"},await new Promise(fe=>setTimeout(fe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${re}`),await new Promise(fe=>setTimeout(fe,50)),t.onExecEnd&&t.onExecEnd(),ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${re}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${re}`},ze++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let Rn=L(j.args),lo=Rn.path||Rn.targetPath||null;if(lo){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Y=Z.resolve(lo),ae=Z.resolve(process.cwd());if(v&&!Y.startsWith(ae)){let me="Access Denied. You are not allowed to access files outside the current workspace.";if(A==="write_file"||A==="update_file"){let Ge=`\u2718 ${A==="write_file"?"Write Canceled":"Edit Canceled"}: ${Rn.path||"..."}`,De=115;process.stdout.isTTY&&(De=process.stdout.columns-5||120);let Re=Math.min(Ge.length+4,De),re=`${Ge.padEnd(Re-2).substring(0,Re-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1068
1069
  `:""}${re}
1069
- `)},je=!1}ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${xe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${xe}`},ze++;continue}}if(t.onToolApproval&&(A==="write_file"||A==="update_file"||A==="exec_command")){let Y=t.systemSettings||{},ae=Y.autoExec,xe=null,Te=!1,Ge=!1,De=!1;if(A==="exec_command"){let{command:Le}=L(j.args),wt=(Le||"").trim(),Oe=(Qt,Tt)=>{if(!Tt)return!1;let mn=Tt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),dt=Qt.toLowerCase();return mn.some(Zt=>dt.startsWith(Zt))},rt=Oe(wt,Y.alwaysAskCommands),ye=Oe(wt,Y.autoApproveCommands);if(Ge=Oe(wt,Y.autoDisallowCommands),rt?Te=!0:(ye||Y.autoApproveGit&&/^git\s+commit\b/i.test(wt))&&(xe="allow"),!Te&&!xe){if(Y.networkAccess===!1){let Tt=wt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),dt=Tt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=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"]),ut=!1;Zt.has(dt)&&(ut=!0);let lt=En=>Tt.slice(1).some(_n=>En.includes(_n)),ft=En=>{let _n=Tt.findIndex(Dn=>En.includes(Dn)),_o=Tt.findIndex(Dn=>["run","exec","test"].includes(Dn));return _n!==-1&&!(_o!==-1&&_o<_n)};dt==="git"&&lt(["clone","pull","push","fetch"])&&(ut=!0),dt==="go"&&lt(["get","install"])&&(ut=!0),dt==="npm"&&ft(["install","i","update","add"])&&(ut=!0),dt==="yarn"&&ft(["add","install","upgrade"])&&(ut=!0),dt==="pnpm"&&ft(["add","install","update"])&&(ut=!0),dt==="bun"&&ft(["add","install","update"])&&(ut=!0),dt==="deno"&&lt(["install","add"])&&(ut=!0),dt==="pip"&&lt(["install","download"])&&(ut=!0),dt==="pip3"&&lt(["install","download"])&&(ut=!0),dt==="cargo"&&lt(["install","add"])&&(ut=!0),["bash","sh","zsh","fish"].includes(dt)&&lt(["-c"])&&(ut=!0),dt==="cmd"&&lt(["/c"])&&(ut=!0),ut&&(xe="deny",De=!0)}!xe&&Ge&&(xe="deny")}!Te&&!xe&&ae&&(xe="allow")}else ae&&(xe="allow");let Re=xe,re="";xe==="deny"&&(De?re="network":Ge?re="settings":re="prohibited");let fe=!1,le="",$e=[],Je=0,Ae=!1,Jt="";if(!Re){if(A==="write_file"||A==="update_file")try{let Oe=L(j.args),{path:rt}=Oe;if(rt){let ye=Z.resolve(process.cwd(),rt),Qt=lt=>lt?lt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",Tt=Qt(ye),mn="",dt=!1,Zt=await xo(),ut=Qt(Zt?.file_focused);if(Zt&&ut===Tt&&Zt.full_content?(mn=Zt.full_content,dt=!0):Fe.existsSync(ye)&&(mn=Fe.readFileSync(ye,"utf8"),dt=!0),le=mn,await ht.recordFileChange(ye,mn),dt){let lt=mn;if(A==="write_file"){let ft=Oe.content||Oe.newContent||"";lt=ft.endsWith(`
1070
+ `)},je=!1}ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${me}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${me}`},ze++;continue}}if(t.onToolApproval&&(A==="write_file"||A==="update_file"||A==="exec_command")){let Y=t.systemSettings||{},ae=Y.autoExec,me=null,Te=!1,Ge=!1,De=!1;if(A==="exec_command"){let{command:Le}=L(j.args),wt=(Le||"").trim(),Oe=(Qt,Tt)=>{if(!Tt)return!1;let mn=Tt.split(",").map(Zt=>Zt.trim().toLowerCase()).filter(Boolean),dt=Qt.toLowerCase();return mn.some(Zt=>dt.startsWith(Zt))},rt=Oe(wt,Y.alwaysAskCommands),we=Oe(wt,Y.autoApproveCommands);if(Ge=Oe(wt,Y.autoDisallowCommands),rt?Te=!0:(we||Y.autoApproveGit&&/^git\s+commit\b/i.test(wt))&&(me="allow"),!Te&&!me){if(Y.networkAccess===!1){let Tt=wt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),dt=Tt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Zt=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"]),ut=!1;Zt.has(dt)&&(ut=!0);let lt=En=>Tt.slice(1).some(_n=>En.includes(_n)),ft=En=>{let _n=Tt.findIndex(Dn=>En.includes(Dn)),_o=Tt.findIndex(Dn=>["run","exec","test"].includes(Dn));return _n!==-1&&!(_o!==-1&&_o<_n)};dt==="git"&&lt(["clone","pull","push","fetch"])&&(ut=!0),dt==="go"&&lt(["get","install"])&&(ut=!0),dt==="npm"&&ft(["install","i","update","add"])&&(ut=!0),dt==="yarn"&&ft(["add","install","upgrade"])&&(ut=!0),dt==="pnpm"&&ft(["add","install","update"])&&(ut=!0),dt==="bun"&&ft(["add","install","update"])&&(ut=!0),dt==="deno"&&lt(["install","add"])&&(ut=!0),dt==="pip"&&lt(["install","download"])&&(ut=!0),dt==="pip3"&&lt(["install","download"])&&(ut=!0),dt==="cargo"&&lt(["install","add"])&&(ut=!0),["bash","sh","zsh","fish"].includes(dt)&&lt(["-c"])&&(ut=!0),dt==="cmd"&&lt(["/c"])&&(ut=!0),ut&&(me="deny",De=!0)}!me&&Ge&&(me="deny")}!Te&&!me&&ae&&(me="allow")}else ae&&(me="allow");let Re=me,re="";me==="deny"&&(De?re="network":Ge?re="settings":re="prohibited");let fe=!1,le="",$e=[],Je=0,Ae=!1,Jt="";if(!Re){if(A==="write_file"||A==="update_file")try{let Oe=L(j.args),{path:rt}=Oe;if(rt){let we=Z.resolve(process.cwd(),rt),Qt=lt=>lt?lt.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,ft=>ft.toUpperCase()):"",Tt=Qt(we),mn="",dt=!1,Zt=await xo(),ut=Qt(Zt?.file_focused);if(Zt&&ut===Tt&&Zt.full_content?(mn=Zt.full_content,dt=!0):Fe.existsSync(we)&&(mn=Fe.readFileSync(we,"utf8"),dt=!0),le=mn,await ht.recordFileChange(we,mn),dt){let lt=mn;if(A==="write_file"){let ft=Oe.content||Oe.newContent||"";lt=ft.endsWith(`
1070
1071
  `)?ft:ft+`
1071
- `,Jt=lt}else{let{patchPairs:ft,allowMultiple:En,error:_n}=Os(Oe);if(_n){let Mt=`[TOOL RESULT]: ERROR: ${_n}`;ne.push({role:"user",text:Mt}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Mt,toolName:A},ze++;continue}let _o=Oe.allowMultiple!==void 0?Oe.allowMultiple===!0||String(Oe.allowMultiple).toLowerCase()==="true":En;Je=ft.length;let Dn=Ds(mn,ft,{allowMultiple:_o});lt=Dn.content,Jt=lt,$e=Dn.results;let Ss=$e.filter(Mt=>Mt.success),At=$e.filter(Mt=>!Mt.success);if(Ss.length===0){let Mt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Z.basename(ye)}].
1072
+ `,Jt=lt}else{let{patchPairs:ft,allowMultiple:En,error:_n}=Os(Oe);if(_n){let Mt=`[TOOL RESULT]: ERROR: ${_n}`;ne.push({role:"user",text:Mt}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Mt,toolName:A},ze++;continue}let _o=Oe.allowMultiple!==void 0?Oe.allowMultiple===!0||String(Oe.allowMultiple).toLowerCase()==="true":En;Je=ft.length;let Dn=Ds(mn,ft,{allowMultiple:_o});lt=Dn.content,Jt=lt,$e=Dn.results;let Ss=$e.filter(Mt=>Mt.success),At=$e.filter(Mt=>!Mt.success);if(Ss.length===0){let Mt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Z.basename(we)}].
1072
1073
  ${At.map(Ko=>` \u2022 ${Ko.error}`).join(`
1073
- `)}`,Co=`\u2714 Edited: ${Z.basename(ye.replaceAll("\\","/"))}`,zo=115;process.stdout.isTTY&&(zo=process.stdout.columns-5||120);let $o=Math.min(Co.length+4,zo),ks=`${Co.padEnd($o-2).substring(0,$o-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1074
- `:""}${ks}`)},je=!1,ne.push({role:"user",text:Mt}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Mt,toolName:A},ze++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Z.basename(ye)}`},fi(ye,mn,lt),fe=!0,await new Promise(ft=>setTimeout(ft,50))}else if(A==="write_file"){let lt=Oe.content||Oe.newContent||"",ft=lt.endsWith(`
1074
+ `)}`,Co=`\u2714 Edited: ${Z.basename(we.replaceAll("\\","/"))}`,zo=115;process.stdout.isTTY&&(zo=process.stdout.columns-5||120);let $o=Math.min(Co.length+4,zo),ks=`${Co.padEnd($o-2).substring(0,$o-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1075
+ `:""}${ks}`)},je=!1,ne.push({role:"user",text:Mt}),await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A),yield{type:"tool_result",content:Mt,toolName:A},ze++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Z.basename(we)}`},fi(we,mn,lt),fe=!0,await new Promise(ft=>setTimeout(ft,50))}else if(A==="write_file"){let lt=Oe.content||Oe.newContent||"",ft=lt.endsWith(`
1075
1076
  `)?lt:lt+`
1076
- `;Jt=ft,Fe.existsSync(ye)||(Ae=!0,Fe.mkdirSync(Z.dirname(ye),{recursive:!0}),Fe.writeFileSync(ye,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Z.basename(ye)}`},fi(ye,"",ft),fe=!0,await new Promise(En=>setTimeout(En,50))}}}catch(Oe){console.error("Simulation/Diff Error:",Oe)}let Le=null;ui(Oe=>{Le=Oe});let wt=t.onToolApproval;if(Re=await new Promise(async Oe=>{let rt=setInterval(()=>{Le&&(nr.onIDEApproval&&nr.onIDEApproval(Le),clearInterval(rt),Oe(Le))},100);try{let ye=await wt(A,j.args);clearInterval(rt),Oe(ye)}catch{clearInterval(rt),Oe("deny")}}),ui(null),A==="write_file"||A==="update_file"){let{path:Oe}=L(j.args);if(Oe){let rt=Z.resolve(process.cwd(),Oe);if(sl(rt,Re),Re==="deny"&&Ae&&Fe.existsSync(rt))try{Fe.unlinkSync(rt)}catch{}}}Re==="deny"&&(re="user")}if(Re==="allow"&&fe&&Hs()){let{path:Le}=L(j.args),wt=Z.resolve(process.cwd(),Le),Oe=At=>At?Z.resolve(At).replace(/\\/g,"/").toLowerCase():"",rt=await xo(),ye="";if(rt&&rt.file_focused&&Oe(rt.file_focused)===Oe(wt)&&rt.full_content&&(ye=rt.full_content),!ye&&Fe.existsSync(wt)){let At=Fe.readFileSync(wt,"utf8");At&&(ye=At)}!ye&&Jt&&(ye=Jt),(ye||Ae)&&Fe.writeFileSync(wt,ye,"utf8");let Qt=ye.split(/\r?\n/),Tt=Qt.length,mn=Buffer.byteLength(ye,"utf8"),dt="";le&&(dt=`Old File contents:
1077
+ `;Jt=ft,Fe.existsSync(we)||(Ae=!0,Fe.mkdirSync(Z.dirname(we),{recursive:!0}),Fe.writeFileSync(we,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Z.basename(we)}`},fi(we,"",ft),fe=!0,await new Promise(En=>setTimeout(En,50))}}}catch(Oe){console.error("Simulation/Diff Error:",Oe)}let Le=null;ui(Oe=>{Le=Oe});let wt=t.onToolApproval;if(Re=await new Promise(async Oe=>{let rt=setInterval(()=>{Le&&(nr.onIDEApproval&&nr.onIDEApproval(Le),clearInterval(rt),Oe(Le))},100);try{let we=await wt(A,j.args);clearInterval(rt),Oe(we)}catch{clearInterval(rt),Oe("deny")}}),ui(null),A==="write_file"||A==="update_file"){let{path:Oe}=L(j.args);if(Oe){let rt=Z.resolve(process.cwd(),Oe);if(sl(rt,Re),Re==="deny"&&Ae&&Fe.existsSync(rt))try{Fe.unlinkSync(rt)}catch{}}}Re==="deny"&&(re="user")}if(Re==="allow"&&fe&&Hs()){let{path:Le}=L(j.args),wt=Z.resolve(process.cwd(),Le),Oe=At=>At?Z.resolve(At).replace(/\\/g,"/").toLowerCase():"",rt=await xo(),we="";if(rt&&rt.file_focused&&Oe(rt.file_focused)===Oe(wt)&&rt.full_content&&(we=rt.full_content),!we&&Fe.existsSync(wt)){let At=Fe.readFileSync(wt,"utf8");At&&(we=At)}!we&&Jt&&(we=Jt),(we||Ae)&&Fe.writeFileSync(wt,we,"utf8");let Qt=we.split(/\r?\n/),Tt=Qt.length,mn=Buffer.byteLength(we,"utf8"),dt="";le&&(dt=`Old File contents:
1077
1078
  ${le.split(/\r?\n/).map((Mt,Co)=>`${Co+1} | ${Mt}`).join(`
1078
1079
  `)}
1079
1080
 
@@ -1084,9 +1085,9 @@ ${le.split(/\r?\n/).map((Mt,Co)=>`${Co+1} | ${Mt}`).join(`
1084
1085
 
1085
1086
  ... [${Tt-100} lines truncated for history stability] ...
1086
1087
 
1087
- ${Mt}`}let ut="";if(A==="update_file"){let At=Ls(le,ye,$e,12,t?.compressToolResults||nr?.systemSettings?.compressToolResults);ut=`SUCCESS: File [${Le}] updated via IDE Companion (May have user edits). [${$e.length}/${Je}] blocks applied.
1088
+ ${Mt}`}let ut="";if(A==="update_file"){let At=Ls(le,we,$e,12,t?.compressToolResults||nr?.systemSettings?.compressToolResults);ut=`SUCCESS: File [${Le}] updated via IDE Companion (May have user edits). [${$e.length}/${Je}] blocks applied.
1088
1089
 
1089
- ${At}`}else{let At=ye.split(/\r?\n/),Mt=At.length,Co=Buffer.byteLength(ye,"utf8"),zo="";le&&(zo=`Old File contents:
1090
+ ${At}`}else{let At=we.split(/\r?\n/),Mt=At.length,Co=Buffer.byteLength(we,"utf8"),zo="";le&&(zo=`Old File contents:
1090
1091
  ${le.split(/\r?\n/).map((Ko,vl)=>`${vl+1} | ${Ko}`).join(`
1091
1092
  `)}
1092
1093
 
@@ -1102,19 +1103,19 @@ ${Ko}`}ut=`SUCCESS: File [${Le}] saved via IDE Companion (May have user edits).
1102
1103
  ${zo}- Content Preview:
1103
1104
 
1104
1105
  ${$o}`}let ft=`${Le?"\u2714":"\u2718"} ${A==="write_file"?"Created":"Edited"}: ${Le.replaceAll("\\","/")||"No File Changes"}`,En=115;process.stdout.isTTY&&(En=process.stdout.columns-5||120);let _n=Math.min(ft.length+4,En),_o=`${ft.padEnd(_n-2).substring(0,_n-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1105
- `:""}${_o}`)},je=!1;let Dn=Date.now();K=Dn,yield{type:"tool_time",content:Dn-se};let Ss=`[TOOL RESULT]: ${ut}`;ne.push({role:"user",text:Ss}),fn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",A),yield{type:"tool_result",content:ut,aiContent:Ss,toolName:A},ze++;continue}if(Re==="deny"){let Le=`Permission Denied: Prohibited ${A==="exec_command"?"Command":"file edit"}.`;if(re==="user"?Le="Permission Denied by User":re==="settings"?Le="Permission Denied by User Policy":re==="network"?Le="Permission Denied: Sandbox Network Access Disabled by User Policy.":re==="prohibited"&&A==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),A==="write_file"||A==="update_file"){let Oe=`\u2718 ${A==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(j.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let ye=Math.min(Oe.length+4,rt),Qt=`${Oe.padEnd(ye-2).substring(0,ye-2)}`,Tt=` ${" ".repeat(ye)} `;yield{type:"visual_feedback",content:nn(`${je?`
1106
+ `:""}${_o}`)},je=!1;let Dn=Date.now();K=Dn,yield{type:"tool_time",content:Dn-se};let Ss=`[TOOL RESULT]: ${ut}`;ne.push({role:"user",text:Ss}),fn=!0,await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",A),yield{type:"tool_result",content:ut,aiContent:Ss,toolName:A},ze++;continue}if(Re==="deny"){let Le=`Permission Denied: Prohibited ${A==="exec_command"?"Command":"file edit"}.`;if(re==="user"?Le="Permission Denied by User":re==="settings"?Le="Permission Denied by User Policy":re==="network"?Le="Permission Denied: Sandbox Network Access Disabled by User Policy.":re==="prohibited"&&A==="exec_command"&&(Le="Permission Denied: Prohibited Command in User Policy"),A==="write_file"||A==="update_file"){let Oe=`\u2718 ${A==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(j.args).path.replaceAll("\\","/")||"..."}`,rt=115;process.stdout.isTTY&&(rt=process.stdout.columns-5||120);let we=Math.min(Oe.length+4,rt),Qt=`${Oe.padEnd(we-2).substring(0,we-2)}`,Tt=` ${" ".repeat(we)} `;yield{type:"visual_feedback",content:nn(`${je?`
1106
1107
  `:""}${Qt}
1107
- `)},je=!1}A==="exec_command"&&(await new Promise(wt=>setTimeout(wt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Le}`),await new Promise(wt=>setTimeout(wt,50)),t.onExecEnd&&t.onExecEnd()),ne.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",A),ze++;continue}}if(J){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let Y=Math.min(J.length+4,v),ae=`${J.padEnd(Y-2).substring(0,Y-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1108
- `:""}${ae}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`
1109
- `}`)},je=!1}if(K>0){let v=Date.now()-K,Y=Math.max(0,1e3-v);Y>0&&await new Promise(ae=>setTimeout(ae,Y))}let zn={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:Et(be),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:be,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(A==="write_file"||A==="update_file")try{let{path:v}=L(j.args);if(v){let Y=Z.resolve(process.cwd(),v),ae=await xo();ae&&ae.file_focused===Y&&ae.full_content&&(zn.forcedContent=ae.full_content)}}catch{}sn.push(A);let Ce=await ms(A,j.args,zn);if((A==="write_file"||A==="update_file")&&Ce.startsWith("SUCCESS")){let{path:v}=L(j.args);if(v){let Y=Z.resolve(process.cwd(),v);ol(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();K=Ht,yield{type:"tool_time",content:Ht-se},rn=Ht;let Xt=null;if(typeof Ce=="object"&&Ce.binaryPart&&(Xt=Ce.binaryPart,Ce=Ce.text),A==="search_keyword"){let{keyword:v,path:Y}=L(j.args),ae=typeof Ce=="string"&&Ce.startsWith("[GLOB]");ae&&(Ce=Ce.slice(6).trimStart());let xe=typeof Ce=="string"&&Ce.startsWith("[DIR]");xe&&(Ce=Ce.slice(5).trimStart());let Te=0;if(Ce){let $e=Ce.match(/Found (\d+) match/i);$e&&(Te=parseInt($e[1]))}let Ge=(Y||"").trim().toLowerCase().replaceAll("\\","/"),De=Ge==="#doc"||Ge==="#docs"||Ge==="#documentation"||Ge.includes("#skill/global/fluxflow")||Ge.includes("#skills/global/fluxflow"),Re;if(De)Re=`${v?"\u2714":"\u2718"} Searched Documentation`;else{let $e=Y?Y.replace(/[\/\\]+$/,""):null,Je=$e&&$e!=="."?`"${ae?Y:xe?`${$e}/*`:$e}"`:"./";Re=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Je.replaceAll("\\","/")} \u2192 ${Te} Match${Te===1?"":"es"}`}let re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let fe=Math.min(Re.length+4,re),le=`${Re.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1108
+ `)},je=!1}A==="exec_command"&&(await new Promise(wt=>setTimeout(wt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Le}`),await new Promise(wt=>setTimeout(wt,50)),t.onExecEnd&&t.onExecEnd()),ne.push({role:"user",text:`[TOOL RESULT]: DENIED: ${Le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${Le}`},await Ot("toolDenied"),t.onToolResult&&t.onToolResult("denied",A),ze++;continue}}if(J){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let Y=o?.()??null,ae=Math.min(J.length+4,v),me=`${J.padEnd(ae-2).substring(0,ae-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1109
+ `:""}${me}${J.includes("\u2714")&&(J.includes("Created")||J.includes("Edited"))?"":`${Y?"":`
1110
+ `}`}`)},je=!1}if(K>0){let v=Date.now()-K,Y=Math.max(0,1e3-v);Y>0&&await new Promise(ae=>setTimeout(ae,Y))}let zn={chatId:d,history:n,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:i,isMultiModal:Et(be),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:be,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(A==="write_file"||A==="update_file")try{let{path:v}=L(j.args);if(v){let Y=Z.resolve(process.cwd(),v),ae=await xo();ae&&ae.file_focused===Y&&ae.full_content&&(zn.forcedContent=ae.full_content)}}catch{}sn.push(A);let Ce=await ms(A,j.args,zn);if((A==="write_file"||A==="update_file")&&Ce.startsWith("SUCCESS")){let{path:v}=L(j.args);if(v){let Y=Z.resolve(process.cwd(),v);ol(Y)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Ht=Date.now();K=Ht,yield{type:"tool_time",content:Ht-se},rn=Ht;let Xt=null;if(typeof Ce=="object"&&Ce.binaryPart&&(Xt=Ce.binaryPart,Ce=Ce.text),A==="search_keyword"){let{keyword:v,path:Y}=L(j.args),ae=typeof Ce=="string"&&Ce.startsWith("[GLOB]");ae&&(Ce=Ce.slice(6).trimStart());let me=typeof Ce=="string"&&Ce.startsWith("[DIR]");me&&(Ce=Ce.slice(5).trimStart());let Te=0;if(Ce){let $e=Ce.match(/Found (\d+) match/i);$e&&(Te=parseInt($e[1]))}let Ge=(Y||"").trim().toLowerCase().replaceAll("\\","/"),De=Ge==="#doc"||Ge==="#docs"||Ge==="#documentation"||Ge.includes("#skill/global/fluxflow")||Ge.includes("#skills/global/fluxflow"),Re;if(De)Re=`${v?"\u2714":"\u2718"} Searched Documentation`;else{let $e=Y?Y.replace(/[\/\\]+$/,""):null,Je=$e&&$e!=="."?`"${ae?Y:me?`${$e}/*`:$e}"`:"./";Re=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Je.replaceAll("\\","/")} \u2192 ${Te} Match${Te===1?"":"es"}`}let re=115;process.stdout.isTTY&&(re=process.stdout.columns-5||120);let fe=Math.min(Re.length+4,re),le=`${Re.padEnd(fe-2).substring(0,fe-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1110
1111
  `:""}${le}
1111
- `)},je=!1}if(A==="EmergencyRollback"){let{method:v}=L(j.args);if(v==="forceRevert"){let Y=0;if(Ce){let Re=Ce.match(/Total\s*:\s*(\d+)/i);Re&&(Y=parseInt(Re[1]))}let xe=Ce&&Ce.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${Y} file${Y===1?"":"s"} processed`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let Ge=Math.min(xe.length+4,Te),De=`${xe.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1112
+ `)},je=!1}if(A==="EmergencyRollback"){let{method:v}=L(j.args);if(v==="forceRevert"){let Y=0;if(Ce){let Re=Ce.match(/Total\s*:\s*(\d+)/i);Re&&(Y=parseInt(Re[1]))}let me=Ce&&Ce.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${Y} file${Y===1?"":"s"} processed`,Te=115;process.stdout.isTTY&&(Te=process.stdout.columns-5||120);let Ge=Math.min(me.length+4,Te),De=`${me.padEnd(Ge-2).substring(0,Ge-2)}`;yield{type:"visual_feedback",content:nn(`${je?`
1112
1113
  `:""}${De}
1113
- `)},je=!1}}if(A==="todo"){let{method:v,tasks:Y,markDone:ae}=L(j.args),xe="",Te=[],Ge=De=>{if(!De)return[];let Re=Array.isArray(De)?De:[];if(Re.length===0&&typeof De=="string"){let re=De.trim();if(re.startsWith("[")&&re.endsWith("]")){let fe=re.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?Re=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Re=re.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Re=De.split(`
1114
- `)}return Re.filter(re=>String(re).trim()).map(re=>{let fe=String(re).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(v==="create"?(xe="\x1B[32m\u2192\x1B[0m Created Goals",Te=Ge(Y).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):v==="append"?(xe="\x1B[34m\u2795\x1B[0m Added New Goals",Te=Ge(Y).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):v==="get"&&(xe=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",Te=(Ce||"").split(`
1114
+ `)},je=!1}}if(A==="todo"){let{method:v,tasks:Y,markDone:ae}=L(j.args),me="",Te=[],Ge=De=>{if(!De)return[];let Re=Array.isArray(De)?De:[];if(Re.length===0&&typeof De=="string"){let re=De.trim();if(re.startsWith("[")&&re.endsWith("]")){let fe=re.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);fe?Re=fe.map(le=>le.slice(1,-1).replace(/\\(.)/g,"$1")):Re=re.slice(1,-1).split(",").map(le=>le.trim()).filter(Boolean)}else Re=De.split(`
1115
+ `)}return Re.filter(re=>String(re).trim()).map(re=>{let fe=String(re).trim();return fe.startsWith("- [")?fe.substring(6).trim():fe})};if(v==="create"?(me="\x1B[32m\u2192\x1B[0m Created Goals",Te=Ge(Y).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):v==="append"?(me="\x1B[34m\u2795\x1B[0m Added New Goals",Te=Ge(Y).map(De=>`\x1B[90m\u25CB\x1B[0m ${De}`)):v==="get"&&(me=ae?"\x1B[36m\u21BB\x1B[0m Updated Goals":"\x1B[35m\u2022\x1B[0m Reviewed Goals",Te=(Ce||"").split(`
1115
1116
  `).slice(1).join(`
1116
1117
  `).split(`
1117
- `).filter(Re=>Re.trim().startsWith("- [")).map(Re=>{let re=Re.trim(),fe=re.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${re.substring(6).trim()}\x1B[0m`})),xe&&Te.length>0){let De=[`${xe}`,...Te.map(Re=>` ${Re}`)].join(`
1118
+ `).filter(Re=>Re.trim().startsWith("- [")).map(Re=>{let re=Re.trim(),fe=re.startsWith("- [x]");return`${fe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${fe?"\x1B[90m":"\x1B[37m"}${re.substring(6).trim()}\x1B[0m`})),me&&Te.length>0){let De=[`${me}`,...Te.map(Re=>` ${Re}`)].join(`
1118
1119
  `);yield{type:"visual_feedback",content:nn(`${je?`
1119
1120
  `:""}${De}
1120
1121
  `)},je=!1}}A==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let In=Ce&&Ce.startsWith("DENIED:");Ce&&!Ce.startsWith("ERROR:")&&!In?(await Ot("toolSuccess"),t.onToolResult&&t.onToolResult("success",A)):In||(await Ot("toolFailure"),t.onToolResult&&t.onToolResult("failure",A));let qt=(Ce||"").toString().replaceAll("[UI_CONTEXT]","");qt.includes("[[VERIFIED]]")&&(qt=qt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
@@ -1123,7 +1124,7 @@ ${$o}`}let ft=`${Le?"\u2714":"\u2718"} ${A==="write_file"?"Created":"Edited"}: $
1123
1124
  `)}
1124
1125
  [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else On=`[TOOL RESULT]: ${qt}`;ne.push({role:"user",text:On,binaryPart:Xt}),fn=!0;let Ie=`[TOOL RESULT]: ${Ce.replaceAll(`[[VERIFIED]]
1125
1126
  `,"").replaceAll(`
1126
- [[/VERIFIED]]`,"")||""}`;(A==="view_file"||A==="web_scrape"||A==="file_map")&&(Ie=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:On,binaryPart:Xt,toolName:A},A==="memory"&&Ce.includes("SUCCESS")&&(yield{type:"memory_updated"}),ze++}if(u==="Google"&&Tn&&Date.now()-lr>=150){yield*io();let j=Ho(Tn);for(let se of j)yield se;Tn="",lr=Date.now()}}N.usageMetadata&&(Mn=N.usageMetadata),Mn&&(yield{type:"liveTokens",content:Mn.totalTokenCount})}if(de&&(de=!1,Wt?Ve+="</think>":(pe+="</think>",u==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ve.length>0){let N=0,ie=Math.min(it.length,Ve.length);for(let q=ie;q>0;q--)if(it.endsWith(Ve.substring(0,q))){N=q;break}let G=Ve.substring(N);if(G){let ke=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ke)if(pe+=ke,u==="Google")Tn+=ke;else{yield*io();let ge=Ho(ke);for(let _e of ge)yield _e}}Wt=!1,Ve=""}if(yield*io(),It)break;let qo=(pe||"").trim(),El=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(qo.toLowerCase())||/\[\[END\]\]/i.test(qo.toLowerCase()),_l=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(qo.toLowerCase()),Cl=ne.length>0||Ut!==null,cr=on(qo).trim(),$l=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(cr),Al=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(cr.trim()),Ml=/[.!?}"'`’“”]$|```$/s.test(cr)||Al||$l;!El&&!_l&&!Cl&&qo.length>0,ot=!0,await Ot("agent",u)}catch(Se){if(It){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1127
+ [[/VERIFIED]]`,"")||""}`;(A==="view_file"||A==="web_scrape"||A==="file_map")&&(Ie=`[TOOL RESULT]: ${J} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Ie,aiContent:On,binaryPart:Xt,toolName:A},A==="memory"&&Ce.includes("SUCCESS")&&(yield{type:"memory_updated"}),ze++}if(u==="Google"&&Tn&&Date.now()-lr>=150){yield*io();let j=Ho(Tn);for(let se of j)yield se;Tn="",lr=Date.now()}}N.usageMetadata&&(Mn=N.usageMetadata),Mn&&(yield{type:"liveTokens",content:Mn.totalTokenCount})}if(de&&(de=!1,Wt?Ve+="</think>":(pe+="</think>",u==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Wt&&Ve.length>0){let N=0,ie=Math.min(it.length,Ve.length);for(let q=ie;q>0;q--)if(it.endsWith(Ve.substring(0,q))){N=q;break}let G=Ve.substring(N);if(G){let ke=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):G.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(ke)if(pe+=ke,u==="Google")Tn+=ke;else{yield*io();let ye=Ho(ke);for(let _e of ye)yield _e}}Wt=!1,Ve=""}if(yield*io(),It)break;let qo=(pe||"").trim(),El=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(qo.toLowerCase())||/\[\[END\]\]/i.test(qo.toLowerCase()),_l=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(qo.toLowerCase()),Cl=ne.length>0||Ut!==null,cr=on(qo).trim(),$l=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(cr),Al=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(cr.trim()),Ml=/[.!?}"'`’“”]$|```$/s.test(cr)||Al||$l;!El&&!_l&&!Cl&&qo.length>0,ot=!0,await Ot("agent",u)}catch(Se){if(It){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
1127
1128
 
1128
1129
  \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Se).includes("Incomplete JSON segment at the end")){de&&(de=!1,Wt?Ve+="</think>":(pe+="</think>",yield{type:"text",content:"</think>"})),ot=!0,await Ot("agent",u);break}if(de&&(de=!1,Wt?Ve+="</think>":pe+="</think>"),Wt&&Ve.length>0){let qn=0,an=Math.min(it.length,Ve.length);for(let Pt=an;Pt>0;Pt--)if(it.endsWith(Ve.substring(0,Pt))){qn=Pt;break}let Lt=Ve.substring(qn);if(Lt){let $t=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(it)?Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Lt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");$t&&(pe+=$t)}Wt=!1,Ve=""}let ue=Se instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Se.message).error.message).error.message}catch{return String(Se)}})():String(Se),at=new Date().toLocaleString(),jt=Z.join(hn,"agent");Fe.existsSync(jt)||Fe.mkdirSync(jt,{recursive:!0}),Fe.appendFileSync(Z.join(jt,"error.log"),`ERROR [${at}]: ${ue}
1129
1130