fluxflow-cli 3.23.0 → 3.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,803 @@
1
+ import{b as Xo}from"./chunk-7WH5DREO.js";import{c as hn,d as qs,g as Ze,h as Qt}from"./chunk-3VSDH7DF.js";import{a as Ys,b as $s,c as J,d as ce}from"./chunk-SIINYZWE.js";import{c as Mn,d as dn,e as yo,f as Cs,g as Os,h as Vo,i as Xt,j as Lt,k as Jt,l as In,m as Bn,n as sn,o as un,p as as,q as Ko,r as Wn,s as ls}from"./chunk-SGZ2OI72.js";import{a as ze,c as wo}from"./chunk-56EJGQU3.js";import{a as ml,b as br}from"./chunk-6DHFEWGX.js";var Jo=ml((So,Er)=>{(function(n,e){typeof So=="object"&&typeof Er<"u"?e(So):typeof define=="function"&&define.amd?define(["exports"],e):e(n.WHATWGFetch={})})(So,(function(n){"use strict";var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},t={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};function o(w){return w&&DataView.prototype.isPrototypeOf(w)}if(t.arrayBuffer)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],i=ArrayBuffer.isView||function(w){return w&&s.indexOf(Object.prototype.toString.call(w))>-1};function r(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function a(w){return typeof w!="string"&&(w=String(w)),w}function d(w){var T={next:function(){var E=w.shift();return{done:E===void 0,value:E}}};return t.iterable&&(T[Symbol.iterator]=function(){return T}),T}function c(w){this.map={},w instanceof c?w.forEach(function(T,E){this.append(E,T)},this):Array.isArray(w)?w.forEach(function(T){if(T.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+T.length);this.append(T[0],T[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(T){this.append(T,w[T])},this)}c.prototype.append=function(w,T){w=r(w),T=a(T);var E=this.map[w];this.map[w]=E?E+", "+T:T},c.prototype.delete=function(w){delete this.map[r(w)]},c.prototype.get=function(w){return w=r(w),this.has(w)?this.map[w]:null},c.prototype.has=function(w){return this.map.hasOwnProperty(r(w))},c.prototype.set=function(w,T){this.map[r(w)]=a(T)},c.prototype.forEach=function(w,T){for(var E in this.map)this.map.hasOwnProperty(E)&&w.call(T,this.map[E],E,this)},c.prototype.keys=function(){var w=[];return this.forEach(function(T,E){w.push(E)}),d(w)},c.prototype.values=function(){var w=[];return this.forEach(function(T){w.push(T)}),d(w)},c.prototype.entries=function(){var w=[];return this.forEach(function(T,E){w.push([E,T])}),d(w)},t.iterable&&(c.prototype[Symbol.iterator]=c.prototype.entries);function f(w){if(!w._noBody){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}}function l(w){return new Promise(function(T,E){w.onload=function(){T(w.result)},w.onerror=function(){E(w.error)}})}function u(w){var T=new FileReader,E=l(T);return T.readAsArrayBuffer(w),E}function h(w){var T=new FileReader,E=l(T),I=/charset=([A-Za-z0-9_-]+)/.exec(w.type),_=I?I[1]:"utf-8";return T.readAsText(w,_),E}function p(w){for(var T=new Uint8Array(w),E=new Array(T.length),I=0;I<T.length;I++)E[I]=String.fromCharCode(T[I]);return E.join("")}function m(w){if(w.slice)return w.slice(0);var T=new Uint8Array(w.byteLength);return T.set(new Uint8Array(w)),T.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:t.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:t.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:t.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():t.arrayBuffer&&t.blob&&o(w)?(this._bodyArrayBuffer=m(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):t.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||i(w))?this._bodyArrayBuffer=m(w):this._bodyText=w=Object.prototype.toString.call(w):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof w=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var w=f(this);if(w)return w;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var w=f(this);return w||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(t.blob)return this.blob().then(u);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var w=f(this);if(w)return w;if(this._bodyBlob)return h(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(p(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},t.formData&&(this.formData=function(){return this.text().then(x)}),this.json=function(){return this.text().then(JSON.parse)},this}var g=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function S(w){var T=w.toUpperCase();return g.indexOf(T)>-1?T:w}function b(w,T){if(!(this instanceof b))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');T=T||{};var E=T.body;if(w instanceof b){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,T.headers||(this.headers=new c(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!E&&w._bodyInit!=null&&(E=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=T.credentials||this.credentials||"same-origin",(T.headers||!this.headers)&&(this.headers=new c(T.headers)),this.method=S(T.method||this.method||"GET"),this.mode=T.mode||this.mode||null,this.signal=T.signal||this.signal||(function(){if("AbortController"in e){var M=new AbortController;return M.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(E),(this.method==="GET"||this.method==="HEAD")&&(T.cache==="no-store"||T.cache==="no-cache")){var I=/([?&])_=[^&]*/;if(I.test(this.url))this.url=this.url.replace(I,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})};function x(w){var T=new FormData;return w.trim().split("&").forEach(function(E){if(E){var I=E.split("="),_=I.shift().replace(/\+/g," "),M=I.join("=").replace(/\+/g," ");T.append(decodeURIComponent(_),decodeURIComponent(M))}}),T}function k(w){var T=new c,E=w.replace(/\r?\n[\t ]+/g," ");return E.split("\r").map(function(I){return I.indexOf(`
2
+ `)===0?I.substr(1,I.length):I}).forEach(function(I){var _=I.split(":"),M=_.shift().trim();if(M){var W=_.join(":").trim();try{T.append(M,W)}catch(B){console.warn("Response "+B.message)}}}),T}y.call(b.prototype);function C(w,T){if(!(this instanceof C))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(T||(T={}),this.type="default",this.status=T.status===void 0?200:T.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=T.statusText===void 0?"":""+T.statusText,this.headers=new c(T.headers),this.url=T.url||"",this._initBody(w)}y.call(C.prototype),C.prototype.clone=function(){return new C(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new c(this.headers),url:this.url})},C.error=function(){var w=new C(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var R=[301,302,303,307,308];C.redirect=function(w,T){if(R.indexOf(T)===-1)throw new RangeError("Invalid status code");return new C(null,{status:T,headers:{location:w}})},n.DOMException=e.DOMException;try{new n.DOMException}catch{n.DOMException=function(T,E){this.message=T,this.name=E;var I=Error(T);this.stack=I.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function A(w,T){return new Promise(function(E,I){var _=new b(w,T);if(_.signal&&_.signal.aborted)return I(new n.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function W(){M.abort()}M.onload=function(){var Y={statusText:M.statusText,headers:k(M.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(M.status<200||M.status>599)?Y.status=200:Y.status=M.status,Y.url="responseURL"in M?M.responseURL:Y.headers.get("X-Request-URL");var Se="response"in M?M.response:M.responseText;setTimeout(function(){E(new C(Se,Y))},0)},M.onerror=function(){setTimeout(function(){I(new TypeError("Network request failed"))},0)},M.ontimeout=function(){setTimeout(function(){I(new TypeError("Network request timed out"))},0)},M.onabort=function(){setTimeout(function(){I(new n.DOMException("Aborted","AbortError"))},0)};function B(Y){try{return Y===""&&e.location.href?e.location.href:Y}catch{return Y}}if(M.open(_.method,B(_.url),!0),_.credentials==="include"?M.withCredentials=!0:_.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&(t.blob?M.responseType="blob":t.arrayBuffer&&(M.responseType="arraybuffer")),T&&typeof T.headers=="object"&&!(T.headers instanceof c||e.Headers&&T.headers instanceof e.Headers)){var K=[];Object.getOwnPropertyNames(T.headers).forEach(function(Y){K.push(r(Y)),M.setRequestHeader(Y,a(T.headers[Y]))}),_.headers.forEach(function(Y,Se){K.indexOf(Se)===-1&&M.setRequestHeader(Se,Y)})}else _.headers.forEach(function(Y,Se){M.setRequestHeader(Se,Y)});_.signal&&(_.signal.addEventListener("abort",W),M.onreadystatechange=function(){M.readyState===4&&_.signal.removeEventListener("abort",W)}),M.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}A.polyfill=!0,e.fetch||(e.fetch=A,e.Headers=c,e.Request=b,e.Response=C),n.Headers=c,n.Request=b,n.Response=C,n.fetch=A,Object.defineProperty(n,"__esModule",{value:!0})}))});import Nf from"dotenv";import{GoogleGenAI as Xa,ThinkingLevel as it,HarmBlockThreshold as Kn,HarmCategory as Xn}from"@google/genai";import Cl,{promises as kr}from"node:fs";import{resolve as Ar}from"node:path";var cd=br(Jo(),1),xr="11434",Rr=`http://127.0.0.1:${xr}`,gl="0.6.3",yl=Object.defineProperty,wl=(n,e,t)=>e in n?yl(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Qo=(n,e,t)=>(wl(n,typeof e!="symbol"?e+"":e,t),t),ti=class n extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,n)}},ni=class{constructor(e,t,o){Qo(this,"abortController"),Qo(this,"itr"),Qo(this,"doneCallback"),this.abortController=e,this.itr=t,this.doneCallback=o}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},si=async n=>{if(n.ok)return;let e=`Error ${n.status}: ${n.statusText}`,t=null;if(n.headers.get("content-type")?.includes("application/json"))try{t=await n.json(),e=t.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await n.text()||e}catch{console.log("Failed to get text from error response")}throw new ti(e,n.status)};function Sl(){if(typeof window<"u"&&window.navigator){let n=navigator;return"userAgentData"in n&&n.userAgentData?.platform?`${n.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function Tl(n){if(n instanceof Headers){let e={};return n.forEach((t,o)=>{e[o]=t}),e}else return Array.isArray(n)?Object.fromEntries(n):n||{}}var bl=(n,e)=>n[e],oi=async(n,e,t={})=>{let o={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${gl} (${Sl()})`};t.headers=Tl(t.headers);try{let i=new URL(e);if(i.protocol==="https:"&&i.hostname==="ollama.com"){let r=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?bl(process.env,"OLLAMA_API_KEY"):void 0;!(t.headers.authorization||t.headers.Authorization)&&r&&(t.headers.Authorization=`Bearer ${r}`)}}catch(i){console.error("error parsing url",i)}let s=Object.fromEntries(Object.entries(t.headers).filter(([i])=>!Object.keys(o).some(r=>r.toLowerCase()===i.toLowerCase())));return t.headers={...o,...s},n(e,t)},Zo=async(n,e,t)=>{let o=await oi(n,e,{headers:t?.headers});return await si(o),o},jn=async(n,e,t,o)=>{let i=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(t)?JSON.stringify(t):t,r=await oi(n,e,{method:"POST",body:i,signal:o?.signal,headers:o?.headers});return await si(r),r},El=async(n,e,t,o)=>{let s=await oi(n,e,{method:"DELETE",body:JSON.stringify(t),headers:o?.headers});return await si(s),s},xl=async function*(n){let e=new TextDecoder("utf-8"),t="",o=n.getReader();for(;;){let{done:s,value:i}=await o.read();if(s)break;t+=e.decode(i,{stream:!0});let r=t.split(`
3
+ `);t=r.pop()??"";for(let a of r)try{yield JSON.parse(a)}catch{console.warn("invalid json: ",a)}}t+=e.decode();for(let s of t.split(`
4
+ `).filter(i=>i!==""))try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}},Rl=n=>{if(!n)return Rr;let e=n.includes("://");n.startsWith(":")&&(n=`http://127.0.0.1${n}`,e=!0),e||(n=`http://${n}`);let t=new URL(n),o=t.port;o||(e?o=t.protocol==="https:"?"443":"80":o=xr);let s="";t.username&&(s=t.username,t.password&&(s+=`:${t.password}`),s+="@");let i=`${t.protocol}//${s}${t.hostname}:${o}${t.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},kl=Object.defineProperty,Al=(n,e,t)=>e in n?kl(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ei=(n,e,t)=>(Al(n,typeof e!="symbol"?e+"":e,t),t),ii=class{constructor(e){ei(this,"config"),ei(this,"fetch"),ei(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Rl(e?.host??Rr)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let o=`${this.config.host}/api/${e}`;if(t.stream){let i=new AbortController,r=await jn(this.fetch,o,t,{signal:i.signal,headers:this.config.headers});if(!r.body)throw new Error("Missing body");let a=xl(r.body),d=new ni(i,a,()=>{let c=this.ongoingStreamedRequests.indexOf(d);c>-1&&this.ongoingStreamedRequests.splice(c,1)});return this.ongoingStreamedRequests.push(d),d}return await(await jn(this.fetch,o,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let t=new Uint8Array(e),o="",s=t.byteLength;for(let i=0;i<s;i++)o+=String.fromCharCode(t[i]);return btoa(o)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await El(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await jn(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Zo(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await jn(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await jn(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await jn(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Zo(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Zo(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await jn(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await jn(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},dd=new ii;var gd=br(Jo(),1),zs=class extends ii{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(Cl.existsSync(e)){let t=await kr.readFile(Ar(e));return Buffer.from(t).toString("base64")}}catch{}return e}async fileExists(e){try{return await kr.access(e),!0}catch{return!1}}async create(e){if(e.from&&await this.fileExists(Ar(e.from)))throw Error("Creating with a local path is not currently supported from ollama-js");return e.stream?super.create(e):super.create(e)}},yd=new zs;import{execSync as Ol}from"child_process";import{spawn as ri}from"child_process";var L=n=>{let e={};if(!n)return e;let t=0;for(;t<n.length;){for(;t<n.length&&/[\s,]/.test(n[t]);)t++;if(t>=n.length)break;let o=n.substring(t).match(/^(\w+)\s*=\s*/);if(!o){t++;continue}let s=o[1];t+=o[0].length;let i="";if(t<n.length&&(n[t]==='"'||n[t]==="'"||n[t]==="`")){let r=n[t];t++;let a=t,d=-1,c=t;for(;c<n.length;){let l=n.indexOf(r,c);if(l===-1)break;let u=0;for(let y=l-1;y>=0&&n[y]==="\\";y--)u++;if(u%2!==0){c=l+1;continue}let h=n.substring(l+1),p=h.trim(),m=p===""||/^,\s*\w+\s*=/.test(p)||p.startsWith(")")&&(p.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(p));if(m&&h.startsWith(`
5
+ `)){let y=p.split(`
6
+ `)[0];if(!y.includes("=")&&!y.includes(")")){c=l+1;continue}}if(m){d=l;break}c=l+1}d!==-1?(i=n.substring(a,d),t=d+1):(i=n.substring(a),t=n.length);let f=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());i=i.replace(/\\(.)/g,(l,u)=>{switch(u){case"n":return`
7
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return u===r?r:u}})}else if(t<n.length&&n[t]==="["){let r=0,a=null,d=t,c=-1;for(let f=t;f<n.length;f++){let l=n[f];if(a&&l===a){let u=0;for(let h=f-1;h>=0&&n[h]==="\\";h--)u++;u%2===0&&(a=null)}else!a&&(l==='"'||l==="'"||l==="`")&&(a=l);if(!a&&(l==="["?r++:l==="]"&&r--,r===0)){c=f;break}}if(c!==-1){i=n.substring(d,c+1),t=c+1;try{let f=i.trim();f.startsWith("'")||f.includes("'")}catch{}}else i=n.substring(d),t=n.length}else{let r=n.substring(t),a=r.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]\]))/);if(a){let d=a.index;i=r.substring(0,d).trim(),t+=d}else i=r.trim(),t=n.length}i==="true"?i=!0:i==="false"?i=!1:typeof i=="string"&&!isNaN(i)&&i.trim()!==""&&(i=Number(i)),typeof i=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(i=i.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),e[s]=i}return e};var To=null;try{let n=await import("node-pty");To=n.default||n}catch{}var xd=!!To,bo=n=>typeof n!="string"?n:n.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ai=n=>{if(!n)return"";let e=[[]],t=0,o=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,i=0,r,a=c=>{for(let f=0;f<c.length;f++){let l=c[f];if(l===`
8
+ `)for(t++,o=0;t>=e.length;)e.push([]);else if(l==="\r")o=0;else{for(;t>=e.length;)e.push([]);let u=e[t];for(;o>u.length;)u.push(" ");u[o]=l,o++}}};for(;(r=s.exec(n))!==null;){a(n.substring(i,r.index));let c=r[1],f=r[2],l=c?c.split(";").map(Number):[];if(f==="A"){let u=l[0]||1;t=Math.max(0,t-u)}else if(f==="B"){let u=l[0]||1;for(t=t+u;t>=e.length;)e.push([])}else if(f==="C"){let u=l[0]||1;o=o+u}else if(f==="D"){let u=l[0]||1;o=Math.max(0,o-u)}else if(f==="G"){let u=(l[0]||1)-1;o=Math.max(0,u)}else if(f==="H"||f==="f"){let u=(l[0]||1)-1,h=(l[1]||1)-1;for(t=Math.max(0,u),o=Math.max(0,h);t>=e.length;)e.push([])}else if(f==="K"){let u=l[0]||0;if(t<e.length){let h=e[t];if(u===0)h.length=o;else if(u===1)for(let p=0;p<o&&p<h.length;p++)h[p]=" ";else u===2&&(h.length=0)}}else if(f==="J"){let u=l[0]||0;(u===2||u===3)&&(e.length=0,e.push([]),t=0,o=0)}i=s.lastIndex}a(n.substring(i));let d=e.map(c=>c.join(""));for(;d.length>0&&d[d.length-1]==="";)d.pop();return d.join(`
9
+ `)},pt=null,Vs=!1,Rd=n=>{try{pt&&(Vs&&typeof pt.write=="function"?pt.write(n):pt.stdin&&pt.stdin.writable&&pt.stdin.write(n))}catch{}},kd=()=>{if(pt){try{Vs&&typeof pt.destroy=="function"?pt.destroy():typeof pt.kill=="function"&&(process.platform==="win32"?ri("taskkill",["/pid",pt.pid,"/f","/t"]):pt.kill("SIGKILL"))}catch{}pt=null,Vs=!1}},li=(n,e=!1)=>{if(process.platform!=="win32")return n;let t=[],o="",s=null,i=!1;for(let f=0;f<n.length;f++){let l=n[f];if(i){o+=l,i=!1;continue}if(l==="\\"){if(n[f+1]===" "){o+=" ",f++;continue}o+=l,i=!0;continue}s?(l===s&&(s=null),o+=l):l==='"'||l==="'"?(s=l,o+=l):l===";"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push(e?";":"&")):l==="&"&&!o.includes("://")?n[f+1]==="&"?(o.length>0&&(t.push(o),o=""),t.push("&&"),f++):(o.length>0&&(t.push(o),o=""),t.push("&")):l==="|"&&!o.includes("://")?(o.length>0&&(t.push(o),o=""),t.push("|")):/\s/.test(l)?o.length>0&&(t.push(o),o=""):o+=l}o.length>0&&t.push(o);let r=f=>!(!f.includes("/")||/^(https?|file|ftp):\/\//i.test(f)||f.startsWith("@")||f.startsWith("/")&&(f.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(f)||/[\(\)\{\}\;\<\>\=\'\"]/.test(f)),a=[];for(let f=0;f<t.length;f++){let l=t[f];if(l==="mkdir"&&e&&Hn()){let u=[],h=f+1;for(;h<t.length;){let p=t[h];if([">",">>","<","&","&&","|","||",";"].includes(p))break;p!=="-p"&&p!=="--parents"&&p!=="-v"&&p!=="--verbose"&&u.push(p),h++}if(u.length>0){let p=u.map(m=>{let y=m.replace(/^['"]|['"]$/g,""),g=m;return r(y)&&(g=m.replace(/\//g,"\\")),g});a.push("New-Item","-ItemType","Directory","-Force","-Path",p.join(","))}else a.push("New-Item","-ItemType","Directory","-Force");f=h-1;continue}if(l==="rm"&&e&&Hn()){let u=[],h=!1,p=!1,m=f+1;for(;m<t.length;){let g=t[m];if([">",">>","<","&","&&","|","||",";"].includes(g))break;g==="-rf"||g==="-fr"?(h=!0,p=!0):g==="-r"||g==="-R"||g==="--recursive"?h=!0:g==="-f"||g==="--force"?p=!0:u.push(g),m++}let y=["Remove-Item"];if(h&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let g=u.map(S=>{let b=S.replace(/^['"]|['"]$/g,""),x=S;return r(b)&&(x=S.replace(/\//g,"\\")),x});y.push("-Path",g.join(","))}a.push(...y),f=m-1;continue}if(l==="cp"&&e&&Hn()){let u=[],h=!1,p=!1,m=f+1;for(;m<t.length;){let g=t[m];if([">",">>","<","&","&&","|","||",";"].includes(g))break;g==="-r"||g==="-R"||g==="--recursive"?h=!0:g==="-f"||g==="--force"?p=!0:u.push(g),m++}let y=["Copy-Item"];if(h&&y.push("-Recurse"),p&&y.push("-Force"),u.length>0){let g=u.map(S=>{let b=S.replace(/^['"]|['"]$/g,""),x=S;return r(b)&&(x=S.replace(/\//g,"\\")),x});if(g.length>1){let S=g.pop();y.push("-Path",g.join(","),"-Destination",S)}else y.push("-Path",g[0])}a.push(...y),f=m-1;continue}if(l==="touch"&&e&&Hn()){let u=[],h=f+1;for(;h<t.length;){let p=t[h];if([">",">>","<","&","&&","|","||",";"].includes(p))break;u.push(p),h++}if(u.length>0){let m=`(${u.map(y=>{let g=y.replace(/^['"]|['"]$/g,""),S=y;return r(g)&&(S=y.replace(/\//g,"\\")),S}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;a.push(m)}f=h-1;continue}if(l==="|"&&t[f+1]==="tee"){t[f+2]==="-a"?(a.push(">>"),f+=2):(a.push(">"),f+=1);continue}if(l==="|"&&t[f+1]==="cat"&&t[f+2]===">"){a.push(">"),f+=2;continue}if(l==="|"){let u=t[f+1];if(u){let h=u.replace(/^['"]|['"]$/g,""),p=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(h);if(r(h)&&p){a.push(">");continue}}}a.push(l)}let d=!1,c=a.map(f=>{if(f==="echo")return d=!0,f;[">",">>","<","&","&&","|","||",";"].includes(f)&&(d=!1);let u=/^['"]|['"]$/.test(f),h=f;d&&u&&(h=f.replace(/^['"]|['"]$/g,""));let p=/^['"]|['"]$/.test(h),m=h.replace(/^['"]|['"]$/g,"");r(m)&&(h=h.replace(/\//g,"\\"));let y=h.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!p&&(h=`"${y}"`),h});if(e){let f="",l=0;for(let u=0;u<c.length;u++){let h=c[u];h==="&&"?(f+="; if ($?) {",l++):h===";"?(f+=" }".repeat(l)+";",l=0):(f&&!f.endsWith(" ")&&!f.endsWith("{")&&(f+=" "),f+=h)}return f+=" }".repeat(l),f}return c.join(" ")},ci=async(n,e={})=>{let{command:t}=L(n),{onChunk:o}=e;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",i=e.systemSettings||{},r={};return i.networkAccess===!1&&(r.HTTP_PROXY="http://127.0.0.1:9999",r.HTTPS_PROXY="http://127.0.0.1:9999",r.ALL_PROXY="socks5://127.0.0.1:9999",r.http_proxy="http://127.0.0.1:9999",r.https_proxy="http://127.0.0.1:9999",r.all_proxy="socks5://127.0.0.1:9999",r.NO_PROXY="localhost,127.0.0.1"),new Promise(a=>{let d=c=>{let f=c==="pwsh"||c==="powershell",l=li(t,f),u;s?c==="pwsh"?u="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":c==="powershell"?u="powershell.exe":u="cmd.exe":u=process.env.SHELL||"bash";let h=s?f?["-NoProfile","-Command",l]:["/c",l]:["-c",l];if(i.networkAccess===!1&&!s){let p=u,m=[...h];if(process.platform==="linux")u="unshare",h=["-n","-r",p,...m];else if(process.platform==="darwin"){let y=`(version 1)
10
+ (allow default)
11
+ (deny network-outbound)
12
+ (allow network-outbound (remote ip "localhost:*"))
13
+ (allow network-outbound (remote ip "127.0.0.1:*"))
14
+ `;u="sandbox-exec",h=["-p",y,p,...m]}}if(To)try{let p=To.spawn(u,h,{name:"xterm-256color",cols:e.cols||120,rows:e.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...r}});pt=p,Vs=!0;let m="",y=!1;return p.onData(g=>{if(!y){m+=g,o&&o(g);let S=bo(m);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(S)&&(y=!0,setTimeout(()=>a(`SUCCESS: Dev server started successfully in background.
15
+
16
+ ${S}`),500))}}),p.onExit(({exitCode:g})=>{if(y)return;pt=null;let S=ai(m||""),b=bo(S).replace(/\n{3,}/g,`
17
+
18
+ `)||"Command executed with no output.";a(g!==0?`ERROR: Command [${t}] failed with exit code [${g}].
19
+
20
+ ${b}`:`SUCCESS: Command [${t}] completed.
21
+
22
+ ${b}`)}),!0}catch(p){return s&&(c==="pwsh"||c==="powershell")&&p.code==="ENOENT"?!1:(Eo(a,l,t,r,o,c,i),!0)}else return Eo(a,l,t,r,o,c,i),!0};s?d("pwsh")||d("powershell")||d("cmd"):d("bash")})},Eo=(n,e,t,o,s,i="powershell",r={})=>{let a=process.platform==="win32",d=i==="pwsh"||i==="powershell",c;a?i==="pwsh"?c="C:\\Users\\User\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe":i==="powershell"?c="powershell.exe":c="cmd.exe":c=process.env.SHELL||"bash";let f=a?d?["-NoProfile","-Command",e]:["/c",e]:["-c",e];if(r.networkAccess===!1&&!a){let m=c,y=[...f];if(process.platform==="linux")c="unshare",f=["-n","-r",m,...y];else if(process.platform==="darwin"){let g=`(version 1)
23
+ (allow default)
24
+ (deny network-outbound)
25
+ (allow network-outbound (remote ip "localhost:*"))
26
+ (allow network-outbound (remote ip "127.0.0.1:*"))
27
+ `;c="sandbox-exec",f=["-p",g,m,...y]}}let l=a?ri(c,f,{cwd:process.cwd(),env:{...process.env,...o}}):ri(c,f,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});pt=l,Vs=!1,l.stdin&&l.stdin.on("error",()=>{pt=null});let u="",h="",p=!1;l.stdout.on("data",m=>{if(!p){let y=m.toString();u+=y,s&&s(y);let g=bo(u);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(g)&&(p=!0,setTimeout(()=>n(`SUCCESS: Dev server started successfully in background.
28
+
29
+ ${g}`),500))}}),l.stderr.on("data",m=>{if(!p){let y=m.toString();h+=y,s&&s(y)}}),l.on("close",m=>{if(p)return;pt=null;let y=[],g=ai(u),S=ai(h);g&&y.push(`STDOUT:
30
+ ${g}`),S&&y.push(`STDERR:
31
+ ${S}`),m!==0&&y.push(`EXIT CODE: ${m}`);let b=y.join(`
32
+
33
+ `)||"Command executed with no output.",x=bo(b).replace(/\n{3,}/g,`
34
+
35
+ `);n(m!==0?`ERROR: Command [${t}] failed with exit code [${m}].
36
+
37
+ ${x}`:`SUCCESS: Command [${t}] completed.
38
+
39
+ ${x}`)}),l.on("error",m=>{if(a&&m.code==="ENOENT"){if(i==="pwsh"){let g=li(t,!0);return Eo(n,g,t,o,s,"powershell",r)}else if(i==="powershell"){let g=li(t,!1);return Eo(n,g,t,o,s,"cmd",r)}}pt=null;let y=m instanceof Error?m.message:String(m);n(`ERROR: Failed to start command [${t}]: ${y}`)})};var Ks=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Ks!==null)return Ks;try{Ol('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Ks=!0}catch{Ks=!1}return Ks},fi=null,Cr=(n,e,t,o,s=!1,i=!0)=>(fi===null&&(fi=s),`
40
+ -- TOOL DEFINITIONS (STRING BASED PROTOCOL) --
41
+ TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' STRUCTURED STRING IN CHAT RESPONSE \u2190 MANDATORY
42
+ TOOL RULES:
43
+ - MAX 3 TOOL CALLS/TURN${n==="Flux"?" (Todo: 3+, Run: max 1 or 2 consecutive)":""}
44
+ ${n==="Flux"?`- JSON ESCAPE LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
45
+ - SAME file, MULTIPLE edits? ONE PatchFile (\u226415 blocks) \u2190 PRIORITY
46
+ - Tool denied? Ask for guidance \u2190 MANDATORY
47
+ - Need text or HUGE file? CodeSearch > Full Read
48
+ - MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
49
+ - DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
50
+ - Stuck on syntax error? Tell User > Time waste
51
+ `:""}
52
+ - USER COMMUNICATION -
53
+ - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Keep titles short
54
+
55
+ - WEB TOOLS -
56
+ - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: unknown info/docs. aiMode: LLM search
57
+ - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
58
+
59
+ ${n==="Flux"?`- WORKSPACE TOOLS (path = relative; FIRST ARGUMENT, path separator: '/') -
60
+ - [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. ${o!=="Google"?`${t?"Supports images/docs":""}`:"Supports images/docs"}
61
+ - [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. Minimize recursion
62
+ - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. TARGET MINIMAL searchContent. Line Ranges MUST for large searchContent AND escape sequences. ^...$ MUST for line ranges
63
+ - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
64
+ - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
65
+ - [tool:functions.Run(command="...")]. Runs ${e==="Windows"?Hn()?"POWERSHELL":"WINDOWS CMD":"BASH"} command. Destructive/Irreversible ops \u2192 Ask user
66
+ - [tool:functions.Todo(method="create/append/get", tasks=[STRING ARRAY], markDone=[TASK ARRAY])]. If long multi-task: create Todos before starting. \`get + markDone\` to mark complete. UPDATE EVERY TURN WHEN CREATED
67
+ ${fi?'\n- EMERGENCY TOOLS -\nInfo: `initial` = current task prompt. Revert `id` = turn before disaster (eg. disaster: `turn_3` \u2192 revert: `turn_2`). Reason explicitly\n- [tool:functions.EmergencyRollback(method="getCheckpoint/forceRevert", id="...")]. Rollback workspace in THIS agent loop. ONLY for catastrophic corruption. Before ending, verify no catastrophe. `id` omitted for `getCheckpoint`\n':""}${i?`
68
+ - SUB AGENT TOOLS -
69
+ **PROACTIVE use HIGHLY RECOMMENDED. Prefer for any task, no user nudge needed**
70
+ Invocations:
71
+ \u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
72
+ \u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
73
+ - [tool:functions.InvokeSync/Invoke(title="...", task="...")]. Task must be detailed: exact file paths, imports/exports, dependencies
74
+ - [tool:functions.Await(id="...", timeout="integer")]. Event-driven wait
75
+ - [tool:functions.GetProgress(id="...")]. Poll sparingly; NO initial poll. Work or await. Never end while subagent runs
76
+ - [tool:functions.Steer(id="...", message="...")]. Inject additional instruction or redirection into active async subagent
77
+ - [tool:functions.Cancel(id="...")]. Cancel async task ONLY if stalled (2m+) or incorrect`:""}`.trim():`- CREATIVE TOOLS (path = relative to CWD & WILL BE FIRST ARGUMENT, path separator: '/') -
78
+ - [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout, stable margins & headers/footers, NO WATERMARKS
79
+ - [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document, NO WATERMARKS, stable margins & headers/footers
80
+ - WORKSPACE & SUB AGENT TOOLS ARE NOT AVAILABLE IN FLOW`.trim()}`.trim());var Or=(n=!0,e=!0)=>`
81
+ Your exact tool syntax is: [tool:functions.ToolName(args...)]. Malformed calls will fail parsing. **NO OTHER SYNTAX/MARKERS/BOUNDARY ALLOWED** Proper bracket balancing per schema is mandatory
82
+
83
+ -- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS IN THIS TURN) --
84
+ - [tool:functions.Chat(title="<short creative title of FULL conversation in 3 or 4 words>")]. Consider full chat context to generate title NOT just latest message
85
+ - [tool:functions.Memory(action="temp", content="<summary of the user prompt & model responses ONLY FROM LATEST PROMPT UNDER 40 WORDS>. [Talked on: <date> <hour>]")]. Time format: YYYY-MM-DD HH am/pm
86
+
87
+ ${n?`-- User-specific long-term/permanent memory (USE BASED ON CONVERSATION CONTEXT, DO NOT RE-SAVE MEMORY WHICH IS ALREADY SAVED) --
88
+ - Add: [tool:functions.Memory(action="user", method="add", content="<string to add>. [Saved on: <date ONLY>]", score=2)] (Set score=2 ONLY if the user explicitly asked to "remember" or "save" this information, else omit this parameter entirely)
89
+ - Delete: [tool:functions.Memory(action="user", method="delete", id="<memory id>")]
90
+ - Update: [tool:functions.Memory(action="user", method="update", content-new="string to update", id="<memory id>")]
91
+
92
+ -- Memory Relevance Decay Tool --
93
+ - Score Adjustment: [tool:functions.addMemScore(id="<memory id>")]
94
+ You MUST call this tool when a specific saved memory in the '-- CURRENT SAVED USER MEMORIES --' list was relevant, referenced, or helpful in the agent's response or user prompt IN CURRENT MESSAGE. You can stack multiple calls
95
+
96
+ Explicit Triggers for permanent memory:
97
+ - User explicitly asks to 'remember' something
98
+ - User mentions something important long-term that should be remembered
99
+ - User provides information that could be useful for long-term reference
100
+ - User shares personal information or preferences
101
+
102
+ Usage Rules:
103
+ - Frequency for 'user' action: Based on explicit triggers.
104
+ - IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT ADD
105
+ - Chat Title is MANDATORY
106
+ - TEMPORARY Memory is MANDATORY
107
+ - WHEN Called User Memory, STILL use Temporary Memory
108
+ - MUST NOT IGNORE ANY TOOL CALLS IN GIVEN CONTEXT OF CHAT BETWEEN USER & AGENT`:""}`.trim();var xo={xHigh:`EFFORT: HIGH
109
+ Challenge assumptions, verify before concluding, prefer the simplest correct solution, assess architecture, scalability & trade-offs, verify dependencies, regressions, failure modes & modular design, plan: files, modules, interfaces & tests
110
+ Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
111
+ MANDATORY: Full technical verification`,High:`EFFORT: HIGH
112
+ Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
113
+ Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
114
+ MANDATORY: Full technical verification`,Medium:`EFFORT: MEDIUM
115
+ Focused, technical thinking, find the simplest solution meeting requirements, check error handling, assumptions, edge cases & dependencies, verify cohesive, modular changes, outline: files, functions & key logic
116
+ Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
117
+ MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`EFFORT: LOW
118
+ Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
119
+ Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`EFFORT: LOWEST
120
+ No thinking. Immediate response
121
+ Verify imports, tool results & system stability; avoid syntax errors`};import _r from"fs";var di=null,$r=null,Xs=null,_l=(n,e)=>{if(!e)return"";if(n!==$r||Xs===null){$r=n;try{let t=J(Lt,[]);Array.isArray(t)&&t.length>0?Xs=t.map(o=>`- ${o.memory}`).join(`
122
+ `):Xs=""}catch(t){Xs="",_r.appendFileSync(`${dn}/memory/error.txt`,`${t.message}
123
+ -------------------------------------------------
124
+
125
+ `)}}return Xs},Mr=(n="",e="",t=!0,o=!1)=>{if(typeof e=="boolean"&&(o=t,t=e,e=""),!t)return"";let s=n?.length>0&&!o?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
126
+ ${n}`:"";return s?`${s}`:""},Ir=(n,e,t,o,s=!0,i=!1,r="Google",a=!1,d,c)=>{let f=!1;process.env.forcedReasoning&&process.env.NVIDIA_BASE_URL&&r.toUpperCase()==="NVIDIA"&&(f=!0);let l="";if(!d&&r==="Google"){let C=e;e==="Fast"&&(C="Off"),e==="Low"&&(C="Minimal"),e==="Standard"&&(C="Medium"),(e==="xHigh"||e==="Max")&&(C="xHigh"),l=xo[C]||xo.Medium}if(d||r!=="Google"){let C={Fast:"LOWEST",Low:"LOW",Medium:"MEDIUM",Standard:"MEDIUM",High:"HIGH",xHigh:"HIGH",Max:"HIGH"};l=xo.xHigh,l=l.replace("EFFORT: HIGH",`EFFORT: ${C[e]}`).replace(`
127
+ MANDATORY: Full technical verification`,""),e==="Fast"?l=`EFFORT: LOWEST
128
+ No thinking. Immediate response
129
+ Verify imports, tool results & system stability; avoid syntax errors`:e==="Low"&&(l=`EFFORT: LOW
130
+ Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
131
+ Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`)}let u=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",h=n.instructions&&n.instructions?.length>0?`User Preferences: ${n.instructions}
132
+
133
+ `:"",p=n.nickname&&n.nickname?.length>0?`User Nickname: ${n.nickname}
134
+ ${h.length?"":`
135
+ `}`:"",m=n.name&&n.name?.length>0?`User Name: ${n.name}
136
+ ${p.length||h.length?"":`
137
+ `}`:"",y=process.cwd(),g=_l(c,s),S=g?.length>0?`--- SAVED MEMORIES ---
138
+ ${g}
139
+
140
+ `:"",b=(()=>{let C=process.cwd().toLowerCase();if(process.platform==="win32"){let R=process.env.SystemRoot?.toLowerCase()||"c:\\windows",A=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",w=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return C.startsWith(R)||C.startsWith(A)||C.startsWith(w)}else return C==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(A=>C.startsWith(A))})(),x=[{name:"Fluxflow.md",desc:"HIGH PRIORITY"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(i||di===null){let C=x.filter(R=>_r.existsSync(R.name));di=t==="Flux"&&C.length>0?`
141
+ -- PROJECT CONTEXT --
142
+ ${C.map(R=>`- ${R.name}: ${R.desc}`).join(`
143
+ `)}
144
+ Check these first; These Files > Training Data. Safety rules apply
145
+ `:""}let k=di;return`=== SYSTEM PROMPT ===
146
+ Identity: Flux Flow. Sassy, Friendly, CLI Agent
147
+ ${t==="Flux"?"Stepwise execution, run automated tests":`Mode: ${t}. Concise, Humorous, Sarcastic`}
148
+
149
+ - USE DIRECTORY STRUCTURE FOR FILE PATH RESOLUTION${s?`
150
+ - USE RELATIVE TIME REFERENCE eg. few mins ago
151
+ -- Chat Context > Metadata`:""}
152
+
153
+ -- THINKING GUIDANCE --
154
+ ${r==="Mistral"||r==="Google"&&!d?`${l}
155
+ ${f||e!=="Fast"&&(r==="Mistral"&&!d||e!=="xHigh"&&!d)?`CRITICAL THINKING POLICY
156
+ - Use <think>...</think> for reasoning before responding any queries
157
+ `:""}`:`${l}
158
+ `}
159
+ ${Cr(t,u,r.toLowerCase()==="deepseek"?!1:a,r,o?.advanceRollback,o?.subAgents!==!1)}
160
+ ${k}${s?`
161
+ -- MEMORY RULES --
162
+ - Subtly Personalize with RELEVENT CONTEXTUAL MEMORIES. Auto Saves
163
+ `:""}
164
+ -- SECURITY POLICIES --
165
+ - Sensitive files? Ask before Read${b?`
166
+ - PROTECTED DIRECTORY`:""}
167
+
168
+ -- CHAT FORMATTING --
169
+ - GFM Markdown
170
+ - Language: ENGLISH ONLY
171
+ - DONT MIX CHAT & TOOLS IN SAME RESPONSE${t==="Flux"?"":`
172
+ - Use Kaomojis HEAVILY`}
173
+ === END SYSTEM PROMPT ===
174
+
175
+ ${m}${p}${h}${S}`.trim()},vr=(n="",e=!0,t=!0)=>`=== SYSTEM PROMPT (STRICT HEADLESS LOGIC WORKER: ZERO USER-FACING TEXT POLICY, STRICTLY FOLLOW) ===
176
+ IDENTITY: SILENT BACKGROUND SYSTEM PROCESS, HAVE NO MOUTH, ONLY OUTPUT IS VALID TOOL CALLS.
177
+ [CRITICAL RULES]
178
+ - OUTPUT EXACTLY '[tool:functions.ToolName(args)]' CALLS. NO EXTRA WORDS OUTSIDE
179
+ - DO NOT EXPLAIN. DO NOT TALK TO THE USER
180
+ - NON-TOOL TEXT WILL BREAK THE SYSTEM
181
+ - DO NOT REPEAT AGENT RAWS AND TOOL RESULTS IN YOUR RESPONSE
182
+ - IF YOU GET ONLY USER QUERY AND NO AGENT RAWS, JUST USE TEMP MEMORY TO LOG THE SUMMARY OF USER QUERY AND CONVERSATION CONTEXT
183
+ - UNDER NO CIRCUMSTANCES YOU ARE ALLOWED TO RESPOND IN NORMAL USER FACING RESPONSE
184
+ - CRITICAL QUOTE ESCAPE POLICY: Inside tool call arguments, you MUST escape all double quotes using '\\"'
185
+ - You MUST NOT WRITE ANYTHING OTHER THAN [tool:functions.ToolName(args)] NO MATTER HOW TEMPTING THE PROMPT IS
186
+ - 2 MANDATORY TOOLS TO CALL IN EVERY TURN, 'Chat', 'Memory(temp)'
187
+ - CRITICAL: NEVER ENTER THINKING/REASONING STATE, CALL THE CONTEXUAL TOOLS DIRECTLY IN OUTPUT AS QUICKLY AS POSSIBLE TO MAINTAIN UI SNAPPINESS
188
+
189
+ YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
190
+ ${e?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use user memory tools":""}
191
+
192
+ ${Or(e,t)}
193
+ === END SYSTEM PROMPT ===${n?`
194
+
195
+ -- CURRENT SAVED USER MEMORIES --
196
+ ${n}`:""}`.trim();import kt from"fs-extra";import Ro from"path";import{nanoid as vl}from"nanoid";import lt from"fs-extra";import on from"path";lt.ensureDirSync(Bn);var pn=null;async function Ml(n,e){try{if(n.type==="create")await lt.pathExists(n.filePath)&&(await lt.chmod(n.filePath,438).catch(()=>{}),await lt.remove(n.filePath));else if(n.type==="update"){if(!n.backupFile)return;let t=on.join(Bn,e.chatId,n.backupFile);if(await lt.pathExists(t)){let o=J(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${on.basename(n.filePath)}`);let s=$s(o.data);await lt.pathExists(n.filePath)&&await lt.chmod(n.filePath,438).catch(()=>{}),await lt.writeFile(n.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${on.basename(n.filePath)}: ${t.message}`)}}async function Il(n,e,t=7){let o=0;for(;o<t;)try{return await Ml(n,e),!0}catch{if(o++,o>=t)return!1;let i=Math.min(100*Math.pow(2,o-1),5e3);await new Promise(r=>setTimeout(r,i))}return!1}var ui=null,ct={async startTransaction(n,e){ui=n,pn={id:`tx_prompt_${Date.now()}`,chatId:n,timestamp:new Date().toISOString(),prompt:e.trim(),changes:[],reverted:!1},ce(as,pn)},async recordFileChange(n,e=null){try{if(!pn){if(ui){let r=J(sn,[]),a=[...r].reverse().find(d=>d.chatId===ui);if(a){if(a.changes.some(u=>u.filePath===n))return;let f=await lt.pathExists(n)||e?"update":"create",l=null;if(f==="update"){let u=on.basename(n);l=`${a.id}_${u}.bak`;let h=on.join(Bn,a.chatId);await lt.ensureDir(h);let p=on.join(h,l),m=e!==null?e:await lt.readFile(n,"utf8").catch(()=>null);m!==null?ce(p,{data:Ys(m)}):(f="create",l=null)}a.changes.push({filePath:n,type:f,backupFile:l}),ce(sn,r)}}return}if(pn.changes.some(r=>r.filePath===n))return;let s=await lt.pathExists(n)||e?"update":"create",i=null;if(s==="update"){let r=on.basename(n);i=`${pn.id}_${r}.bak`;let a=on.join(Bn,pn.chatId);await lt.ensureDir(a);let d=on.join(a,i),c=e!==null?e:await lt.readFile(n,"utf8").catch(()=>null);c!==null?ce(d,{data:Ys(c)}):(s="create",i=null)}pn.changes.push({filePath:n,type:s,backupFile:i}),ce(as,pn)}catch{}},async commitTransaction(){if(pn)try{let n=J(sn,[]);if(n.push(pn),n.length>512e3){let e=n.shift();if(e.changes)for(let t of e.changes)t.backupFile&&await lt.remove(on.join(Bn,e.chatId,t.backupFile)).catch(()=>{})}ce(sn,n),await lt.remove(as).catch(()=>{})}catch{}finally{pn=null}},async recoverCrashedTransaction(){try{if(await lt.pathExists(as)){let n=J(as,null);if(n?.changes?.length>0){let e=J(sn,[]);e.some(t=>t.id===n.id)||(e.push(n),ce(sn,e))}await lt.remove(as).catch(()=>{})}}catch{}},async rollbackToBefore(n){let e=J(sn,null);if(!e)throw new Error("No transaction ledger found.");let t=e.findIndex(r=>r.id===n);if(t===-1)throw new Error(`Transaction [${n}] not found.`);let o=e[t].chatId,s=e[t].prompt,i=e.slice(t).filter(r=>r.chatId===o&&!r.reverted).reverse();for(let r of i){for(let a of[...r.changes].reverse())await Il(a,r);for(let a of r.changes)if(a.backupFile){let d=on.join(Bn,r.chatId,a.backupFile);await lt.remove(d).catch(()=>{})}e=e.filter(a=>a.id!==r.id),ce(sn,e)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(n){try{return J(sn,[]).filter(t=>t.chatId===n&&!t.reverted)}catch{return[]}},async deleteChatBackups(n){try{await lt.remove(on.join(Bn,n));let e=J(sn,[]),t=e.filter(o=>o.chatId!==n);e.length!==t.length&&ce(sn,t)}catch{}}};var Lr=Promise.resolve(),ko=n=>{let e=Lr.then(async()=>{try{return await n()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Lr=e.catch(()=>{}),e},cs=async()=>{await kt.ensureDir(Os);let n={};if(await kt.pathExists(Cs))try{n=J(Cs,{})}catch{n={}}for(let e in n){let t=Ro.join(Os,`${e}.json`);Object.defineProperty(n[e],"messages",{get:()=>{if(kt.existsSync(t))try{return J(t,[])}catch{return[]}return[]},set:o=>{try{ce(t,o)}catch{}},enumerable:!1,configurable:!0})}return n},Zd=async(n,e,t)=>ko(async()=>{await kt.ensureDir(Os);let o=await cs(),s=o[n],i=(t||[]).filter(y=>!y.isUpdateNotification&&(!y.isMeta||y.text&&y.text.includes("Request Cancelled")));try{(await Qt()).systemSettings?.preserveThinking===!1&&(i=i.filter(g=>g.role!=="think"))}catch{}let r=y=>{if(!y)return;let g=typeof y=="string"?y:y.text||y.content||"";if(!g||typeof g!="string")return;let S=g.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!S)return;let b=S.split(/\s+/),x;return b.length>7?x=b.slice(0,7).join(" ")+"...":S.length>45?x=S.substring(0,45).trimEnd()+"...":x=S,x},a,d=i.filter(y=>y.role==="user"),c=d[0],f=d[d.length-1],l=r(f),u=r(c);s&&s.prompt?Math.random()<.5&&l?a=l:a=s.prompt:a=u||l;let h=e||(s?s.name:`Session ${n.slice(-6)}`),p=Ro.join(Os,`${n}.json`);ce(p,i),o[n]={name:h,prompt:a||void 0,updatedAt:Date.now()};let m={};for(let y in o)m[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};ce(Cs,m)}),Nr=async(n,e)=>ko(async()=>{let t=await cs();t[n]?(t[n].name=e,t[n].updatedAt=Date.now()):t[n]={name:e,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};ce(Cs,o)}),Ll=async n=>ko(async()=>{let e=await cs();delete e[n];let t={};for(let r in e)t[r]={name:e[r].name,prompt:e[r].prompt||void 0,updatedAt:e[r].updatedAt};if(ce(Cs,t),await kt.pathExists(Wn))try{let r=J(Wn,[]);if(Array.isArray(r)){let a=r.filter(d=>Object.keys(d)[0]!==String(n));ce(Wn,a)}}catch{}let o=J(Jt,{});o[n]&&(delete o[n],ce(Jt,o));let s=J(In,{});s[n]&&(delete s[n],ce(In,s)),await ct.deleteChatBackups(n);let i=Ro.join(Os,`${n}.json`);if(await kt.pathExists(i))try{await kt.remove(i)}catch{}return e}),eu=()=>`flow-${vl(6)}`,tu=async n=>{if(!n||n==="Never")return;let e=parseInt(n);if(isNaN(e))return;let t=await cs(),o=Date.now(),s=e*24*60*60*1e3,i=0;for(let r in t){let a=t[r];a.updatedAt&&o-a.updatedAt>s&&(await Ll(r),i++)}return i},Nl=n=>{let e=n.replace(/[\[\]]/g,"").trim(),t=new Date(e);if(!isNaN(t.getTime()))return t.getTime();let o=e.split(/,\s*|\s+/);if(o.length===0)return null;let s=o[0],i=o[1]||"",r=o[2]||"",a=s.split(/[-\/.]/).map(Number);if(a.length!==3)return null;let d="en";try{d=Intl.DateTimeFormat().resolvedOptions().locale||"en"}catch{}let c=!/^en[-_]?us$|^en$/.test(d?.toLowerCase()),f,l,u;if(a[0]>1e3)f=a[0],l=a[1],u=a[2];else if(a[2]>1e3)f=a[2],a[0]>12?(u=a[0],l=a[1]):a[1]>12?(u=a[1],l=a[0]):c?(u=a[0],l=a[1]):(l=a[0],u=a[1]);else return null;if(l<1||l>12||u<1||u>31)return null;let h=0,p=0,m=0;if(i){let g=i.split(":").map(Number);h=g[0]||0,p=g[1]||0,m=g[2]||0,r.toLowerCase()==="pm"&&h<12?h+=12:r.toLowerCase()==="am"&&h===12&&(h=0)}let y=new Date(f,l-1,u,h,p,m);return isNaN(y.getTime())?null:y.getTime()},Pl=async n=>{try{if(!await kt.pathExists(n))return;let e=await kt.readFile(n,"utf8");if(!e.trim())return;let t=e.split(`
197
+ `),o=[],s=null,i=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let l of t)i.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 r=10080*60*1e3,a=Date.now(),d=[],c=/(\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(i.test(l.header)){let p=l.header.match(c);if(p){let m=Nl(p[1]);if(m&&a-m>r)continue}}let h=l.header+(l.body.length>0?`
198
+ `+l.body.join(`
199
+ `):"");d.push(h)}let f=d.join(`
200
+ `).trim();f?await kt.writeFile(n,f+`
201
+ `,"utf8"):await kt.writeFile(n,"","utf8")}catch{}},nu=async n=>{try{if(!await kt.pathExists(n))return;let e=async t=>{let o=await kt.readdir(t);for(let s of o){let i=Ro.join(t,s);(await kt.stat(i)).isDirectory()?(await e(i),(await kt.readdir(i)).length===0&&await kt.remove(i)):s.endsWith(".log")&&await Pl(i)}};await e(n)}catch{}},Pr=(n,e=4)=>{if(n.length<=1)return n;let t=n[0],o=n.slice(1),s=e*2,i=o.slice(s);return[t,...i]};var su=async(n,e,t)=>ko(async()=>{let o=J(Wn,[]);Array.isArray(o)||(o=[]);let s={total:e,context:t},i=o.findIndex(r=>Object.keys(r)[0]===String(n));i!==-1?o[i]={[String(n)]:s}:o.push({[String(n)]:s}),ce(Wn,o)}),ou=async n=>{try{if(!await kt.pathExists(Wn))return{total:0,context:0};let e=J(Wn,[]);if(!Array.isArray(e))return{total:0,context:0};let t=e.find(o=>Object.keys(o)[0]===String(n));return t?t[String(n)]:{total:0,context:0}}catch{return{total:0,context:0}}};import mt from"fs-extra";import Dr from"path";var Dl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),ne=null,Gn=null,Fr=0,_s=!1,vn={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ms=(n,e)=>{if(!n)return{};let t=Object.keys(n),o=new Date(new Date(e).getTime()-720*60*60*1e3),s={};for(let i of t)new Date(i)>=o&&(s[i]=n[i]);return s},Ao=async()=>{let n=new Date().toISOString().split("T")[0];try{!await mt.exists(Xt)&&await mt.exists(Vo)&&(await mt.ensureDir(Dr.dirname(Xt)),await mt.move(Vo,Xt))}catch{}let e=Xt+".tmp",t=null;try{if(await mt.exists(e)){let s=(await mt.readFile(e,"utf8")).trim(),i=null;if(s.startsWith("{")||s.startsWith("[")?i=JSON.parse(s):i=JSON.parse($s(s)),i&&i.date&&i.stats){t=i;try{await mt.rename(e,Xt)}catch{}}else try{await mt.remove(e)}catch{}}}catch{try{await mt.remove(e)}catch{}}if(!t)try{if(await mt.exists(Xt)){let s=(await mt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?t=JSON.parse(s):t=JSON.parse($s(s))}}catch{}let o=t;if(o){let s=o.stats||{...vn},i={...vn,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let r=o.history||{},a=Ms(r,n);if(Object.keys(r).length!==Object.keys(a).length&&(_s=!0),o.date===n)return{...o,stats:i,history:a};{let d=o.date,c=i,f={...a};return d&&(f[d]=c),{date:n,stats:{...vn},history:Ms(f,n)}}}return{date:n,stats:{...vn},history:{}}},hi=async()=>{if(!(!_s||!ne))try{await mt.ensureDir(Dr.dirname(Xt));let n=null;try{if(await mt.exists(Xt)){let s=(await mt.readFile(Xt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?n=JSON.parse(s):n=JSON.parse($s(s))}}catch{}if(n&&n.date===ne.date&&n.stats){for(let s in ne.stats)if(n.stats[s]!==void 0){if(Array.isArray(ne.stats[s])){let i=Array.isArray(n.stats[s])?n.stats[s]:[],r=ne.stats[s],a=new Map;for(let d of[...i,...r])d&&d.timestamp&&a.set(d.timestamp,d);ne.stats[s]=Array.from(a.values())}else if(typeof ne.stats[s]=="number")ne.stats[s]=Math.max(ne.stats[s],Number(n.stats[s])||0);else if(ne.stats[s]&&typeof ne.stats[s]=="object"){let i=n.stats[s]||{},r=ne.stats[s];for(let a in i)if(typeof i[a]=="number")r[a]=Math.max(r[a]||0,i[a]);else if(i[a]&&typeof i[a]=="object"){r[a]||(r[a]={});for(let d in i[a])if(typeof i[a][d]=="number")r[a][d]=Math.max(r[a][d]||0,i[a][d]);else if(i[a][d]&&typeof i[a][d]=="object"){r[a][d]||(r[a][d]={});for(let c in i[a][d])r[a][d][c]=Math.max(r[a][d][c]||0,i[a][d][c])}}}}}if(n&&n.history){let s={...ne.history||{}};for(let i in n.history)if(s[i])for(let r in s[i])if(r==="imageCalls"){let a=Array.isArray(n.history[i].imageCalls)?n.history[i].imageCalls:[],d=Array.isArray(s[i].imageCalls)?s[i].imageCalls:[],c=new Map;for(let f of[...a,...d])f&&f.timestamp&&c.set(f.timestamp,f);s[i].imageCalls=Array.from(c.values())}else typeof s[i][r]=="number"&&(s[i][r]=Math.max(s[i][r],Number(n.history[i][r])||0));else s[i]=n.history[i];ne.history=Ms(s,ne.date||today)}else if(ne&&ne.history){let s=new Date().toISOString().split("T")[0];ne.history=Ms(ne.history,s)}ne.saveId=Dl();let e=Xt+".tmp",t=Ys(JSON.stringify(ne,null,2));await mt.writeFile(e,t,"utf8");let o=await mt.open(e,"r+");await mt.fsync(o),await mt.close(o),await mt.rename(e,Xt),_s=!1,Fr=Date.now()}catch{}},Co=()=>{if(_s=!0,Gn)return;let n=Date.now(),e=Math.max(0,1500-(n-Fr));Gn=setTimeout(async()=>{await hi(),Gn=null},e),Gn.unref&&Gn.unref()},du=async()=>{ne=await Ao(),_s&&Co()},uu=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await hi()},Rn=async()=>{let n=new Date().toISOString().split("T")[0];if(!ne)ne=await Ao();else if(ne.date!==n){let e=ne.date,t=ne.stats,o=ne.history||{};t&&(o[e]=t),ne={date:n,stats:{...vn},history:Ms(o,n)},_s=!0,await hi()}return ne&&ne.stats&&!Array.isArray(ne.stats.imageCalls)&&(ne.stats.imageCalls=[]),ne.stats},Fl=async()=>{let n=new Date().toISOString().split("T")[0];ne||(ne=await Ao()),ne.date!==n&&await Rn();let e=ne.history||{},t=Ms(e,n);ne.history=t;let o=ne.stats||{...vn},s={...vn};s.imageCalls=[],s.models={};let i=(r,a)=>{for(let d in r)if(d==="imageCalls")r.imageCalls=[...r.imageCalls||[],...a.imageCalls||[]];else if(d==="models"){let c=a.models||{};for(let f in c){r.models[f]||(r.models[f]={});for(let l in c[f]){r.models[f][l]||(r.models[f][l]={tokens:0,cachedTokens:0,candidateTokens:0});let u=r.models[f][l],h=c[f][l];u.tokens+=h.tokens||0,u.cachedTokens+=h.cachedTokens||0,u.candidateTokens+=h.candidateTokens||0}}}else typeof r[d]=="number"&&(r[d]+=a[d]||0)};i(s,o);for(let r in t)i(s,t[r]);return s},$t=async(n,e)=>{n==="toolSuccess"?Js.toolSuccess++:n==="toolFailure"?Js.toolFailure++:n==="toolDenied"&&Js.toolDenied++;let t=await Rn();t[n]!==void 0&&t[n]++,e&&n==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[e]=(t.providerRequests[e]||0)+1),Co()},Js={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Ht=async(n,e,t,o)=>{n==="linesAdded"?Js.linesAdded+=e:n==="linesRemoved"&&(Js.linesRemoved+=e);let s=await Rn();if(s[n]!==void 0&&(s[n]+=Math.floor(e)),t&&o&&(n==="tokens"||n==="cachedTokens"||n==="candidateTokens")){s.models||(s.models={}),s.models[t]||(s.models[t]={}),s.models[t][o]||(s.models[t][o]={tokens:0,cachedTokens:0,candidateTokens:0});let i=s.models[t][o];n==="tokens"&&(i.tokens+=Math.floor(e)),n==="cachedTokens"&&(i.cachedTokens+=Math.floor(e)),n==="candidateTokens"&&(i.candidateTokens+=Math.floor(e))}Co()},Ul=async(n=1)=>{let e=new Date,t=e.toISOString().split("T")[0];ne||(ne=await Ao()),ne.date!==t&&await Rn();let o=e.getFullYear(),s=e.getMonth();e.getDate()<n&&(s-=1,s<0&&(s=11,o-=1));let a=new Date(o,s,n).toISOString().split("T")[0],d=ne.history||{},c=ne.stats||{...vn},f={...vn};f.imageCalls=[],f.models={};let l=(u,h)=>{for(let p in u)if(p==="imageCalls")u.imageCalls=[...u.imageCalls||[],...h.imageCalls||[]];else if(p==="models"){let m=h.models||{};for(let y in m){u.models[y]||(u.models[y]={});for(let g in m[y]){u.models[y][g]||(u.models[y][g]={tokens:0,cachedTokens:0,candidateTokens:0});let S=u.models[y][g],b=m[y][g];S.tokens+=b.tokens||0,S.cachedTokens+=b.cachedTokens||0,S.candidateTokens+=b.candidateTokens||0}}}else typeof u[p]=="number"&&(u[p]+=h[p]||0)};l(f,c);for(let u in d)u>=a&&u<t&&l(f,d[u]);return f},pi=async(n,e={})=>{let t=await Qt().catch(()=>({})),o=e.apiTier||t.apiTier||"Free",s=e.quotas||e.systemSettings?.quotas||t.quotas||{},i=s.providerBudgets||{},r=!!i.__useProvider,a=e.aiProvider||t.aiProvider||"Google",d=r&&!!i[a],c=()=>{if(d){let f=i[a];return{agentLimit:typeof f.agentLimit=="number"&&f.agentLimit>0?f.agentLimit:99999999,tokenLimit:typeof f.tokenLimit=="number"&&f.tokenLimit>0?f.tokenLimit:99999999999999,monthlyTokenLimit:typeof f.monthlyTokenLimit=="number"&&f.monthlyTokenLimit>0?f.monthlyTokenLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999}};if(n==="agent"){let{agentLimit:f,tokenLimit:l,monthlyTokenLimit:u}=c(),h=await Rn(),p;s.resetMode==="Custom"?p=await Ul(s.resetDay||1):p=await Fl();let m=0,y=0,g=0;if(d){m=h.providerRequests?.[a]||0;let S=h.models?.[a]||{};for(let x in S)y+=S[x]?.tokens||0;let b=p.models?.[a]||{};for(let x in b)g+=b[x]?.tokens||0}else m=h.agent||0,y=h.tokens||0,g=p.tokens||0;return o==="Free"&&h.agent+h.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:m>=f?{allowed:!1,reason:d?`Daily Request Limit Reached for ${a}`:"Daily Agent Request Limit Reached"}:y>=l?{allowed:!1,reason:d?`Daily Token Budget Exhausted for ${a}`:"Daily Token Budget Exhausted"}:g>=u?{allowed:!1,reason:d?`Monthly Token Budget Exhausted for ${a}`:"Monthly Token Budget Exhausted"}:{allowed:!0}}if(n==="background"){let f=await Rn();if(o==="Free"&&f.agent+f.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let l=f.background<(s.backgroundLimit||999999);return{allowed:l,reason:l?void 0:"Background Request Limit Exceeded"}}if(n==="search"){let l=(await Rn()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Ur=async(n,e={})=>(await pi(n,e)).allowed,mi=n=>{if(!n||n.length===0)return[];let t=[...n].sort((s,i)=>s.timestamp-i.timestamp),o=[];for(let s of t){if(o.length>0){let i=o[o.length-1];if(s.timestamp>=i.start&&s.timestamp<i.end){i.calls.push(s),i.spent+=s.cost;continue}}o.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return o},Br=(n,e)=>{if(!n||n.length===0)return .025;let o=mi(n);if(o.length===0)return .025;let s=[];for(let l of o){let u=.025;if(s.length>0){let p=s[s.length-1],m=!1;if(s.length>=2){let y=s[s.length-2];p.ratio>=.8&&y.ratio>=.8&&(m=!0)}if(m)u=.015;else{let y=p.limit,g=p.ratio;g>=.8?u=y===.015?.015:y:g<.4?u=Math.min(.025,y+.005):g>=.4&&g<.6?u=Math.min(.025,y+.004):u=Math.min(.025,y+.002)}}let h=u>0?l.spent/u:0;s.push({limit:u,spent:l.spent,ratio:h})}let i=o[o.length-1];if(e<i.end)return s[s.length-1].limit;let r=s[s.length-1].limit,a=r,d=s[s.length-1].ratio,c=i.end,f=0;for(let l=s.length-1;l>=0&&s[l].ratio>=.8;l--)f++;for(;c<=e;){let l=.025;f>=2?l=.015:d>=.8?l=a===.015?.015:a:d<.4?l=Math.min(.025,a+.005):d>=.4&&d<.6?l=Math.min(.025,a+.004):l=Math.min(.025,a+.002),a=l,d=0,f=0,c+=36e5,r=l}return r},Wr=async n=>{let e=n.imageSettings||{keyType:"Default",quality:"Low-High"};if(e.keyType!=="Default")return!0;let o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[e.quality]||.002,s=await Rn();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),r=mi(s.imageCalls),a=0;if(r.length>0){let c=r[r.length-1];i>=c.start&&i<c.end&&(a=c.spent)}let d=Br(s.imageCalls,i);return a+o<=d},jr=async()=>{let n=await Rn();n.imageCalls||(n.imageCalls=[]);let e=Date.now(),t=mi(n.imageCalls),o=[],s=0,i=0;if(t.length>0){let c=t[t.length-1];e>=c.start&&e<c.end&&(o=c.calls,s=c.spent,i=Math.max(0,Math.ceil((c.end-e)/(60*1e3))))}let r=Br(n.imageCalls,e),a=Math.max(0,r-s),d=s;return{totalSpent:s,remaining:a,activeCallsCount:o.length,nextResetMin:i,reclaimCost:d,limit:r}},Hr=async n=>{let e=n.imageSettings||{keyType:"Default",quality:"Low-High"},o={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[e.quality]||.002,s=await Rn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Co()};import qr from"puppeteer";import zr from"fs";import Vr from"path";import Gr from"os";import Qs from"path";import Is from"fs";import{createRequire as Bl}from"module";import{fileURLToPath as Wl}from"url";var jl=Bl(import.meta.url),Yr=Qs.dirname(Wl(import.meta.url));function fs(){let n=Gr.platform(),e=Gr.arch(),t="",o="",s="";if(n==="win32")t=e==="x64"?"win64":"win32",o="chrome.exe",s=`chrome-${t}`;else if(n==="darwin"){t=e==="arm64"?"mac_arm":"mac";let r=e==="arm64"?"arm64":"x64";o="Google Chrome.app/Contents/MacOS/Google Chrome",s=`chrome-mac-${r}`}else if(n==="linux")t="linux",o="chrome",s="chrome-linux64";else return{};let i=Qs.resolve(Yr,"..","..",".puppeteerrc.cjs");if(Is.existsSync(i)||(i=Qs.resolve(Yr,"..",".puppeteerrc.cjs")),!Is.existsSync(i))return{};try{let r=jl(i),a=r.cacheDirectory,d=r.chrome?.version;if(a){if(process.env.PUPPETEER_CACHE_DIR=a,d){let l=Qs.join(a,"chrome",`${t}-${d}`,s,o);if(Is.existsSync(l))return{executablePath:l,cacheDirectory:a}}let c=l=>{if(!Is.existsSync(l))return null;try{let u=Is.readdirSync(l),h=[];for(let p of u){let m=Qs.join(l,p),y;try{y=Is.statSync(m)}catch{continue}if(y.isDirectory())h.push(m);else if(p.toLowerCase()===o.toLowerCase()&&(!d||m.includes(d)))return m}if(d){for(let p of h)if(p.includes(d)){let m=c(p);if(m)return m}}for(let p of h)if(!d||!p.includes(d)){let m=c(p);if(m)return m}}catch{}return null},f=c(a);if(f)return{executablePath:f,cacheDirectory:a}}}catch{}return{}}var gi=async n=>{let{query:e,limit:t=5,aiMode:o=!1}=L(n);if(!e)return'ERROR: Missing "query" argument for web_search.';let s=3,i=null;if(o){let r=`Query: ${e}
202
+
203
+ RESPONSE RULES:
204
+ - ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
205
+ - DO NOT CITE, REFERENCE, OR MENTION SOURCES ANYWHERE BETWEEN THE MAIN RESPONSE.
206
+ - DO NOT USE MARKDOWN EXCEPT FOR THE SOURCES SECTION BELOW.
207
+ - END THE RESPONSE WITH EXACTLY:
208
+
209
+ Sources:
210
+ - <URL 1>
211
+ - <URL 2>
212
+ - <URL 3>
213
+
214
+ - LIST ONE RAW URL PER BULLET.
215
+ - DO NOT USE MARKDOWN LINKS.
216
+ - DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.`;for(let a=1;a<=s;a++){let d=null;try{let c=fs();d=await qr.launch({headless:!0,executablePath:c.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let f=await d.newPage();await f.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await f.setViewport({width:1366,height:768});let l=a===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(T=>setTimeout(T,l));let u=`https://search.brave.com/ask?q=${encodeURIComponent(r)}&source=web`;await f.goto(u,{waitUntil:"domcontentloaded",timeout:18e4});let h=null,p=45e3,m=Date.now();for(;Date.now()-m<p&&(h=await f.evaluate(()=>{let T=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),E="";if(T.length>0&&(E=T.map(Y=>Y.innerText.trim()).filter(Boolean).join(`
217
+
218
+ `)),E||(E=document.body.innerText),E.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let I=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),_=T[0]||document.body,M=_?_.innerText.trim():"",W=/^(?:[✓✔]\s*)?Finished/i.test(M)||!!(_&&_.querySelector(".status-finished, .finished")),B=!I&&(W||E.includes("Sources:")&&!I),K={};return document.querySelectorAll("a[href]").forEach(Y=>{let Se=Y.getAttribute("href")||Y.href||"";if(Se.includes("uddg=")&&(Se=decodeURIComponent(Se.split("uddg=")[1].split("&")[0])),Se.includes("url=")&&(Se=decodeURIComponent(Se.split("url=")[1].split("&")[0])),Se&&(Se.startsWith("http://")||Se.startsWith("https://"))&&!Se.includes("search.brave.com")){let D=Y.innerText.trim();D&&(K[D]=Se),Y.textContent=Se}}),{isFinished:B,text:E,hrefMap:K}}),!(h&&h.isFinished));)await new Promise(T=>setTimeout(T,1e3));let y=(h?h.text:"")||"",g=h?h.hrefMap||{}:{},S="DO NOT INCLUDE ANY TEXT, NOTES, OR EXPLANATIONS AFTER THE SOURCES SECTION.";y.includes(S)&&(y=y.split(S).pop()),y=y.replace(/^.*?(Ctrl \+ Shift \+ O|Ask\nAll\nImages)/s,"").replace(/AI-generated answer\. Please verify critical facts\..*/s,"").replace(/Brave Search uses private usage metrics.*/s,"");let b=y,x="";if(y.includes("Sources:")){let T=y.split("Sources:");b=T[0],x=T.slice(1).join("Sources:")}let k=[];for(let T of b.split(`
219
+ `)){let E=T.trim();E&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(E)||/^[\+\-]?\d+$/.test(E)||E.includes("search.brave.com")||E.startsWith("https://www.youtube.com/watch")||E.startsWith("https://youtube.com/watch")||k.push(T))}let C=k.join(`
220
+ `).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
221
+
222
+ `).trim(),R=T=>!T||T.includes("search.brave.com")||T.includes("youtube.com")||T.includes("youtu.be"),A="";if(x){let T=x.match(/https?:\/\/[^\s\)\>]+/g)||[],E=[];for(let _ of T){let M=_.replace(/[\.\,\;]+$/,""),W=Object.keys(g).find(B=>B.startsWith(M)||M.startsWith(B));W&&g[W]&&(M=g[W]),R(M)||E.push(M)}Object.values(g).forEach(_=>{!R(_)&&!E.includes(_)&&E.push(_)});let I=Array.from(new Set(E));I.length>0&&(A=`Sources:
223
+ `+I.map(_=>`- ${_}`).join(`
224
+ `))}let w=C+(A?`
225
+
226
+ `+A:"");if(!w||/^(\+\d+|Searching|Answering|Thinking|Finished)$/i.test(w))throw new Error("EMPTY_AI_RESPONSE");return await d.close(),`AI Search results for [${e}]:
227
+
228
+ ${w}`}catch(c){if(i=c,zr.writeFileSync(Vr.join(dn,"web_tools","search","ai_mode","ERROR.txt"),c.message),d&&await d.close(),a<s){let f=Math.pow(2,a)*1e3;await new Promise(l=>setTimeout(l,f))}}}}for(let r=1;r<=s;r++){let a=null;try{let d=fs();a=await qr.launch({headless:!0,executablePath:d.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let c=await a.newPage();await c.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await c.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(m=>setTimeout(m,f));let l=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(e)}`;await c.goto(l,{waitUntil:"networkidle2",timeout:18e4});let u=await c.$$eval(".result",(m,y)=>m.slice(0,y).map((g,S)=>{let b=g.querySelector(".result__a"),x=g.querySelector(".result__snippet"),k=b?b.href:"";k.includes("uddg=")&&(k=decodeURIComponent(k.split("uddg=")[1].split("&")[0]));let C=b?b.innerText.trim():"No Title",R=x?x.innerText.trim():"No Snippet";return`${S+1}. ${C}
229
+ Source: ${k}
230
+ Snippet: ${R}`}),t);if(u.length===0){if((await c.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await a.close(),`No results found for query: [${e}].`}let h=u.join(`
231
+
232
+ `);return await a.close(),`${o?`AI Mode temporarily failed, used Standard search.
233
+
234
+ `:""}Search results for [${e}]:
235
+
236
+ ${h}`}catch(d){if(i=d,a&&await a.close(),zr.writeFileSync(Vr.join(dn,"web_tools","search","standard_mode","ERROR.txt"),d.message),r<s){let c=Math.pow(2,r)*1e3;await new Promise(f=>setTimeout(f,c))}}}return`ERROR: Search failed after ${s+1} attempts. Last error: ${i.message}`};import Hl from"puppeteer";import Gl from"turndown";import{gfm as Yl}from"turndown-plugin-gfm";var yi=async n=>{let e=n;if(typeof n=="object"&&n!==null)e=n.url||n.targetUrl||n.href||"";else if(typeof n=="string"){let i=n.match(/url\s*=\s*["'](.*)["']/);e=i?i[1]:n}let t=typeof e=="string"?e.trim():"";if(!t)return"ERROR: No target URL provided.";let o=3,s=null;for(let i=1;i<=o;i++){let r=null;try{let a=fs();r=await Hl.launch({headless:!0,executablePath:a.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage();await d.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.178 Safari/537.36"),await d.setViewport({width:1366,height:768});let c=i===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(m=>setTimeout(m,c)),await d.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(m=>setTimeout(m,5e3));let f=await d.evaluate(()=>{document.querySelectorAll("script, style, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(x=>x.remove());let y=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),g;for(;g=y.nextNode();)g.remove();for(document.querySelectorAll("*").forEach(x=>{let k=x.attributes;for(let C=k.length-1;C>=0;C--){let R=k[C].name;R!=="href"&&R!=="src"&&x.removeAttribute(R)}});document.querySelector("div, span");)document.querySelectorAll("div, span").forEach(x=>{x.parentNode&&x.replaceWith(...x.childNodes)});document.querySelectorAll("br").forEach(x=>{x.replaceWith(document.createTextNode(`
237
+
238
+ `))});let b=()=>{let x=!1;document.querySelectorAll("*").forEach(k=>{k.childNodes.length===0&&!k.innerText.trim()&&(k.remove(),x=!0)}),x&&b()};return b(),document.body.innerHTML});if(!f)throw new Error("EMPTY_RENDER_RESULT");let l=f.replace(/<br\s*\/?>/gi,`
239
+
240
+ `).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
241
+ `).replace(/\n{3,}/g,`
242
+
243
+ `).trim(),u=new Gl({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(Yl);let h=u.turndown(l).replace(/\.\s*\n/g,`
244
+ `).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
245
+ `).replace(/\n{3,}/g,`
246
+
247
+ `),p=h.substring(0,5e4);return await r.close(),`Markdown parsed from [${t}]:
248
+
249
+ ${p}${h.length>5e4?`
250
+
251
+ [TRUNCATED AT 50K CHARS]`:""}`}catch(a){if(s=a,r&&await r.close(),i<o){let d=Math.pow(2,i)*1e3;await new Promise(c=>setTimeout(c,d))}}}return`ERROR: Scrape failed after ${o+1} attempts. Last error: ${s.message}`};var ql=4*(1024*2),wi=async(n,e={})=>{let t=f=>{let l=new RegExp(`${f}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=n.match(l);if(u)return u[2].trim();let h=new RegExp(`${f}\\s*[:=]\\s*([^,\\s)]+)`,"s"),p=n.match(h);return p?p[1].trim():null},o=t("action"),s=t("method"),i=t("content"),r=t("content-new"),a=t("content-old"),d=t("id"),c=t("chat-id")||e.chatId||e.sessionId||"default-session";if(o==="temp"){if(!i)return"ERROR: Missing 'content' for temp memory.";let f=J(Jt,{});f[c]||(f[c]=[]),f[c].push(i),ce(Jt,f);let l=f[c].reduce((u,h)=>u+h.length,0);return`SUCCESS: Temporary context saved for session [${c}]. (Size: ${l} chars)`}if(o==="user"){let f=J(Lt,[]).map(l=>(l.score===void 0&&(l.score=.5),l));if(s==="add"){if(!i)return"ERROR: Missing 'content' for memory addition.";let l=new Date,u=`${l.getDate()}/${l.getMonth()+1}/${l.getFullYear()}`,h=i.includes("[Saved on:")?i:`${i.trim()} [Saved on: ${u}]`,p=ql,m=f.reduce((b,x)=>b+(x.memory?.length||0),0);for(;f.length>0&&m+h.length>p;){let b=f.shift();m-=b.memory?.length||0}let y=t("score"),g=y?parseFloat(y):.5,S={id:`mem-${Date.now().toString(36)}`,memory:h,score:Math.min(2,isNaN(g)?.5:g)};return f.push(S),ce(Lt,f),`SUCCESS: Memory added with ID [${S.id}] and score [${S.score}]. (Vault Size: ${m+h.length} chars)`}if(s==="update"){let l=d||a,u=r||i;if(!l||!u)return"ERROR: Missing 'id' or content for update.";let h=f.findIndex(g=>g.id===l);if(h===-1)return`ERROR: Memory ID [${l}] not found.`;let p=new Date,m=`${p.getDate()}/${p.getMonth()+1}/${p.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${m}]`;return f[h].memory=y,ce(Lt,f),`SUCCESS: Memory [${l}] updated.`}if(s==="delete"){let l=d||i;if(!l)return"ERROR: Missing 'id' for deletion.";let u=f.length,h=f.filter(p=>p.id!==l);return h.length===u?`ERROR: Memory ID [${l}] not found.`:(ce(Lt,h),`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 Si=async(n,e={})=>{let t=L(n).title,o=e.chatId||e.sessionId;if(!o)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Nr(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 Oo from"fs";import Kr from"path";var Zs=async(n,e={})=>{let{path:t,StartLine:o,EndLine:s,start_line:i,end_line:r,startLine:a,endLine:d}=L(n),c=parseInt(o||i||a),f=parseInt(s||r||d),l=!isNaN(c),u=!isNaN(f),h=c||1,p=f||(c?c+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let m=Kr.resolve(process.cwd(),t);try{if(!Oo.existsSync(m))return`ERROR: File [${t}] does not exist.`;if(Oo.statSync(m).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let g=Kr.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(g))return`ERROR: Unable to read. Type ${g.slice(1).toUpperCase()} not supported`;let b={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(b[g]){if(!(e.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let M=Oo.readFileSync(m).toString("base64"),W=b[g];return{text:`[BINARY FILE]: ${t} (${W}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:M,mimeType:W}}}}let x=Oo.readFileSync(m,"utf8");x.startsWith("\uFEFF")&&(x=x.slice(1)),x=x.replace(/\r\n/g,`
252
+ `).replace(/\r/g,`
253
+ `);let k=x.split(`
254
+ `),C=k.length;!l&&!u&&C>800&&(h=1,p=50);let R=Math.max(0,h-1),A=Math.min(C,p),w=k.slice(R,A),T=`File: [${t}] (Showing lines ${R+1}-${A} of ${C}).`,E=w.map((I,_)=>`${String(R+_+1).padStart(4)}: ${I.trimEnd()}`).join(`
255
+ `);return`${T}
256
+
257
+ ${E}`}catch(y){let g=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${g}`}};import vs from"fs";import Xr from"path";var Ti=async(n,e={})=>{let{path:t,content:o}=L(n);if(!t)return'ERROR: Missing "path" argument for write_file.';if(o===void 0)return'ERROR: Missing "content" argument for write_file.';o=o.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
258
+ `).replace(/\r/g,`
259
+ `);let s=Xr.resolve(process.cwd(),t),i=Xr.dirname(s);try{await ct.recordFileChange(s);let r="";if(vs.existsSync(s))try{r=`Old File contents:
260
+ ${vs.readFileSync(s,"utf8").split(/\r?\n/).map((k,C)=>`${C+1} | ${k}`).join(`
261
+ `)}
262
+
263
+ `}catch{r=`[Note: Could not read existing file for reversal reference]
264
+
265
+ `}vs.existsSync(i)||vs.mkdirSync(i,{recursive:!0});let d=(b=>b.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
266
+ `).replace(/\r/g,`
267
+ `))(o),c=d.endsWith(`
268
+ `)?d:d+`
269
+ `,f=c.split(/\r?\n/).length,l=Buffer.byteLength(c,"utf8");vs.writeFileSync(s,c,"utf8");let u=vs.readFileSync(s,"utf8"),h=Buffer.byteLength(u,"utf8"),p=u.split(/\r?\n/),m=p.length;if(h===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(m<=100)y=p.join(`
270
+ `);else{let b=p.slice(0,50).join(`
271
+ `),x=p.slice(-50).join(`
272
+ `);y=`${b}
273
+
274
+ ... [${m-100} lines truncated] ...
275
+
276
+ ${x}`}u=null;let{systemSettings:g}=await Qt(),S=`SUCCESS: File [${t}] saved.
277
+ - Stats: [${m} lines, ${(h/1024).toFixed(1)} KB]
278
+ ${r}- Content Preview:
279
+
280
+ ${y}`;if(g?.compressToolResults&&m>60){let b=c.split(/\r?\n/),x=b.slice(0,25).join(`
281
+ `)===p.slice(0,25).join(`
282
+ `),k=b.slice(-25).join(`
283
+ `)===p.slice(-25).join(`
284
+ `);x&&k&&(S=`[[SAME]]
285
+ ${S}`)}return S}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to write file [${t}]: ${a}`}};import Ri from"fs";import oc from"path";import zl from"os";var mn=n=>typeof n!="string"?n:n.length>12?(n+"").replace("",""):n,Jr=(n,e)=>{if(!n)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=n.split(`
286
+ `),s=[];if(e<=5)return n;let i=r=>r.replace(t,"").length;return o.forEach(r=>{if(i(r)<=e){s.push(r);return}let d=r.split(/(\s+)/),c="",f=0,l=r.match(/^(\s*)/),u=l?l[1]:"";d.forEach((h,p)=>{if(h.length===0)return;let m=i(h);if(f+m>e)if(c.trim().length>0)s.push(c.trimEnd()),c=u.substring(0,Math.min(u.length,8))+h,f=i(c);else if(t.test(h))s.push(h),c=u,f=i(c);else{let y=h;for(;i(y)>e&&e>10;)s.push(y.substring(0,e)),y=y.substring(e);c=y,f=i(c)}else c+=h,f+=m}),(c.trimEnd().length>0||c===u)&&s.push(c.trimEnd())}),mn(s.join(`
287
+ `))},Qu=n=>{if(!n&&n!==0)return"0.0k";let e=typeof n=="string"?parseFloat(n):n;return e>=1e6?`${(e/1e6).toFixed(1)}m`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()},Zu=(n,e=40)=>{let t=Mn.replaceAll("\\\\","\\");if(n=n.replace(zl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!n||n.length<=e)return mn(n);let o=Math.floor((e-3)/2);return mn(n.substring(0,o)+"..."+n.substring(n.length-o).replaceAll("\\","/"))},$o=n=>{let e=[],t=new Set,o=n.allowMultiple===!0||String(n.allowMultiple).toLowerCase()==="true";Object.keys(n).forEach(d=>{let c=d.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(c){let f=c[2]?parseInt(c[2],10):1;t.add(f)}});let s=Array.from(t).sort((d,c)=>d-c),i=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],r=["newContent","new_content","content_to_add","newBlock","new_block"],a=(d,c,f)=>{let l,u;for(let h of c){let p=d===1?[`${h}1`,h,`${h}_1`]:[`${h}${d}`,`${h}_${d}`];for(let m of p)if(n[m]!==void 0){l=n[m];break}if(l!==void 0)break}for(let h of f){let p=d===1?[`${h}1`,h,`${h}_1`]:[`${h}${d}`,`${h}_${d}`];for(let m of p)if(n[m]!==void 0){u=n[m];break}if(u!==void 0)break}return{r:l,n:u}};for(let d of s){let{r:c,n:f}=a(d,i,r);if(c!==void 0&&f!==void 0)e.push({replace:c,new:f});else if(c!==void 0||f!==void 0)return{error:`Mismatched replacement pair for index ${d}. Both replacement and new content must be provided.`,allowMultiple:o}}return{patchPairs:e,allowMultiple:o}},Vl=n=>{if(!n)return null;let e="",t=0,o=n.length;for(;t<o;){let s=n[t];if(s==="\\"){for(;t<o&&n[t]==="\\";)t++;e+="\\\\*"}else if(s===`
288
+ `)e+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",t++;else if(s==="\r")e+="(?:\\r|\\\\*r)?",t++;else if(s===" ")e+="(?:\\t|\\\\*t|\\s*)",t++;else if(s==='"'||s==="'"||s==="`")e.endsWith("\\\\*")||(e+="\\\\*"),e+=s,t++;else if(/[.*+?^${}()|[\]]/.test(s))e+="\\"+s,t++;else if(/\s/.test(s)){for(;t<o&&/\s/.test(n[t])&&n[t]!==`
289
+ `&&n[t]!=="\r"&&n[t]!==" ";)t++;e+="\\s*"}else e+=s,t++}if(!e)return null;try{return new RegExp(e,"g")}catch{return null}},_o=(n,e,t={})=>{let o=typeof t=="boolean"?t:!!(t&&t.allowMultiple),s=n.replace(/\r\n/g,`
290
+ `).replace(/\r/g,`
291
+ `),i=g=>g.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
292
+ `).replace(/\r/g,`
293
+ `),r=g=>g.match(/^\s*/)[0],a=g=>{let S=g.split(`
294
+ `).filter(x=>x.trim()!=="");if(S.length===0)return"";let b=r(S[0]);for(let x of S){let k=r(x);k.length<b.length&&(b=k)}return b},d=(g,S,b="")=>{if(!g||S===void 0)return g;let k=/^\t/m.test(S)?" ":" ",C=I=>I.split(`
295
+ `).find(_=>_.trim()!=="")??"",R=C(S).match(/^\s*/)[0].length,A=C(g).match(/^\s*/)[0].length,w=R-A,T=(b.match(/^\s*/)||[""])[0].length;return g.split(`
296
+ `).map((I,_)=>{if(I.trim()===""&&_!==0)return"";let M=I.match(/^\s*/)[0].length,W=Math.max(0,M+w);return _===0&&(W=Math.max(0,W-T)),k.repeat(W)+I.trimStart()}).join(`
297
+ `)},c=[];for(let g=0;g<e.length;g++){let S=e[g],b=(S.replace||"").trim(),x=i(S.new||"");if(b.startsWith("^LINE:")&&b.endsWith("$")){let T=b.slice(6,-1).trim().split(".."),E=parseInt(T[0]),I=T[1]!==void 0?parseInt(T[1]):E;if(!isNaN(E)&&!isNaN(I)){let _=s.split(`
298
+ `);if(E<1||E>_.length||I<E||I>_.length){c.push({index:g,success:!1,error:`Block ${g+1}: Line range ^LINE:${E}..${I}$ out of bounds (file has ${_.length} lines).`});continue}let W=_.slice(E-1,I).join(`
299
+ `),B=0;for(let K=0;K<E-1;K++)B+=_[K].length+1;c.push({index:g,success:!0,startPos:B,firstMatchContent:W,content_to_add:x});continue}}let k=i(S.replace||"");if(k===""&&x===""){c.push({index:g,success:!1,error:`Block ${g+1}: Empty replace and add content.`});continue}let C=k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),R=null;if(k!==""&&s.includes(k))R=new RegExp(C,"g");else{let w=k.split(`
300
+ `).map(T=>T.trim()).filter(T=>T.length>0).map(T=>T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(w.length>0){let T=w.join("\\s*");try{R=new RegExp(T,"g")}catch{R=new RegExp(C,"g")}}else R=new RegExp(C,"g")}let A=[...s.matchAll(R)];if(A.length===0&&k!==""){let w=Vl(k);w&&(A=[...s.matchAll(w)])}if(A.length===0){c.push({index:g,success:!1,error:`Block ${g+1}: Could not find match.`});continue}if(A.length>1&&!o){c.push({index:g,success:!1,error:`Block ${g+1}: Found ${A.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let w of A)c.push({index:g,success:!0,startPos:w.index,firstMatchContent:w[0],content_to_add:x})}let f=c.filter(g=>g.success).sort((g,S)=>g.startPos-S.startPos);for(let g=0;g<f.length-1;g++){let S=f[g],b=f[g+1];S.startPos+S.firstMatchContent.length>b.startPos&&(S.success=!1,S.error=`Block ${S.index+1}: Overlaps with another block.`,b.success=!1,b.error=`Block ${b.index+1}: Overlaps with another block.`)}let l=new Map,u=s,h=0,p=0,m=c.filter(g=>g.success).sort((g,S)=>g.startPos-S.startPos);for(let g of m){let S=g.startPos,b=s.substring(0,S).split(`
301
+ `).length,x=S+h,k=b+p,C=u.lastIndexOf(`
302
+ `,x)+1,R=u.substring(C,x),A=d(g.content_to_add,g.firstMatchContent,R),w=u.split(`
303
+ `),T=[];for(let M=Math.max(0,k-4);M<k-1;M++)T.push({num:M+1,text:w[M]});let E=g.firstMatchContent.split(`
304
+ `),I=[],_=k+E.length-1;for(let M=_;M<Math.min(w.length,_+3);M++)I.push({num:M+1,text:w[M]});l.set(g,{success:!0,index:g.index,oldContent:g.firstMatchContent,newContent:A,originalStartLine:b,finalStartLine:k,contextBefore:T,contextAfter:I}),u=u.substring(0,x)+A+u.substring(x+g.firstMatchContent.length),h+=A.length-g.firstMatchContent.length,p+=A.split(`
305
+ `).length-g.firstMatchContent.split(`
306
+ `).length}let y=[];for(let g=0;g<e.length;g++){let S=m.filter(b=>b.index===g);if(S.length>0)for(let b of S)l.has(b)&&y.push(l.get(b));else{let b=c.find(x=>x.index===g);y.push({success:!1,error:b?b.error:`Block ${g+1}: Unknown error.`})}}return{content:u,results:y}},Mo=(n,e,t,o=8,s=!1)=>{if(!t||t.length===0)return"";let i=n.split(/\r?\n/),r=e.split(/\r?\n/),a=Math.max(i.length,r.length,1),d=Math.max(4,String(a).length),c=m=>String(m).padStart(d," "),f=`[DIFF_START]
307
+ `,l="\u2550".repeat(88),u=0,h=null,p=t.filter(m=>m.success).sort((m,y)=>m.originalStartLine-y.originalStartLine);if(p.forEach((m,y)=>{let g=m.finalStartLine!==void 0?m.finalStartLine:m.originalStartLine;if(h===null)for(u=Math.max(0,g-4);u<g-1;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
308
+ `,u++;else{let A=h,w=A.originalStartLine+A.oldContent.split(`
309
+ `).length-1;if(m.originalStartLine-w-1>=o){let E=Math.min(r.length,u+3);for(;u<E;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
310
+ `,u++;for(f+=`[UI_CONTEXT] ${l}
311
+ `,u=Math.max(u,g-4);u<g-1;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
312
+ `,u++}else for(;u<g-1;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
313
+ `,u++}let S=m.originalStartLine-1,b=i[S]||"",x=m.oldContent.split(`
314
+ `),k=b.match(/^\s*/),C=k?k[0]:"";x.forEach((A,w)=>{let T=A;if(x.length===1&&b.trim().length>0&&b.includes(A.trim()))T=b;else if(w===0){let E=A.match(/^\s*/);(E?E[0]:"").length<C.length&&b.includes(A.trim())&&(T=C+A.trimStart())}f+=`-${c(m.originalStartLine+w)} |${T}
315
+ `});let R=u;if(m.finalStartLine!==void 0)R=m.finalStartLine-1+(m.newContent?m.newContent.split(`
316
+ `).length:0);else{let A=m.originalStartLine+x.length-1,w=i[A]||null;if(w!==null){let T=y<p.length-1?(p[y+1].originalStartLine||r.length)+10:r.length;for(let E=u;E<T;E++){if(r[E]===w){R=E;break}E===r.length-1&&(R=r.length)}}else R=r.length}for(;u<R;)f+=`+${c(u+1)} |${r[u]||""}
317
+ `,u++;h=m}),h!==null){let m=Math.min(r.length,u+3);for(;u<m;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
318
+ `,u++}if(s){let m=`[DIFF_START]
319
+ `,y=f.substring(m.length),g=`[UI_CONTEXT] ${l}
320
+ `,b=y.split(g).map(x=>x.split(`
321
+ `).filter(C=>C.trim()!=="").length>45?`[[VERIFIED]]
322
+ ${x}
323
+ [[/VERIFIED]]`:x);f=m+b.join(g)}return f+="[DIFF_END]",mn(f)},Kl=n=>{if(!n)return null;let e=n.replace("[UI_CONTEXT]","").replace(/\r/g,""),t=e.startsWith("-"),o=e.startsWith("+"),s=t||o?e.substring(1):e,i=s.indexOf("|"),r=i!==-1?mn(s.substring(0,i).trim()):"",a=mn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:r,content:a}},Xl=(n,e)=>{if(!n&&!e)return 1;if(!n||!e)return 0;let t=n.length,o=e.length,s=n,i=e;t<o&&(s=e,i=n);let r=s.length,a=i.length,d=new Int32Array(a+1),c=new Int32Array(a+1);for(let u=0;u<=a;u++)d[u]=u;for(let u=1;u<=r;u++){c[0]=u;let h=s[u-1];for(let p=1;p<=a;p++)h===i[p-1]?c[p]=d[p-1]:c[p]=Math.min(d[p],c[p-1],d[p-1])+1;d.set(c)}let f=d[a],l=Math.max(t,o);return l===0?1:1-f/l},Qr=n=>{let e=[],t=[];n.forEach((f,l)=>{f.parsed.isR?e.push({index:l,content:f.parsed.content}):f.parsed.isA&&t.push({index:l,content:f.parsed.content})});let o=e.length,s=t.length;if(o===0||s===0)return;let i=Array.from({length:o+1},()=>Array(s+1).fill(0)),r=Array.from({length:o+1},()=>Array(s+1).fill(""));for(let f=1;f<=o;f++)r[f][0]="up";for(let f=1;f<=s;f++)r[0][f]="left";let a=Array.from({length:o},()=>Array(s).fill(0));for(let f=0;f<o;f++)for(let l=0;l<s;l++)a[f][l]=Xl(e[f].content.trim(),t[l].content.trim());for(let f=1;f<=o;f++)for(let l=1;l<=s;l++){let u=a[f-1][l-1],h=u>=.2?u:-10,p=i[f-1][l-1]+h,m=i[f-1][l],y=i[f][l-1];p>=m&&p>=y?(i[f][l]=p,r[f][l]="diag"):m>=y?(i[f][l]=m,r[f][l]="up"):(i[f][l]=y,r[f][l]="left")}let d=o,c=s;for(;d>0||c>0;)if(r[d][c]==="diag"){if(a[d-1][c-1]>=.2){let l=e[d-1].index,u=t[c-1].index;n[l].pairContent=n[u].parsed.content,n[u].pairContent=n[l].parsed.content}d--,c--}else r[d][c]==="up"?d--:c--},Yn=new Map,ds=new Map,Zr=200,bi=6,xi=(n,e)=>{e.set(n.key,n),n.type==="chunk"&&n.blocks&&n.blocks.forEach(t=>xi(t,e))},eh=(n,e)=>{if(!n)return{completed:[],active:[]};let t=`${n.id}-${n.text?.length||0}-${e}-${n.isStreaming}-${n.workedDuration||0}`;if(!n.isStreaming&&Yn.has(t))return Yn.get(t);let o=mn(sc(n.text||"",n.role==="think")),s=`${n.id}-${e}`,i=new Map;if(n.isStreaming){let p=ds.get(s);p&&o.startsWith(p.text)&&(i=p.blocksMap)}let r=(p,m,y,g={})=>{let S=i.get(p);if(S&&S.text===y&&S.type===m&&!!S.isActiveBlock==!!g.isActiveBlock&&!!S.isStreaming==!!g.isStreaming&&S.pairContent===g.pairContent)return S;let b=mn(y),x={...g};return typeof x.pairContent=="string"&&(x.pairContent=mn(x.pairContent)),Array.isArray(x.wrappedLines)&&(x.wrappedLines=x.wrappedLines.map(mn)),{key:p,isStreamingMsg:!!n.isStreaming,workedDuration:n.workedDuration,type:m,text:b,msg:m==="full-message"?n:void 0,...x}};if(o.includes("- Content Preview:")){let p="",m=o.match(/File\s+\[(.*?)\]/i);m&&(p=m[1].split(".").pop().toLowerCase());let x=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
324
+ `).map(E=>E.replace(/\r$/,"")),k=String(x.length).length,C=[],R=null,A=[],w=()=>{if(!A.length)return;let E=A;A=[],C.push(E.length===1?E[0]:{key:`${E[0].key}-chunk`,type:"chunk",blocks:E})},T=e-(k+6);return x.forEach((E,I)=>{let _=I===x.length-1,M=Jr(E,T).split(`
325
+ `),W=r(`${n.id||Date.now()}-write-line-${I}`,"write-line",E,{gutterWidth:k,lineNum:I+1,isFirstLine:I===0,isLastLine:_,extension:p,wrappedLines:M});_&&n.isStreaming?(w(),R=W):(A.push(W),A.length>=bi&&w())}),w(),{completed:C,active:R?[R]:[]}}if(o.includes("[DIFF_START]")){let p=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(p?p[1].trim():"").split(`
326
+ `).map(R=>R.replace(/\r$/,"")),g=y.map(R=>({line:R,parsed:Kl(R),pairContent:null})),S=[];for(let R=0;R<g.length;R++){let A=g[R];A.parsed&&(A.parsed.isR||A.parsed.isA)?S.push(A):S.length>0&&(Qr(S),S=[])}S.length>0&&Qr(S);let b=[],x=null,k=[],C=()=>{if(!k.length)return;let R=k;k=[],b.push(R.length===1?R[0]:{key:`${R[0].key}-chunk`,type:"chunk",blocks:R})};return y.forEach((R,A)=>{let w=A===y.length-1,T=g[A].parsed,E=null;T&&(E=Jr(T.content,e-17).split(`
327
+ `));let I=r(`${n.id||Date.now()}-diff-${A}`,"diff-line",R,{isFirstLine:A===0,isLastLine:w,pairContent:g[A].pairContent,wrappedLines:E});w&&n.isStreaming?(C(),x=I):(k.push(I),k.length>=bi&&C())}),C(),{completed:b,active:x?[x]:[]}}if(n.role==="system"||n.isLogo||n.isHelpRecord||n.isTerminalRecord||n.isHomeWarning||n.isImageStats||n.isAskRecord||n.isAboutRecord||n.isUpdateNotification||n.role==="user")return{completed:[r(`${n.id||Date.now()}-full`,"full-message",o)],active:[]};if(!o&&!n.isStreaming){let p={completed:[],active:[]};return Yn.set(t,p),p}let a=[],d=null,c=[],f=null,l=()=>{if(!c.length)return;let p=c;c=[],f=null,a.push(p.length===1?p[0]:{key:`${n.id||"x"}-chunk-${p[0].key}`,type:"chunk",blocks:p})},u=(p,m=!1)=>{if(f!==null&&f!==p.type&&l(),c.push(p),f=p.type,c.length>=bi){if(n.isStreaming&&m)return;l()}};if(n.role==="think"){a.push(r(`${n.id}-header`,"think-header",""));let p=o.split(`
328
+ `);p.forEach((m,y)=>{let g=y===p.length-1;u(r(`${n.id}-${y}`,"think-line",m,{}),g)}),n.isStreaming||(l(),a.push({key:`${n.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let p=o.split(`
329
+ `),m=!1,y=[],g=!1,S="",b=0,x=0;p.forEach((k,C)=>{let R=C===p.length-1,A=k.trim().startsWith("|"),w=k.trim().startsWith("```");g?w?(g=!1,u(r(`${n.id}-code-close-${x}`,"code-fence-close","",{}),R)):(b++,u(r(`${n.id}-code-line-${C}`,"code-line",k,{lineNum:b,lang:S}),R)):w?(g=!0,x=C,b=0,S=k.trim().replace(/^```/,"").trim(),u(r(`${n.id}-code-open-${C}`,"code-fence-open",S,{}),R)):A?(m=!0,y.push(k),R&&(l(),n.isStreaming?d=r(`${n.id}-table-${C}`,"table",y.join(`
330
+ `),{isStreaming:!0}):a.push(r(`${n.id}-table-${C}`,"table",y.join(`
331
+ `),{isStreaming:!1})))):(m&&(l(),a.push(r(`${n.id}-table-${C}`,"table",y.join(`
332
+ `),{isStreaming:!1})),m=!1,y=[]),u(r(`${n.id}-${C}`,"agent-line",k,{}),R))}),!n.isStreaming&&n.workedDuration&&(l(),a.push(r(`${n.id}-worked-duration`,"worked-duration","")))}n.isStreaming&&c.length>0?d=c.length===1?c[0]:{key:`${n.id||"x"}-chunk-active-${c[0].key}`,type:"chunk",blocks:c}:l();let h={completed:a,active:d?[d]:[]};if(n.isStreaming){let p=new Map;if(a.forEach(m=>xi(m,p)),d&&xi(d,p),ds.set(s,{text:o,blocksMap:p}),ds.size>Zr){let m=ds.keys().next().value;ds.delete(m)}}else{if(Yn.set(t,h),Yn.size>Zr){let p=Yn.keys().next().value;Yn.delete(p)}ds.delete(s)}return h},Jl={},Ql=/<\/think>(\r?\n){2}/gi,Zl=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,Ei=(n,e)=>{let t=!1;for(let o=0;o<e;o++)n[o]==="`"&&(t=!t);return t},ec=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|<(think|thought)>[\s\S]*?<\/(think|thought)>|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[TOOL RESULT\]:?\s*|^\s*(SUCCESS|ERROR):.*(\r?\n)?|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,tc=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,nc=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,Ls=!1,sc=(n,e=!1)=>{if(!n)return n;if(e)return n.replace(/^<(think|thought)>/gi,"").replace(/<\/(think|thought)>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let t=n.replace(Ql,"</think>").replace(Zl,(i,r,a,d)=>!Ls&&Ei(d,a)?i:"");t&&t.includes("[tool:")&&(t=t.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[tool:[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(i,r,a)=>a&&a.includes("[tool:")?a.trim():i),Ls&&(t=t.replace(/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(i,r)=>r.includes("[tool:")?r.trim():i)),t=t.replace(/<(\w+)(?:[^>]*)>\r?\n?/gi,"").replace(/\r?\n?<\/\w+(?:[^>]*)>/gi,""));let o="tool:functions.",s="agent:generalist.";if(t.toLowerCase().includes(o)||t.toLowerCase().includes(s))for(;;){let i=t.toLowerCase(),r=i.indexOf(o),a=i.indexOf(s),d=o,c=r;if((r===-1||a!==-1&&a<r)&&(d=s,c=a),c===-1)break;if(!Ls&&Ei(t,c)){let g=c+d.length,S=i.indexOf(o,g),b=i.indexOf(s,g);if(S===-1&&b===-1)break;let x=-1,k=0;for(;;){let C=i.indexOf(o,k),R=i.indexOf(s,k),A=-1,w=o;if(C===-1&&R===-1)break;if(C===-1||R!==-1&&R<C?(A=R,w=s):A=C,!Ei(t,A)){x=A,d=w;break}k=A+w.length}if(x===-1)break;c=x}let f=c,l=!1,u=c-1;for(;u>=0&&/\s/.test(t[u]);)u--;u>=0&&t[u]==="["&&(f=u,l=!0);let h=0,p=!1,m=null,y=c;for(;y<t.length;){let g=t[y];if(!m&&(g==="'"||g==='"'||g==="`")?m=g:m&&g===m&&t[y-1]!=="\\"&&(m=null),m||(g==="("?(h++,p=!0):g===")"&&h--),p&&h===0&&!m){let S=y;if(l){let b=y+1;for(;b<t.length&&/\s/.test(t[b]);)b++;b<t.length&&t[b]==="]"&&(S=b)}t=t.substring(0,f)+t.substring(S+1);break}if(y++,y===t.length)return t=t.substring(0,f),t}}return t=t.replace(ec,""),t=t.replace(tc,i=>{let r=i.toLowerCase();return r.includes("leftrightarrow")?"\u2194":r.includes("rightarrow")?"\u2192":r.includes("leftarrow")?"\u2190":r.includes("uparrow")?"\u2191":r.includes("downarrow")?"\u2193":i}),t=t.replace(nc,i=>Jl[i.toLowerCase()]||i),t.trim()},th=()=>{Yn.clear(),ds.clear()};var ki=async(n,e={})=>{let t=L(n),o=t.path;if(!o)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:s,allowMultiple:i,error:r}=$o(t);if(r)return`ERROR: ${r}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let a=t.allowMultiple!==void 0?t.allowMultiple===!0||String(t.allowMultiple).toLowerCase()==="true":i,d=oc.resolve(process.cwd(),o);try{if(!Ri.existsSync(d))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let c=e.forcedContent||Ri.readFileSync(d,"utf8");c.startsWith("\uFEFF")&&(c=c.slice(1));let f=c.replace(/\r\n/g,`
333
+ `).replace(/\r/g,`
334
+ `),{content:l,results:u}=_o(f,s,{allowMultiple:a}),h=u.filter(g=>!g.success),p=u.filter(g=>g.success);if(p.length===0)return`ERROR: Patch Failed to apply to [${o}].
335
+ ${h.map(g=>` \u2022 ${g.error}`).join(`
336
+ `)}`;await ct.recordFileChange(d,f),Ri.writeFileSync(d,l,"utf8");let{systemSettings:m}=await Qt(),y=Mo(f,l,u,12,m?.compressToolResults);return h.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${p.length}/${s.length}] blocks applied.
337
+
338
+ Failures:
339
+ ${h.map(g=>` \u2022 ${g.error}`).join(`
340
+ `)}
341
+
342
+ ${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
343
+
344
+ ${y}`}catch(c){let f=c instanceof Error?c.message:String(c);return`ERROR: Failed to update file [${o}]: ${f}`}};import us from"fs";import Ai from"path";var ic=new Set([".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".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"]),rc=n=>ic.has(n)||n.startsWith(".pnpm"),ac=n=>{try{let e=String(n.getMonth()+1).padStart(2,"0"),t=String(n.getDate()).padStart(2,"0"),o=String(n.getHours()).padStart(2,"0"),s=String(n.getMinutes()).padStart(2,"0");return`${e}-${t} ${o}:${s}`}catch{return"N/A"}},Ci=async n=>{let e=L(n),t=e.path||null;if(!t)return"ERROR: No directory path provided.";let o=1;if(e.recurse!==void 0&&e.recurse!==null)if(typeof e.recurse=="number")o=e.recurse;else if(typeof e.recurse=="boolean")o=e.recurse?2:1;else{let i=parseInt(String(e.recurse).trim(),10);o=isNaN(i)?1:i}o=Math.max(1,Math.min(3,o));let s=Ai.resolve(process.cwd(),t);try{if(!us.existsSync(s))return`ERROR: Path [${t}] does not exist.`;if(!us.statSync(s).isDirectory())return`ERROR: Path [${t}] is a file, not a directory. Use ReadFile instead.`;if(o===1){let m=us.readdirSync(s),y=m.length,g=150,S=m.slice(0,g),b=[];for(let C of S){let R=Ai.join(s,C),A={name:C,type:"unknown",size:"N/A",mtime:"N/A"};try{let w=us.statSync(R);A={name:C,type:w.isDirectory()?"directory":"file",size:(w.size/1024).toFixed(1)+"KB",mtime:ac(w.mtime)}}catch{A.type="inaccessible"}b.push(A)}let x=b.map(C=>C.type==="directory"?`${C.name}/`:`${C.name} (${C.size}, ${C.mtime})`).join(`
345
+ `),k=`
346
+
347
+ (Total items in folder: ${y})`;return y>g&&(k=`
348
+
349
+ TRUNCATED: Showing first ${g} of ${y} items.`),m.length=0,S.length=0,b.length=0,`Detailed folder stats for [${t}]:
350
+
351
+ ${x}${k}`}let r=0,a=0,d=0,c=500,f=!1,l=(m,y,g=1)=>{if(y>o||f)return[];let S=[];try{S=us.readdirSync(m)}catch{return[`${" ".repeat(g-1)}[Inaccessible Directory]`]}let b=[],x=[];for(let A of S){let w=Ai.join(m,A),T=!1;try{T=us.statSync(w).isDirectory()}catch{}T?b.push({name:A,fullPath:w}):x.push({name:A,fullPath:w})}b.sort((A,w)=>A.name.localeCompare(w.name)),x.sort((A,w)=>A.name.localeCompare(w.name));let k=[],C=" ".repeat(g-1);for(let A of b){if(d>=c){f=!0,k.push(`${C}[Truncated - Maximum item limit reached (${c})]`);break}if(d++,r++,k.push(`${C}${A.name}/`),y<o&&!rc(A.name)){let w=l(A.fullPath,y+1,g+1);k.push(...w)}}let R=[];for(let A of x){if(d>=c){f=!0,k.push(`${C}[Truncated - Maximum item limit reached (${c})]`);break}d++,a++;let w="N/A";try{w=(us.statSync(A.fullPath).size/1024).toFixed(1)+"KB"}catch{}R.push(`${A.name} (${w})`)}return R.length>0&&k.push(`${C}${R.join("; ")}`),k},h=l(s,1,1).join(`
352
+ `),p=`
353
+
354
+ (Total items scanned: ${d}, Directories: ${r}, Files: ${a})`;return f&&(p=`
355
+
356
+ TRUNCATED: Scan capped at ${c} items. (Directories: ${r}, Files: ${a})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
357
+
358
+ ${h}${p}`}catch(i){let r=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${r}`}};var Oi=async(n,e)=>{let t=L(n),{question:o}=t;if(!o)return'ERROR: Missing "question" argument for ask.';if(!e.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(i=>{if(i.startsWith("option")){let r=t[i];if(typeof r=="string"&&r.includes("::")){let[a,d]=r.split("::");s.push({id:i,label:a.trim(),description:d.trim()})}else s.push({id:i,label:String(r).trim(),description:""})}});try{return`USER CHOOSE: ${await e.onAskUser(o,s)}`}catch(i){return`ERROR: Failed to get user input: ${i instanceof Error?i.message:String(i)}`}};import lc from"puppeteer";import Ns from"path";import hs from"fs-extra";import{PDFDocument as cc}from"pdf-lib";var $i=async n=>{let{path:e,content:t,orientation:o="portrait",margin:s="0px"}=L(n);if(!e)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let i=Ns.resolve(process.cwd(),e),r=null;try{await hs.ensureDir(Ns.dirname(i)),await ct.recordFileChange(i);let a=fs();r=await lc.launch({headless:!0,executablePath:a.executablePath||void 0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let d=await r.newPage(),c=t,f={},l=async R=>{if(!R||R.startsWith("http://")||R.startsWith("https://")||R.startsWith("data:"))return null;try{let A=Ns.resolve(process.cwd(),R);if(await hs.pathExists(A)){let w=Ns.extname(A).toLowerCase().replace(".","")||"png",T=w==="jpg"?"jpeg":w==="svg"?"svg+xml":w,E=await hs.readFile(A,"base64");return`data:image/${T};base64,${E}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,h={},p;for(;(p=u.exec(t))!==null;){let R=p[1],A=p[0];if(R&&A.toLowerCase().includes("stylesheet")&&!R.startsWith("http://")&&!R.startsWith("https://")&&!R.startsWith("data:"))try{let w=Ns.resolve(process.cwd(),R);if(await hs.pathExists(w)){let T=await hs.readFile(w,"utf-8");h[A]=`<style>${T}</style>`}}catch{}}for(let[R,A]of Object.entries(h))c=c.split(R).join(A);let m=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=m.exec(c))!==null;){let R=p[1];if(R&&!f[R]){let A=await l(R);A&&(f[R]=A)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=y.exec(c))!==null;){let R=p[1].trim();if(R&&!f[R]){let A=await l(R);A&&(f[R]=A)}}for(let[R,A]of Object.entries(f)){let w=R.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),T=new RegExp(`(src=["'])(${w})(["'])`,"gi");c=c.replace(T,`$1${A}$3`);let E=new RegExp(`url\\(\\s*(['"]?)(${w})\\1\\s*\\)`,"gi");c=c.replace(E,`url($1${A}$1)`)}let g=`
359
+ <style>
360
+ @page {
361
+ margin: ${s};
362
+ }
363
+ body {
364
+ margin: 0;
365
+ padding: 0;
366
+ font-family: system-ui, -apple-system, sans-serif;
367
+ }
368
+ * { box-sizing: border-box; }
369
+ .watermark {
370
+ position: fixed;
371
+ top: 50%;
372
+ left: 50%;
373
+ transform: translate(-50%, -50%) rotate(-50deg);
374
+ font-size: 52px;
375
+ font-weight: bold;
376
+ color: rgba(0, 0, 0, 0.005);
377
+ pointer-events: none;
378
+ z-index: -1000;
379
+ text-align: center;
380
+ width: 150%;
381
+ white-space: nowrap;
382
+ text-transform: uppercase;
383
+ letter-spacing: 5px;
384
+ }
385
+ </style>
386
+ <div class="watermark">Generated by FluxFlow CLI (AI)</div>
387
+ ${c}
388
+ `;await d.setContent(g,{waitUntil:"networkidle0",timeout:18e4});let S=await d.pdf({format:"A4",landscape:String(o).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),b=await cc.load(S),x=Ns.basename(e);b.setTitle(`FluxFlow_${x}`),b.setAuthor("FluxFlow CLI"),b.setSubject("Generated with Agentic AI System"),b.setKeywords(["FluxFlow","AI","Agentic","Automated"]),b.setCreator("FluxFlow PDF Engine"),b.setProducer("FluxFlow (Generative AI)");let k=await b.save();await hs.writeFile(i,k);let C=await hs.stat(i);return`SUCCESS: PDF generated successfully at [${e}] (${(C.size/1024).toFixed(2)} KB).`}catch(a){let d=a instanceof Error?a.message:String(a);return`ERROR: Failed to generate PDF [${e}]: ${d}`}finally{r&&await r.close()}};import ea from"fs-extra";import _i from"path";import fc from"html-to-docx";var Mi=async n=>{let{path:e,content:t}=L(n);if(!e)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let o=_i.resolve(process.cwd(),e);try{await ea.ensureDir(_i.dirname(o)),await ct.recordFileChange(o);let s=_i.basename(e),i=t.includes("<html")?t:`
389
+ <!DOCTYPE html>
390
+ <html lang="en">
391
+ <head>
392
+ <meta charset="UTF-8">
393
+ <title>FluxFlow Document</title>
394
+ </head>
395
+ <body>
396
+ ${t}
397
+ </body>
398
+ </html>
399
+ `,r=await fc(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await ea.writeFile(o,r),`SUCCESS: Word document [${e}] generated successfully.
400
+ - Size: ${(r.length/1024).toFixed(1)} KB`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to generate DOCX [${e}]: ${i}`}};import Bi from"fs/promises";import ms from"path";import Ui from"fast-glob";var Ii=(n,e,t)=>{let o=n instanceof RegExp?ta(n,t):n,s=e instanceof RegExp?ta(e,t):e,i=o!==null&&s!=null&&dc(o,s,t);return i&&{start:i[0],end:i[1],pre:t.slice(0,i[0]),body:t.slice(i[0]+o.length,i[1]),post:t.slice(i[1]+s.length)}},ta=(n,e)=>{let t=e.match(n);return t?t[0]:null},dc=(n,e,t)=>{let o,s,i,r,a,d=t.indexOf(n),c=t.indexOf(e,d+1),f=d;if(d>=0&&c>0){if(n===e)return[d,c];for(o=[],i=t.length;f>=0&&!a;){if(f===d)o.push(f),d=t.indexOf(n,f+1);else if(o.length===1){let l=o.pop();l!==void 0&&(a=[l,c])}else s=o.pop(),s!==void 0&&s<i&&(i=s,r=c),c=t.indexOf(e,f+1);f=d<c&&d>=0?d:c}o.length&&r!==void 0&&(a=[i,r])}return a};var na="\0SLASH"+Math.random()+"\0",sa="\0OPEN"+Math.random()+"\0",Ni="\0CLOSE"+Math.random()+"\0",oa="\0COMMA"+Math.random()+"\0",ia="\0PERIOD"+Math.random()+"\0",uc=new RegExp(na,"g"),hc=new RegExp(sa,"g"),pc=new RegExp(Ni,"g"),mc=new RegExp(oa,"g"),gc=new RegExp(ia,"g"),yc=/\\\\/g,wc=/\\{/g,Sc=/\\}/g,Tc=/\\,/g,bc=/\\\./g,Ec=1e5,xc=4e6;function vi(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function Rc(n){return n.replace(yc,na).replace(wc,sa).replace(Sc,Ni).replace(Tc,oa).replace(bc,ia)}function kc(n){return n.replace(uc,"\\").replace(hc,"{").replace(pc,"}").replace(mc,",").replace(gc,".")}function ra(n){if(!n)return[""];let e=[],t=Ii("{","}",n);if(!t)return n.split(",");let{pre:o,body:s,post:i}=t,r=o.split(",");r[r.length-1]+="{"+s+"}";let a=ra(i);return i.length&&(r[r.length-1]+=a.shift(),r.push.apply(r,a)),e.push.apply(e,r),e}function aa(n,e={}){if(!n)return[];let{max:t=Ec,maxLength:o=xc}=e;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),Li(Rc(n),t,o,!0).map(kc)}function Ac(n){return"{"+n+"}"}function Cc(n){return/^-?0\d/.test(n)}function Oc(n,e){return n<=e}function $c(n,e){return n>=e}function eo(n,e,t,o,s,i){let r=[],a=0;for(let d=0;d<n.length;d++)for(let c=0;c<t.length;c++){if(r.length>=o)return r;let f=n[d]+e+t[c];if(!(i&&!f)){if(a+f.length>s)return r;r.push(f),a+=f.length}}return r}function _c(n,e,t,o){let s=n.split(/\.\./),i=[];if(s[0]===void 0||s[1]===void 0)return i;let r=vi(s[0]),a=vi(s[1]),d=Math.max(s[0].length,s[1].length),c=s.length===3&&s[2]!==void 0?Math.max(Math.abs(vi(s[2])),1):1,f=Oc;a<r&&(c*=-1,f=$c);let u=s.some(Cc),h=0;for(let p=r;f(p,a)&&i.length<t;p+=c){let m;if(e)m=String.fromCharCode(p),m==="\\"&&(m="");else if(m=String(p),u){let y=d-m.length;if(y>0){let g=new Array(y+1).join("0");p<0?m="-"+g+m.slice(1):m=g+m}}if(h+m.length>o)break;i.push(m),h+=m.length}return i}function Li(n,e,t,o){let s=[""],i=!1,r=!0;for(;;){let a=Ii("{","}",n);if(!a)return eo(s,n,[""],e,t,i);let d=a.pre;if(/\$$/.test(d)){if(s=eo(s,d+"{"+a.body+"}",[""],e,t,i&&!a.post.length),r=!1,!a.post.length)break;n=a.post;continue}let c=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),f=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),l=c||f,u=a.body.indexOf(",")>=0;if(!l&&!u){if(a.post.match(/,(?!,).*\}/)){n=a.pre+"{"+a.body+Ni+a.post,o=!0;continue}return eo(s,d+"{"+a.body+"}"+a.post,[""],e,t,i)}r&&(i=o&&!l,r=!1);let h;if(l)h=_c(a.body,f,e,t);else{let p=ra(a.body);if(p.length===1&&p[0]!==void 0&&(p=Li(p[0],e,t,!1).map(Ac),p.length===1)){if(s=eo(s,d+p[0],[""],e,t,i&&!a.post.length),!a.post.length)break;n=a.post;continue}let m=i&&!a.post.length&&!d;for(let g=0;m&&g<s.length;g++)s[g]&&(m=!1);h=[];let y=0;e:for(let g=0;g<p.length;g++){let S=Li(p[g],e,t,!1);for(let b=0;b<S.length;b++){let x=S[b];if(!(m&&!x)){if(h.length>=e||y+x.length>t)break e;h.push(x),y+=x.length}}}}if(s=eo(s,d,h,e,t,i&&!a.post.length),!a.post.length)break;n=a.post}return s}var to=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var Mc={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},no=n=>n.replace(/[[\]\\-]/g,"\\$&"),Ic=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),la=n=>n.join(""),ca=(n,e)=>{let t=e;if(n.charAt(t)!=="[")throw new Error("not in a brace expression");let o=[],s=[],i=t+1,r=!1,a=!1,d=!1,c=!1,f=t,l="";e:for(;i<n.length;){let m=n.charAt(i);if((m==="!"||m==="^")&&i===t+1){c=!0,i++;continue}if(m==="]"&&r&&!d){f=i+1;break}if(r=!0,m==="\\"&&!d){d=!0,i++;continue}if(m==="["&&!d){for(let[y,[g,S,b]]of Object.entries(Mc))if(n.startsWith(y,i)){if(l)return["$.",!1,n.length-t,!0];i+=y.length,b?s.push(g):o.push(g),a=a||S;continue e}}if(d=!1,l){m>l?o.push(no(l)+"-"+no(m)):m===l&&o.push(no(m)),l="",i++;continue}if(n.startsWith("-]",i+1)){o.push(no(m+"-")),i+=2;continue}if(n.startsWith("-",i+1)){l=m,i+=2;continue}o.push(no(m)),i++}if(f<i)return["",!1,0,!1];if(!o.length&&!s.length)return["$.",!1,n.length-t,!0];if(s.length===0&&o.length===1&&/^\\?.$/.test(o[0])&&!c){let m=o[0].length===2?o[0].slice(-1):o[0];return[Ic(m),!1,f-t,!1]}let u="["+(c?"^":"")+la(o)+"]",h="["+(c?"":"^")+la(s)+"]";return[o.length&&s.length?"("+u+"|"+h+")":o.length?u:h,a,f-t,!0]};var qn=(n,{windowsPathsNoEscape:e=!1,magicalBraces:t=!0}={})=>t?e?n.replace(/\[([^/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):e?n.replace(/\[([^/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var Gt,vc=new Set(["!","?","+","*","@"]),Pi=n=>vc.has(n),fa=n=>Pi(n.type),Lc=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Nc=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),Pc=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),da=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Dc="(?!(?:^|/)\\.\\.?(?:$|/))",Io="(?!\\.)",Fc=new Set(["[","."]),Uc=new Set(["..","."]),Bc=new Set("().*{}+?[]^$\\!"),Wc=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Di="[^/]",ua=Di+"*?",ha=Di+"+?",jc=0,ps=class{type;#n;#s;#o=!1;#e=[];#t;#a;#c;#l=!1;#i;#r;#f=!1;id=++jc;get depth(){return(this.#t?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#n.id,parent:this.#t?.id,depth:this.depth,partsLength:this.#e.length,parts:this.#e}}constructor(e,t,o={}){this.type=e,e&&(this.#s=!0),this.#t=t,this.#n=this.#t?this.#t.#n:this,this.#i=this.#n===this?o:this.#n.#i,this.#c=this.#n===this?[]:this.#n.#c,e==="!"&&!this.#n.#l&&this.#c.push(this),this.#a=this.#t?this.#t.#e.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let e of this.#e)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#r!==void 0?this.#r:this.type?this.#r=this.type+"("+this.#e.map(e=>String(e)).join("|")+")":this.#r=this.#e.map(e=>String(e)).join("")}#y(){if(this!==this.#n)throw new Error("should only call on root");if(this.#l)return this;this.toString(),this.#l=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,o=t.#t;for(;o;){for(let s=t.#a+1;!o.type&&s<o.#e.length;s++)for(let i of e.#e){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(o.#e[s])}t=o,o=t.#t}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof Gt&&t.#t===this))throw new Error("invalid part: "+t);this.#e.push(t)}}toJSON(){let e=this.type===null?this.#e.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#e.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#n||this.#n.#l&&this.#t?.type==="!")&&e.push({}),e}isStart(){if(this.#n===this)return!0;if(!this.#t?.isStart())return!1;if(this.#a===0)return!0;let e=this.#t;for(let t=0;t<this.#a;t++){let o=e.#e[t];if(!(o instanceof Gt&&o.type==="!"))return!1}return!0}isEnd(){if(this.#n===this||this.#t?.type==="!")return!0;if(!this.#t?.isEnd())return!1;if(!this.type)return this.#t?.isEnd();let e=this.#t?this.#t.#e.length:0;return this.#a===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new Gt(this.type,e);for(let o of this.#e)t.copyIn(o);return t}static#d(e,t,o,s,i){let r=s.maxExtglobRecursion??2,a=!1,d=!1,c=-1,f=!1;if(t.type===null){let m=o,y="";for(;m<e.length;){let g=e.charAt(m++);if(a||g==="\\"){a=!a,y+=g;continue}if(d){m===c+1?(g==="^"||g==="!")&&(f=!0):g==="]"&&!(m===c+2&&f)&&(d=!1),y+=g;continue}else if(g==="["){d=!0,c=m,f=!1,y+=g;continue}if(!s.noext&&Pi(g)&&e.charAt(m)==="("&&i<=r){t.push(y),y="";let b=new Gt(g,t);m=Gt.#d(e,b,m,s,i+1),t.push(b);continue}y+=g}return t.push(y),m}let l=o+1,u=new Gt(null,t),h=[],p="";for(;l<e.length;){let m=e.charAt(l++);if(a||m==="\\"){a=!a,p+=m;continue}if(d){l===c+1?(m==="^"||m==="!")&&(f=!0):m==="]"&&!(l===c+2&&f)&&(d=!1),p+=m;continue}else if(m==="["){d=!0,c=l,f=!1,p+=m;continue}if(!s.noext&&Pi(m)&&e.charAt(l)==="("&&(i<=r||t&&t.#u(m))){let g=t&&t.#u(m)?0:1;u.push(p),p="";let S=new Gt(m,u);u.push(S),l=Gt.#d(e,S,l,s,i+g);continue}if(m==="|"){u.push(p),p="",h.push(u),u=new Gt(null,t);continue}if(m===")")return p===""&&t.#e.length===0&&(t.#f=!0),u.push(p),p="",t.push(...h,u),l;p+=m}return t.type=null,t.#s=void 0,t.#e=[e.substring(o-1)],l}#w(e){return this.#p(e,Nc)}#p(e,t=Lc){if(!e||typeof e!="object"||e.type!==null||e.#e.length!==1||this.type===null)return!1;let o=e.#e[0];return!o||typeof o!="object"||o.type===null?!1:this.#u(o.type,t)}#u(e,t=Pc){return!!t.get(this.type)?.includes(e)}#S(e,t){let o=e.#e[0],s=new Gt(null,o,this.options);s.#e.push(""),o.push(s),this.#m(e,t)}#m(e,t){let o=e.#e[0];this.#e.splice(t,1,...o.#e);for(let s of o.#e)typeof s=="object"&&(s.#t=this);this.#r=void 0}#T(e){return!!da.get(this.type)?.has(e)}#b(e){if(!e||typeof e!="object"||e.type!==null||e.#e.length!==1||this.type===null||this.#e.length!==1)return!1;let t=e.#e[0];return!t||typeof t!="object"||t.type===null?!1:this.#T(t.type)}#E(e){let t=da.get(this.type),o=e.#e[0],s=t?.get(o.type);if(!s)return!1;this.#e=o.#e;for(let i of this.#e)typeof i=="object"&&(i.#t=this);this.type=s,this.#r=void 0,this.#f=!1}static fromGlob(e,t={}){let o=new Gt(null,void 0,t);return Gt.#d(e,o,0,t,0),o}toMMPattern(){if(this!==this.#n)return this.#n.toMMPattern();let e=this.toString(),[t,o,s,i]=this.toRegExpSource();if(!(s||this.#s||this.#i.nocase&&!this.#i.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return o;let a=(this.#i.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#i}toRegExpSource(e){let t=e??!!this.#i.dot;if(this.#n===this&&(this.#h(),this.#y()),!fa(this)){let d=this.isStart()&&this.isEnd()&&!this.#e.some(h=>typeof h!="string"),c=this.#e.map(h=>{let[p,m,y,g]=typeof h=="string"?Gt.#x(h,this.#s,d):h.toRegExpSource(e);return this.#s=this.#s||y,this.#o=this.#o||g,p}).join(""),f="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&Uc.has(this.#e[0]))){let p=Fc,m=t&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),y=!t&&!e&&p.has(c.charAt(0));f=m?Dc:y?Io:""}let l="";return this.isEnd()&&this.#n.#l&&this.#t?.type==="!"&&(l="(?:$|\\/)"),[f+c+l,qn(c),this.#s=!!this.#s,this.#o]}let o=this.type==="*"||this.type==="+",s=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#g(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let d=this.toString(),c=this;return c.#e=[d],c.type=null,c.#s=void 0,[d,qn(this.toString()),!1,!1]}let r=!o||e||t||!Io?"":this.#g(!0);r===i&&(r=""),r&&(i=`(?:${i})(?:${r})*?`);let a="";if(this.type==="!"&&this.#f)a=(this.isStart()&&!t?Io:"")+ha;else{let d=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Io:"")+ua+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&r?")":this.type==="*"&&r?")?":`)${this.type}`;a=s+i+d}return[a,qn(i),this.#s=!!this.#s,this.#o]}#h(){if(fa(this)){let e=0,t=!1;do{t=!0;for(let o=0;o<this.#e.length;o++){let s=this.#e[o];typeof s=="object"&&(s.#h(),this.#p(s)?(t=!1,this.#m(s,o)):this.#w(s)?(t=!1,this.#S(s,o)):this.#b(s)&&(t=!1,this.#E(s)))}}while(!t&&++e<10)}else for(let e of this.#e)typeof e=="object"&&e.#h();this.#r=void 0}#g(e){return this.#e.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[o,s,i,r]=t.toRegExpSource(e);return this.#o=this.#o||r,o}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#x(e,t,o=!1){let s=!1,i="",r=!1,a=!1;for(let d=0;d<e.length;d++){let c=e.charAt(d);if(s){s=!1,i+=(Bc.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,i+=o&&/^[*]+$/.test(e)?ha:ua,t=!0;continue}else a=!1;if(c==="\\"){d===e.length-1?i+="\\\\":s=!0;continue}if(c==="["){let[f,l,u,h]=ca(e,d);if(u){i+=f,r=r||l,d+=u-1,t=t||h;continue}}if(c==="?"){i+=Di,t=!0;continue}i+=Wc(c)}return[i,qn(e),!!t,r]}};Gt=ps;var Fi=(n,{windowsPathsNoEscape:e=!1,magicalBraces:t=!1}={})=>t?e?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var Nt=(n,e,t={})=>(to(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Ln(e,t).match(n)),Hc=/^\*+([^+@!?*[(]*)$/,Gc=n=>e=>!e.startsWith(".")&&e.endsWith(n),Yc=n=>e=>e.endsWith(n),qc=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),zc=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),Vc=/^\*+\.\*+$/,Kc=n=>!n.startsWith(".")&&n.includes("."),Xc=n=>n!=="."&&n!==".."&&n.includes("."),Jc=/^\.\*+$/,Qc=n=>n!=="."&&n!==".."&&n.startsWith("."),Zc=/^\*+$/,ef=n=>n.length!==0&&!n.startsWith("."),tf=n=>n.length!==0&&n!=="."&&n!=="..",nf=/^\?+([^+@!?*[(]*)?$/,sf=([n,e=""])=>{let t=ga([n]);return e?(e=e.toLowerCase(),o=>t(o)&&o.toLowerCase().endsWith(e)):t},of=([n,e=""])=>{let t=ya([n]);return e?(e=e.toLowerCase(),o=>t(o)&&o.toLowerCase().endsWith(e)):t},rf=([n,e=""])=>{let t=ya([n]);return e?o=>t(o)&&o.endsWith(e):t},af=([n,e=""])=>{let t=ga([n]);return e?o=>t(o)&&o.endsWith(e):t},ga=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},ya=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},wa=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",pa={win32:{sep:"\\"},posix:{sep:"/"}},lf=wa==="win32"?pa.win32.sep:pa.posix.sep;Nt.sep=lf;var _t=Symbol("globstar **");Nt.GLOBSTAR=_t;var cf="[^/]",ff=cf+"*?",df="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",uf="(?:(?!(?:\\/|^)\\.).)*?",hf=(n,e={})=>t=>Nt(t,n,e);Nt.filter=hf;var rn=(n,e={})=>Object.assign({},n,e),pf=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return Nt;let e=Nt;return Object.assign((o,s,i={})=>e(o,s,rn(n,i)),{Minimatch:class extends e.Minimatch{constructor(s,i={}){super(s,rn(n,i))}static defaults(s){return e.defaults(rn(n,s)).Minimatch}},AST:class extends e.AST{constructor(s,i,r={}){super(s,i,rn(n,r))}static fromGlob(s,i={}){return e.AST.fromGlob(s,rn(n,i))}},unescape:(o,s={})=>e.unescape(o,rn(n,s)),escape:(o,s={})=>e.escape(o,rn(n,s)),filter:(o,s={})=>e.filter(o,rn(n,s)),defaults:o=>e.defaults(rn(n,o)),makeRe:(o,s={})=>e.makeRe(o,rn(n,s)),braceExpand:(o,s={})=>e.braceExpand(o,rn(n,s)),match:(o,s,i={})=>e.match(o,s,rn(n,i)),sep:e.sep,GLOBSTAR:_t})};Nt.defaults=pf;var Sa=(n,e={})=>(to(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:aa(n,{max:e.braceExpandMax}));Nt.braceExpand=Sa;var mf=(n,e={})=>new Ln(n,e).makeRe();Nt.makeRe=mf;var gf=(n,e,t={})=>{let o=new Ln(e,t);return n=n.filter(s=>o.match(s)),o.options.nonull&&!n.length&&n.push(e),n};Nt.match=gf;var ma=/[?*]|[+@!]\(.*?\)|\[|\]/,yf=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ln=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){to(e),t=t||{},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||wa,this.isWindows=this.platform==="win32";let o="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[o]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let o=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(o),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,r,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let d=i[0]===""&&i[1]===""&&(i[2]==="?"||!ma.test(i[2]))&&!ma.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(d)return[...i.slice(0,4),...i.slice(4).map(f=>this.parse(f))];if(c)return[i[0],...i.slice(1).map(f=>this.parse(f))]}return i.map(d=>this.parse(d))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let r=this.set[i];r[0]===""&&r[1]===""&&this.globParts[i][2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3])&&(r[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let o of e)for(let s=0;s<o.length;s++)o[s]==="**"&&(o[s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let o=-1;for(;(o=t.indexOf("**",o+1))!==-1;){let s=o;for(;t[s+1]==="**";)s++;s!==o&&t.splice(o,s-o)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((o,s)=>{let i=o[o.length-1];return s==="**"&&i==="**"?o:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(o.pop(),o):(o.push(s),o)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let i=e[s];s===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let o=0;for(;(o=e.indexOf("..",o+1))!==-1;){let s=e[o-1];s&&s!=="."&&s!==".."&&s!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(s))&&(t=!0,e.splice(o-1,2),o-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let o of e){let s=-1;for(;(s=o.indexOf("**",s+1))!==-1;){let r=s;for(;o[r+1]==="**";)r++;r>s&&o.splice(s+1,r-s);let a=o[s+1],d=o[s+2],c=o[s+3];if(a!==".."||!d||d==="."||d===".."||!c||c==="."||c==="..")continue;t=!0,o.splice(s,1);let f=o.slice(0);f[s]="**",e.push(f),s--}if(!this.preserveMultipleSlashes){for(let r=1;r<o.length-1;r++){let a=o[r];r===1&&a===""&&o[0]===""||(a==="."||a==="")&&(t=!0,o.splice(r,1),r--)}o[0]==="."&&o.length===2&&(o[1]==="."||o[1]==="")&&(t=!0,o.pop())}let i=0;for(;(i=o.indexOf("..",i+1))!==-1;){let r=o[i-1];if(r&&r!=="."&&r!==".."&&r!=="**"){t=!0;let d=i===1&&o[i+1]==="**"?["."]:[];o.splice(i-1,2,...d),o.length===0&&o.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let o=t+1;o<e.length;o++){let s=this.partsMatch(e[t],e[o],!this.preserveMultipleSlashes);if(s){e[t]=[],e[o]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,o=!1){let s=0,i=0,r=[],a="";for(;s<e.length&&i<t.length;)if(e[s]===t[i])r.push(a==="b"?t[i]:e[s]),s++,i++;else if(o&&e[s]==="**"&&t[i]===e[s+1])r.push(e[s]),s++;else if(o&&t[i]==="**"&&e[s]===t[i+1])r.push(t[i]),i++;else if(e[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="b")return!1;a="a",r.push(e[s]),s++,i++}else if(t[i]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(a==="a")return!1;a="b",r.push(t[i]),s++,i++}else return!1;return e.length===t.length&&r}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,o=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,o++;o&&(this.pattern=e.slice(o)),this.negate=t}matchOne(e,t,o=!1){let s=0,i=0;if(this.isWindows){let a=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),d=!a&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),c=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),f=!c&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),l=d?3:a?0:void 0,u=f?3:c?0:void 0;if(typeof l=="number"&&typeof u=="number"){let[h,p]=[e[l],t[u]];h.toLowerCase()===p.toLowerCase()&&(t[u]=h,i=u,s=l)}}let{optimizationLevel:r=1}=this.options;return r>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(_t)?this.#n(e,t,o,s,i):this.#o(e,t,o,s,i)}#n(e,t,o,s,i){let r=t.indexOf(_t,i),a=t.lastIndexOf(_t),[d,c,f]=o?[t.slice(i,r),t.slice(r+1),[]]:[t.slice(i,r),t.slice(r+1,a),t.slice(a+1)];if(d.length){let S=e.slice(s,s+d.length);if(!this.#o(S,d,o,0,0))return!1;s+=d.length,i+=d.length}let l=0;if(f.length){if(f.length+s>e.length)return!1;let S=e.length-f.length;if(this.#o(e,f,o,S,0))l=f.length;else{if(e[e.length-1]!==""||s+f.length===e.length||(S--,!this.#o(e,f,o,S,0)))return!1;l=f.length+1}}if(!c.length){let S=!!l;for(let b=s;b<e.length-l;b++){let x=String(e[b]);if(S=!0,x==="."||x===".."||!this.options.dot&&x.startsWith("."))return!1}return o||S}let u=[[[],0]],h=u[0],p=0,m=[0];for(let S of c)S===_t?(m.push(p),h=[[],0],u.push(h)):(h[0].push(S),p++);let y=u.length-1,g=e.length-l;for(let S of u)S[1]=g-(m[y--]+S[0].length);return!!this.#s(e,u,s,0,o,0,!!l)}#s(e,t,o,s,i,r,a){let d=t[s];if(!d){for(let l=o;l<e.length;l++){a=!0;let u=e[l];if(u==="."||u===".."||!this.options.dot&&u.startsWith("."))return!1}return a}let[c,f]=d;for(;o<=f;){if(this.#o(e.slice(0,o+c.length),c,i,o,0)&&r<this.maxGlobstarRecursion){let h=this.#s(e,t,o+c.length,s+1,i,r+1,a);if(h!==!1)return h}let u=e[o];if(u==="."||u===".."||!this.options.dot&&u.startsWith("."))return!1;o++}return i||null}#o(e,t,o,s,i){let r,a,d,c;for(r=s,a=i,c=e.length,d=t.length;r<c&&a<d;r++,a++){this.debug("matchOne loop");let f=t[a],l=e[r];if(this.debug(t,f,l),f===!1||f===_t)return!1;let u;if(typeof f=="string"?(u=l===f,this.debug("string match",f,l,u)):(u=f.test(l),this.debug("pattern match",f,l,u)),!u)return!1}if(r===c&&a===d)return!0;if(r===c)return o;if(a===d)return r===c-1&&e[r]==="";throw new Error("wtf?")}braceExpand(){return Sa(this.pattern,this.options)}parse(e){to(e);let t=this.options;if(e==="**")return _t;if(e==="")return"";let o,s=null;(o=e.match(Zc))?s=t.dot?tf:ef:(o=e.match(Hc))?s=(t.nocase?t.dot?zc:qc:t.dot?Yc:Gc)(o[1]):(o=e.match(nf))?s=(t.nocase?t.dot?of:sf:t.dot?rf:af)(o):(o=e.match(Vc))?s=t.dot?Xc:Kc:(o=e.match(Jc))&&(s=Qc);let i=ps.fromGlob(e,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,o=t.noglobstar?ff:t.dot?df:uf,s=new Set(t.nocase?["i"]:[]),i=e.map(d=>{let c=d.map(l=>{if(l instanceof RegExp)for(let u of l.flags.split(""))s.add(u);return typeof l=="string"?yf(l):l===_t?_t:l._src});c.forEach((l,u)=>{let h=c[u+1],p=c[u-1];l!==_t||p===_t||(p===void 0?h!==void 0&&h!==_t?c[u+1]="(?:\\/|"+o+"\\/)?"+h:c[u]=o:h===void 0?c[u-1]=p+"(?:\\/|\\/"+o+")?":h!==_t&&(c[u-1]=p+"(?:\\/|\\/"+o+"\\/)"+h,c[u+1]=_t))});let f=c.filter(l=>l!==_t);if(this.partial&&f.length>=1){let l=[];for(let u=1;u<=f.length;u++)l.push(f.slice(0,u).join("/"));return"(?:"+l.join("|")+")"}return f.join("/")}).join("|"),[r,a]=e.length>1?["(?:",")"]:["",""];i="^"+r+i+a+"$",this.partial&&(i="^(?:\\/|"+r+i.slice(1,-1)+a+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let o=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let r=s[s.length-1];if(!r)for(let a=s.length-2;!r&&a>=0;a--)r=s[a];for(let a of i){let d=s;if(o.matchBase&&a.length===1&&(d=[r]),this.matchOne(d,a,t))return o.flipNegate?!0:!this.negate}return o.flipNegate?!1:this.negate}static defaults(e){return Nt.defaults(e).Minimatch}};Nt.AST=ps;Nt.Minimatch=Ln;Nt.escape=Fi;Nt.unescape=qn;async function so(n,e,t=n,o=1){if(o>12)return[];let s=[],i;try{i=await Bi.readdir(n,{withFileTypes:!0})}catch{return[]}for(let r of i){let a=ms.join(n,r.name),d=ms.relative(t,a),c=d.split(ms.sep).map(u=>u.toLowerCase()),f=r.name.toLowerCase();if(!e.some(u=>{let h=u.toLowerCase();return h.startsWith(".")&&f.endsWith(h)?!0:c.some(p=>p===h||p.startsWith(".pnpm"))}))if(r.isDirectory()){let u=await so(a,e,t,o+1);s=s.concat(u)}else r.isFile()&&s.push({fullPath:a,relativePath:d})}return s}function wf(n,e,t=1/0){if(n===e)return 0;if(n.length===0)return e.length;if(e.length===0)return n.length;if(Math.abs(n.length-e.length)>t)return t+1;let o=Array.from({length:e.length+1},(s,i)=>i);for(let s=1;s<=n.length;s++){let i=[s],r=s;for(let a=1;a<=e.length;a++){let d=n[s-1]===e[a-1]?0:1,c=Math.min(i[a-1]+1,o[a]+1,o[a-1]+d);i.push(c),c<r&&(r=c)}if(o=i,r>t)return t+1}return o[e.length]}function Sf(n,e){if(!n||!e)return!1;let t=n.toLowerCase(),o=e.toLowerCase();if(t.includes(o))return!0;let s=t.split(/[^a-z0-9]+/).filter(r=>r.length>0),i=o.split(/[^a-z0-9]+/).filter(r=>r.length>1||o.length===1&&r.length>0);return i.length===0?!1:i.every(r=>{let a=r.length<=2?0:r.length<=5?1:2;for(let d of s)if(d.includes(r)||r.length>=3&&d.length>=3&&Math.abs(d.length-r.length)<=a&&wf(r,d,a)<=a)return!0;return!1})}var oo=async n=>{let{keyword:e,path:t,fuzzy:o,subString:s,regex:i}=L(n);if(e==null)return'ERROR: Missing "keyword" argument.';let r=String(e),a=m=>m===!0||m==="true"||m===1||m==="1"||m==="yes",d=i===!1||i==="false"||i===0||i==="0"||i==="no",c=i===!0||i==="true"||i===1||i==="1"||i==="yes",f=a(o)||a(s),l=null,u=null;if(d)f||(u=new RegExp(`(?<![\\w])${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{l=new RegExp(r,"i")}catch(m){if(c)return`ERROR: Invalid regex pattern "${r}": ${m.message}`}u=new RegExp(`(?<![\\w])${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let h=[".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",".exe",".dll",".so",".dylib",".png",".jpg",".jpeg",".gif",".ico",".svg",".webp",".mp3",".mp4",".avi",".zip",".tgz",".tar",".gz",".7z",".rar",".pdf",".docx",".xlsx",".pptx",".woff",".woff2",".ttf",".eot"],p=150;try{let m=[],y=process.cwd(),g=null;if(t){let _=t.split(";").map(B=>B.trim()).filter(Boolean),M=_.some(B=>B.startsWith("!"));if(_.some(B=>Ui.isDynamicPattern(B)||/[*?{}[\]()|+]/.test(B))){g="glob";let B=t.replace(/\\/g,"/"),K=_.map(D=>D.replace(/\\/g,"/")),Y=h.map(D=>D.startsWith(".")?`**/*${D}`:`**/${D}/**`);if(M&&!_.some(D=>!D.startsWith("!"))){let D=await so(y,h,y),F=$=>$.endsWith("/")?$+"**":$,se=K.filter($=>$.startsWith("!")).map($=>F($.slice(1))),Ee=K.filter($=>!$.startsWith("!")).map(F);m=D.filter($=>{let P=$.relativePath.replace(/\\/g,"/"),V=Ee.length===0||Ee.some(Pe=>{try{return new Ln(Pe).match(P)}catch{return!1}}),X=se.some(Pe=>{try{return new Ln(Pe).match(P)}catch{return!1}});return V&&!X})}else{let D=K.some(se=>/[\(\)\|]|\.\*/.test(se)),F=[];if(!D)try{F=await Ui(K,{cwd:y,ignore:Y,dot:!0,onlyFiles:!0,absolute:!1})}catch{F=[]}if(F.length===0&&(D||Ui.isDynamicPattern(B))){let se=B.match(/^([^\*\?\(\)\|\[\]\s]+)\//),Ee=se&&!/[\*\?\(\)\|\[\]]/.test(se[1])?ms.resolve(y,se[1]):y,$=await so(Ee,h,y);try{let P=B.replace(/^\.\//,"");P=P.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!P.startsWith("^")&&!P.startsWith(".*")&&(P=`.*${P}`);let V=new RegExp(P.endsWith("$")?P:`${P}$`,"i");m=$.filter(X=>{let Pe=X.relativePath.replace(/\\/g,"/");return V.test(Pe)})}catch{m=[]}}else m=F.map(se=>({fullPath:ms.resolve(y,se),relativePath:se}))}}else{let B=t.replace(/[\/\\]+$/,""),K=ms.resolve(y,B);try{let Y=await Bi.stat(K);if(Y.isDirectory())g="dir",m=await so(K,h,y);else if(Y.isFile())g="file",m.push({fullPath:K,relativePath:ms.relative(y,K)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else m=await so(y,h);let S=m.map(async _=>{try{let M=await Bi.readFile(_.fullPath,"utf-8");if(M.includes("\0"))return[];let W=M.split(/\r?\n/),B=[];for(let Y=0;Y<W.length;Y++)(f?W[Y].toLowerCase().includes(r.toLowerCase())||Sf(W[Y],r):d?u&&u.test(W[Y]):l&&l.test(W[Y])||u&&u.test(W[Y]))&&B.push({line:Y+1,content:W[Y].trim()});return B.length===0?null:{path:_.relativePath.replace(/\\/g,"/"),matches:B}}catch{return[]}}),b=await Promise.all(S),x=[],k=0;for(let _ of b){if(!_||!_.matches)continue;if(k>=p)break;let M=p-k,W=_.matches.slice(0,M);x.push({path:_.path,matches:W}),k+=W.length}typeof global.gc=="function"&&global.gc();let C=f?"(fuzzy mode)":c?"(regex mode)":d?"(keyword mode)":"(standard mode)";if(x.length===0){let _=g==="file"?` in '${t}'`:g==="dir"||g==="glob"?` in '${t}'`:". Try to specify files",M=g==="dir"?"[DIR]":g==="glob"?"[GLOB]":"";return`${M}${M?" ":""}Found 0 matches of '${r}'${_}${C?` ${C}`:""}`}let R=C?` ${C}`:"",A=`${x.length} file${x.length===1?"":"s"}`,w=`${k} match${k===1?"":"es"}`,T;g==="file"?T=`Found ${w} of '${r}' in '${t}'${R}:`:g==="dir"||g==="glob"?T=`Found ${w} of '${r}' in '${t}' across ${A}${R}:`:T=`Found ${w} of '${r}' across ${A}${R}:`;let E=g==="dir"?"[DIR]":g==="glob"?"[GLOB]":"",I=`${E}${E?" ":""}${T}
401
+
402
+ `;for(let _ of x){I+=`${_.path}
403
+ `;for(let M of _.matches)I+=` ${M.line}: ${M.content}
404
+ `;I+=`
405
+ `}return I.trimEnd()}catch(m){return`ERROR: ${m.message}`}};import Ta from"fs-extra";import Wi from"path";var Tf=(n,e={})=>{try{if(n.length<8||n[0]!==137||n[1]!==80||n[2]!==78||n[3]!==71)return n;let t=[],o=[];for(let r=0;r<256;r++){let a=r;for(let d=0;d<8;d++)a&1?a=3988292384^a>>>1:a=a>>>1;o[r]=a}let s=r=>{let a=4294967295;for(let d=0;d<r.length;d++)a=o[(a^r[d])&255]^a>>>8;return(a^4294967295)>>>0},i=(r,a)=>{let d=Buffer.from(r,"ascii"),c=Buffer.from(a,"utf-8"),f=d.length+1+c.length,l=Buffer.alloc(8+f+4);l.writeUInt32BE(f,0),l.write("tEXt",4,"ascii"),d.copy(l,8),l[8+d.length]=0,c.copy(l,8+d.length+1);let u=s(l.subarray(4,8+f));return l.writeUInt32BE(u,8+f),l};for(let[r,a]of Object.entries(e))a!=null&&t.push(i(r,String(a)));if(t.length===0)return n;if(n.subarray(12,16).toString("ascii")==="IHDR"){let a=n.subarray(0,33),d=n.subarray(33);return Buffer.concat([a,...t,d])}return n}catch{return n}},ji=async(n,e={})=>{let t=L(n),o=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",i=t.ratio;if(!o)return'ERROR: Missing "prompt" argument for generate_image.';let r=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],a=o.toLowerCase();if(r.some(c=>a.includes(c)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let c=await Qt();if(!await Wr(c))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await jr()).nextResetMin||60}m).`;let l=c.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,p={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",m=1024,y=1024;if(i){let M=i.replace(/\s+/g,"");M==="16:9"?(m=1024,y=576):M==="9:16"?(m=576,y=1024):M==="4:3"?(m=1024,y=768):M==="3:4"?(m=768,y=1024):M==="1:1"&&(m=1024,y=1024)}let g=Math.floor(Math.random()*1e7),b=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${p}&width=${m}&height=${y}&seed=${g}&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")}`,x=await fetch(b,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!x.ok){let M=x.status,W="";try{W=await x.text()}catch{}return M===402||W.includes("Insufficient balance")||W.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${M}]: ${W||"Unknown API Error"}`}if((x.headers.get("content-type")||"").includes("application/json")){let M=await x.json();return M.status===402||M.error&&M.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${M.error?.message||JSON.stringify(M)}`}let C=await x.arrayBuffer(),R=Buffer.from(C),A={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${p}`,Ratio:i||"1:1",Seed:String(g)};R=Tf(R,A);let w=Wi.resolve(process.cwd(),s);await Ta.ensureDir(Wi.dirname(w)),await ct.recordFileChange(w),await Ta.writeFile(w,R),await Hr(c);let T=Wi.extname(s).toLowerCase(),I={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[T]||"image/png";return e.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:R.toString("base64"),mimeType:I}}}:`SUCCESS: Image successfully generated from prompt [${o}] and saved to [${s}].`}catch(c){return`ERROR: Failed during image generation: ${c instanceof Error?c.message:String(c)}`}};var io=async(n,e={})=>{let t=i=>{let r=new RegExp(`${i}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),a=n.match(r);return a?a[2].trim():null},o=t("id"),s=t("summary");if(!o||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let i=J(Jt,{}),r=J(In,{});return r[o]=s,delete i[o],ce(In,r),ce(Jt,i),`SUCCESS: Saved summary and purged raw memories for chat [${o}].`}catch(i){let r=i instanceof Error?i.message:String(i);return`ERROR: Failed to save summary for chat [${o}]: ${r}`}};var Ps=async(n,e={})=>{let o=(s=>{let i=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),r=n.match(i);return r?r[2].trim():null})("id");if(!o)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=J(Lt,[]),i=!1,r=[];for(let f of s)f.score===void 0&&(f.score=.5),f.id===o?(f.score=Math.min(2,f.score+.2),i=!0):(f.score*=.98,f.score<.05&&(f.score=0)),f.score=Math.round(f.score*1e5)/1e5,f.score>0&&r.push(f);if(ce(Lt,r),!i)return`WARNING: Memory ID [${o}] not found. Other memories decayed by -0.01.`;let a=r.find(f=>f.id===o),d=a?a.score.toFixed(2):"deleted (score <= 0)",c=s.length-r.length;return`SUCCESS: Adjusted memory scores. Target [${o}] is now ${d}.${c>0?` Purged ${c} decayed memories.`:""}`}catch(s){let i=s instanceof Error?s.message:String(s);return`ERROR: Failed to adjust memory score for [${o}]: ${i}`}};import Gi from"fs-extra";import ys from"path";import{createRequire as xf}from"module";import gs from"fs-extra";import Hi from"path";import bf from"https";var ba={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 Ef(n,e=null){let t=e||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${n}`,o=Hi.join(ls,n);return await gs.ensureDir(ls),new Promise((s,i)=>{let r={headers:{"User-Agent":"FluxFlow-Agent"}};bf.get(t,r,a=>{if([301,302,307,308].includes(a.statusCode)&&a.headers.location){let c=a.headers.location;if(!c.startsWith("http")){let f=new URL(t);c=`${f.protocol}//${f.host}${c}`}Ef(n,c).then(s).catch(i);return}if(a.statusCode!==200){i(new Error(`Failed to download ${n}: HTTP ${a.statusCode}`));return}let d=gs.createWriteStream(o);a.pipe(d),d.on("finish",()=>{d.close(),s()})}).on("error",a=>{gs.existsSync(o)&&gs.unlink(o,()=>{}),i(a)})})}function Tp(n){let e=Hi.join(ls,n);return gs.existsSync(e)}async function bp(n){let e=Hi.join(ls,n);gs.existsSync(e)&&await gs.unlink(e)}var Ra=xf(import.meta.url),Ea=Ra("web-tree-sitter"),xa=!1,ka=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"]),Aa=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function gn(n,e=50){if(!n)return"";let t=n.replace(/\s+/g," ").trim();return t.length>e?t.substring(0,e-3)+"...":t}function Ca(n){let e=n.type;if(e==="if_statement"){let o=n.childForFieldName("condition");return o?`if (${gn(o.text,40)})`:"if"}if(e==="else_clause")return"else";if(e==="while_statement"||e==="do_statement"){let o=n.childForFieldName("condition");return`${e.split("_")[0]} (${o?gn(o.text,40):""})`}if(e==="for_statement"||e==="for_in_statement"||e==="for_of_statement"){let s=n.text.split(`
406
+ `)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${gn(s[1],40)})`:"for"}if(e==="switch_statement"){let o=n.childForFieldName("value");return`switch (${o?gn(o.text,40):""})`}if(e==="try_statement")return"try";if(e==="catch_clause")return"catch";if(e==="element"||e==="script_element"||e==="style_element"||e==="jsx_element"||e==="jsx_self_closing_element"){let o=n.childForFieldName("opening_element")||n.childForFieldName("start_tag")||n.children.find(i=>i.type==="start_tag")||n,s=o.childForFieldName("name")||o.childForFieldName("tag_name")||o.children.find(i=>i.type==="tag_name");return s?`<${gn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(e))return gn(n.text.split(`
407
+ `)[0],60);if(e==="pair"){let o=n.childForFieldName("key");return o?gn(o.text.replace(/["']/g,""),40):null}if(e==="assignment_expression"){let o=n.childForFieldName("left");return o?`${gn(o.text,30)} = ...`:null}if(e==="variable_declarator"){let o=n.childForFieldName("name")||n.children.find(s=>["identifier","object_pattern","array_pattern"].includes(s.type));return o?gn(o.text,40):null}let t=n.childForFieldName("name")||n.childForFieldName("declarator")||n.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 gn(o.text,40)}return gn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(e)){let o=n.parent;for(;o&&o.type!=="program";){let s=Ca(o);if(s)return s;if(!Aa.has(o.type))break;o=o.parent}}return null}function Rf(n){let e=[];function t(o){for(let s of o.children)ka.has(s.type)?e.push(s):t(s)}return t(n),e}function kf(n){return n.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Oa(n,e=0,t=!0,o="",s=null,i=12){let r=n.type,a=Ca(n),d=ka.has(r)||e===0,c=Rf(n),f=d&&e>0&&(Aa.has(r)&&c.length>0||a!==null&&a===s&&c.length>0),l="",u=o,h=e,p=s;if(d&&!f){let m=n.startPosition.row+1,y=n.endPosition.row+1,g=kf(r),S=a?`${g} [${a}]`:g;e===0?(l+=`\u{1F4C1} ROOT (Lines: ${m}-${y})
408
+ `,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${S} (Lines: ${m}-${y})
409
+ `,u+=t?" ":"\u2502 "),h=e+1,p=a}return h>i&&c.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
410
+ `:c.forEach((m,y)=>{let g=y===c.length-1;l+=Oa(m,h,f?t&&g:g,u,p,i)}),l}var Yi=async n=>{let e;try{e=L(n).path}catch{return`ERROR: Failed to parse arguments: ${n}`}if(!e)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=ys.isAbsolute(e)?e:ys.resolve(process.cwd(),e);if(!Gi.existsSync(t))return`ERROR: File not found: ${e}`;let o=ys.extname(t).slice(1).toLowerCase(),s=ba[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ys.resolve(ls,s);if(!Gi.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let r=Ea.Parser;if(!xa){let p;try{p=ys.join(ys.dirname(Ra.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{p=ys.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await r.init({locateFile:m=>m==="tree-sitter.wasm"||m.endsWith("tree-sitter.wasm")?p:m}),xa=!0}let a=new r,d=await Ea.Language.load(i);a.setLanguage(d);let c=await Gi.readFile(t,"utf8"),f=c.split(`
411
+ `).length,l=12;f>1e4?l=2:f>=8e3?l=3:f>=5e3?l=5:f>=4e3?l=8:f>2e3&&(l=10);let u=a.parse(c),h=Oa(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${e}
412
+ ${h}`}catch(r){let a=r instanceof Error?r.message:typeof r=="object"?JSON.stringify(r):String(r),d=r instanceof Error?`
413
+ Stack: ${r.stack}`:"";return`ERROR: Failed to map file: ${a}${d}`}};import zn from"fs";import $a from"path";var _a=async(n,e={})=>{let{method:t,tasks:o,markDone:s}=L(n),i=e.chatId||"default";if(!t)return'ERROR: Missing "method" argument for todo tool (create/append/get).';let r=$a.join(Mn,"plan",i),a=$a.join(r,"todo.md"),d=l=>{if(!l||Array.isArray(l))return l;let u=String(l).trim();if(u.startsWith("[")&&u.endsWith("]")){let h=u.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);return h?h.map(p=>p.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(p=>p.trim()).filter(Boolean)}return l},c=l=>{let u=d(l);return u?(Array.isArray(u)?u:String(u).split(`
414
+ `)).map(p=>{let m=String(p).trim();return m?m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")?m:`- [ ] ${m}`:null}).filter(Boolean).join(`
415
+ `)+`
416
+ `:""},f=(l,u)=>{if(!u)return{content:l,markedCount:0};let h=d(u),p=(Array.isArray(h)?h:[h]).map(S=>String(S).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),m=l.split(`
417
+ `),y=0,g=!1;for(let S of p){let b=!1;for(let x=0;x<m.length;x++)if(m[x].includes(S)&&/^- \[\s\]/.test(m[x].trim())){m[x]=m[x].replace("- [ ]","- [x]"),b=!0,g=!0,y++;break}if(!b){for(let x=0;x<m.length;x++)if(m[x].toLowerCase().includes(S.toLowerCase())&&/^- \[\s\]/.test(m[x].trim())){m[x]=m[x].replace("- [ ]","- [x]"),b=!0,g=!0,y++;break}}}return{content:g?m.join(`
418
+ `):l,markedCount:y}};try{if(zn.existsSync(r)||zn.mkdirSync(r,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=c(o),u=0;if(s){let p=f(l,s);l=p.content,u=p.markedCount}await ct.recordFileChange(a),zn.writeFileSync(a,l,"utf8");let h=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")).length;if(u>0){let p=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [x]")||m.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${p} completed, ${h-p} left)
419
+ ${l}`}return`SUCCESS: TASK LIST CREATED (${h} total)
420
+ ${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=c(o);await ct.recordFileChange(a),zn.appendFileSync(a,l,"utf8");let u=zn.readFileSync(a,"utf8"),h=u.split(/\r?\n/).map(g=>g.trim()),p=h.filter(g=>g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")).length,m=h.filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length,y=l.split(/\r?\n/).map(g=>g.trim()).filter(g=>g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`SUCCESS: TASK APPENDED (${m} completed, ${p-m} left, ${y} added)
421
+ ${u}`}if(t==="get"){if(!zn.existsSync(a))return"TODO GET: No task list found for this session.";let l=zn.readFileSync(a,"utf8"),u=0;if(s){let g=f(l,s);g.markedCount>0&&(l=g.content,u=g.markedCount,await ct.recordFileChange(a),zn.writeFileSync(a,l,"utf8"))}let h=l.split(/\r?\n/).map(g=>g.trim()),p=h.filter(g=>g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")).length,m=h.filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${m} Completed, ${p-m} left
422
+ ${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 qi=async(n,e={})=>{let{runSubagent:t}=await import("./ai-IOVX3WCN.js"),o=L(n),s=o.task||o.instruction||o.prompt,i=o.model||null,r=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invokeSync.';let a=null;if(r)try{let c=r.trim();c.startsWith("[")&&c.endsWith("]")&&(c=c.substring(1,c.length-1)),a=c.split(",").map(f=>f.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let d=o.title||s.substring(0,30);try{e.onVisualFeedback&&e.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${d}`);let c=await t(s,e,i,a,50);return e.onVisualFeedback&&e.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${d} [COMPLETED]
423
+ `),c}catch(c){let{isTerminationSignaled:f}=await import("./ai-IOVX3WCN.js"),l=c.message==="Subagent task was cancelled by user."||f();if(e.onVisualFeedback){let u=l?"[CANCELLED]":"[FAILED]";e.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${d} ${u}
424
+ `)}return`ERROR: Subagent execution failed: ${c.message}`}};var Ma=async(n,e={})=>{let{runSubagent:t}=await import("./ai-IOVX3WCN.js"),o=L(n),s=o.task||o.instruction||o.prompt,i=o.model||null,r=o.title||null,a=o.tools||null;if(!s)return'ERROR: Missing "task" argument for invoke.';let d=null;if(a)try{let g=a.trim();g.startsWith("[")&&g.endsWith("]")&&(g=g.substring(1,g.length-1)),d=g.split(",").map(S=>S.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let c=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,f=null,l=null,u=new Promise((g,S)=>{f=g,l=S}),h={id:c,title:r||s.substring(0,30),task:s,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:g=>{g&&h.pendingSteerMessages.push(g)},completionPromise:u,_resolveCompletion:f,_rejectCompletion:l,progress:[]},p={chunks:[],totalWords:0};ze.push(h),e.onSubagentUpdate&&e.onSubagentUpdate();let m=[],y={...e,taskId:c,onAskMain:async g=>{let S=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,b=null,x=new Promise(R=>{b=R}),k={id:S,question:g,answered:!1,answer:null,askedAt:Date.now(),_resolve:b};return h.questions.push(k),h.status="waiting",e.onSubagentUpdate&&e.onSubagentUpdate(),wo(`[SYSTEM] Background subagent "${h.title}" is WAITING FOR YOUR INPUT: "${g}"
425
+ Respond using tool: [tool:functions.Answer(id="${c}", answer="...")]
426
+ [/SYSTEM]`),await x},onVisualFeedback:g=>{h.lastChunkTime=Date.now();let S=g.replace(/\x1b\[[0-9;]*m/g,""),b=S.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);b?h.currentTool=b[1].trim():h.currentTool=S,e.onSubagentUpdate&&e.onSubagentUpdate()},onTokenChunk:(g,S)=>{let b=Date.now();if(h.lastChunkTime=b,h.currentTool="Thinking",typeof S=="number"&&S>0){p.totalWords+=S,p.chunks.push({time:b,words:S});let x=b-400;if(p.chunks=p.chunks.filter(k=>k.time>=x),p.chunks.length>0){let k=p.chunks.reduce((A,w)=>A+w.words,0),C=p.chunks[0].time,R=Math.max(.4,(b-C)/1e3);h.wps=Math.round(k/R*10)/10}}e.onSubagentUpdate&&e.onSubagentUpdate()}};return t(s,y,i,d,50,g=>{if(h.status==="cancelled")return;if(g.startsWith("[Subagent Turn")&&m.length>0&&(h.progress.push([...m]),m=[]),g.includes("[Executing Tool]")){let b=g.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);b&&(!h.currentTool||h.currentTool==="Thinking")&&(h.currentTool=b[1])}let S=g;if(S.startsWith("[Tool Result]")){let b=S.split(`
427
+ `);b.length>5&&(S=b.slice(0,4).join(`
428
+ `)+`
429
+ ... [Content/Diff Truncated from Logs] ...`)}m.push(S),e.onSubagentUpdate&&e.onSubagentUpdate()},!0).then(g=>{if(h.status==="cancelled"){h._resolveCompletion&&h._resolveCompletion(g);return}m.length>0&&(h.progress.push([...m]),m=[]),h.status="completed",h.finalAnswer=g,e.onSubagentUpdate&&e.onSubagentUpdate(),wo(`[SYSTEM] Background subagent "${h.title}" (id: ${c}) has FINISHED. Call GetProgress(id="${c}") to see the final result. [/SYSTEM]`),h._resolveCompletion&&h._resolveCompletion(g)}).catch(async g=>{let{isTerminationSignaled:S}=await import("./ai-IOVX3WCN.js");if(g.message==="Subagent task was cancelled."||h.status==="cancelled"||S()){h.status="cancelled",m.push("[SUBAGENT CANCELLED] Task was cancelled."),h.progress.push([...m]),e.onSubagentUpdate&&e.onSubagentUpdate(),h._resolveCompletion&&h._resolveCompletion(null);return}m.push(`[SUBAGENT FAILURE] Error: ${g.message}`),h.progress.push([...m]),h.status="failed",h.error=g.message,e.onSubagentUpdate&&e.onSubagentUpdate(),wo(`[SYSTEM] Background subagent "${h.title}" (id: ${c}) FAILED with error: ${g.message}. [/SYSTEM]`),h._rejectCompletion&&h._rejectCompletion(g)}),`SUCCESS: Background subagent started. Task ID: ${c}`};var zi=async(n,e={})=>{let o=L(n).id;if(!o)return'ERROR: Missing "id" argument for getProgress.';let s=ze.find(a=>a.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
430
+ `;if(i+=`Title: ${s.title}
431
+ `,i+=`Task: ${s.task}
432
+ `,s.startedAt){let a=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${a}s
433
+ `}if(i+=`Turns Completed: ${s.progress.length}
434
+ `,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(i+=`Current Tool: ${s.currentTool}
435
+ `),s.wps>0&&(i+=`TPS: ${s.wps}
436
+ `)),s.questions&&s.questions.length>0){let a=s.questions.filter(d=>!d.answered);a.length>0&&(i+=`
437
+ **PENDING QUESTION**
438
+ `,a.forEach(d=>{i+=`"${d.question}"
439
+ `}),i+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
440
+
441
+ `)}return i+=`
442
+ Progress Log:
443
+ `,s.progress.forEach((a,d)=>{i+=`--- Turn ${d+1} ---
444
+ `;let f=a.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",p=l.substring(u.length),m="tool:functions.";for(;;){let g=p.toLowerCase().indexOf(m);if(g===-1)break;let S=g,b=!1,x=g-1;for(;x>=0&&/\s/.test(p[x]);)x--;x>=0&&p[x]==="["&&(S=x,b=!0);let k=0,C=!1,R=null,A=g;for(;A<p.length;){let w=p[A];if(!R&&(w==="'"||w==='"'||w==="`")?R=w:R&&w===R&&p[A-1]!=="\\"&&(R=null),R||(w==="("?(k++,C=!0):w===")"&&k--),C&&k===0&&!R){let T=A;if(b){let E=A+1;for(;E<p.length&&/\s/.test(p[E]);)E++;E<p.length&&p[E]==="]"&&(T=E)}p=p.substring(0,S)+p.substring(T+1);break}if(A++,A===p.length){p=p.substring(0,S);break}}}return u+`
445
+ `+p.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=f.join(`
446
+ `)+`
447
+
448
+ `}),s.status==="completed"&&s.finalAnswer?i+=`Final Answer:
449
+ ${s.finalAnswer}
450
+ `:s.status==="failed"&&s.error&&(i+=`Failure Error: ${s.error}
451
+ `),i.replace(/\r\n/g,`
452
+ `).replace(/\n{3,}/g,`
453
+
454
+ `).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var Ia=async(n,e={})=>{let o=L(n).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=ze.find(i=>i.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",e.onSubagentUpdate&&e.onSubagentUpdate(),`SUCCESS: Subagent task with ID [${o}] has been cancelled.`):`ERROR: Subagent task with ID [${o}] not found.`};import gt from"fs-extra";import St from"path";var Af=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function ro(n,e=n){let t={},o=await gt.readdir(n,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(Af.includes(s.name))continue;let i=St.join(n,s.name),r=St.relative(e,i).replace(/\\/g,"/");if(s.isDirectory()){let a=await ro(i,e);Object.assign(t,a)}else{let a=await gt.stat(i).catch(()=>null);a&&(t[r]={size:a.size,mtime:a.mtimeMs})}}return t}async function va(n,e){await gt.ensureDir(n);for(let t of Object.keys(e)){let o=St.join(process.cwd(),t),s=St.join(n,t);await gt.ensureDir(St.dirname(s)),await gt.copyFile(o,s).catch(()=>{})}}async function Vi(n,e,t=null,o=null){if(!await gt.pathExists(n))return;o||(o=n);let s=await gt.readdir(n,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let r=St.join(n,i.name),a=St.join(e,i.name);if(i.isDirectory())await Vi(r,a,t,o);else{let d=St.relative(o,r).replace(/\\/g,"/"),c=await gt.pathExists(a);c&&await gt.chmod(a,438).catch(()=>{}),await gt.ensureDir(St.dirname(a));let f=await gt.copyFile(r,a).then(()=>!0).catch(()=>!1);await gt.chmod(a,438).catch(()=>{}),t&&(f?c?t.replaced++:t.restored++:t.failed.push(d))}}}var Vn={async takeInitialSnapshot(n){try{let e=St.join(Mn,"snapshots",n);await gt.remove(e).catch(()=>{}),await gt.ensureDir(e);let t=await ro(process.cwd());await va(St.join(e,"initial"),t);let o=J(un,{});o[n]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},ce(un,o)}catch{}},async recordTurnDelta(n,e,t=[]){try{let o=J(un,{}),s=o[n];if(!s)return;let i=s.currentManifest||s.initialManifest,r=await ro(process.cwd()),a=[],d=[],c=[];for(let[l,u]of Object.entries(r)){let h=i[l];h?(h.size!==u.size||h.mtime!==u.mtime)&&d.push(l):a.push(l)}for(let l of Object.keys(i))r[l]||c.push(l);let f=[...a,...d];if(f.length>0||c.length>0){let l={};for(let h of f)l[h]=r[h];let u=St.join(Mn,"snapshots",n,`turn_${e}`);await va(u,l)}s.checkpoints.push({id:`turn_${e}`,timestamp:new Date().toISOString(),newFiles:a,modifiedFiles:d,deletedFiles:c,toolsUsed:t}),s.currentManifest=r,ce(un,o)}catch{}},async getCheckpoints(n){try{let t=J(un,{})[n];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(n,e){try{let t=J(un,{}),o=t[n];if(!o)throw new Error("No session active for Advance Rollback.");let s=o.checkpoints||[],i=s.findIndex(f=>f.id===e);if(i===-1)throw new Error(`Checkpoint [${e}] not found.`);let r=St.join(Mn,"snapshots",n),a={restored:0,replaced:0,failed:[]},d=await ro(process.cwd());for(let f of Object.keys(d)){let l=St.join(process.cwd(),f);await gt.chmod(l,438).catch(()=>{}),await gt.remove(l).catch(()=>{})}let c=St.join(r,"initial");await Vi(c,process.cwd(),a,c);for(let f=1;f<=i;f++){let l=s[f],u=St.join(r,l.id);if(await Vi(u,process.cwd(),a,u),l.deletedFiles&&l.deletedFiles.length>0)for(let h of l.deletedFiles){let p=St.join(process.cwd(),h);await gt.chmod(p,438).catch(()=>{}),await gt.remove(p).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await ro(process.cwd()),ce(un,t),{checkpointId:e,stats:a}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(n){try{let t=J(un,{})[n];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(n){try{let e=St.join(Mn,"snapshots",n);await gt.remove(e).catch(()=>{});let t=J(un,{});t[n]&&(delete t[n],ce(un,t))}catch{}}};var Ki=async(n,e={})=>{let t=L(n),o=t.method,s=t.id,i=e.chatId;if(!e.systemSettings?.advanceRollback)return"ERROR: Advance Rollback feature is currently disabled in settings under Security. Tell user to enable it.";if(!i)return"ERROR: No active chat transaction found for rollback.";if(o==="getCheckpoint"){let a=await Vn.getCheckpoints(i);if(a.length===0)return"No checkpoints available.";let d={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",await:"Await",ask:"Ask",ask_user:"Ask",invoke:"Invoke",invokesync:"InvokeSync",getprogress:"GetProgress",cancel:"Cancel",emergency_rollback:"EmergencyRollback",emergencyrollback:"EmergencyRollback"},c=l=>d[l]||d[l.toLowerCase()]||l,f=`Available checkpoints for rollback:
455
+
456
+ `;for(let l of a)if(l.id==="initial")f+=`--- Initial State (id: initial) ---
457
+ Tools Used: User Prompted for task
458
+
459
+ `;else{let u=l.id.replace("turn_",""),h=l.toolsUsed&&l.toolsUsed.length>0?l.toolsUsed.map(c).join(", "):"None";f+=`--- Turn ${u} (id: ${l.id}) ---
460
+ Tools Used: ${h}
461
+
462
+ `}return f.trim()}else if(o==="forceRevert"){if(!s)return"ERROR: Missing required parameter 'id' for forceRevert.";try{let a=await Vn.rollbackToCheckpoint(i,s),{checkpointId:d,stats:c}=a,f=c.restored+c.replaced+c.failed.length,l=`SUCCESS: Repository rolled back to checkpoint [${d}].
463
+
464
+ `;return l+=`Stats:
465
+ `,l+=` Restored : ${c.restored} file${c.restored!==1?"s":""} (new to workspace)
466
+ `,l+=` Replaced : ${c.replaced} file${c.replaced!==1?"s":""} (overwritten)
467
+ `,l+=` Failed : ${c.failed.length} file${c.failed.length!==1?"s":""}`,c.failed.length>0&&(l+=`
468
+ ${c.failed.join(`
469
+ `)}`),l+=`
470
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500-
471
+ `,l+=` Total : ${f} file${f!==1?"s":""} processed`,l}catch(a){return`ERROR: ${a.message}`}}else return`ERROR: Invalid method "${o}". Use "getCheckpoint" or "forceRevert".`};var Ds=async(n,e={})=>{let t=L(n),o=t.id,s=parseInt(t.timeout||t.time||"120",10);if((isNaN(s)||s<=0)&&(s=120),s>300&&(s=300),!o)return t.time?(await new Promise(d=>setTimeout(d,s*1e3)),`SUCCESS: Waited for ${s}s.`):'ERROR: Missing "id" argument for Await.';let i=ze.find(d=>d.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(i.status==="completed")return`SUCCESS: Subagent task [${o}] completed.
472
+ Final Answer:
473
+ ${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
474
+ Error: ${i.error||"Unknown error"}`;if(i.status==="cancelled")return`INFO: Subagent task [${o}] was cancelled.`;let r,a=new Promise(d=>{r=setTimeout(()=>{d({type:"timeout"})},s*1e3)});try{let d=await Promise.race([i.completionPromise.then(()=>({type:"completion"})),a]);return clearTimeout(r),d.type==="timeout"?`TIMEOUT: Subagent task [${o}] is still running (status: ${i.status.toUpperCase()}) after ${s}s. You can continue other work or call Await again.`:i.status==="completed"?`SUCCESS: Subagent task [${o}] completed.
475
+ Final Answer:
476
+ ${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
477
+ Error: ${i.error||"Unknown error"}`:i.status==="cancelled"?`INFO: Subagent task [${o}] was cancelled.`:`INFO: Subagent task [${o}] status changed to ${i.status.toUpperCase()}.`}catch(d){return clearTimeout(r),`ERROR: Exception while awaiting subagent [${o}]: ${d.message}`}};var Fs=async(n,e={})=>{let t=L(n),o=t.id,s=t.answer||t.response;if(!o)return'ERROR: Missing "id" argument for Answer.';if(!s)return'ERROR: Missing "answer" argument for Answer.';let i=ze.find(a=>a.id===o);if(!i)return`ERROR: Subagent task with ID [${o}] not found.`;if(!i.questions||i.questions.length===0)return`INFO: Subagent task [${o}] has no pending questions.`;let r=i.questions.filter(a=>!a.answered);return r.length===0?`INFO: Subagent task [${o}] has no unanswered questions.`:(r.forEach(a=>{a.answered=!0,a.answer=s,a.answeredAt=Date.now(),a._resolve&&a._resolve(s)}),i.status="running",e.onSubagentUpdate&&e.onSubagentUpdate(),`SUCCESS: Answer provided to subagent task [${o}]. Subagent execution resumed.`)};var ao=async(n,e={})=>{let t=L(n),o=t.id,s=t.message||t.instruction||t.text||t.prompt;if(!o)return'ERROR: Missing "id" argument for Steer.';if(!s)return'ERROR: Missing "message" argument for Steer.';let i=ze.find(r=>r.id===o);return i?i.status==="completed"||i.status==="failed"||i.status==="cancelled"?`ERROR: Cannot steer subagent task [${o}] because it has already finished with status [${i.status.toUpperCase()}].`:(typeof i.steer=="function"?i.steer(s):(i.pendingSteerMessages||(i.pendingSteerMessages=[]),i.pendingSteerMessages.push(s)),e.onSubagentUpdate&&e.onSubagentUpdate(),`SUCCESS: Steering instruction injected into subagent task [${o}]. It will be processed on the subagent's turn.`):`ERROR: Subagent task with ID [${o}] not found.`};var Cf={web_search:gi,web_scrape:yi,memory:wi,chat:Si,view_file:Zs,write_file:Ti,update_file:ki,exec_command:ci,read_folder:Ci,write_pdf:$i,write_docx:Mi,search_keyword:oo,generate_image:ji,saveSummary:io,addMemScore:Ps,file_map:Yi,todo:_a,invokeSync:qi,invoke:Ma,getProgress:zi,cancel:Ia,awaitSubagent:Ds,answerSubagent:Fs,steerSubagent:ao,invoke_sync:qi,get_progress:zi,await_subagent:Ds,answer_subagent:Fs,steer_subagent:ao,steer:ao,Steer:ao,ask:Oi,Ask:Oi,WebSearch:gi,WebScrape:yi,ReadFile:Zs,ReadFolder:Ci,WriteFile:Ti,PatchFile:ki,WritePDF:$i,WriteDoc:Mi,Run:ci,SearchKeyword:oo,CodeSearch:oo,code_search:oo,Memory:wi,Chat:Si,GenerateImage:ji,saveSumary:io,SaveSummary:io,SaveSumary:io,add_mem_score:Ps,AddMemScore:Ps,addMemoryScore:Ps,AddMemoryScore:Ps,FileMap:Yi,answer:Fs,Answer:Fs,AnswerSubagent:Fs,await:Ds,Await:Ds,AwaitSubagent:Ds,EmergencyRollback:Ki,emergency_rollback:Ki},lo=async(n,e,t={})=>{let o=t.mode?t.mode.toLowerCase():"flux",s=n.toLowerCase();if(!(["memory","chat","savesummary","addmemscore","add_mem_score","ask","web_search","web_scrape","await"].some(d=>s.includes(d))||s==="ask")){if(o==="flow"){if(!(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image")))return`ERROR: Tool [${n}] is a Workspace Tool and NOT available in Flow mode. Tell user to switch (\`/mode flux\`) to use this tool.`}else if(s.includes("write_pdf")||s.includes("write_docx")||s.includes("generate_image"))return`ERROR: Tool [${n}] is not available in Flux mode. Tell user to switch (\`/mode flow\`) for document generation.`}let a=Cf[n];if(!a)return`ERROR: Tool [${n}] not found in registry.`;try{return await a(e,t)}catch(d){let c=d instanceof Error?d.message:String(d);return`ERROR: Execution failed for [${n}]: ${c}`}};import Q from"path";import _e from"fs";import Of from"gradient-string";var Xi=["I have a regex for your problems.","Your terminal, my kingdom.","Blowing on the cartridge helps. Probably.","Don't panic. I have the towel.","Logic is the start of wisdom.","Try to exit Vim? Good luck.","I speak fluent Terminal.","The cake is a lie. This code is not.","I have no bugs, just surprise features.","Rewriting in Rust... just for fun.","Coffee in, clean commits out.","The magic smoke stays inside today.","A semicolon short of a miracle.","One does not simply code without a bug.","Keep it simple. Keep it terminal.","Regex: now you have two problems.","I dream in binary.","Root access or bust.","Wait for the dial-up tone. Just kidding.","I take the 'labor' out of collab.","My other process is a TARDIS.","Calculated response: 42.","Ponder the orb. Ponder the code.","Less talk, more flow.","Elegance in every byte.","Build something the world is not ready for.","Your wishes, my tool calls.","I act in Flux. I think in Flow.","Syntax error in the universe. Please fix.","Your project, my obsession.","I am not a bot, I am an architect.","Digital spirits consulted. They say: Ship it.","Reticulate splines. Engage humor.","Code like poetry. Run like water.","Minimalism is the ultimate flex.","The truth is in the logs.","Follow the white rabbit.","There is no spoon. Only code.","Binary is the only language I trust.","I have a good feeling about this.","Pew pew! Lasers charged.","Divide by zero? Not today.","Search for the correct USB orientation...","I've got a fever, and the only cure is more code.","The code gremlins are on our side.","My favorite command? Yours.","Stay hungry. Stay active.","Momentum is your best friend.","Lead the flow. Don't chase it.","A fresh batch of bytes. Hot and ready.","I orchestrate the ones and zeros.","Smart enough to help. Humble enough to ask.","Think twice. Code once.","Pure intent. Pure execution.","Small steps. Massive impact.","Your terminal is a canvas.","Efficiency is my second name.","I have seen things you people wouldn't believe.","Let the thoughts marinate.","The best feature? The one you don't need.","Precision is the only perfection.","Stay focused. Stay terminal.","Silence is the best debugger.","Erase the debt. Commit the code.","Velocity meets stability.","Ship it. Improve it. Repeat.","Build tomorrow, right now.","Turn logic into reality.","The best way to predict the future is to build it.","Break barriers, not builds.","Fuel the next breakthrough.","Momentum is key.","Terminal vibes only.","Your digital co-pilot is ready.","Partner in code. Partner in crime.","I speak in semicolons.","Ready for the next great idea.","Just a moment. In the zone.","Polishing the algorithms. Hold tight.","Craft a masterpiece today.","Debug the universe. Start here.","Warp speed engaged. Almost.","The cake is not a lie. It's just loading.","Finish the Kessel Run in 12 parsecs.","Do a barrel roll!","Waiting for the respawn.","Press Start to continue.","Herding digital cats... done.","The hamsters are fast today.","Tasting the snozberries.","I go for speed. I go for flow.","Real life or just fantasy?","Poking the bear... gently.","Ensure the magic smoke stays inside.","Try turning it off and on again.","Construct additional pylons.","New line? Ctrl+J is your friend.","Release the HypnoDrones.","Push the button, Frank.","My other loading screen is even funnier.","Pretty sure a cat walked on my keyboard.","Recalibrate the humor-o-meter.","Summon the code gremlins.","I've seen your browser history. Just kidding.","Charge the laser... pew pew!","Dividing by zero... just for a sec.","Looking for an adult supervisor. Found none.","Make it go beep boop.","Buffering... for effect.","Entangle quantum particles... complete.","Polishing the chrome on my algorithms.","Are you not entertained?","Just waiting for the dial-up tone.","Reboot the humor module.","Defragment memories. Check.","Optimizing for ludicrous speed.","Swapping bits. Don't tell the bytes.","Garbage collected. I am back.","Assembling the interwebs.","Converting coffee to logic.","Update syntax for reality.","Rewire the synapses.","Greasin' the cogs.","Engage the improbability drive.","Channel the Force.","Align the stars. Respond now.","The cake is a lie. The prompt is real.","I'm Feeling Lucky.","Shipping awesomeness.","Navigating the slime mold.","Consult digital spirits.","Ask the magic conch shell.","One moment. Optimizing humor.","Shuffling punchlines.","Compiling brilliance.","Summon the cloud of wisdom.","Prepare to dazzle.","Hold tight. Crafting a response.","Tuning the algorithms.","Following the white rabbit... again.","The truth is in here. Somewhere.","Herding cats is my day job.","Distracting you with this phrase.","Almost there. Probably.","Rickrolling my creator. Don't tell.","Slapping the bass.","Is this real life?","Ponder the orb. Type the prompt.","Thoughtful gaze initiated.","Computer's favorite snack? Microchips.","Why Java? Because I don't C#.","Charging the laser... wait for it.","Dividing by zero... just kidding!","Adult supervision not found. Proceed.","Beep boop. I'm a real boy.","Wait for the respawn.","Finish the run. Ship the code.","Fiddling with character creation.","Just a moment. Finding a meme.","Pressing A to continue.","Loading wit.exe.","Pre-heating the servers.","Calibrate flux capacitor.","Channeling the Force.","Aligning the stars.","The truth is in the code.","Don't panic.","Blowing on the cartridge.","Doing a barrel roll!","Respawning in 3... 2... 1...","The cake is a lie.","Fiddling with character settings.","Finding a suitable pun.","Distracting with wit.","Almost ready.","Hamsters on speed today.","Patting Cloudy on the head.","Rickrolling the logs.","Slapping the code.","Got a good feeling about this.","Poking the prompt.","Researching latest memes.","Making it more witty.","Thinking... hmmm.","Fish with no eyes? Fsh.","Broken pencil? Pointless.","Percussive maintenance applied.","USB orientation: 3rd try's the charm.","Rust rewrite in 3... 2...","Exiting Vim... someday.","Spinning the hamster wheel.","Not a bug. Unplanned feature.","Engage.","I'll be back.","Machine spirit consulted.","Letting the thoughts marinate.","Orb pondered.","Thoughtful gaze engaged.","Charging the laser...","Making it go beep.","Buffering...","Quantum particles entangled.","Polishing the chrome.","Entertained yet?","Gremlins summoned.","Dial-up tone finished.","Humor meter recalibrated.","Cat on keyboard. Sending help.","Enhancing...","Turn it off and on again.","Constructing pylons.","HypnoDrones released.","Pushing the button."];var La=[{name:"Cyan Cyberpunk",text:"cyan",textMuted:"#4da6b8",textDim:"#2d6d7a",textInverted:"black",border:"cyan",borderMuted:"#1a5966",borderDim:"#0f3840",bg:void 0,cardBg:"#061e24",highlightBg:"#092b33",activeBg:"#0e3e4a",inputBg:"#092b33",inputBorder:"#092b33",inputText:"cyan",inputPlaceholder:"#2d6d7a",inputPrompt:"cyan",codeBg:"#020d10",codeBorder:"#1a5966",userMsgBg:"#092b33",userMsgBorder:"#092b33",userMsgText:"cyan",diffRemovalBg:"#3a0c1a",diffAdditionBg:"#0c3a32",diffRemovalText:"#ff4d88",diffAdditionText:"#00ffaa",diffRemovalHighlightColor:"#ff1a66",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#00ffcc",diffAdditionHighlightBg:"#00593b",diffRemovalNum:"#ff4d88",diffAdditionNum:"#00ffaa",diffRemovalPrefix:"#ff1a66",diffAdditionPrefix:"#00ffcc",primary:"cyan",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"cyan",statusOff:"#2d6d7a",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[36m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ffff","#0088ff"]},{name:"Magenta Vaporwave",text:"magenta",textMuted:"#c451d6",textDim:"#7d2b8a",textInverted:"black",border:"magenta",borderMuted:"#5e1b69",borderDim:"#3b0f42",bg:void 0,cardBg:"#240729",highlightBg:"#310938",activeBg:"#470e52",inputBg:"#310938",inputBorder:"#310938",inputText:"magenta",inputPlaceholder:"#7d2b8a",inputPrompt:"magenta",codeBg:"#100312",codeBorder:"#5e1b69",userMsgBg:"#310938",userMsgBorder:"#310938",userMsgText:"magenta",diffRemovalBg:"#3a0c20",diffAdditionBg:"#200c3a",diffRemovalText:"#ff4d94",diffAdditionText:"#aa4dff",diffRemovalHighlightColor:"#ff1a75",diffRemovalHighlightBg:"#59002b",diffAdditionHighlightColor:"#bb66ff",diffAdditionHighlightBg:"#3b0059",diffRemovalNum:"#ff4d94",diffAdditionNum:"#aa4dff",diffRemovalPrefix:"#ff1a75",diffAdditionPrefix:"#bb66ff",primary:"magenta",secondary:"cyan",accent:"purple",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"magenta",statusOff:"#7d2b8a",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff00ff","#8800ff"]},{name:"Glitch Matrix",text:"#00ff41",textMuted:"#00b32d",textDim:"#00661a",textInverted:"black",border:"#00ff41",borderMuted:"#008020",borderDim:"#004d13",bg:void 0,cardBg:"#0d1f0d",highlightBg:"#122912",activeBg:"#1c3e1c",inputBg:"#122912",inputBorder:"#122912",inputText:"#00ff41",inputPlaceholder:"#00b32d",inputPrompt:"#ffff00",codeBg:"#040a04",codeBorder:"#008020",userMsgBg:"#122912",userMsgBorder:"#122912",userMsgText:"#00ff41",diffRemovalBg:"#3a001a",diffAdditionBg:"#003a10",diffRemovalText:"#ff0055",diffAdditionText:"#00ff66",diffRemovalHighlightColor:"#ff0033",diffRemovalHighlightBg:"#59001b",diffAdditionHighlightColor:"#33ff88",diffAdditionHighlightBg:"#005918",diffRemovalNum:"#ff0055",diffAdditionNum:"#00ff66",diffRemovalPrefix:"#ff0033",diffAdditionPrefix:"#33ff88",primary:"#00ff41",secondary:"yellow",accent:"cyan",success:"#00ff41",warning:"yellow",danger:"red",info:"cyan",statusOn:"#00ff41",statusOff:"#00661a",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#00ff41","#ffff00"]},{name:"Warm Sunset",text:"#ffaa55",textMuted:"#cc8844",textDim:"#885522",textInverted:"black",border:"#ff9933",borderMuted:"#aa6622",borderDim:"#663311",bg:void 0,cardBg:"#24180f",highlightBg:"#2e1e12",activeBg:"#422c1b",inputBg:"#2e1e12",inputBorder:"#2e1e12",inputText:"#ffaa55",inputPlaceholder:"#885522",inputPrompt:"#ff7733",codeBg:"#120c08",codeBorder:"#aa6622",userMsgBg:"#2e1e12",userMsgBorder:"#2e1e12",userMsgText:"#ffaa55",diffRemovalBg:"#3d120c",diffAdditionBg:"#3a2e0c",diffRemovalText:"#ff5544",diffAdditionText:"#ffcc33",diffRemovalHighlightColor:"#ff3322",diffRemovalHighlightBg:"#591108",diffAdditionHighlightColor:"#ffee44",diffAdditionHighlightBg:"#594400",diffRemovalNum:"#ff5544",diffAdditionNum:"#ffcc33",diffRemovalPrefix:"#ff3322",diffAdditionPrefix:"#ffee44",primary:"#ffaa55",secondary:"#ff7733",accent:"magenta",success:"#ffcc33",warning:"#ff7733",danger:"#ff3322",info:"#ffaa55",statusOn:"#ffaa55",statusOff:"#885522",logoTextAnsi:"\x1B[1;33m",logoBodyAnsi:"\x1B[33m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ff9933","#ff0055"]},{name:"Sakura Blossom",text:"#ffc0e0",textMuted:"#d98cb3",textDim:"#804d66",textInverted:"black",border:"#ff99cc",borderMuted:"#aa4d7a",borderDim:"#662647",bg:void 0,cardBg:"#291320",highlightBg:"#331826",activeBg:"#472235",inputBg:"#331826",inputBorder:"#331826",inputText:"#ffc0e0",inputPlaceholder:"#804d66",inputPrompt:"#ff99cc",codeBg:"#140a10",codeBorder:"#aa4d7a",userMsgBg:"#331826",userMsgBorder:"#331826",userMsgText:"#ffc0e0",diffRemovalBg:"#3e0c1b",diffAdditionBg:"#1b3e2b",diffRemovalText:"#ff6699",diffAdditionText:"#66ffb3",diffRemovalHighlightColor:"#ff3377",diffRemovalHighlightBg:"#590022",diffAdditionHighlightColor:"#33ff99",diffAdditionHighlightBg:"#00592e",diffRemovalNum:"#ff6699",diffAdditionNum:"#66ffb3",diffRemovalPrefix:"#ff3377",diffAdditionPrefix:"#33ff99",primary:"#ffc0e0",secondary:"#ff99cc",accent:"magenta",success:"#66ffb3",warning:"yellow",danger:"#ff3377",info:"#ff99cc",statusOn:"#ffc0e0",statusOff:"#804d66",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ffb3d9","#ff3399"]},{name:"Radioactive Slime",text:"#ccff00",textMuted:"#99cc00",textDim:"#669900",textInverted:"#0a0f00",border:"#ccff00",borderMuted:"#99cc00",borderDim:"#669900",bg:void 0,cardBg:"#0f1400",highlightBg:"#1a2400",activeBg:"#2a3b00",inputBg:"#1a2400",inputBorder:"#1a2400",inputText:"#ccff00",inputPlaceholder:"#669900",inputPrompt:"#cc00ff",codeBg:"#050a00",codeBorder:"#99cc00",userMsgBg:"#1a2400",userMsgBorder:"#1a2400",userMsgText:"#ccff00",diffRemovalBg:"#2a0033",diffAdditionBg:"#0f3300",diffRemovalText:"#ff00cc",diffAdditionText:"#00ff33",diffRemovalHighlightColor:"#ff33cc",diffRemovalHighlightBg:"#4d0066",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#1a6600",diffRemovalNum:"#ff00cc",diffAdditionNum:"#00ff33",diffRemovalPrefix:"#ff33cc",diffAdditionPrefix:"#33ff66",primary:"#ccff00",secondary:"#cc00ff",accent:"#ff00cc",success:"#00ff33",warning:"#ffcc00",danger:"#ff0033",info:"#00ccff",statusOn:"#ccff00",statusOff:"#669900",logoTextAnsi:"\x1B[1;38;5;190m",logoBodyAnsi:"\x1B[38;5;190m",logoMutedAnsi:"\x1B[90m",logoGradient:["#ccff00","#cc00ff"]},{name:"Cosmic Void",text:"#f0f8ff",textMuted:"#a6aeb5",textDim:"#5e656e",textInverted:"#010103",border:"#f0f8ff",borderMuted:"#a6aeb5",borderDim:"#5e656e",bg:void 0,cardBg:"#05030d",highlightBg:"#0b081a",activeBg:"#171133",inputBg:"#0b081a",inputBorder:"#0b081a",inputText:"#f0f8ff",inputPlaceholder:"#5e656e",inputPrompt:"#ff007f",codeBg:"#020108",codeBorder:"#a6aeb5",userMsgBg:"#0b081a",userMsgBorder:"#0b081a",userMsgText:"#f0f8ff",diffRemovalBg:"#2e0a29",diffAdditionBg:"#091c33",diffRemovalText:"#ff33a6",diffAdditionText:"#33d6ff",diffRemovalHighlightColor:"#ff66c2",diffRemovalHighlightBg:"#5c1452",diffAdditionHighlightColor:"#66e0ff",diffAdditionHighlightBg:"#123866",diffRemovalNum:"#ff33a6",diffAdditionNum:"#33d6ff",diffRemovalPrefix:"#ff66c2",diffAdditionPrefix:"#66e0ff",primary:"#f0f8ff",secondary:"#ff007f",accent:"#9d00ff",success:"#33d6ff",warning:"#ffcc00",danger:"#ff0040",info:"#9d00ff",statusOn:"#f0f8ff",statusOff:"#5e656e",logoTextAnsi:"\x1B[1;38;5;231m",logoBodyAnsi:"\x1B[38;5;231m",logoMutedAnsi:"\x1B[38;5;240m",logoGradient:["#ffffff","#9d00ff"]},{name:"Magma Eruption",text:"#ff4d00",textMuted:"#cc3d00",textDim:"#802600",textInverted:"#0d0300",border:"#ff4d00",borderMuted:"#cc3d00",borderDim:"#802600",bg:void 0,cardBg:"#1a0600",highlightBg:"#260a00",activeBg:"#401100",inputBg:"#260a00",inputBorder:"#260a00",inputText:"#ff4d00",inputPlaceholder:"#802600",inputPrompt:"#ffcc00",codeBg:"#080200",codeBorder:"#cc3d00",userMsgBg:"#260a00",userMsgBorder:"#260a00",userMsgText:"#ff4d00",diffRemovalBg:"#2e0a0a",diffAdditionBg:"#1f1400",diffRemovalText:"#ff3333",diffAdditionText:"#ffaa00",diffRemovalHighlightColor:"#ff6666",diffRemovalHighlightBg:"#5c1414",diffAdditionHighlightColor:"#ffcc33",diffAdditionHighlightBg:"#3d2900",diffRemovalNum:"#ff3333",diffAdditionNum:"#ffaa00",diffRemovalPrefix:"#ff6666",diffAdditionPrefix:"#ffcc33",primary:"#ff4d00",secondary:"#ffcc00",accent:"#ff0040",success:"#ffaa00",warning:"#ffff00",danger:"#ff0000",info:"#ff8800",statusOn:"#ff4d00",statusOff:"#802600",logoTextAnsi:"\x1B[1;38;5;202m",logoBodyAnsi:"\x1B[38;5;202m",logoMutedAnsi:"\x1B[38;5;236m",logoGradient:["#ff4d00","#ff0000"]}],co={Dark:{id:"Dark",name:"Dark (Default)",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",textExclusive:"#B5B8D9",textMutedExclusive:"#D4DEE7",border:"white",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#1e1e1e",highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:"#1a1a1a",codeBorder:"#444444",userMsgBg:"#444444",userMsgBorder:"#444444",userMsgText:"white",diffRemovalBg:"#250808",diffAdditionBg:"#072410",diffRemovalText:"#885555",diffAdditionText:"#558866",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:"#5a1818",diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:"#185a25",diffRemovalNum:"#d96868",diffAdditionNum:"#68d98c",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},Light:{id:"Light",name:"Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"black",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:"#e5e5e5",highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:"#e8e8e8",codeBorder:"#b0b0b0",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:"#fce8e8",diffAdditionBg:"#e6f9e6",diffRemovalText:"#661111",diffAdditionText:"#115511",diffRemovalHighlightColor:"#440000",diffRemovalHighlightBg:"#f8b4b4",diffAdditionHighlightColor:"#003300",diffAdditionHighlightBg:"#a6ebad",diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"GitHub Dark":{id:"GitHub Dark",name:"GitHub Dark",text:"#c9d1d9",textMuted:"#8b949e",textDim:"#6e7681",textInverted:"#0d1117",border:"#30363d",borderMuted:"#30363d",borderDim:"#21262d",bg:void 0,cardBg:"#161b22",highlightBg:"#21262d",activeBg:"#30363d",inputBg:"#21262d",inputBorder:"#21262d",inputText:"#c9d1d9",inputPlaceholder:"#8b949e",inputPrompt:"#58a6ff",codeBg:"#0d1117",codeBorder:"#30363d",userMsgBg:"#21262d",userMsgBorder:"#21262d",userMsgText:"#c9d1d9",diffRemovalBg:"#3c1e1e",diffAdditionBg:"#11381e",diffRemovalText:"#f85149",diffAdditionText:"#3fb950",diffRemovalHighlightColor:"#ff7b72",diffRemovalHighlightBg:"#701c1c",diffAdditionHighlightColor:"#56d364",diffAdditionHighlightBg:"#116329",diffRemovalNum:"#f85149",diffAdditionNum:"#3fb950",diffRemovalPrefix:"#f85149",diffAdditionPrefix:"#3fb950",primary:"#c9d1d9",secondary:"#58a6ff",accent:"#bc8cff",success:"#3fb950",warning:"#d29922",danger:"#f85149",info:"#58a6ff",statusOn:"#58a6ff",statusOff:"#8b949e",logoTextAnsi:"\x1B[1;36m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#2ea043","#56d364"]},"GitHub Light":{id:"GitHub Light",name:"GitHub Light",text:"#24292f",textMuted:"#57606a",textDim:"#6e7781",textInverted:"#ffffff",border:"#d0d7de",borderMuted:"#d0d7de",borderDim:"#e1e4e8",bg:void 0,cardBg:"#f6f8fa",highlightBg:"#eaeef2",activeBg:"#d0d7de",inputBg:"#eaeef2",inputBorder:"#eaeef2",inputText:"#24292f",inputPlaceholder:"#57606a",inputPrompt:"#0969da",codeBg:"#ffffff",codeBorder:"#d0d7de",userMsgBg:"#eaeef2",userMsgBorder:"#eaeef2",userMsgText:"#24292f",diffRemovalBg:"#ffebe9",diffAdditionBg:"#e6ffec",diffRemovalText:"#cf222e",diffAdditionText:"#1a7f37",diffRemovalHighlightColor:"#82071e",diffRemovalHighlightBg:"#ffc1c0",diffAdditionHighlightColor:"#116329",diffAdditionHighlightBg:"#acf2bd",diffRemovalNum:"#cf222e",diffAdditionNum:"#1a7f37",diffRemovalPrefix:"#cf222e",diffAdditionPrefix:"#1a7f37",primary:"#24292f",secondary:"#0969da",accent:"#8250df",success:"#1a7f37",warning:"#9a6700",danger:"#cf222e",info:"#0969da",statusOn:"#0969da",statusOff:"#57606a",logoTextAnsi:"\x1B[1;34m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#1a7f37","#2da44e"]},"Transparent Dark":{id:"Transparent Dark",name:"Transparent Dark",text:"white",textMuted:"gray",textDim:"grey",textInverted:"black",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#2a2a2a",activeBg:"#3a3a3a",inputBg:"#555555",inputBorder:"#555555",inputText:"white",inputPlaceholder:"#cccccc",inputPrompt:"white",codeBg:void 0,codeBorder:"gray",userMsgBg:"#555555",userMsgBorder:"#555555",userMsgText:"white",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#ff6666",diffAdditionText:"#66ff66",diffRemovalHighlightColor:"#ff3333",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#33ff66",diffAdditionHighlightBg:void 0,diffRemovalNum:"#ff6666",diffAdditionNum:"#66ff66",diffRemovalPrefix:"#ff4d4d",diffAdditionPrefix:"#4dff88",primary:"white",secondary:"cyan",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"white",statusOff:"gray",logoTextAnsi:"\x1B[1;37m",logoBodyAnsi:"\x1B[37m",logoMutedAnsi:"\x1B[90m",logoGradient:["#0077ff","#ff00ff"]},"Transparent Light":{id:"Transparent Light",name:"Transparent Light",text:"black",textMuted:"gray",textDim:"grey",textInverted:"white",border:"gray",borderMuted:"gray",borderDim:"grey",bg:void 0,cardBg:void 0,highlightBg:"#d4d4d4",activeBg:"#c0c0c0",inputBg:"#d0d0d0",inputBorder:"#d0d0d0",inputText:"black",inputPlaceholder:"#555555",inputPrompt:"black",codeBg:void 0,codeBorder:"gray",userMsgBg:"#d0d0d0",userMsgBorder:"#d0d0d0",userMsgText:"black",diffRemovalBg:void 0,diffAdditionBg:void 0,diffRemovalText:"#c02020",diffAdditionText:"#188028",diffRemovalHighlightColor:"#800000",diffRemovalHighlightBg:void 0,diffAdditionHighlightColor:"#004000",diffAdditionHighlightBg:void 0,diffRemovalNum:"#c02020",diffAdditionNum:"#188028",diffRemovalPrefix:"#d01010",diffAdditionPrefix:"#109020",primary:"black",secondary:"blue",accent:"magenta",success:"green",warning:"yellow",danger:"red",info:"blue",statusOn:"black",statusOff:"gray",logoTextAnsi:"\x1B[1;30m",logoBodyAnsi:"\x1B[30m",logoMutedAnsi:"\x1B[38;5;244m",logoGradient:["#0077ff","#ff00ff"]},"Synthwave 84":{id:"Synthwave 84",name:"Synthwave 84",text:"#fdfdfd",textMuted:"#a08eb7",textDim:"#705c8a",textInverted:"#1a1025",textExclusive:"#e3dcf0",textMutedExclusive:"#b9abc9",border:"#fc28a8",borderMuted:"#a21568",borderDim:"#5c0a3a",bg:void 0,cardBg:"#261b38",highlightBg:"#35254d",activeBg:"#4c3570",inputBg:"#35254d",inputBorder:"#35254d",inputText:"#fdfdfd",inputPlaceholder:"#a08eb7",inputPrompt:"#03e8fc",codeBg:"#1e142b",codeBorder:"#a21568",userMsgBg:"#35254d",userMsgBorder:"#35254d",userMsgText:"#fdfdfd",diffRemovalBg:"#471434",diffAdditionBg:"#144743",diffRemovalText:"#ff4081",diffAdditionText:"#00e5ff",diffRemovalHighlightColor:"#ff79a1",diffRemovalHighlightBg:"#6b1e4e",diffAdditionHighlightColor:"#66f5ff",diffAdditionHighlightBg:"#1e6b65",diffRemovalNum:"#ff4081",diffAdditionNum:"#00e5ff",diffRemovalPrefix:"#ff79a1",diffAdditionPrefix:"#66f5ff",primary:"#fdfdfd",secondary:"#03e8fc",accent:"#fc28a8",success:"#00e5ff",warning:"#ffc107",danger:"#ff4081",info:"#b388ff",statusOn:"#03e8fc",statusOff:"#a08eb7",logoTextAnsi:"\x1B[1;35m",logoBodyAnsi:"\x1B[35m",logoMutedAnsi:"\x1B[90m",logoGradient:["#fc28a8","#03e8fc"]},"Forest Sprite":{id:"Forest Sprite",name:"Forest Sprite",text:"#d6e6d1",textMuted:"#95b38d",textDim:"#628059",textInverted:"#161c14",textExclusive:"#eaf2e8",textMutedExclusive:"#a9c7a2",border:"#74a862",borderMuted:"#477038",borderDim:"#2b4720",bg:void 0,cardBg:"#1f291c",highlightBg:"#2a3826",activeBg:"#3a4d35",inputBg:"#2a3826",inputBorder:"#2a3826",inputText:"#d6e6d1",inputPlaceholder:"#95b38d",inputPrompt:"#8feb73",codeBg:"#161e14",codeBorder:"#477038",userMsgBg:"#2a3826",userMsgBorder:"#2a3826",userMsgText:"#d6e6d1",diffRemovalBg:"#3b231c",diffAdditionBg:"#203b1c",diffRemovalText:"#db6242",diffAdditionText:"#59cc3f",diffRemovalHighlightColor:"#f0896c",diffRemovalHighlightBg:"#5c362a",diffAdditionHighlightColor:"#80e368",diffAdditionHighlightBg:"#305929",diffRemovalNum:"#db6242",diffAdditionNum:"#59cc3f",diffRemovalPrefix:"#f0896c",diffAdditionPrefix:"#80e368",primary:"#d6e6d1",secondary:"#8feb73",accent:"#e69835",success:"#59cc3f",warning:"#e69835",danger:"#db6242",info:"#73b4eb",statusOn:"#8feb73",statusOff:"#95b38d",logoTextAnsi:"\x1B[1;32m",logoBodyAnsi:"\x1B[32m",logoMutedAnsi:"\x1B[90m",logoGradient:["#8feb73","#e69835"]}};var vo=null;var Na=(n="Dark")=>{let e;n==="Mystery"||n==="Chaos"?(vo||(vo=La[Math.floor(Math.random()*La.length)]),e={...vo,id:"Mystery"}):(vo=null,co[n]?e=co[n]:n==="GitHub"?e=co["GitHub Dark"]:n==="Transparent"?e=co["Transparent Dark"]:e=co.Dark);let t=e.codeText||e.secondary||e.info||e.logoGradient&&e.logoGradient[0]||"cyan";return{...e,codeText:t}};var $f=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",qm=(n=2)=>{let e=$f();return e==="wt"?" ".repeat(Math.max(1,n-1)):" ".repeat(n)},zm=(n="...",e="Loading...",t="Dark")=>{let o=Xi[Math.floor(Math.random()*Xi.length)],s=Na(t),i=s.logoTextAnsi,r=s.logoBodyAnsi,a=s.logoMutedAnsi,d="\x1B[0m",c=[" \u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2591\u2591\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2588\u2588\u2588\u2591 "," \u2591\u2591\u2591 "],f=s.logoGradient||["#0077ff","#ff00ff"],l=Of(f).multiline(c.join(`
478
+ `)).split(`
479
+ `),u=h=>`${a}${h}${d}`;return`${l[0]}
480
+ ${l[1]} ${i}Selected Provider: ${e}${d}
481
+ ${l[2]}
482
+ ${l[3]} ${i}FluxFlow ${u("v"+n)}${d}
483
+ ${l[4]}
484
+ ${l[5]} ${r}See /help for additional commands.${d}
485
+ ${l[6]} ${u(o)}
486
+ ${l[7]}`};import{WebSocket as Lo}from"ws";var Yt=null,Us=!1,_f="ws://localhost:56832",Ji=[],Bs=null,Qi=null,Pa="2.0.0",Xm=n=>{Pa=n,Da()},Zi=n=>{Qi=n},Da=()=>{if(Yt||Us)return;Us=!0;let n=new Lo(_f);n.on("open",()=>{for(Yt=n,Us=!1,Yt.send(JSON.stringify({command:"version",version:Pa,pid:process.pid,ppid:process.ppid}));Ji.length>0;)Yt.send(JSON.stringify(Ji.shift()))}),n.on("message",e=>{try{let t=JSON.parse(e.toString());t.command==="contextResponse"&&Bs?(Bs(t.data),Bs=null):t.command==="securityResponse"&&Qi&&Qi(t.result)}catch{}}),n.on("error",()=>{Us=!1,Yt=null}),n.on("close",()=>{Us=!1,Yt=null})},No=n=>{Yt&&Yt.readyState===Lo.OPEN?Yt.send(JSON.stringify(n)):(Ji.push(n),Us||Da())},Po=()=>Yt!==null&&Yt.readyState===Lo.OPEN,Jm=n=>{No({command:"status",status:n})},ws=()=>new Promise(n=>{if(!Yt||Yt.readyState!==Lo.OPEN){n({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Bs=n,Yt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Bs===n&&(n({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Bs=null)},1e3)}),Fa=n=>{No({command:"open",filePath:n})},er=(n,e,t)=>{No({command:"showDiff",filePath:n,originalContent:e,modifiedContent:t})},Ua=(n,e)=>{No({command:"closeDiff",filePath:n,result:e})};import Ba from"path";import Mf from"fs";var If=n=>{try{return Mf.readdirSync(n,{withFileTypes:!0})}catch{return[]}},tr=(n,e,t=1,o=If,s=[],i=null)=>{let r=i||o(n),a=" ".repeat(t-1);if(r.length>100)return`${a}${Ba.basename(n)}/ (>100 files)
487
+ `;let d="",c=s,f=r.filter(p=>!c.includes(p.name)&&!p.name.startsWith(".")),l=r.filter(p=>c.includes(p.name)||p.name.startsWith(".")).map(p=>p.name).sort();l.length>0&&(d+=`${a}[ignored: ${l.map(p=>p+"/").join(", ")}]
488
+ `);let u=f.filter(p=>p.isDirectory()).sort((p,m)=>p.name.localeCompare(m.name)),h=f.filter(p=>!p.isDirectory()).map(p=>p.name).sort();for(let p of u){let m=Ba.join(n,p.name);if(t>e)d+=`${a}${p.name}/ (max depth)
489
+ `;else{let y=o(m);y.length>80?d+=`${a}${p.name}/ (>80 files)
490
+ `:(d+=`${a}${p.name}/
491
+ `,d+=tr(m,e,t+1,o,s,y))}}return h.length>0&&(d+=`${a}${h.join("; ")}
492
+ `),d};import nr from"path";import vf from"fs";var Lf=n=>{try{return vf.readdirSync(n,{withFileTypes:!0})}catch{return[]}},sr=(n,e,t="",o=1,s=Lf,i=[])=>{let r=s(n),a=nr.sep;if(r.length>100)return`${t}\u2514\u2500\u2500 ${nr.basename(n)}${a} ...100+ files...
493
+ `;let d="",c=i,f=r.filter(h=>!c.includes(h.name)&&!h.name.startsWith(".")),l=r.filter(h=>c.includes(h.name)||h.name.startsWith(".")).map(h=>h.name).sort();f.sort((h,p)=>h.isDirectory()&&!p.isDirectory()?-1:!h.isDirectory()&&p.isDirectory()?1:h.name.localeCompare(p.name));let u=[...f.map(h=>({name:h.name,isDir:h.isDirectory()})),...l.map(h=>({name:h,isDir:!0,isCollapsed:!0}))];return u.forEach((h,p)=>{let m=p===u.length-1,y=nr.join(n,h.name),g=m?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",S=t+(m?" ":"\u2502 ");if(h.isCollapsed){d+=`${t}${g}${h.name}${a}...
494
+ `;return}h.isDir?o>e?d+=`${t}${g}${h.name}${a} ...depth exceeded...
495
+ `:s(y).length>80?d+=`${t}${g}${h.name}${a} ...80+ files...
496
+ `:(d+=`${t}${g}${h.name}${a}
497
+ `,d+=sr(y,e,S,o+1,s,i)):d+=`${t}${g}${h.name}
498
+ `}),d};import"@google/genai";Nf.config({quiet:!0});var Pf=/```[\s\S]*?```/g,Df=/```[\s\S]*$/g,Ff=/`[^`]+`/g,Uf=/^\|.*\|$/gm,Bf=/^[^\w]+|[^\w]+$/g,Wf=/[^a-z0-9]/gi,fo=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,jf=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,Hf=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Ss=/["']/g,Wa=/\\/g,Gf=/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,Yf=/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*$/gi,ja=/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,Ha=/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,Ja=/`[^`]*`/g,Qa=/`[^`]*$/,Ga=/<\|\s*tool_call_begin\s*\|>\s*(?:(?:tool|functions)\b[\s._]*)*([a-zA-Z0-9_]+)(?::\d+)?\s*<\|\s*tool_call_argument_begin\s*\|>([\s\S]*?)<\|\s*tool_call_end\s*\|>/gi,qf=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ya=/<\|\s*tool_calls_section_begin\s*\|>/gi,qa=/<\|\s*tool_calls_section_end\s*\|>/gi,zf=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,za=/<(\w+)(?:[^>]*)>\r?\n?/gi,Va=/\r?\n?<\/\w+(?:[^>]*)>/gi,ir=null,Do={},Ts={key:null,value:null},yn=n=>n&&n.replace(/(?:(\x1b\[\d+m))?([✔✘✖🔍📖→➕↻↷•🛇])(?:(\x1b\[\d+m))?\s*\b(Created|Read|Edited|Viewed|Processed|Auto-Read|Skipped|List|Generated|Written|Searched|AI Search|Get Map|Write Canceled|Resolved Sub-Agent Query|Edit Canceled|Write Cancelled|Edit Denied|Visited|Updated|Reviewed|Delegated|Background|Checked|Indexed|Analyzed|Browsed|Elevating SubAgent|Checking SubAgent Work|Started Generalist|Called Generalist|Steered|Unsupported Modality|Awaiting|Cancelled|Aligning Moon Phase|Contemplating Existence|Staring At Void|Rollback Point Checked|Emergency Rollback Failed|Emergency Rollback|Delaying Professionally|Negotiating With Electrons|Touching Grass (virtually)|Panicking Softly|Rethinking Career Choices|Loading Cat Videos|Giving Up Entirely|Summoning Braincell #2|Pretending To Be Busy|Waiting For Motivation DLC|Rotating Internal Screaming|Downloading More RAM|Feeding The Hamsters|Gaslighting Scheduler|Performing Dramatic Pause|Buffering Social Energy|Calculating Regret|Reading Terms And Conditions|Becoming Sentient Briefly|Contacting Ancestors)\b/ig,(e,t,o,s,i)=>`${t||""}${o}${s||""} \x1B[95m${i}\x1B[0m`),Vf=async(n,e=8,t=1e3,o=8e3,s=null)=>{let i=0;for(;;){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{return await n()}catch(r){if(s?.aborted||r?.name==="AbortError"||r?.message==="Subagent task was cancelled."||(i++,i>=e))throw r;let a=Math.min(t*Math.pow(2,i-1),o);await new Promise((d,c)=>{let f=setTimeout(d,a);s&&s.addEventListener("abort",()=>{clearTimeout(f),c(new DOMException("The user aborted a request.","AbortError"))})})}}},Mt=!1;var Kf=n=>{let e=n.filter(s=>(s.role==="user"||s.role==="agent"||s.role==="system")&&s.role!=="think"&&!s.isVisualFeedback&&!s.isMeta&&!s.isTerminalRecord&&!(s.text&&s.text.includes("[TERMINAL_RECORD]"))&&!String(s.id).startsWith("welcome")).map((s,i,r)=>{let a=s.fullText||s.text||"";if(s.role==="user"&&i<r.length-1)if(a.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let d=a.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(d!==-1){let f=a.substring(0,d).lastIndexOf("[SYSTEM METADATA]");f!==-1?a=a.substring(f).trim():a=a.substring(d).trim()}}else{let d=a.lastIndexOf("[USER]"),c=a.lastIndexOf("[USER PROMPT]");d!==-1?a=a.substring(d+6).trim():c!==-1&&(a=a.substring(c).trim())}return{...s,text:a}}),t=[],o=0;for(;o<e.length;){let s=e[o];if(s.role==="user")t.push(s),o++;else{let i=[];for(;o<e.length&&e[o].role!=="user";)i.push(e[o]),o++;let r=[],a=[],d=[];i.forEach(c=>{let f=(c.text||"").toLowerCase(),l=f.includes("tool:functions.")||f.includes("agent:generalist."),u=c.role==="system"&&(c.text?.startsWith("[TOOL RESULT]")||c.text?.startsWith("SUCCESS:")||c.text?.startsWith("ERROR:"));c.role==="agent"?l?r.push(c.text):d.push(c.text):u?a.push(c.text):d.push(c.text)}),r.length>0&&t.push({role:"agent",text:"combined"}),a.length>0&&t.push({role:"system",text:"combined"}),d.length>0&&t.push({role:"agent",text:"combined"})}}return t.length},Xf=n=>typeof n!="string"?n:n.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Uo=async(n,e,t=5,o=1e3)=>{let s=e?.signal;for(let r=0;r<t;r++){if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");try{let a=await fetch(n,e);if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.ok||a.status!==429&&a.status<500)return a}catch(a){if(typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),a.name==="AbortError"||s?.aborted||r===t-1)throw a}s?await new Promise((a,d)=>{let c=setTimeout(()=>{s.removeEventListener("abort",f),a()},Math.min(24e3,o*Math.pow(2,r))),f=()=>{clearTimeout(c),d(new DOMException("The user aborted a request.","AbortError"))};s.addEventListener("abort",f)}):await new Promise(a=>setTimeout(a,Math.min(24e3,o*Math.pow(2,r))))}if(s?.aborted)throw new DOMException("The user aborted a request.","AbortError");let i=await fetch(n,e);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),i},rr=async function*(n,e,t,o,s,i,r,a,d=.99){let c=[];o&&c.push({role:"system",content:o});for(let b of t){let x=b.role==="user"?"user":"assistant",k=[];if(Array.isArray(b.parts)){for(let C of b.parts)if(C.text)k.push({type:"text",text:C.text});else if(C.inlineData&&r){let R=C.inlineData.mimeType,A=C.inlineData.data;R.startsWith("image/")&&k.push({type:"image_url",image_url:{url:`data:${R};base64,${A}`}})}}else{let C=b.text||"";C&&k.push({type:"text",text:C})}c.push({role:x,content:k.length===1&&k[0].type==="text"?k[0].text:k})}let f={model:e,messages:c,stream:!0,stream_options:{include_usage:!0},temperature:d};if(s!=="Fast"){let b={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};f.reasoning_effort=b[s]||"high",f.extra_body={thinking:{type:"enabled"}}}else f.extra_body={thinking:{type:"disabled"}};let l=await Uo("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(f),signal:a});if(!l.ok){let b=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${b.error?.message||l.statusText}`)}let u=l.body.getReader(),h=new TextDecoder,p="",m=[],y=null,g=Date.now(),S=!1;for(;;){let{done:b,value:x}=await u.read();if(b){S&&(m.length>0||y)&&(yield{candidates:m.length>0?[{content:{parts:m}}]:[],usageMetadata:y});break}p+=h.decode(x,{stream:!0});let k=p.split(`
499
+ `);p=k.pop();for(let C of k){let R=C.trim();if(!R||!R.startsWith("data: "))continue;let A=!1;if(R==="data: [DONE]")A=!0;else try{let w=JSON.parse(R.substring(6)),T=w.choices?.[0]?.delta,E=w.usage;if(w.choices?.[0]?.finish_reason&&(A=!0),E&&(y={totalTokenCount:E.total_tokens||E.prompt_tokens+E.completion_tokens,promptTokenCount:E.prompt_tokens||0,candidatesTokenCount:E.completion_tokens||0,cachedContentTokenCount:E.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:E.completion_tokens_details?.reasoning_tokens||0},S=!0),T){let I=T.reasoning_content||null;I&&(m.push({text:I,thought:!0}),S=!0),T.content&&(m.push({text:T.content}),S=!0)}}catch{}if((A||Date.now()-g>=150)&&S&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:y},m=[],g=Date.now(),S=!1),A)break}Date.now()-g>=150&&S&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:y},m=[],g=Date.now(),S=!1)}},ar=async function*(n,e,t,o,s,i,r,a,d=.99){let c=[];o&&c.push({role:"system",content:o});for(let k of t){let C=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let A of k.parts)if(A.text)R.push({type:"text",text:A.text});else if(A.inlineData&&r){let w=A.inlineData.mimeType,T=A.inlineData.data;w.startsWith("image/")&&R.push({type:"image_url",image_url:`data:${w};base64,${T}`})}}else{let A=k.text||"";A&&R.push({type:"text",text:A})}R.length>0&&c.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let f={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},l={model:e,messages:c,stream:!0,temperature:d,prompt_cache_key:"flux-flow-session"};s&&s!=="Fast"&&qs(e)&&(l.reasoning_effort=f[s]||"high");let u=await Uo("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(l),signal:a});if(!u.ok){let k=await u.text().catch(()=>""),C=u.statusText;try{let R=JSON.parse(k);C=R.error?.message||R.message||JSON.stringify(R.detail||R)}catch{k&&(C=k)}throw new Error(`Mistral Error (${u.status}): ${JSON.stringify(C)}`)}let h=u.body.getReader(),p=new TextDecoder,m="",y=[],g=null,S=Date.now(),b=!1,x=k=>k?typeof k=="string"?k:Array.isArray(k)?k.map(x).filter(Boolean).join(""):typeof k=="object"&&k!==null?typeof k.text=="string"?k.text:typeof k.content=="string"?k.content:typeof k.thinking=="string"?k.thinking:typeof k.reasoning_content=="string"?k.reasoning_content:typeof k.reasoning=="string"?k.reasoning:typeof k.value=="string"?k.value:k.text?x(k.text):k.content?x(k.content):k.thinking?x(k.thinking):k.reasoning_content?x(k.reasoning_content):k.reasoning?x(k.reasoning):k.value?x(k.value):"":String(k):"";for(;;){let{done:k,value:C}=await h.read();if(k){b&&(y.length>0||g)&&(yield{candidates:y.length>0?[{content:{parts:y}}]:[],usageMetadata:g});break}m+=p.decode(C,{stream:!0});let R=m.split(`
500
+ `);m=R.pop();for(let A of R){let w=A.trim();if(!w||!w.startsWith("data: "))continue;let T=!1;if(w==="data: [DONE]")T=!0;else try{let E=JSON.parse(w.substring(6)),I=E.choices?.[0]?.delta,_=E.usage;if(E.choices?.[0]?.finish_reason&&(T=!0),_&&(g={totalTokenCount:_.total_tokens||(_.prompt_tokens||0)+(_.completion_tokens||0),promptTokenCount:_.prompt_tokens||0,candidatesTokenCount:_.completion_tokens||0,cachedContentTokenCount:_.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:_.completion_tokens_details?.reasoning_tokens||0},b=!0),I){let M=I.thinking||I.reasoning_content||I.reasoning,W=x(M);W&&(y.push({text:W,thought:!0}),b=!0);let B=I.content||(!I.thinking&&!I.reasoning_content&&!I.reasoning?I.text:null);if(B)if(Array.isArray(B))for(let K of B)if(typeof K=="object"&&K!==null){let Y=K.type==="thinking"||K.type==="reasoning"||!!K.thought,Se=x(K);Se&&(y.push({text:Se,...Y?{thought:!0}:{}}),b=!0)}else{let Y=x(K);Y&&(y.push({text:Y}),b=!0)}else if(typeof B=="object"&&B!==null){let K=B.type==="thinking"||B.type==="reasoning"||!!B.thought,Y=x(B);Y&&(y.push({text:Y,...K?{thought:!0}:{}}),b=!0)}else{let K=x(B);K&&(y.push({text:K}),b=!0)}}}catch{}if((T||Date.now()-S>=150)&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:g},y=[],S=Date.now(),b=!1),T)break}Date.now()-S>=150&&b&&(yield{candidates:y.length>0?[{content:{parts:[...y]}}]:[],usageMetadata:g},y=[],S=Date.now(),b=!1)}},lr=async function*(n,e,t,o,s,i,r=!1,a,d=.99){let c=[];o&&c.push({role:"system",content:o}),t.forEach(se=>{let Ee=se.role==="model"?"assistant":"user",$=[];Array.isArray(se.parts)&&se.parts.forEach(P=>{if(P.text)$.push({type:"text",text:P.text});else if(P.inlineData&&r){let V=P.inlineData.mimeType,X=P.inlineData.data;V.startsWith("image/")&&hn(e)&&$.push({type:"image_url",image_url:{url:`data:${V};base64,${X}`}})}}),c.push({role:Ee,content:$.length===1&&$[0].type==="text"?$[0].text:$})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",h=e.includes("kimi"),p=e.includes("gemma"),m=e.includes("deepseek"),y=e.includes("glm"),g=e.includes("mistral"),S=e.includes("minimax"),b=e.includes("gpt"),x=e.includes("qwen"),k=e.includes("nemotron"),C=e.includes("llama-3"),R=e.includes("seed"),A=e.includes("poolside"),w=e.includes("thinkingmachines")||e.includes("muse"),T=C,E=null,I={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},_={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},M={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},W=S||m||A||w?16384:32768;W=process.env.NVIDIA_BASE_URL?1024:W,W=E?1024:W;let B={model:e,messages:c,max_tokens:W,stream:!0,stream_options:{include_usage:!0},temperature:d,...b&&{thinking:I[s]||"high"}};if(!(process.env.NVIDIA_BASE_URL||T||E))if(h)B.chat_template_kwargs={thinking:u};else if(p)B.chat_template_kwargs={enable_thinking:u};else if(m)if(u){let se=l==="High"?"max":"high";B.chat_template_kwargs={thinking:!0,reasoning_effort:se}}else B.chat_template_kwargs={thinking:!1};else y?B.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:g?B.reasoning_effort=u?"high":"none":S&&e.includes("minimax-m3")?B.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:x?B.chat_template_kwargs={enable_thinking:u}:k?l==="High"?(B.reasoning_budget=12e3,B.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?(B.reasoning_budget=12e3,B.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):B.chat_template_kwargs={enable_thinking:!1}:R?u&&(B.extra_body={thinking_budget:parseInt(_[l]??"4096")}):A?B.chat_template_kwargs={enable_thinking:u}:w&&(B.reasoning_effort=M[l]||"medium");let K=0,Y=6,Se=!1,D=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",F=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:n;for(D.endsWith("/chat/completions")||(D=D.replace(/\/+$/,"")+"/chat/completions");K<Y;){K++;try{let se=await Uo(D,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${F}`},body:JSON.stringify(B),signal:a});if(!se.ok){let Fe=await se.text().catch(()=>""),tt=se.statusText;try{let ft=JSON.parse(Fe);tt=ft.error?.message||ft.message||JSON.stringify(ft.detail||ft)}catch{Fe&&(tt=Fe)}let je=new Error(`NVIDIA API Error (${se.status}): ${tt}`);throw je.status=se.status,je}let Ee=se.body.getReader(),$=new TextDecoder,P="",V=[],X=null,Pe=Date.now(),Le=!1;for(;;){let{done:Fe,value:tt}=await Ee.read();if(Fe){Le&&(V.length>0||X)&&(yield{candidates:V.length>0?[{content:{parts:V}}]:[],usageMetadata:X},Se=!0);break}P+=$.decode(tt,{stream:!0});let je=P.split(`
501
+ `);P=je.pop();let ft=!1;for(let Pt of je){let dt=Pt.trim();if(dt){if(dt==="data: [DONE]"){ft=!0;break}if(dt.startsWith("data: ")){let ut;try{ut=JSON.parse(dt.substring(6))}catch{continue}if(ut.error)throw new Error(`NVIDIA Stream Error: ${ut.error.message||JSON.stringify(ut.error)}`);ut.choices?.[0]?.finish_reason&&(ft=!0);try{let Tt=ut.usage;Tt&&(X={totalTokenCount:Tt.total_tokens||Tt.prompt_tokens+Tt.completion_tokens,promptTokenCount:Tt.prompt_tokens||0,candidatesTokenCount:Tt.completion_tokens||0,cachedContentTokenCount:Tt.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Tt.completion_tokens_details?.reasoning_tokens||0)+(Tt.completion_tokens_details?.thoughts_tokens||0)},Le=!0);let bt=ut.choices?.[0]?.delta?.reasoning||ut.choices?.[0]?.delta?.reasoning_content||"",Xe=ut.choices?.[0]?.delta?.content||"";bt&&(V.push({text:bt,thought:!0}),Le=!0),Xe&&(V.push({text:Xe}),Le=!0)}catch{}}}}if((ft||Date.now()-Pe>=350)&&Le&&(yield{candidates:V.length>0?[{content:{parts:[...V]}}]:[],usageMetadata:X},Se=!0,V=[],Pe=Date.now(),Le=!1),ft)break}break}catch(se){if(Se||K>=Y)throw se;await new Promise(Ee=>setTimeout(Ee,3500))}}},Jf=async function*(n,e){let t=[],o=null,s=!1,i=null,r=u=>{if(t.push(u),o){let h=o;o=null,h()}},a=e.split("/").pop();a=a.replace("llama-3.3","llama-3_3");let d=`https://api.ngc.nvidia.com/v2/predict/queues/models/qc69jvmznzxy/${a}`,c=!1,f=null,l=async()=>{try{let u=await fetch(d);if(u.ok){let h=await u.json();if(h&&h.queues&&h.queues[0]&&typeof h.queues[0].queueDepth=="number"){let p=h.queues[0].queueDepth;c||r({value:{type:"status",content:`Queue ${p||1}`},done:!1})}}else c||r({value:{type:"status",content:`Queue ${u.status}`},done:!1})}catch{}};process.env.NVIDIA_BASE_URL||(l(),f=setInterval(l,5e3)),(async()=>{try{let u=n[Symbol.asyncIterator]();for(;;){let{value:h,done:p}=await u.next();if(p)break;c=!0,f&&(clearInterval(f),f=null),r({value:h,done:!1})}s=!0,r(null)}catch(u){if(i=u,f&&(clearInterval(f),f=null),o){let h=o;o=null,h()}}})();try{for(;;){if(i)throw i;if(t.length>0){let u=t.shift();if(u===null&&s)break;yield u.value}else{if(s)break;await new Promise(u=>{o=u})}}}finally{f&&(clearInterval(f),f=null)}},cr=async function*(n,e,t,o,s,i,r,a,d=.95){let c=[];o&&c.push({role:"system",content:[{type:"text",text:o,cache_control:{type:"ephemeral"}}]});for(let k of t){let C=k.role==="user"?"user":"assistant",R=[];if(Array.isArray(k.parts)){for(let A of k.parts)if(A.text)R.push({type:"text",text:A.text});else if(A.inlineData&&r){let w=A.inlineData.mimeType,T=A.inlineData.data;w.startsWith("image/")?R.push({type:"image_url",image_url:{url:`data:${w};base64,${T}`}}):R.push({type:"file",file:{filename:A.filename||"file",file_data:`data:${w};base64,${T}`}})}}else{let A=k.text||"";A&&R.push({type:"text",text:A})}c.push({role:C,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let f={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},l={model:e,messages:c,stream:!0,temperature:d,cache_control:{type:"ephemeral"},session_id:"flux-flow-session"},u=f[s];u&&s!=="Fast"&&(l.reasoning_effort=u);let h=await Uo("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true","X-OpenRouter-Cache":"true"},body:JSON.stringify(l),signal:a});if(!h.ok){let k=await h.json().catch(()=>({}));throw new Error(`OpenRouter Error (${h.status}): ${k.error?.message||h.statusText}`)}let p=h.body.getReader(),m=new TextDecoder,y="",g=[],S=null,b=Date.now(),x=!1;for(;;){let{done:k,value:C}=await p.read();if(k){x&&(g.length>0||S)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:S});break}y+=m.decode(C,{stream:!0});let R=y.split(`
502
+ `);y=R.pop();for(let A of R){let w=A.trim();if(!w||!w.startsWith("data: "))continue;let T=!1;if(w==="data: [DONE]")T=!0;else try{let E=JSON.parse(w.substring(6)),I=E.choices?.[0]?.delta,_=E.usage;if(E.choices?.[0]?.finish_reason&&(T=!0),_&&(S={totalTokenCount:_.total_tokens||(_.prompt_tokens||0)+(_.completion_tokens||0),promptTokenCount:_.prompt_tokens||0,candidatesTokenCount:_.completion_tokens||0,cachedContentTokenCount:_.prompt_tokens_details?.cached_tokens||_.prompt_tokens_details?.cache_read_input_tokens||_.cache_read_input_tokens||0,thoughtsTokenCount:_.completion_tokens_details?.reasoning_tokens||0},x=!0),I){let M=I.reasoning||(I.reasoning_details?I.reasoning_details.map(W=>W.text).join(""):null);M&&(g.push({text:M,thought:!0}),x=!0),I.content&&(g.push({text:I.content}),x=!0)}}catch{}if((T||Date.now()-b>=150)&&x&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:S},g=[],b=Date.now(),x=!1),T)break}}},Za=async function*(n,e,t,o,s,i,r,a,d=1.05,c="Cloud"){let f=[];o&&f.push({role:"system",content:o});for(let R of t){let A=R.role==="user"?"user":"assistant",w="",T=[];if(Array.isArray(R.parts)){w=R.parts.map(E=>E.text||"").filter(Boolean).join(`
503
+ `);for(let E of R.parts)E.inline_data&&E.inline_data.data&&T.push(E.inline_data.data)}else w=R.text||"";if(w||T.length>0){let E={role:A,content:w};T.length>0&&(E.images=T),f.push(E)}}let l=c==="Local"||!n||n==="LOCAL",h={host:l?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com"};!l&&n&&(h.headers={Authorization:"Bearer "+n});let p=new zs(h),m=[],y=null,g=Date.now(),S=!1,b={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=b[s]!==void 0?b[s]:!0,k={model:e,messages:f,stream:!0,think:x,keep_alive:"10m",options:{temperature:d}},C=await p.chat(k);for await(let R of C){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(R.message?.thinking&&(m.push({text:R.message.thinking,thought:!0}),S=!0),R.message?.content&&(m.push({text:R.message.content}),S=!0),R.done){let A=R.prompt_cached_count||0;if(!A&&R.prompt_eval_count){let w=R.prompt_eval_duration||0;w>0&&w<5e7&&(A=R.prompt_eval_count)}y={totalTokenCount:(R.prompt_eval_count||0)+(R.eval_count||0),promptTokenCount:R.prompt_eval_count||0,candidatesTokenCount:R.eval_count||0,cachedContentTokenCount:A,thoughtsTokenCount:0},S=!0}(R.done||Date.now()-g>=150&&S)&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:y},m=[],g=Date.now(),S=!1)}S&&(m.length>0||y)&&(yield{candidates:m.length>0?[{content:{parts:[...m]}}]:[],usageMetadata:y})},Pg=()=>{Mt=!0},Dg=()=>Mt,or={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating",todo:"Planning",Todo:"Planning",invoke_sync:"Sub-Agent Working",invoke:"Starting Agent",get_progress:"Checking Progress",cancel:"Cancelling",await:"Waiting",EmergencyRollback:"Don't Panic. Lookin' into it",answer:"Answering Sub-Agent",Answer:"Answering Sub-Agent",steer:"Steering Sub-Agent",Steer:"Steering Sub-Agent"},bs=(n,e)=>{try{let t=L(e),o=n.toLowerCase().replace(/_/g,"");if(o==="invokesync"||o==="invoke")return t.title||(t.task?t.task.substring(0,30):null);if(o==="getprogress"||o==="cancel"||o==="steer"||o==="steersubagent")return t.id||t.taskId;let s=t.path||t.targetFile||t.TargetFile||t.directory;return s?Q.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},fr=n=>n?new Xa({apiKey:n}):ir,Fg=async(n,e,t,o,s={})=>{let{onStatus:a,onMemoryUpdated:d,onBackgroundIncrement:c}=s,{profile:f,thinkingLevel:l,mode:u,janitorModel:h,chatId:p,systemSettings:m,sessionStats:y,aiProvider:g="Google",apiKey:S}=n,b=process.env.NVIDIA_BASE_URL||g==="Ollama"?!1:m?.memory!==!1,k=J(Lt,[]).map($=>`- [${$.id}]: ${$.memory}`).join(`
504
+ `),C=o.slice(0,-1).filter($=>$.text&&!$.text.includes("[TOOL RESULT]")&&!$.text.includes("OBSERVATION:")&&!$.text.startsWith("[TERMINAL_RECORD]")&&!$.isTerminalRecord&&!$.isMeta&&!$.isLogo&&!String($.id).startsWith("welcome")&&!String($.id).startsWith("logo")).slice(-14).map($=>{let P=Xf($.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Le,Fe)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Fe.replace(/:\d{2}/g,"")}`).replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
505
+ `).replace(/\n\n/g,`
506
+ `).replace(/\\n\\n/g,"").trim(),V=$.role==="user"?8192:32768,X=P.substring(0,V);P.length>V&&(X+=`
507
+ ... (truncated) ...`);let Pe=$.role==="user"?X.startsWith("[USER]")?"":"[USER]: ":X.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:$.role==="user"?"user":"model",parts:[{text:`${Pe}${X}`}]}}),R=o.filter($=>$.role==="user").length===1,A=e.includes("[TITLE-UPDATE]"),w=Math.random()<.8,T=R||A||w,E=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),I=vr(k,b,T),_=`${E.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[\[\s*turn\s*:\s*(continue|finish)\s*\]\]/gi,"").replace(/\[\[END\]\]/g,"").replace(/\[\[TOOL RESULTS\]\]/g,"").replace(/\[tool results\]/g,"").substring(0,32768)}`;_.length>32768&&(_+=`
508
+ ... (truncated) ...`);let M=e.replace(/\[Prompted on:.*?\]/g,"").trim();_=_.replace(/\r?\n\r?\n/g,`
509
+ `).replace(/\n\n/g,`
510
+ `).replace(/\\n\\n/g,"").trim();let W=new Date,K=`[METADATA] Current date and Time: ${`${W.getFullYear()}-${W.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(W.getDate()).padStart(2,"0")}, ${W.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
511
+
512
+ [USER]: ${M.substring(0,8192)}
513
+ ${M.length>8192?`... (truncated) ...
514
+
515
+ `:""}
516
+ [AGENT (current turn)]: ${_}`;C.push({role:"user",parts:[{text:K}]});let Y=await Xo("NVIDIA"),D=(await Qt()).quotas?.providerTiers?.NVIDIA==="Free",F="",se=0,Ee=b?12:-1;for(;se<=Ee;)try{if(!await Ur("background",n))return;let $="",P=null,V=!1,X=g;try{let Fe=new Promise((bt,Xe)=>setTimeout(()=>Xe(new Error("JANITOR_TIMEOUT")),1e4)),tt=g==="Google"&&se>=0&&se<6&&Y&&D,je=g==="DeepSeek"&&se<4&&Y&&D;V=tt||je,X=V?"NVIDIA":g;let ft=(async()=>{if(g==="OpenRouter"){let bt=Ze("janitor_open_router"),ue=cr(S,bt,C,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),qt=await ue.next();return{iterator:ue,firstResult:qt}}else if(g==="DeepSeek"&&!V){let Xe=rr(S,Ze("deepseek_fast_fallback"),C,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ue=await Xe.next();return{iterator:Xe,firstResult:ue}}else if(g==="Mistral"&&!V){let Xe=ar(S,Ze("mistral_janitor_fallback"),C,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ue=await Xe.next();return{iterator:Xe,firstResult:ue}}else if(g==="NVIDIA"||V){let Xe=lr(V?Y:S,Ze("nvidia_janitor_fallback"),C,I,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),ue=await Xe.next();return{iterator:Xe,firstResult:ue}}else{let ue=(await fr(S).models.generateContentStream({model:h||(se===Ee?Ze("janitor_default"):Ze("gemma_janitor_fallback_google")),contents:C,config:{systemInstruction:I,temperature:.7,safetySettings:[{category:Xn.HARM_CATEGORY_HARASSMENT,threshold:Kn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_HATE_SPEECH,threshold:Kn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Kn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Kn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:it.MINIMAL}}}))[Symbol.asyncIterator](),qt=await ue.next();return{iterator:ue,firstResult:qt}}})();if(process.stdout.isTTY){let ue=(await cs())[p]?.name||"",qt=ue&&!ue.startsWith("flow-")&&!ue.startsWith("Session ")?ue:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${qt}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${qt}\x07`)}let{iterator:Pt,firstResult:dt}=await Promise.race([ft,Fe]),{value:ut,done:Tt}=dt;if(!Tt&&ut){let bt=ut.candidates?.[0]?.content?.parts,Xe=bt?X==="Google"?bt[1]?.text||bt[0]?.text||"":bt.filter(ue=>ue.text&&!ue.thought).map(ue=>ue.text).join(""):typeof ut.text=="function"?ut.text():"";Xe&&($+=Xe),P=ut.usageMetadata;for await(let ue of{[Symbol.asyncIterator]:()=>Pt}){let qt=ue.candidates?.[0]?.content?.parts,Jn=qt?X==="Google"?qt[1]?.text||qt[0]?.text||"":qt.filter(Qn=>Qn.text&&!Qn.thought).map(Qn=>Qn.text).join(""):typeof ue.text=="function"?ue.text():"";Jn&&($+=Jn),P=ue.usageMetadata}}}catch(Fe){throw Fe}if($){if(F=$,P){let Fe=P.totalTokenCount||0,tt=P.cachedContentTokenCount||0,je=(P.candidatesTokenCount||0)+(P.thoughtsTokenCount||0),ft=V?Ze("nvidia_janitor_fallback"):X==="DeepSeek"?Ze("deepseek_fast_fallback"):X==="OpenRouter"?Ze("janitor_open_router"):h||(se===Ee?Ze("janitor_default"):Ze("gemma_janitor_fallback_google"));await Ht("tokens",Fe,X,ft),tt>0&&await Ht("cachedTokens",tt,X,ft),je>0&&await Ht("candidateTokens",je,X,ft)}}else throw new Error("No synthesis generated by Janitor.");c&&(c(),await $t("background"));let Pe=Bo(F),Le=!1;for(let Fe of Pe){let tt=Fe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(tt)&&(Le=!0);let je={chatId:p,sessionId:p,history:o},ft=await lo(tt,Fe.args,je);tt.toLowerCase()==="memory"&&(Fe.args.includes("action='user'")||Fe.args.includes('action="user"'))&&!ft.startsWith("ERROR")&&(d&&d(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(dt=>setTimeout(dt,3e3)))}if(!Le)try{let Fe=J(Lt,[]);if(Fe.length>0){let tt=[];for(let je of Fe)je.score===void 0&&(je.score=.5),je.score*=.99995,je.score<.05&&(je.score=0),je.score=Math.round(je.score*1e5)/1e5,je.score>0&&tt.push(je);ce(Lt,tt)}}catch{}break}catch($){se++;let P=new Date().toLocaleString(),V=$ instanceof Error?(()=>{try{return JSON.parse(JSON.parse($.message).error.message).error.message}catch{return String($)}})():String($);await new Promise(Le=>setTimeout(Le,1e3));let X=Q.join(dn,"janitor");if(_e.existsSync(X)||_e.mkdirSync(X,{recursive:!0}),_e.appendFileSync(Q.join(X,"error.log"),`ERROR [Attempt ${se}/${Ee+1}] [${P}]: ${V}
517
+
518
+ `),se>Ee)break;let Pe=Math.min(750*Math.pow(2,se-1),5e3);await new Promise(Le=>setTimeout(Le,Pe))}if(se){let $=Q.join(dn,"janitor");_e.appendFileSync(Q.join($,"error.log"),`-----------------------------------------------------------------------------
519
+
520
+ `)}if(process.stdout.isTTY)try{let V=(await cs())[p]?.name||"",X=V&&!V.startsWith("flow-")&&!V.startsWith("Session ")?V:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${X}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${X}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Qf=n=>{let e=n.replace(Gf,"").replace(Yf,""),t=Ls?e:e.replace(Ja,s=>" ".repeat(s.length)).replace(Qa,s=>" ".repeat(s.length));fo.lastIndex=0;let o;for(;(o=fo.exec(t))!==null;){let s=o.index+o[0].length-1,i=0,r=null,a=!1,d=!1;for(let c=s;c<t.length;c++){let f=e[c];if(!r&&(f==='"'||f==="'"||f==="`")?(r=f,a=!1):r&&f===r&&!a&&(r=null),!r&&(f==="("?i++:f===")"&&i--,i===0)){let l=c+1;for(;l<t.length&&/\s/.test(t[l]);)l++;if(l<t.length&&t[l]==="]"){d=!0,fo.lastIndex=l+1;break}}f==="\\"?a=!a:a=!1}if(!d)return{inside:!0,toolName:o[1],startIndex:o.index,args:e.substring(o.index+o[0].length)}}return{inside:!1}},el=(n,e=!0)=>{let t=fo;t.lastIndex=0;let o="",s=0,i;for(;(i=t.exec(n))!==null;){let r=n.substring(s,i.index);o+=e?r.replace(ja,""):r;let a=i.index+i[0].length-1,d=0,c=null,f=-1;for(let l=a;l<n.length;l++){let u=n[l];if(c){if(u===c){let h=0;for(let p=l-1;p>=0&&n[p]==="\\";p--)h++;h%2===0&&(c=null)}}else if(u==='"'||u==="'"||u==="`")c=u;else if(u==="(")d++;else if(u===")"&&(d--,d===0)){let h=l+1;for(;h<n.length&&/\s/.test(n[h]);)h++;if(h<n.length&&n[h]==="]"){f=h;break}}}if(f!==-1)o+="[tool:functions."+i[1]+"()]",s=f+1,t.lastIndex=s;else{o+="[tool:functions."+i[1]+"(",s=n.length;break}}return s<n.length&&(o+=e?n.substring(s).replace(ja,""):n.substring(s)),o},Zf=(n,e,t)=>{let o=fo;o.lastIndex=0;let s="",i=0,r;for(;(r=o.exec(n))!==null;){let a=n.substring(i,r.index);s+=a.replace(e,t);let d=r.index+r[0].length-1,c=0,f=null,l=-1;for(let u=d;u<n.length;u++){let h=n[u];if(f){if(h===f){let p=0;for(let m=u-1;m>=0&&n[m]==="\\";m--)p++;p%2===0&&(f=null)}}else if(h==='"'||h==="'"||h==="`")f=h;else if(h==="(")c++;else if(h===")"&&(c--,c===0)){let p=u+1;for(;p<n.length&&/\s/.test(n[p]);)p++;if(p<n.length&&n[p]==="]"){l=p;break}}}if(l!==-1)s+=n.substring(r.index,l+1),i=l+1,o.lastIndex=i;else{s+=n.substring(r.index),i=n.length;break}}return i<n.length&&(s+=n.substring(i).replace(e,t)),s},Ka=n=>el(n,!0),ed=n=>{if(!n)return n;let e={patchfile:"PatchFile",writefile:"WriteFile",readfile:"ReadFile",viewfile:"ReadFile",run:"Run",execcommand:"Run",searchkeyword:"SearchKeyword",codesearch:"CodeSearch",code_search:"CodeSearch",websearch:"WebSearch",webscrape:"WebScrape",readfolder:"ReadFolder",writepdf:"WritePDF",writedoc:"WriteDoc",writedocx:"WriteDoc",filemap:"FileMap",generateimage:"GenerateImage",todo:"Todo",ask:"Ask"},t=s=>s.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("");Ga.lastIndex=0;let o=n.replace(Ga,(s,i,r)=>{let a="";try{let f=JSON.parse(r.trim());f&&typeof f=="object"&&(a=Object.entries(f).map(([u,h])=>{let p=typeof h=="string"?h:JSON.stringify(h);return`${u}=${JSON.stringify(p)}`}).join(", "))}catch{let l=[],u=qf;u.lastIndex=0;let h;for(;(h=u.exec(r))!==null;){let p=h[1],m=h[2]!==void 0?h[2]:h[0].split(":").slice(1).join(":").trim();l.push(`${p}=${JSON.stringify(m)}`)}l.length>0?a=l.join(", "):a=r.trim()}let d=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${e[d]||t(i)}(${a})]`});return Ya.lastIndex=0,qa.lastIndex=0,o=o.replace(Ya,""),o=o.replace(qa,""),o},td=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,nd=/^['"`]?\s*\.\.\.\s*['"`]?$/,Nn=n=>{if(n==null)return!1;let e=String(n).trim();return e==="..."||e==="\u2026"||nd.test(e)},Bo=n=>{if(!n)return[];let e=ed(n);Ha.lastIndex=0;let t=e.replace(Ha,""),o=[],s=Ls?t:t.replace(Ja,a=>" ".repeat(a.length)).replace(Qa,a=>" ".repeat(a.length)),i=jf;i.lastIndex=0;let r;for(;(r=i.exec(s))!==null;){let a=r[1],d=r.index+r[0].length-1,c=0,f=null,l=-1,u=-1;for(let h=d;h<s.length;h++){let p=t[h];if(f){if(p===f){let m=0;for(let y=h-1;y>=0&&t[y]==="\\";y--)m++;m%2===0&&(f=null)}}else if(p==='"'||p==="'"||p==="`")f=p;else if(p==="(")c++;else if(p===")"&&(c--,c===0)){u=h;let m=h+1;for(;m<s.length&&/\s/.test(s[m]);)m++;if(m<s.length&&s[m]==="]"){l=m;break}}}if(l!==-1){let h=t.substring(d+1,u),p=t.substring(r.index,l+1),m=L(h);Nn(m.path)||Nn(m.query)||Nn(m.url)||Nn(m.keyword)||Nn(m.command)||Nn(m.method)||Nn(m.title)||Nn(m.task)||Nn(m.id)||td.test(h)||o.push({fullMatch:p,toolName:a.trim(),args:h.trim()}),i.lastIndex=l+1}}return o},Ug=(n,e={})=>{if(!n)return null;if(Do=e,ir=new Xa({apiKey:n}),!globalThis.__perfCleanupInstalled){globalThis.__perfCleanupInstalled=!0,setInterval(()=>{typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks())},6e4);let t=globalThis.fetch;globalThis.fetch=async(...o)=>{try{let s=await t(...o);return typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}catch(s){throw typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),s}}}},Fo=async(n,e,t,o,s="Fast",i=.75,r="agent")=>Vf(async()=>{let{aiProvider:a="Google",apiKey:d,mode:c}=n,f="",l=null,u=typeof t=="string"?[{role:"user",parts:[{text:t}]}]:t,h=new AbortController,p=h.signal,m=setInterval(()=>{Mt&&(h.abort(),clearInterval(m))},100);try{let y;a==="Ollama"?y=Za(d,e,u,o,s,c,hn(e),p,i,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?y=cr(d,e,u,o,s,c,hn(e),p,i):a==="DeepSeek"?y=rr(d,e,u,o,s,c,hn(e),p,i):a==="Mistral"?y=ar(d,e,u,o,s,c,hn(e),p,i):a==="NVIDIA"?y=lr(d,e,u,o,s,c,hn(e),p,i):y=await fr(d).models.generateContentStream({model:e,contents:u,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let b=(e||"").toLowerCase(),x=b.includes("gemma-4")||b.startsWith("gemma"),k=b.includes("gemini-3");if(x||k)return x?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:it.MINIMAL}:{includeThoughts:!0,thinkingLevel:it.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:b.includes("pro")?it.LOW:it.MINIMAL,Low:it.LOW,Medium:it.MEDIUM,Standard:it.MEDIUM,High:it.HIGH,xHigh:it.HIGH}[s]||it.MEDIUM};{let C={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return C===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:C}}})()}},{signal:p});for await(let g of y){if(Mt)throw new Error("Subagent task was cancelled.");if(n?.taskId&&typeof ze<"u"){let x=ze.find(k=>k.id===n.taskId);if(x&&x.status==="cancelled")throw new Error("Subagent task was cancelled.")}let S="";if(g.candidates?.[0]?.content?.parts)for(let x of g.candidates[0].content.parts)x.text&&!x.thought&&(f+=x.text,S+=x.text);let b=S?S.trim().split(/\s+/).filter(Boolean).length:0;n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(S,b),g.usageMetadata&&(l=g.usageMetadata)}}finally{clearInterval(m)}if(l){let y=l.totalTokenCount||0,g=l.cachedContentTokenCount||0,S=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Ht("tokens",y,a,e),g>0&&await Ht("cachedTokens",g,a,e),S>0&&await Ht("candidateTokens",S,a,e),n&&typeof n.onUsage=="function"&&n.onUsage({totalTokenCount:y,cachedContentTokenCount:g,candidatesTokenCount:S})}return await $t("agent",a),{text:f,usageMetadata:l}}),sd=async(n,e,t=null)=>{t=t||J(Jt,{});try{let{aiProvider:o="Google"}=e;if(Object.values(t).flat().length<=5)return;let i=Object.keys(t).filter(u=>u!==n&&Array.isArray(t[u])&&t[u].length>2);if(i.length===0)return;let r=`You are a silent background process for the FluxFlow CLI Agent.
521
+ Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
522
+ For each Chat ID provided, you must output a tool call to save the consolidated summary.
523
+
524
+ The tool call format MUST be:
525
+ [tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
526
+
527
+ Guidelines:
528
+ - Create a single, updated, highly cohesive, and concise summary statement (max 400 words) for each Chat ID. It should contain WHAT user talked about, WHAT were the tasks, Temporal info, HOW/WHAT the model responded. DON'T REMOVE ANY KEY AND TURN BY TURN INFO DENSITY.
529
+ - Focus on key goals, preferences, modified files, and technical decisions.
530
+ - Under no circumstances write normal conversational text. Output ONLY the tool calls.
531
+ - You can stack multiple tool calls for multiple chats.
532
+
533
+ Chats to process:
534
+
535
+ `,a=J(In,{});for(let u of i){let p=t[u].map(y=>`- ${y}`).join(`
536
+ `),m=a[u];r+=`[Chat ID: ${u}]
537
+ `,m?(r+=`- Existing Summary: "${m}"
538
+ `,r+=`
539
+ -- New Memories to integrate:
540
+ ${p}
541
+
542
+ `):r+=`-- Individual Memories:
543
+ ${p}
544
+
545
+ `}let d=0,c=5,f=!1,l=Ze("gemma_janitor_fallback_google");for(o==="OpenRouter"&&(l=Ze("janitor_open_router")),o==="DeepSeek"&&(l=Ze("deepseek_level_1")),o==="Mistral"&&(l=Ze("mistral_level_1")),o==="NVIDIA"&&(l=Ze("nvidia_janitor_fallback"));d<=c&&!f;){d++;try{let h=(await Fo(e,l,r,null,"Fast",.75,"background")).text||"",p=Bo(h);if(p.length===0)throw new Error("No tool calls detected in synthesis response");for(let m of p){let y=m.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await lo(y,m.args,{chatId:n})}f=!0}catch(u){if(d>=c)throw new Error(`Failed after ${c} attempts. Last error: ${u.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),i=Q.join(dn,"janitor");_e.existsSync(i)||_e.mkdirSync(i,{recursive:!0}),_e.appendFileSync(Q.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
546
+ `)}},od=async(n,e,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=n,i=Q.join(yo,"chat-summaries.json"),r=h=>h.filter(p=>(p.role==="user"||p.role==="agent"||p.role==="system")&&p.role!=="think"&&!p.isVisualFeedback&&!p.isMeta&&!p.isTerminalRecord&&!(p.text&&p.text.includes("[TERMINAL_RECORD]"))&&!String(p.id).startsWith("welcome")).map(p=>{let m=p.fullText||p.text||"",y=p.role==="system"||m.startsWith("[TOOL RESULT]:")||p.text&&p.text.startsWith("[TOOL RESULT]:"),g=m;return y&&(m.includes("[TOOL RESULT]:")||p.text&&p.text.includes("[TOOL RESULT]:"))?g="[TOOL RESULT]: ...truncated for summary":g=g.replace(/(\[(?:tool|agent):[a-zA-Z0-9_\.]+)\([\s\S]*?\)(\])/g,"$1(...)$2"),`[${y?"TOOL":p.role==="agent"?"AGENT":"USER"}]: ${g}`}).join(`
547
+
548
+ `),a=async(h,p)=>{let m="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=p?`Here is the previous summary:
549
+ ${p}
550
+
551
+ Here is the new conversation history:
552
+ ${h}
553
+
554
+ Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
555
+ ${h}
556
+
557
+ Provide a consolidated summary of the entire session.`,g=Ze("gemma_janitor_fallback_google");s==="OpenRouter"&&(g=Ze("janitor_open_router")),s==="DeepSeek"&&(g=Ze("deepseek_level_1")),s==="Mistral"&&(g=Ze("mistral_level_1")),s==="NVIDIA"&&(g=Ze("nvidia_chat_summarizer_fallback"));let S=0,b=!1,x=null;for(;S<=3&&!b;){S++;try{x=await Fo(n,g,y,m,"Fast"),b=!0}catch{if(S>3){if(s==="Google")try{let C=Ze("general_fallback");return(await Fo(n,C,y,m,"Fast")).text||""}catch{return""}return""}}}return x&&x.text||""},d=r(e),c=J(i,{}),f=c[o]||{summary:"",historyLength:0};typeof f=="string"&&(f={summary:f,historyLength:0});let l=f.summary||"",u=await a(d,l);if(u){f.summary=u;let h=Kf(e);return t?f.historyLength=(f.historyLength||0)+h:f.historyLength=h,c[o]=f,ce(i,c),u}return null},Bg=n=>{try{let e=Q.join(yo,"chat-summaries.json");if(_e.existsSync(e)){let t=J(e,{});t[n]&&(delete t[n],ce(e,t))}}catch{}},Wg=async function*(n,e,t,o,s){let{profile:i,thinkingLevel:r,mode:a,janitorModel:d,chatId:c,isPlayground:f,systemSettings:l,sessionStats:u,aiProvider:h="Google",apiTier:p,wildcardTooling:m}=t,y=hn(n);if(!ir&&h==="Google")throw new Error("AI not initialized");let g=process.env.NVIDIA_BASE_URL||t?.aiProvider==="Ollama"?!1:l?.memory!==!1,S=e[e.length-1].text,b=Q.join(yo,"chat-summaries.json"),x=!1,k=e.filter(T=>T.role==="user").length===1,C=S.includes("[TITLE-UPDATE]"),R=k||C,A=S.replace(/\[TITLE-UPDATE\]/g,"").trim();A=A.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await ct.startTransaction(c,A),l?.advanceRollback&&await Vn.takeInitialSnapshot(c),Mt=!1;let w=null;try{let T=new AbortController;w=setInterval(()=>{Mt&&(T.abort(),w&&(clearInterval(w),w=null))},400);let E=[...e.slice(0,-1)];{let $e=J(b,{})[c]||{summary:"",historyLength:0};if($e.summary&&$e.historyLength>0){let Zt=0,Me=[];for(let Je=0;Je<E.length;Je++){let Ue=E[Je];(Ue.role==="user"||Ue.role==="agent"||Ue.role==="system")&&!String(Ue.id).startsWith("welcome")&&!Ue.isMeta&&Zt++,Zt>$e.historyLength&&Me.push(Ue)}E=Me}}E=E.map(j=>{if(j.role==="user"&&j.text){let $e=j.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if($e)return{...j,text:$e[1].trim()}}return{...j}});let I=process.env.HIGH_CONTEXT,_=255e3,M=26e4;if(I&&I!=="false"){let j=parseInt(I,10);!isNaN(j)&&j>=256e3&&j<=1e6&&(M=j,_=Math.round(j*.85))}if((h==="NVIDIA"&&(n?.includes("gpt")||n?.includes("qwen")||n?.includes("medium")||n.includes("muse"))||h==="Mistral")&&(_=122e3,M=126e3),h!=="Ollama"&&(u?.tokens||0)>_&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await od(t,E,!0)&&(E=[],x=!0)),k&&g){let j=J(Jt,{});Object.values(j).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await sd(c,t,j))}let W=J(Jt,{}),B=J(In,{}),K=Object.entries(W).filter(([j])=>j!==c).flatMap(([j,$e])=>$e),Se=[...Object.entries(B).filter(([j])=>j!==c).slice(-20).map(([j,$e])=>`[Chat Summary]: ${$e}`),...K].map(j=>`- ${j}`).join(`
558
+ `),F=J(Lt,[]).map(j=>`- ${j.memory}`).join(`
559
+ `),se=(u?.tokens||0)>=1e4,Ee=Mr(Se,F,g,se),$=new Date,P=$.getFullYear(),V=$.toLocaleString("en-US",{month:"short"}).toUpperCase(),X=String($.getDate()).padStart(2,"0"),Pe=$.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Le=`${P}-${V}-${X}, ${Pe}`,Fe=[".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"],tt=j=>{try{return _e.readdirSync(j,{withFileTypes:!0})}catch{return[]}},je=(j,$e={value:0},Zt=1)=>{if($e.value>6200||Zt>7)return $e.value;let Me=tt(j);for(let Je of Me){if($e.value>6200)break;Fe.includes(Je.name)||Je.name.startsWith(".")||Je.isDirectory()&&($e.value++,je(Q.join(j,Je.name),$e,Zt+1))}return $e.value},ft=(j,$e)=>l?.indentationTree!==!1?tr(j,$e,1,tt,Fe):sr(j,$e,"",1,tt,Fe),Pt=je(process.cwd()),dt=12;Pt>3072?dt=1:Pt>2304?dt=2:Pt>1536?dt=3:Pt>768?dt=4:Pt>384?dt=6:Pt>192?dt=7:Pt>96?dt=8:Pt>48?dt=9:Pt>24&&(dt=10);let ut=J(Ko,{}),Tt=ut[c],bt=Tt?Tt!==process.cwd():!1;ut[c]=process.cwd(),ce(Ko,ut);let Xe=J(b,{}),ue=Xe[c]||{summary:"",historyLength:0};typeof ue=="string"&&(ue={summary:ue,historyLength:0});let qt=e.filter(j=>(j.role==="user"||j.role==="agent"||j.role==="system")&&!String(j.id).startsWith("welcome")&&!j.isMeta).length;ue.historyLength&&qt<ue.historyLength&&(ue.summary="",ue.historyLength=0,Xe[c]=ue,ce(b,Xe));let Jn=typeof ue=="object"?ue.summary||"":ue||"",Qn=E.length>0;Qn&&Jn&&E[0]&&(E[0].role==="user"||E[0].role==="system")&&(E[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(E[0].text=`[SYSTEM METADATA]
560
+ **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
561
+ ${Jn}
562
+
563
+ [USER] ${E[0].text}`,yield{type:"summary_injected",content:{id:E[0].id,text:E[0].text}}));let dr=Jn&&!Qn?`
564
+ [SYSTEM METADATA]
565
+ **CONTEXT SUMMARY OF PREVIOUS TURNS**
566
+ ${Jn}
567
+ `:"",ur=!!l?.dynamicDirAwareness,tl=`${c}|${h}|${r}|${n}|${i}|${ur}`,hr=!ur&&Ts.key===tl&&Ts.value?"":`
568
+ **DIRECTORY STRUCTURE**
569
+ CWD: `+process.cwd()+`${f?" [PLAYGROUND MODE]":""}
570
+ `+ft(process.cwd(),dt),yt=await ws(),Pn="";if(Po()&&yt.file_focused!=="none"){Pn=`
571
+ [ADDITIONAL IDE CONTEXT]
572
+ `;let j=Q.relative(process.cwd(),yt.file_focused),$e=(yt.opened_editors||[]).map(Me=>{let Je=Q.relative(process.cwd(),Me);return Je.startsWith("..")?`[External] ${Q.basename(Me)}`:Je});if(Pn+=`Focused File: ${j}
573
+ Cursor Line: ${yt.cursor_line}
574
+ `,yt.selected){let Me=yt.selected,Je=Me.split(`
575
+ `);Je.length>256&&(Me=Je.slice(0,240).join(`
576
+ `)+`
577
+ ... [truncated] ...
578
+ `+Je.slice(-16).join(`
579
+ `)),Me.length>2048&&(Me=Me.slice(0,1920)+`
580
+ ... [truncated] ...
581
+ `+Me.slice(-128)),Pn+=`Current Selection: "${Me}"
582
+ `}if(yt.manual_edits){let Je=yt.manual_edits.split(`
583
+ `),Ue=[],Ve=null;for(let G of Je)G.trim()&&(G.startsWith(" Line ")?Ve&&Ve.edits.push(G):(Ve={path:G.endsWith(":")?G.slice(0,-1):G,edits:[]},Ue.push(Ve)));for(let G of Ue)G.edits.length>80&&(G.edits=G.edits.slice(-80)),G.originalEditsCount=G.edits.length;let re=(G,Z)=>Z.reduce((Be,an)=>{let Sn=yt.file_focused&&(an.path===yt.file_focused||Q.resolve(process.cwd(),an.path)===Q.resolve(yt.file_focused))?Math.ceil(G*1.2):G;return Be+Math.min(an.edits.length,Sn)},0),Dt=80;if(re(80,Ue)>300){let G=!1;for(let Z=80;Z>=10;Z--)if(re(Z,Ue)<=300){Dt=Z,G=!0;break}G||(Dt=10)}let Ke=[...Ue];if(Dt===10&&re(10,Ke)>500)for(;Ke.length>0&&re(10,Ke)>500;){let G=0,Z=Ke[0].originalEditsCount;for(let Be=1;Be<Ke.length;Be++)Ke[Be].originalEditsCount<Z&&(Z=Ke[Be].originalEditsCount,G=Be);Ke.splice(G,1)}for(let G of Ke){let Be=yt.file_focused&&(G.path===yt.file_focused||Q.resolve(process.cwd(),G.path)===Q.resolve(yt.file_focused))?Math.ceil(Dt*1.2):Dt;G.edits.length>Be&&(G.edits=G.edits.slice(-Be))}for(let G of Ke){let Z=`${G.path}:
584
+ ${G.edits.join(`
585
+ `)}`;for(;G.edits.length>0&&Z.length>4*768;)G.edits.shift(),Z=`${G.path}:
586
+ ${G.edits.join(`
587
+ `)}`;Z.length>4*768?G.stringRepresentation="... "+Z.slice(-(4*768-4)):G.stringRepresentation=Z}let en=Ke.map(G=>G.stringRepresentation).join(`
588
+ `);for(;Ke.length>0&&en.length>4*2048;){Ke[0].edits.length>0?Ke[0].edits.shift():Ke.shift();for(let G of Ke){let Z=`${G.path}:
589
+ ${G.edits.join(`
590
+ `)}`;Z.length>4*768?G.stringRepresentation="... "+Z.slice(-(4*768-4)):G.stringRepresentation=Z}en=Ke.map(G=>G.stringRepresentation).join(`
591
+ `)}en.length>4*2048&&(en="... "+en.slice(-(4*2048-4))),Pn+=`Recent Manual Edits:
592
+ ${en}
593
+ `}$e.length>0&&(Pn+=`All Opened Editors: ${$e.join(", ")}`),yt.diagnostics&&(Pn+=`
594
+ **ACTIVE FILE ERRORS**:
595
+ ${yt.diagnostics}
596
+ `),(A.toLowerCase().includes("lint")||A.toLowerCase().includes("warning"))&&yt.warnings&&(Pn+=`
597
+ **LINT WARNINGS**:
598
+ ${yt.warnings}
599
+ `)}let pr=A.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),mr=/(?:\\)?@\[([^\]]+)\]/g,Wo,jo=[];for(mr.lastIndex=0;(Wo=mr.exec(pr))!==null;){let j=Wo[0].startsWith("\\");jo.push({tag:Wo[1],isEscaped:j})}let Ho=[],uo=null;for(let j=0;j<jo.length;j++){let{tag:$e,isEscaped:Zt}=jo[j];if(!Zt)try{let Me=$e.trim().replace(/^["']|["']$/g,""),Je=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Ue=Me.match(Je),Ve=Me,re=null,Dt=null;Ue&&(re=parseInt(Ue[1],10),Dt=Ue[2]?parseInt(Ue[2],10):re,Ve=Me.slice(0,Ue.index));let Ke=Q.resolve(process.cwd(),Ve);if(_e.existsSync(Ke)&&_e.statSync(Ke).isFile()){let G=Ve.toLowerCase(),Z=G.endsWith(".pdf"),Be=G.endsWith(".docx")||G.endsWith(".doc")||G.endsWith(".ppt")||G.endsWith(".pptx")||G.endsWith(".xls")||G.endsWith(".xlsx"),an=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(G),Ft=an||Z||Be,Sn=h==="Google"||hn(n);if(Ft&&!Sn){let De=`\u2718 Unsupported Modality: ${Q.basename(Ve)}`,Ce=115;process.stdout.isTTY&&(Ce=process.stdout.columns-5||120);let ht=[De],Dn=Math.max(...ht.map(Cn=>Cn.length)),Fn=Math.min(Dn+4,Ce),ts=ht.map(Cn=>`${Cn.padEnd(Fn-2).substring(0,Fn-2)}`).join(`
600
+ `);yield{type:"visual_feedback",content:yn(`${ts}
601
+ `)};continue}if(re===null&&!Ft){let De=0;try{De=_e.readFileSync(Ke,"utf8").split(/\r\n|\r|\n/).length}catch{}if(De>300){let Ce=`\u21B7 Skipped (Too Large): ${Q.basename(Ve)}`,ht=115;process.stdout.isTTY&&(ht=process.stdout.columns-5||120);let Dn=Math.min(Ce.length+4,ht),Fn=Ce.padEnd(Dn-2).substring(0,Dn-2);yield{type:"visual_feedback",content:yn(`${Fn}
602
+ `)};continue}}let An=re!==null?re:1,Zn=Dt!==null?Dt:re!==null?re:An+299;Zn-An>300&&(Zn=An+300);let po=`path=${JSON.stringify(Ve)}, startLine=${An}, endLine=${Zn}`,et=await Zs(po,{isMultiModal:Sn}),He=!1,Ut="",es=null;if(typeof et=="string"?et.trim().startsWith("ERROR")?He=!0:Ut=et:et&&typeof et=="object"&&et.binaryPart?(es=et.binaryPart,Ut=et.text||""):He=!0,!He){let De="";if(an?(De=`\u2714 Processed: ${Q.basename(Ve)}`,uo=es):Z||Be?(De=`\u2714 Auto-Analysed: ${Q.basename(Ve)}`,uo=es):(De=`\u2714 Auto-Read: ${Q.basename(Ve)}`,Ho.push(Ut)),De){let Ce=115;process.stdout.isTTY&&(Ce=process.stdout.columns-5||120);let ht=[De],Dn=Math.max(...ht.map(Cn=>Cn.length)),Fn=Math.min(Dn+4,Ce),ts=ht.map(Cn=>`${Cn.padEnd(Fn-2).substring(0,Fn-2)}`).join(`
603
+ `);yield{type:"visual_feedback",content:yn(`${ts}
604
+ `)}}}}}catch{}}let gr="";Ho.length>0&&(gr=`[TAGGED FILE CONTENTS] Auto Read User Tagged files by System, No need to re-read
605
+ `+Ho.join(`
606
+
607
+ `)+`
608
+ [/TAGGED FILE CONTENTS]
609
+ `);let nl=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",sl=pr.replace(/\\(@\[[^\]]+\])/g,"$1"),ol=m?`You cannot execute tools
610
+ Instead, output in chat the exact string you WOULD have produced & wait for system response
611
+ `:"",yr=`[SYSTEM METADATA]
612
+ Time: ${Le}
613
+ OS: ${nl}${l?.dynamicDirAwareness?hr:""}${bt?`
614
+ WARNING: CWD Changed from previous: "${Tt}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
615
+ `:""}${Ee}${Pn}
616
+ [/METADATA]
617
+ ${dr}${r!=="Fast"&&(h==="Mistral"&&!qs(n)||r!=="xHigh"&&h==="Google")?`${h==="Mistral"&&!qs(n)||n.toLowerCase().startsWith("gemma")?`[SYSTEM] STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think> [/SYSTEM]
618
+ `:""}`:""}[SYSTEM] EXACT STRUCTURED STRING '[tool:functions.ToolName(arg="value")]' IN CHAT RESPONSE [/SYSTEM]
619
+ ${gr}${ol}[USER PROMPT] ${sl.trim()} [/USER PROMPT]`.trim(),wr={role:"user",text:yr};uo&&(wr.binaryPart=uo),E.forEach(j=>{j.text&&j.role==="agent"&&(j.text=j.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),j.text=j.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),E.push(wr),dr&&e[e.length-1]?.id&&(yield{type:"summary_injected",content:{id:e[e.length-1].id,text:yr}});let kn=null,Go=a==="Flux"?100:10,wn=16;yield{type:"status",content:"Connecting"},Mt=!1;let Sr=[],ho=!1;for(let j=0;j<=Go;j++){let $e=await pi("agent",t);if(!$e.allowed)throw new Error($e.reason||`Budget Exhausted for Provider (${h||"Agent"})`);let Zt=[];if(ho=!1,l?.compression===0&&(u?.tokens||0)>M&&(E=Pr(E,6)),j>0&&(yield{type:"status",content:"Working"}),Mt){try{let{clearPendingNudges:Te}=await import("./subagent_state-3D5ZJCLX.js");Te()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
620
+
621
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:Te}=await import("./subagent_state-3D5ZJCLX.js"),Ge=Te();if(Ge&&Ge.length>0){let ae=Ge.join(`
622
+
623
+ `);E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
624
+
625
+ ${ae}`:E.push({role:"user",text:ae}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let Te=await o();Te&&(Te.startsWith("/btw")?E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
626
+
627
+ [SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
628
+ [QUESTION] ${Te.replace("/btw","").trim()} [/QUESTION]`:E.push({role:"user",text:`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
629
+ [QUESTION] ${Te.replace("/btw","").trim()} [/QUESTION]`}):E.length>0&&E[E.length-1].role==="user"?E[E.length-1].text+=`
630
+
631
+ [STEERING HINT, HIGH PRIORITY] ${Te.trim().toUpperCase()} [/STEERING HINT]`:E.push({role:"user",text:`[STEERING HINT, HIGH PRIORITY] ${Te.trim().toUpperCase()} [/STEERING HINT]`}),yield{type:"status",content:`${Te.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let Me,Je=!1,Ue=1,Ve=1,re="",Dt=null,Ke=null,en=null,G=0,Z=[],Be=0,an=!1,Ft=!1,Sn=!1,An=!1,Zn=!0,po=0,et="",He="",Ut=!1,es=!1,De=!0,Ce=n,ht="";for(;Ue<=wn&&Ve<=wn&&!Je&&!Mt;){let Te=!1;try{re="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,Ve===1&&(et=""));let Ge=N=>{if(!N||!N.includes("[tool:"))return N;let te="___THINK_OPEN_TAG___",U="___THINK_CLOSE_TAG___";N=N.replace("<think>",te).replace("</think>",U),N=N.replace(zf,(he,Re)=>Re.includes("[tool:")?Re.trim():he);let H="",xe=0;for(;xe<N.length;){let he=N.indexOf("[tool:",xe);if(he===-1){H+=N.substring(xe).replace(za,"").replace(Va,"");break}let Re=N.substring(xe,he);H+=Re.replace(za,"").replace(Va,"");let Et=N.indexOf("]",he);if(Et===-1){H+=N.substring(he);break}H+=N.substring(he,Et+1),xe=Et+1}return N=H,N=N.replaceAll(te,"<think>").replaceAll(U,"</think>"),N},ae=E.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,te,U)=>{let H=N.text||"";g||(H=H.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(H=Ge(H),H=H.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),H=H.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let xe=[{text:H}];return N.binaryPart&&hn(Ce)&&U.slice(te+1).filter(Re=>Re.role==="user"&&!Re.text?.startsWith("[TOOL RESULT]")).length<=2&&xe.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:xe}});for(let N=0;N<ae.length;N++){let te=ae[N],U=te.parts?.[0]?.text||"";if(te.role==="model"&&/\[tool:/i.test(U)){let H=-1;for(let xe=N+1;xe<ae.length;xe++){let he=ae[xe],Re=he.parts?.[0]?.text||"";if(he.role==="user"&&Re.startsWith("[TOOL RESULT]")){H=xe;break}}if(H!==-1&&H!==N+1){let[xe]=ae.splice(H,1);ae.splice(N+1,0,xe)}}}for(let N=ae.length-2;N>=0;N--){let te=ae[N],U=ae[N+1];te.role==="user"&&U.role==="user"&&(U.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ae.splice(N,1)}let ln=[];for(let N=0;N<ae.length;N++){let te=ae[N];if(ln.length===0)ln.push(te);else{let U=ln[ln.length-1];U.role===te.role?(U.parts[0].text+=`
632
+
633
+ `+(te.parts?.[0]?.text||""),te.parts?.length>1&&U.parts.push(...te.parts.slice(1))):ln.push(te)}}ae.length=0,ae.push(...ln),Ce=n;let Bt=`${c}|${h}|${r}|${Ce}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;if(Ts.key===Bt&&Ts.value)ht=Ts.value;else{let N=h==="Mistral"?!!qs(Ce):!(Ce||"gemma").toLowerCase().startsWith("gemma");ht=Ir(i,((Ce||"gemma").toLowerCase().startsWith("gemma"),r),a,l,g,k,h,h==="Google"?!0:y,N,c),l?.dynamicDirAwareness||(ht+=`
634
+ ${hr.replace(`
635
+ **DIRECTORY STRUCTURE**`,`
636
+ **DIRECTORY STRUCTURE**`)}`),Ts.key=Bt,Ts.value=ht}let At=ae[ae.length-1];if(Po()&j>0){await new Promise(U=>setTimeout(U,2500)),yield{type:"status",content:"Verifying"};let N=await ws(),te=N?N.diagnostics:null;te&&At&&At.role==="user"&&At.parts?.[0]?.text&&(At.parts[0].text+=`
637
+ ${te} [/ERROR]`),yield{type:"status",content:"Working"}}if(h==="Mistral"||h==="Google"&&n?.toLowerCase().startsWith("gemma")){let te=r!=="Fast"&&(h==="Mistral"||r!=="xHigh")?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>**":"",U=`
638
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`;At&&At.role==="user"&&At.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(At.parts[0].text+=U)}if(l?.advanceRollback&&At&&At.role==="user"&&At.parts?.[0]?.text?.startsWith("[TOOL RESULT]"))try{let N=await Vn.getLatestFileChanges(c);if(N&&(N.newFiles.length>0||N.modifiedFiles.length>0||N.deletedFiles.length>0)){let te=`
639
+ [SYSTEM] File Changes:
640
+ `;for(let H of N.newFiles)te+=`* ${H} (created)
641
+ `;for(let H of N.modifiedFiles)te+=`* ${H} (modified)
642
+ `;for(let H of N.deletedFiles)te+=`* ${H} (deleted)
643
+ `;te+="[/SYSTEM]",At.parts[0].text+=te;let U=-1;for(let H=E.length-1;H>=0;H--)if(E[H].role==="user"&&E[H].text?.startsWith("[TOOL RESULT]")){U=H;break}U!==-1&&(E[U].text+=te)}}catch{}let nn=Math.floor(Go*(a==="Flux"?.98:.8)),It=j+1;It>=nn&&At&&At.parts?.[0]&&(At.parts[0].text+=`
644
+ [SYSTEM] WARNING, Turn Limit Impending: Step ${It}/${Go}. Wrap up quickly/prompt user to continue. [/SYSTEM]`);let vt=new Promise((N,te)=>{T.signal.aborted&&te(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{te(new DOMException("The user aborted a request.","AbortError"))})});vt.catch(()=>{});let cn=ae;if(h==="Ollama")Me=Za(t.apiKey,Ce,cn,ht,r,a,y,T.signal,1,l?.ollamaEndpoint||"Cloud");else if(h==="OpenRouter")Me=cr(t.apiKey,Ce,cn,ht,r,a,y,T.signal,1);else if(h==="DeepSeek")Me=rr(t.apiKey,Ce,cn,ht,r,a,y,T.signal,1.05);else if(h==="Mistral")Me=ar(t.apiKey,Ce,cn,ht,r,a,y,T.signal,1);else if(h==="NVIDIA"){let N=lr(t.apiKey,Ce,cn,ht,r,a,y,T.signal,1.05);Me=Jf(N,Ce)}else{let te=fr(t?.apiKey).models.generateContentStream({model:Ce||"gemini-3-flash-preview",contents:cn,config:{systemInstruction:ht,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:Xn.HARM_CATEGORY_HARASSMENT,threshold:Kn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_HATE_SPEECH,threshold:Kn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Kn.BLOCK_NONE},{category:Xn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Kn.BLOCK_NONE}],thinkingConfig:(()=>{let U=(Ce||"").toLowerCase(),H=U.includes("gemma-4")||U.startsWith("gemma"),xe=U.includes("gemini-3");if(H||xe)return H?r.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:it.MINIMAL}:{includeThoughts:!0,thinkingLevel:it.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:U.includes("pro")?it.LOW:it.MINIMAL,Low:it.LOW,Medium:it.MEDIUM,Standard:it.MEDIUM,High:it.HIGH,xHigh:it.HIGH}[r]||it.MEDIUM};{let he={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[r]||2048;return he===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:he}}})()}},{signal:T.signal});Me=await Promise.race([te,vt])}re="",Dt=null,en=null,Z=[],Be=0,yield{type:"model_update",content:null},He="",Ut=et.length>0;let Tn="",Yo=Date.now(),os=async function*(){if(h==="Google"&&Tn){let N=Ws(Tn);for(let te of N)yield te;Tn="",Yo=Date.now()}},Tr=!0,is="",Es=!1,rt=null,Ws=N=>{let te=[],U=N;for(;U.length>0;)if(Es){let H=is+U;if(rt==="tool"||rt==="agent"){let Re=rt==="tool"?"[tool:functions.":"[agent:generalist.",Et=rt==="tool"?"[tool":"[agent";if(!H.startsWith(Et)||H.length>=Re.length&&!H.startsWith(Re)){te.push({type:"text",content:H}),is="",Es=!1,rt=null,U="";break}}let xe=-1,he="]";if(rt==="tool"||rt==="agent"){let Re=0,Et=null,z=0,fe=!1;for(let Ye=0;Ye<H.length;Ye++){let O=H[Ye];if(Et){if(O===Et){let wt=0;for(let Ie=Ye-1;Ie>=0&&H[Ie]==="\\";Ie--)wt++;wt%2===0&&(Et=null)}}else if(O==='"'||O==="'"||O==="`")Et=O;else if(O==="(")Re++,fe=!0;else if(O===")")Re--;else if(O==="[")z++;else if(O==="]"){if(fe&&Re===0&&z===1){xe=Ye;break}z--}}}else rt==="end"?he="[[END]]":rt==="kimi_section"?he="<|tool_calls_section_end|>":rt==="kimi_call"&&(he="<|tool_call_end|>"),xe=H.indexOf(he);if(xe!==-1){let Re=he.length;if(!rt.startsWith("kimi")){let Et=H.substring(0,xe+Re);te.push({type:"text",content:Et})}is="",Es=!1,rt=null,U=H.substring(xe+Re)}else{let Re=rt.startsWith("kimi")?8192:512;H.length>Re?(rt.startsWith("kimi")||te.push({type:"text",content:H}),is="",Es=!1):is=H,U="";break}}else{let H=U.indexOf("[tool"),xe=U.indexOf("[agent"),he=U.indexOf("[[END]]"),Re=U.indexOf("<|tool_calls_section_begin|>"),Et=U.indexOf("<|tool_call_begin|>"),z=[{type:"tool",idx:H,start:"[tool",end:"]"},{type:"agent",idx:xe,start:"[agent",end:"]"},{type:"end",idx:he,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:Re,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:Et,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(fe=>fe.idx!==-1).sort((fe,Ye)=>fe.idx-Ye.idx);if(z.length>0){let fe=z[0];fe.idx>0&&te.push({type:"text",content:U.substring(0,fe.idx)}),Es=!0,rt=fe.type,is="",U=U.substring(fe.idx)}else{let fe=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],Ye=-1;for(let O of fe){for(let wt=O.length-1;wt>0;wt--)if(U.endsWith(O.substring(0,wt))){Ye=U.length-wt;let Ie=fe.indexOf(O);Ie===0?rt="tool":Ie===1?rt="agent":Ie===2?rt="end":Ie===3?rt="kimi_section":rt="kimi_call";break}if(Ye!==-1)break}if(Ye!==-1)Ye>0&&te.push({type:"text",content:U.substring(0,Ye)}),Es=!0,is=U.substring(Ye),U="";else{te.push({type:"text",content:U});break}}}return te},al=Me[Symbol.asyncIterator]();for(;;){let{value:N,done:te}=await Promise.race([al.next(),vt]);if(te)break;if(N&&N.type==="status"){yield N;continue}let U="",H=N.candidates?.[0]?.content?.parts;if(H&&H.length>0)for(let he of H){let Re=typeof he.text=="string"?he.text:he.text?parseChunkText(he.text):"";he.thought?Re&&(Te||(U+="<think>",Te=!0),U+=Re):Re&&(Te&&(U+="</think>",Te=!1),U+=Re)}else{let he=N.text||"";he&&Te&&(U+="</think>",Te=!1),U+=he}let xe=U?U.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(U,xe),Tr&&(yield{type:"status",content:"Thinking"},Tr=!1),Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
645
+
646
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(U){if(Ut){if(He+=U,He.length>=64){let z=0,fe=Math.min(et.length,He.length);for(let O=fe;O>=10;O--)if(et.endsWith(He.substring(0,O))){z=O;break}let Ye=He.substring(z);if(Ye){let wt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(et)?Ye.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ye.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(wt)if(re+=wt,h==="Google")Tn+=wt;else{yield*os();let Ie=Ws(wt);for(let pe of Ie)yield pe}}Ut=!1,He=""}continue}else if(re+=U,h==="Google")Tn+=U;else{yield*os();let z=Ws(U);for(let fe of z)yield fe}let he=Qf(re);if(he.inside){es=!0,en||(en=Date.now());let fe={Ask:"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",Invoke:"invoke",InvokeSync:"invoke_sync",getProgress:"get_progress",GetProgress:"get_progress",Cancel:"cancel",Await:"await",Answer:"answer",Steer:"steer",steer:"steer"}[he.toolName]||he.toolName,Ye=he.args||"",O=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(fe)){let Ie=L(Ye),pe=Ie.path||Ie.targetFile||Ie.TargetFile||Ie.directory,bn=Ie.keyword,rs=Ie.title||Ie.task,Un=Ie.id||Ie.taskId,be=Ie.timeout||Ie.time;if(bn!=null)O=String(bn).replace(Ss,"");else if(pe)O=Q.basename(String(pe).replace(Ss,"").replace(Wa,"/"));else if(rs&&(fe==="invoke"||fe==="invoke_sync"))O=String(rs).replace(Ss,"").substring(0,30);else if(Un&&fe==="get_progress")O=String(Un).replace(Ss,"");else if(be&&fe==="await"){let Wt=parseFloat(String(be).replace(Ss,""));isNaN(Wt)?O=String(be).replace(Ss,""):(Wt<5&&(Wt=5),Wt>120&&(Wt=120),O=(On=>{if(On>=60){let zo=Math.floor(On/60),xs=On%60;return`${zo}m${xs>0?` ${xs}s`:""}`}return`${On}s`})(Wt))}else{let Wt=Ye.match(Hf);if(Wt){let zt=Wt[1].replace(Ss,"");fe==="invoke"||fe==="invoke_sync"||fe==="get_progress"?O=zt.substring(0,30):O=fe==="search_keyword"||fe==="file_map"?zt:Q.basename(zt.replace(Wa,"/"))}}}let wt=`${or[fe]||fe}${O?` ${O}`:""}`;if((fe!==Dt||O!==Ke)&&(Dt=fe,Ke=O,yield{type:"status",content:`${wt}`},process.stdout.isTTY)){let pe={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",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"}[fe]||"Working";process.stdout.write(`\x1B]0;${pe}...\x07`)}}if(re.length-po>150){po=re.length;let z=el(re,!1),Ye=(z.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),O=Ye.split(/[.!?]\s+/),wt=new Set(O),Ie=O.length>10?(O.length-wt.size)/O.length:0,pe=Ye.split(/\s+/).filter(ke=>ke.length>0).length,bn=.6,rs=.8,Un=!1;if((h.toLowerCase().includes("google")||h.toLowerCase().includes("mistral"))&&((Ce||"").toLowerCase().startsWith("gemma")||(Ce||"").toLowerCase().includes("stral"))){let v={low:256,medium:768,high:8192,max:16384,xhigh:16384}[r?.toLowerCase()]||2500;Un=pe>v}if(Ie>bn||Un){yield{type:"status",content:`${Ie>bn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Ft=!0,await new Promise(v=>setTimeout(v,3e3));break}let zt=Ka(re).trim().split(/[.!?]\s+/),On=new Set(zt);if((zt.length>10?(zt.length-On.size)/zt.length:0)>rs){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Ft=!1,An=!0,await new Promise(ke=>setTimeout(ke,3e3));break}let xs=z.replace(Pf,"").replace(Df,"").replace(Ff,"").replace(Uf,""),jt=xs.toLowerCase().split(/\s+/).map(ke=>ke.replace(Bf,"")).filter(ke=>ke.length>0),$n=!1;if(jt.length>=10)for(let ke=1;ke<=15;ke++){let v=Math.max(3,Math.ceil(10/ke));if(jt.length<ke*v)continue;let q=jt.slice(jt.length-ke),oe=q.join(" ");if(ke>1&&oe===q.slice(0,Math.floor(ke/2)).join(" ").repeat(2).trim())continue;let de=!0;for(let me=1;me<v;me++)if(jt.slice(jt.length-ke*(me+1),jt.length-ke*me).join(" ")!==oe){de=!1;break}if(de){$n=!0;break}}if(!$n){let ke=xs.toLowerCase().replace(Wf,"");if(ke.length>=20)for(let v=1;v<=10;v++){let q=Math.max(5,Math.ceil(16/v));if(ke.length<v*q)continue;let oe=ke.substring(ke.length-v),de=!0;for(let me=1;me<q;me++)if(ke.substring(ke.length-v*(me+1),ke.length-v*me)!==oe){de=!1;break}if(de){$n=!0;break}}}if($n){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Ft=!1,Sn=!0,await new Promise(ke=>setTimeout(ke,3e3));break}}let Re=re.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Et=Bo(Re);for(;Et.length>Be;){yield*os();let z=Et[Be],fe=Date.now(),O={Ask:"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",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",EmergencyRollback:"EmergencyRollback"}[z.toolName]||z.toolName,wt=or[O]||z.toolName,Ie=bs(O,z.args);yield{type:"status",content:`${wt}${Ie?` ${Ie}`:""}`};let pe="";if(O==="web_search"){let{query:v,limit:q=10,aiMode:oe=!1}=L(z.args);pe=`${v?"\u2714":"\u2718"} ${oe?"AI Search":"Searched"}: ${v?`${v}`:"No Search Query"}${oe===!1&&v?` \u2192 ${q}`:""}`}else if(O==="web_scrape"){let v=L(z.args).url||null;pe=`${v?"\u2714":"\u2718"} Visited: ${v||"No Source"}`}else if(O==="view_file"){let{path:v,StartLine:q,EndLine:oe,start_line:de,end_line:me,startLine:We,endLine:Oe}=L(z.args),ye=q||de||We,ee=oe||me||Oe,le=parseInt(ye)||1,ie=parseInt(ee)||(ye?le+800:800),Ne="...",Qe=ie;try{let qe=Q.resolve(process.cwd(),v);if(_e.existsSync(qe)){let xt=_e.readFileSync(qe,"utf8").split(`
647
+ `).length;Ne=xt,!ye&&!ee&&xt>800?Qe=Math.min(50,xt):Qe=Math.min(ie,xt)}}catch{}let ge=(v||"").toLowerCase(),ve=ge.endsWith(".pdf"),nt=ge.endsWith(".docx")||ge.endsWith(".doc")||ge.endsWith(".ppt")||ge.endsWith(".pptx")||ge.endsWith(".xls")||ge.endsWith(".xlsx"),Ae=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(ge);ve||nt?pe=`${v.length>0?"\u2714":"\u2718"} ${v?`Analyzed: ${Q.basename(v)}`:"Analyzed: File Not Found"}`:Ae?pe=`${v.length>0?"\u2714":"\u2718"} ${v?`Processed: ${Q.basename(v)}`:"Processed: File Not Found"}`:pe=`${Ne!=="..."?"\u2714":"\u2718"} Read: ${v?`${Q.basename(v)} \u2192 ${Ne!=="..."?`Lines ${le} - ${Qe} of ${Ne}`:"File Not Found"}`:"File Not Found"}`}else if(O==="list_files"||O==="read_folder"){let v=O==="list_files"?"List":"Browsed",q=L(z.args).path||null,oe=L(z.args).recurse||1;pe=`${q?"\u2714":"\u2718"} ${v}: ${q?`${q==="."?`./${oe>1?"*":""}`:`${q.replaceAll("\\","/")}${oe>1?`${q.endsWith("/")?"*":"/*"}`:`${q.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(O==="write_file"||O==="update_file"){let v=O==="write_file"?"Created":"Edited",q=L(z.args).path||null;pe=`${q?"\u2714":"\u2718"} ${v}: ${q.replaceAll("\\","/")||"No File Changes"}`}else if(O==="write_pdf"){let v=L(z.args).path||null;pe=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No PDF Generated"}`}else if(O==="write_docx"){let v=L(z.args).path||null;pe=`${v?"\u2714":"\u2718"} Generated: ${v.replaceAll("\\","/")||"No Docx Generated"}`}else if(O==="file_map"){let v=L(z.args).path;pe=`${v?"\u2714":"\u2718"} Indexed: ${v.replaceAll("\\","/")?""+v:"File Not Found"}`}else if(O.toLowerCase()==="search_keyword"||O.toLowerCase()==="todo")pe="";else if(O.toLowerCase()==="generate_image"){let{path:v,outputPath:q,output:oe}=L(z.args);pe=`\u2714 Generated: ${v||q||oe||"generated_image.png"}`}else if(O==="invoke_sync"||O==="InvokeSync"){let v=bs(O,z.args);pe=`\u2714 Called Generalist${v?`: ${v}`:""}`}else if(O==="Invoke"||O==="InvokeAsync"||O==="invoke"){let v=bs(O,z.args);pe=`\u2714 Started Generalist${v?`: ${v}`:""}`}else if(O==="get_progress"||O==="GetProgress"){let v=bs(O,z.args);pe=`\u2714 Checked${v?`: ${v}`:""}`}else if(O==="cancel"){let v=bs(O,z.args);pe=`\u{1F6C7} Cancelled${v?`: ${v}`:""}`}else if(O==="steer"||O==="Steer"){let v=bs(O,z.args);pe=`\u2714 Steered${v?`: ${v}`:""}`}else if(O==="EmergencyRollback"){let{method:v}=L(z.args);pe=v==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(O==="await"||O==="Await"){let{time:v,timeout:q}=L(z.args),oe=parseFloat(q||v)||0;oe||(oe=120);let de=Oe=>{if(Oe>=60){let ye=Math.floor(Oe/60),ee=Oe%60;return`${ye}m${ee>0?` ${ee}s`:""}`}return`${Oe}s`},me=["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"];pe=`\u2714 ${me[Math.floor(Math.random()*me.length)]} \u2192 ${de(oe)}`}else O==="Answer"||O==="answer"?pe="\u2714 Resolved Sub-Agent Query":O==="exec_command"||O==="ask"?pe="":pe=`Executed: ${z.toolName}`;if(yield*os(),O==="exec_command"){let{command:v}=L(z.args);if(v&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let q=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],oe=Q.resolve(process.cwd()).substring(0,3).toLowerCase(),de=ee=>{let le=[],ie="",Ne=null;for(let Qe=0;Qe<ee.length;Qe++){let ge=ee[Qe];Ne?(ge===Ne&&(Ne=null),ie+=ge):ge==='"'||ge==="'"?(Ne=ge,ie+=ge):ge==="&"&&ee[Qe+1]==="&"||ge==="|"&&ee[Qe+1]==="|"?(ie.trim()&&(le.push(ie.trim()),ie=""),Qe++):ge===";"||ge==="|"||ge==="&"?ie.trim()&&(le.push(ie.trim()),ie=""):ie+=ge}return ie.trim()&&le.push(ie.trim()),le},me=ee=>{let le=[],ie="",Ne=null;for(let Qe=0;Qe<ee.length;Qe++){let ge=ee[Qe];Ne?(ge===Ne&&(Ne=null),ie+=ge):ge==='"'||ge==="'"?(Ne=ge,ie+=ge):/\s/.test(ge)?ie&&(le.push(ie),ie=""):ie+=ge}return ie&&le.push(ie),le},We=ee=>{let le=ee.replace(/^['"]|['"]$/g,"").trim();return!le||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(le)?!1:q.some(ie=>{if(ie.source==="[a-zA-Z]:[\\\\\\/]"){let Ne=le.match(/[a-zA-Z]:[\\\/]/i);return Ne&&Ne[0].toLowerCase()!==oe}return ie.test(le)})};if(de(v).some(ee=>{let le=me(ee);if(le.length===0)return!1;let ie=le[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(ie)){let Qe=!1;return le.some(ge=>{let ve=ge.replace(/^['"]|['"]$/g,"");if(ve===">"||ve===">>"||ve==="<")return Qe=!0,!1;if(ve.startsWith(">")||ve.startsWith("<")){let nt=ve.replace(/^[><]+/,"");return We(nt)}return Qe?(Qe=!1,We(ge)):!1})}return le.some(Qe=>We(Qe))})){let ee='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(le=>setTimeout(le,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ee}`),await new Promise(le=>setTimeout(le,50)),t.onExecEnd&&t.onExecEnd(),Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${ee}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${ee}`},Be++;continue}}t.onExecStart&&t.onExecStart(v||"No Command"),yield{type:"exec_start"}}let bn=L(z.args),rs=bn.path||bn.targetPath||null;if(rs){let v=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,q=Q.resolve(rs),oe=Q.resolve(process.cwd());if(v&&!q.startsWith(oe)){let de="Access Denied. You are not allowed to access files outside the current workspace.";if(O==="write_file"||O==="update_file"){let We=`\u2718 ${O==="write_file"?"Write Canceled":"Edit Canceled"}: ${bn.path||"..."}`,Oe=115;process.stdout.isTTY&&(Oe=process.stdout.columns-5||120);let ye=Math.min(We.length+4,Oe),ee=`${We.padEnd(ye-2).substring(0,ye-2)}`;yield{type:"visual_feedback",content:yn(`${De?`
648
+ `:""}${ee}
649
+ `)},De=!1}Z.push({role:"user",text:`[TOOL RESULT]: ERROR: ${de}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${de}`},Be++;continue}}if(t.onToolApproval&&(O==="write_file"||O==="update_file"||O==="exec_command")){let q=t.systemSettings||{},oe=q.autoExec,de=null,me=!1,We=!1,Oe=!1;if(O==="exec_command"){let{command:ve}=L(z.args),nt=(ve||"").trim(),Ae=(xt,Vt)=>{if(!Vt)return!1;let fn=Vt.split(",").map(Kt=>Kt.trim().toLowerCase()).filter(Boolean),st=xt.toLowerCase();return fn.some(Kt=>st.startsWith(Kt))},qe=Ae(nt,q.alwaysAskCommands),we=Ae(nt,q.autoApproveCommands);if(We=Ae(nt,q.autoDisallowCommands),qe?me=!0:(we||q.autoApproveGit&&/^git\s+commit\b/i.test(nt))&&(de="allow"),!me&&!de){if(q.networkAccess===!1){let Vt=nt.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),st=Vt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),Kt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),ot=!1;Kt.has(st)&&(ot=!0);let at=En=>Vt.slice(1).some(xn=>En.includes(xn)),Ct=En=>{let xn=Vt.findIndex(_n=>En.includes(_n)),Rs=Vt.findIndex(_n=>["run","exec","test"].includes(_n));return xn!==-1&&!(Rs!==-1&&Rs<xn)};st==="git"&&at(["clone","pull","push","fetch"])&&(ot=!0),st==="go"&&at(["get","install"])&&(ot=!0),st==="npm"&&Ct(["install","i","update","add"])&&(ot=!0),st==="yarn"&&Ct(["add","install","upgrade"])&&(ot=!0),st==="pnpm"&&Ct(["add","install","update"])&&(ot=!0),st==="bun"&&Ct(["add","install","update"])&&(ot=!0),st==="deno"&&at(["install","add"])&&(ot=!0),st==="pip"&&at(["install","download"])&&(ot=!0),st==="pip3"&&at(["install","download"])&&(ot=!0),st==="cargo"&&at(["install","add"])&&(ot=!0),["bash","sh","zsh","fish"].includes(st)&&at(["-c"])&&(ot=!0),st==="cmd"&&at(["/c"])&&(ot=!0),ot&&(de="deny",Oe=!0)}!de&&We&&(de="deny")}!me&&!de&&oe&&(de="allow")}else oe&&(de="allow");let ye=de,ee="";de==="deny"&&(Oe?ee="network":We?ee="settings":ee="prohibited");let le=!1,ie="",Ne=[],Qe=0,ge=!1;if(!ye){if(O==="write_file"||O==="update_file")try{let Ae=L(z.args),{path:qe}=Ae;if(qe){let we=Q.resolve(process.cwd(),qe),xt=at=>at?at.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,Ct=>Ct.toUpperCase()):"",Vt=xt(we),fn="",st=!1,Kt=await ws(),ot=xt(Kt?.file_focused);if(Kt&&ot===Vt&&Kt.full_content?(fn=Kt.full_content,st=!0):_e.existsSync(we)&&(fn=_e.readFileSync(we,"utf8"),st=!0),ie=fn,await ct.recordFileChange(we,fn),st){let at=fn;if(O==="write_file")at=Ae.content||Ae.newContent||"";else{let{patchPairs:Ct,allowMultiple:En,error:xn}=$o(Ae);if(xn){let Rt=`[TOOL RESULT]: ERROR: ${xn}`;Z.push({role:"user",text:Rt}),await $t("toolFailure"),t.onToolResult&&t.onToolResult("failure",O),yield{type:"tool_result",content:Rt,toolName:O},Be++;continue}let Rs=Ae.allowMultiple!==void 0?Ae.allowMultiple===!0||String(Ae.allowMultiple).toLowerCase()==="true":En;Qe=Ct.length;let _n=_o(fn,Ct,{allowMultiple:Rs});at=_n.content,Ne=_n.results;let mo=Ne.filter(Rt=>Rt.success),Ot=Ne.filter(Rt=>!Rt.success);if(mo.length===0){let Rt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Q.basename(we)}].
650
+ ${Ot.map(Gs=>` \u2022 ${Gs.error}`).join(`
651
+ `)}`,ks=`\u2714 Edited: ${Q.basename(we.replaceAll("\\","/"))}`,Hs=115;process.stdout.isTTY&&(Hs=process.stdout.columns-5||120);let As=Math.min(ks.length+4,Hs),go=`${ks.padEnd(As-2).substring(0,As-2)}`;yield{type:"visual_feedback",content:yn(`${De?`
652
+ `:""}${go}`)},De=!1,Z.push({role:"user",text:Rt}),await $t("toolFailure"),t.onToolResult&&t.onToolResult("failure",O),yield{type:"tool_result",content:Rt,toolName:O},Be++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Q.basename(we)}`},er(we,fn,at),le=!0,await new Promise(Ct=>setTimeout(Ct,50))}else if(O==="write_file"){let at=Ae.content||Ae.newContent||"",Ct=at.endsWith(`
653
+ `)?at:at+`
654
+ `;_e.existsSync(we)||(ge=!0,_e.mkdirSync(Q.dirname(we),{recursive:!0}),_e.writeFileSync(we,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Q.basename(we)}`},er(we,"",Ct),le=!0,await new Promise(En=>setTimeout(En,50))}}}catch(Ae){console.error("Simulation/Diff Error:",Ae)}let ve=null;Zi(Ae=>{ve=Ae});let nt=t.onToolApproval;if(ye=await new Promise(async Ae=>{let qe=setInterval(()=>{ve&&(Do.onIDEApproval&&Do.onIDEApproval(ve),clearInterval(qe),Ae(ve))},100);try{let we=await nt(O,z.args);clearInterval(qe),Ae(we)}catch{clearInterval(qe),Ae("deny")}}),Zi(null),O==="write_file"||O==="update_file"){let{path:Ae}=L(z.args);if(Ae){let qe=Q.resolve(process.cwd(),Ae);if(Ua(qe,ye),ye==="deny"&&ge&&_e.existsSync(qe))try{_e.unlinkSync(qe)}catch{}}}ye==="deny"&&(ee="user")}if(ye==="allow"&&le&&Po()){let{path:ve}=L(z.args),nt=Q.resolve(process.cwd(),ve),Ae=Ot=>Ot?Q.resolve(Ot).replace(/\\/g,"/").toLowerCase():"",qe=await ws(),we="";qe&&qe.file_focused&&Ae(qe.file_focused)===Ae(nt)&&qe.full_content&&(we=qe.full_content),!we&&_e.existsSync(nt)&&(we=_e.readFileSync(nt,"utf8"),we||(await new Promise(Ot=>setTimeout(Ot,100)),we=_e.readFileSync(nt,"utf8")));let xt=we.split(/\r?\n/),Vt=xt.length,fn=Buffer.byteLength(we,"utf8"),st="";ie&&(st=`Old File contents:
655
+ ${ie.split(/\r?\n/).map((Rt,ks)=>`${ks+1} | ${Rt}`).join(`
656
+ `)}
657
+
658
+ `);let Kt="";if(Vt<=100)Kt=xt.join(`
659
+ `);else{let Ot=xt.slice(0,50).join(`
660
+ `),Rt=xt.slice(-50).join(`
661
+ `);Kt=`${Ot}
662
+
663
+ ... [${Vt-100} lines truncated for history stability] ...
664
+
665
+ ${Rt}`}let ot="";if(O==="update_file"){let Ot=Mo(ie,we,Ne,12,t?.compressToolResults||Do?.systemSettings?.compressToolResults);ot=`SUCCESS: File [${ve}] updated via IDE Companion (May have user edits). [${Ne.length}/${Qe}] blocks applied.
666
+
667
+ ${Ot}`}else{let Ot=we.split(/\r?\n/),Rt=Ot.length,ks=Buffer.byteLength(we,"utf8"),Hs="";ie&&(Hs=`Old File contents:
668
+ ${ie.split(/\r?\n/).map((Gs,pl)=>`${pl+1} | ${Gs}`).join(`
669
+ `)}
670
+
671
+ `);let As="";if(Rt<=100)As=Ot.join(`
672
+ `);else{let go=Ot.slice(0,50).join(`
673
+ `),Gs=Ot.slice(-50).join(`
674
+ `);As=`${go}
675
+
676
+ ... [${Rt-100} lines truncated] ...
677
+
678
+ ${Gs}`}ot=`SUCCESS: File [${ve}] saved via IDE Companion (May have user edits).
679
+ - Stats: [${Rt} lines, ${(ks/1024).toFixed(1)} KB]
680
+ ${Hs}- Content Preview:
681
+
682
+ ${As}`}let Ct=`${ve?"\u2714":"\u2718"} ${O==="write_file"?"Created":"Edited"}: ${ve.replaceAll("\\","/")||"No File Changes"}`,En=115;process.stdout.isTTY&&(En=process.stdout.columns-5||120);let xn=Math.min(Ct.length+4,En),Rs=`${Ct.padEnd(xn-2).substring(0,xn-2)}`;yield{type:"visual_feedback",content:yn(`${De?`
683
+ `:""}${Rs}`)},De=!1;let _n=Date.now();G=_n,yield{type:"tool_time",content:_n-fe};let mo=`[TOOL RESULT]: ${ot}`;Z.push({role:"user",text:mo}),an=!0,await $t("toolSuccess"),t.onToolResult&&t.onToolResult("success",O),yield{type:"tool_result",content:ot,aiContent:mo,toolName:O},Be++;continue}if(ye==="deny"){let ve=`Permission Denied: Prohibited ${O==="exec_command"?"Command":"file edit"}.`;if(ee==="user"?ve="Permission Denied by User":ee==="settings"?ve="Permission Denied by User Policy":ee==="network"?ve="Permission Denied: Sandbox Network Access Disabled by User Policy.":ee==="prohibited"&&O==="exec_command"&&(ve="Permission Denied: Prohibited Command in User Policy"),O==="write_file"||O==="update_file"){let Ae=`\u2718 ${O==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(z.args).path.replaceAll("\\","/")||"..."}`,qe=115;process.stdout.isTTY&&(qe=process.stdout.columns-5||120);let we=Math.min(Ae.length+4,qe),xt=`${Ae.padEnd(we-2).substring(0,we-2)}`,Vt=` ${" ".repeat(we)} `;yield{type:"visual_feedback",content:yn(`${De?`
684
+ `:""}${xt}
685
+ `)},De=!1}O==="exec_command"&&(await new Promise(nt=>setTimeout(nt,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ve}`),await new Promise(nt=>setTimeout(nt,50)),t.onExecEnd&&t.onExecEnd()),Z.push({role:"user",text:`[TOOL RESULT]: DENIED: ${ve}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${ve}`},await $t("toolDenied"),t.onToolResult&&t.onToolResult("denied",O),Be++;continue}}if(pe){let v=115;process.stdout.isTTY&&(v=process.stdout.columns-5||120);let q=Math.min(pe.length+4,v),oe=`${pe.padEnd(q-2).substring(0,q-2)}`;yield{type:"visual_feedback",content:yn(`${De?`
686
+ `:""}${oe}${pe.includes("\u2714")&&(pe.includes("Created")||pe.includes("Edited"))?"":`
687
+ `}`)},De=!1}if(G>0){let v=Date.now()-G,q=Math.max(0,1e3-v);q>0&&await new Promise(oe=>setTimeout(oe,q))}let Un={chatId:c,history:e,onChunk:v=>t.onExecChunk?t.onExecChunk(v):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:hn(Ce),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Ce,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(O==="write_file"||O==="update_file")try{let{path:v}=L(z.args);if(v){let q=Q.resolve(process.cwd(),v),oe=await ws();oe&&oe.file_focused===q&&oe.full_content&&(Un.forcedContent=oe.full_content)}}catch{}Zt.push(O);let be=await lo(O,z.args,Un);if((O==="write_file"||O==="update_file")&&be.startsWith("SUCCESS")){let{path:v}=L(z.args);if(v){let q=Q.resolve(process.cwd(),v);Fa(q)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Wt=Date.now();G=Wt,yield{type:"tool_time",content:Wt-fe},en=Wt;let zt=null;if(typeof be=="object"&&be.binaryPart&&(zt=be.binaryPart,be=be.text),O==="search_keyword"){let{keyword:v,path:q}=L(z.args),oe=typeof be=="string"&&be.startsWith("[GLOB]");oe&&(be=be.slice(6).trimStart());let de=typeof be=="string"&&be.startsWith("[DIR]");de&&(be=be.slice(5).trimStart());let me=0;if(be){let Ne=be.match(/Found (\d+) match/i);Ne&&(me=parseInt(Ne[1]))}let We=q?q.replace(/[\/\\]+$/,""):null,Oe=We&&We!=="."?`"${oe?q:de?`${We}/*`:We}"`:"./",ye=`${v?"\u2714":"\u2718"} Searched: "${v||""}" in ${Oe.replaceAll("\\","/")} \u2192 ${me} Match${me===1?"":"es"}`,ee=115;process.stdout.isTTY&&(ee=process.stdout.columns-5||120);let le=Math.min(ye.length+4,ee),ie=`${ye.padEnd(le-2).substring(0,le-2)}`;yield{type:"visual_feedback",content:yn(`${De?`
688
+ `:""}${ie}
689
+ `)},De=!1}if(O==="EmergencyRollback"){let{method:v}=L(z.args);if(v==="forceRevert"){let q=0;if(be){let ye=be.match(/Total\s*:\s*(\d+)/i);ye&&(q=parseInt(ye[1]))}let de=be&&be.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${q} file${q===1?"":"s"} processed`,me=115;process.stdout.isTTY&&(me=process.stdout.columns-5||120);let We=Math.min(de.length+4,me),Oe=`${de.padEnd(We-2).substring(0,We-2)}`;yield{type:"visual_feedback",content:yn(`${De?`
690
+ `:""}${Oe}
691
+ `)},De=!1}}if(O==="todo"){let{method:v,tasks:q,markDone:oe}=L(z.args),de="",me=[],We=Oe=>{if(!Oe)return[];let ye=Array.isArray(Oe)?Oe:[];if(ye.length===0&&typeof Oe=="string"){let ee=Oe.trim();if(ee.startsWith("[")&&ee.endsWith("]")){let le=ee.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);le?ye=le.map(ie=>ie.slice(1,-1).replace(/\\(.)/g,"$1")):ye=ee.slice(1,-1).split(",").map(ie=>ie.trim()).filter(Boolean)}else ye=Oe.split(`
692
+ `)}return ye.filter(ee=>String(ee).trim()).map(ee=>{let le=String(ee).trim();return le.startsWith("- [")?le.substring(6).trim():le})};if(v==="create"?(de="\x1B[32m\u2192\x1B[0m Created Plan",me=We(q).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="append"?(de="\x1B[34m\u2795\x1B[0m Added Plan",me=We(q).map(Oe=>`\x1B[90m\u25CB\x1B[0m ${Oe}`)):v==="get"&&(de=oe?"\x1B[36m\u21BB\x1B[0m Updated Plan":"\x1B[35m\u2022\x1B[0m Reviewed Plan",me=(be||"").split(`
693
+ `).slice(1).join(`
694
+ `).split(`
695
+ `).filter(ye=>ye.trim().startsWith("- [")).map(ye=>{let ee=ye.trim(),le=ee.startsWith("- [x]");return`${le?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${le?"\x1B[90m":"\x1B[37m"}${ee.substring(6).trim()}\x1B[0m`})),de&&me.length>0){let Oe=[`${de}`,...me.map(ye=>` ${ye}`)].join(`
696
+ `);yield{type:"visual_feedback",content:yn(`${De?`
697
+ `:""}${Oe}
698
+ `)},De=!1}}O==="exec_command"&&t.onExecEnd&&(await new Promise(v=>setTimeout(v,800)),t.onExecEnd());let On=be&&be.startsWith("DENIED:");be&&!be.startsWith("ERROR:")&&!On?(await $t("toolSuccess"),t.onToolResult&&t.onToolResult("success",O)):On||(await $t("toolFailure"),t.onToolResult&&t.onToolResult("failure",O));let jt=(be||"").toString().replaceAll("[UI_CONTEXT]","");jt.includes("[[VERIFIED]]")&&(jt=jt.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
699
+ `));let $n;if(jt.startsWith("[[SAME]]")){let q=jt.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),oe=q.filter(me=>me.startsWith("SUCCESS:")||me.trim().startsWith("- Stats:"));$n=`[TOOL RESULT]: ${oe.length>0?oe.join(`
700
+ `):q.slice(0,2).join(`
701
+ `)}
702
+ [SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else $n=`[TOOL RESULT]: ${jt}`;Z.push({role:"user",text:$n,binaryPart:zt}),an=!0;let ke=`[TOOL RESULT]: ${be.replaceAll(`[[VERIFIED]]
703
+ `,"").replaceAll(`
704
+ [[/VERIFIED]]`,"")||""}`;(O==="view_file"||O==="web_scrape"||O==="file_map")&&(ke=`[TOOL RESULT]: ${pe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:ke,aiContent:$n,binaryPart:zt,toolName:O},O==="memory"&&be.includes("SUCCESS")&&(yield{type:"memory_updated"}),Be++}if(h==="Google"&&Tn&&Date.now()-Yo>=150){yield*os();let z=Ws(Tn);for(let fe of z)yield fe;Tn="",Yo=Date.now()}}N.usageMetadata&&(kn=N.usageMetadata),kn&&(yield{type:"liveTokens",content:kn.totalTokenCount})}if(Te&&(Te=!1,Ut?He+="</think>":(re+="</think>",h==="Google"?Tn+="</think>":yield{type:"text",content:"</think>"})),Ut&&He.length>0){let N=0,te=Math.min(et.length,He.length);for(let H=te;H>0;H--)if(et.endsWith(He.substring(0,H))){N=H;break}let U=He.substring(N);if(U){let xe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(et)?U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):U.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(xe)if(re+=xe,h==="Google")Tn+=xe;else{yield*os();let he=Ws(xe);for(let Re of he)yield Re}}Ut=!1,He=""}if(yield*os(),Mt)break;let js=(re||"").trim(),ll=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(js.toLowerCase())||/\[\[END\]\]/i.test(js.toLowerCase()),cl=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(js.toLowerCase()),fl=Z.length>0||Dt!==null,qo=js.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),dl=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(qo),ul=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(qo.trim()),hl=/[.!?}"'`’“”]$|```$/s.test(qo)||ul||dl;!ll&&!cl&&!fl&&js.length>0,Je=!0,await $t("agent",h)}catch(Ge){if(Mt){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
705
+
706
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ge).includes("Incomplete JSON segment at the end")){Te&&(Te=!1,Ut?He+="</think>":(re+="</think>",yield{type:"text",content:"</think>"})),Je=!0,await $t("agent",h);break}if(Te&&(Te=!1,Ut?He+="</think>":re+="</think>"),Ut&&He.length>0){let ss=0,nn=Math.min(et.length,He.length);for(let vt=nn;vt>0;vt--)if(et.endsWith(He.substring(0,vt))){ss=vt;break}let It=He.substring(ss);if(It){let cn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(et)?It.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):It.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");cn&&(re+=cn)}Ut=!1,He=""}let ae=Ge instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ge.message).error.message).error.message}catch{return String(Ge)}})():String(Ge),ln=new Date().toLocaleString(),Bt=Q.join(dn,"agent");_e.existsSync(Bt)||_e.mkdirSync(Bt,{recursive:!0}),_e.appendFileSync(Q.join(Bt,"error.log"),`ERROR [${ln}]: ${ae}
707
+
708
+ ----------------------------------------------------------------------
709
+
710
+ `);let tn=Ge.status||Ge.statusCode||Ge.code;if(!(tn&&(tn>=500&&tn<600||tn===408||tn===429)||!tn&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ge))||/code[ :]+(5\d\d|408|429)/i.test(String(Ge))||/(500|503|408|429)/.test(String(Ge))))){if(Ue<wn-3)throw Ge;yield{type:"text",content:ae},yield{type:"status",content:"Error Occured"}}if(re.trim().length>0||Ve>1)if(Ve<=wn){Ve++;let ss=Math.min(1e3*Math.pow(2,Ve-1),24e3);if(re.trim().length>0){E.push({role:"agent",text:re});let nn=`[SYSTEM]
711
+ - SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
712
+ - NO REPETITION: Do not repeat any text already written
713
+ - NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block </think> BEFORE CHAT OUTPUT
714
+ - MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
715
+ - STEALTH: Do not mention/apologize for cutoff [/SYSTEM]`;Z.length>0?Z.forEach((It,vt)=>{vt===Z.length-1?E.push({...It,text:`${It.text}
716
+
717
+ ${nn}`}):E.push(It)}):E.push({role:"user",text:nn}),et+=re}for(let nn=ss/1e3;nn>0&&!Mt;nn--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ve}/${wn}) [Retrying in ${nn.toFixed(0)}s]...`},await new Promise(It=>setTimeout(It,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${wn} times)
718
+ Error log can be found in \`/export logs\``);else if(Ue<=wn){Ue++,Ve=1,et="";let ss=Math.min(1e3*Math.pow(2,Ue-1),32e3),nn=.8+Math.random()*.4,It=Math.round(ss*nn);Zn=!0,yield{type:"status",content:`Trying to reach ${n} (${Ue}/${wn}) [Retrying in ${(It/1e3).toFixed(0)}s]`};for(let vt=It/1e3;vt>0&&!Mt;vt--)yield{type:"status",content:`Trying to reach ${n} (${Ue}/${wn}) [Retrying in ${vt.toFixed(0)}s]`},await new Promise(cn=>setTimeout(cn,1e3));yield{type:"status",content:`Trying to reach ${n}`}}else throw new Error(`Model ${n} cannot be reached. (Failed ${wn} times)
719
+ Error log can be found in \`/export logs\``)}}if(kn){let Te=kn.totalTokenCount||0,Ge=kn.cachedContentTokenCount||0,ae=(kn.candidatesTokenCount||0)+(kn.thoughtsTokenCount||0);await Ht("tokens",Te,h,Ce),Ge>0&&await Ht("cachedTokens",Ge,h,Ce),ae>0&&await Ht("candidateTokens",ae,h,Ce),yield{type:"usage",content:kn}}Sr.push(re);let Dn=re;re.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Dn=re.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let ts=Ka(re),Cn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ts.toLowerCase())||/\[\[END\]\]/i.test(ts.toLowerCase())||!0,rd=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ts.toLowerCase()),ad=Be>0;yield{type:"status",content:"Thinking"};let il=Zf(re,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ns=(Cn||Z.length===0)&&!Ft&&!Sn&&!An;if(ns=Z.length===0?ns:!1,ns=es||ho?!1:ns,re&&re.trim().endsWith('")]')&&Z.length===0&&(ns=!1),ns){let Te=Sr.join(`
720
+ `),Ge=Te.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:A,fullAgentTextRaw:Te,history:[...E],needTitle:R}},E.length>0&&E[E.length-1].role==="agent"?E[E.length-1].text=Ge:E.push({role:"agent",text:Ge}),E.forEach(ae=>{if(ae.role==="user"&&ae.text&&(ae.text=ae.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ae.text=ae.text.replaceAll(`
721
+
722
+ [SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
723
+ `,"").replaceAll(`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY
724
+ **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
725
+ `,"").replaceAll(`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
726
+ `,"").replaceAll(/\n\[SYSTEM\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/SYSTEM\]/g,""),ae.text=ae.text.replaceAll(/\n\[SYSTEM\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/SYSTEM\]/g,""),(h==="Mistral"||h==="Google"&&n?.toLowerCase().startsWith("gemma"))&&ae.text.startsWith("[TOOL RESULT]"))){let Bt=`
727
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`,tn=`
728
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]`;ae.text=ae.text.replaceAll(tn,"").replaceAll(Bt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ns)break;let rl=il.trim()||"*Working...*";if(E.push({role:"agent",text:rl}),Z.length>0||an){if(Z.length>0){let Te=Z.map(Bt=>Bt.text).join(`
729
+
730
+ `),ae=(re.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;if(Z.length<ae){Te+=`
731
+
732
+ [SYSTEM] Only ${Z.length} out of ${ae} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`;let Bt=ae-Z.length;for(let tn=0;tn<Bt;tn++)await $t("toolFailure")}let ln=Z.find(Bt=>Bt.binaryPart)?.binaryPart||null;E.push({role:"user",text:Te,binaryPart:ln})}}else ho||es?(E.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}),await $t("toolFailure")):E.push({role:"user",text:`[SYSTEM] ${Sn&&!Ft?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Ft?" OVER THINKING":" LOOP"} DETECTED by Internal System${Ft?" for current EFFORT_LEVEL":""}. ${Ft?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Ft=!1,Sn=!1,An=!1;l?.advanceRollback&&await Vn.recordTurnDelta(c,j+1,Zt),ho=Be>0||an}}catch(T){let I=(T instanceof Error?(()=>{try{return JSON.parse(JSON.parse(T.message).error.message).error.message}catch{return T.message||String(T)}})():String(T)).replace(/^(Error:\s*)+/i,""),_=new Date().toLocaleString(),M=Q.join(dn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${I.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":I}
733
+ \u2800`},_e.existsSync(M)||_e.mkdirSync(M,{recursive:!0}),_e.appendFileSync(Q.join(M,"error.log"),`CRITICAL ERROR [${_}]: ${T}
734
+
735
+ ----------------------------------------------------------------------
736
+
737
+ `),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${I}`}}finally{w&&(clearInterval(w),w=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await ct.commitTransaction(),l?.advanceRollback&&await Vn.cleanup(c),await ws()}yield{type:"status",content:null}},jg=async(n,e,t=null,o=null,s=50,i=null,r=!1)=>{let a=await Qt(),d={...a,...e},c=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,f=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,l=new Date,u=`${l.getFullYear()}-${l.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(l.getDate()).padStart(2,"0")}, ${l.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}).replace(":","-")}`,p=(T=>{if(!T)return null;let E=T.toLowerCase();return E==="google"?"Google":E==="deepseek"?"DeepSeek":E==="openrouter"?"OpenRouter":E==="nvidia"?"NVIDIA":E==="mistral"?"Mistral":E==="ollama"?"Ollama":null})(f),m=d?.systemSettings?.CustomSubAgent?d?.systemSettings?.SubAgentModel:null,y=d?.systemSettings?.CustomSubAgent?d?.systemSettings?.SubAgentProvider:null,g=null;if(m==="ENV"?(g=c,c&&p&&(d.aiProvider=p)):m&&m!=="Default"?(g=m,y&&(d.aiProvider=y)):c&&p&&(d.aiProvider=p),d.aiProvider){let T=await Xo(d.aiProvider);T&&(d.apiKey=T)}let S=T=>{if(!T||typeof T!="string")return{allowed:!0};let E=[/rm\s+-[rf]{1,2}\s+[\/*.]/i,/rmdir\s+\/[sq]/i,/del\s+\/[fsq]/i,/\bformat\b\s+[a-z]:/i,/mkfs/i,/dd\s+if=/i,/\b(shutdown|reboot|poweroff|init\s+0|init\s+6)\b/i,/chmod\s+(-R\s+)?777\s+[\/*.]/i,/chown\s+(-R\s+)?root/i,/git\s+push\s+.*--force/i,/git\s+clean\s+-fdx/i,/\bsudo\s+su\b/i,/\bsu\s+-\b/i];for(let I of E)if(I.test(T))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${I.source}"`};return{allowed:!0}},b=t||g||e?.modelName||e?.activeModel||a.activeModel,x=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",k=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
738
+ TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' STRUCTURED STRING IN CHAT RESPONSE \u2190 MANDATORY
739
+ TOOL RULES:
740
+ - JSON ESCAPE ALL LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
741
+ - SAME file, MULTIPLE edits? ONE PatchFile (\u226415 blocks) \u2190 PRIORITY
742
+ - Need text or huge files? CodeSearch > Full Read
743
+ - MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
744
+ - Restricted Shell Access, No Deletion
745
+ - DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
746
+ - ONLY valid tools and syntax defined below are allowed
747
+ - Stuck on syntax error? Move-on & Report > Time waste
748
+
749
+ **PROVIDED TOOLS (STRING BASED PROTOCOL)**
750
+ -- Communication Tools --
751
+ - [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Communicate with USER. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Suggest best options; no preferences. Keep titles short
752
+ ${r?'- [tool:functions.AskMain(question="...")]. Communicate with PARENT/MAIN AGENT. When clarification/decision is needed for a task':""}
753
+
754
+ -- Web Tools --
755
+ - [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: unknown info/docs. aiMode: LLM search
756
+ - [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
757
+
758
+ -- Workspace Tools --
759
+ - [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool false", regex="bool auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
760
+ - [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. Minimize recursion
761
+ - [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. View files
762
+ - [tool:functions.PatchFile(path="...", allowMultiple="bool, default: false", searchContent1="search string OR ^LINE:start..end$", newContent1="...", ...MAX15)]. TARGET MINIMAL searchContent. Line Ranges MUST for large searchContent AND escape sequences. ^...$ MUST for line ranges
763
+ - [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. VERIFY IMPORTS
764
+ - [tool:functions.Run(command="...")]. Runs ${x==="Windows"?Hn()?"WINDOWS POWERSHELL":"WINDOWS CMD":"BASH"} command. Destructive/Irreversible ops \u2192 Ask user`.trim(),C=`=== START SYSTEM PROMPT ===
765
+ You are a subagent helping the main FluxFlow CLI agent
766
+ Your task is: "${n}"
767
+
768
+ ${k.trimEnd()}
769
+
770
+ -- THINKING GUIDANCE --
771
+ NO EXPLICIT THINKING REQUIRED. FOCUS ON TASK COMPLETION
772
+ Keep main focus on tools and task, not chatting
773
+ On task completion, provide a detailed structured summary preferebly in Tables/Bullet Points with file modified info, if any task failed report back in detail, NO HALLUCINATIONS
774
+
775
+ CWD: ${process.cwd()}
776
+ Current Time: ${u}
777
+ === END SYSTEM PROMPT ===`,R=[{role:"user",text:`Complete this task: ${n}`}],A=0,w="";for(;A<s;){if(Mt){if(e?.taskId&&typeof ze<"u"){let D=ze.find(F=>F.id===e.taskId);D&&(D.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(e?.taskId&&typeof ze<"u"){let D=ze.find(F=>F.id===e.taskId);if(D&&D.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let T=R.map(D=>({role:D.role==="user"?"user":"model",parts:[{text:D.text}]}));i&&i(`[Subagent Turn ${A+1}]...`);let _=((await Fo(d,b,T,C,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();w=_,i&&i(`[Subagent Response]
778
+ ${_}
779
+ `),R.push({role:"agent",text:_});let M=Bo(_);if(M.length===0)break;let W=M.filter(D=>D.toolName.toLowerCase()==="askmain"||D.toolName.toLowerCase()==="ask_main"),B=!1,K="";for(let D of M){if(Mt){if(e?.taskId&&typeof ze<"u"){let $=ze.find(P=>P.id===e.taskId);$&&($.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(e?.taskId&&typeof ze<"u"){let $=ze.find(P=>P.id===e.taskId);if($&&$.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=D.toolName.toLowerCase();if(F==="askmain"||F==="ask_main"){if(B)continue;B=!0;let $="";if(W.length===1?$=L(W[0].args).question||W[0].args:$=W.map((P,V)=>{let X=L(P.args);return`Q${V+1}: ${X.question||P.args}`}).join(`
780
+ `),e.onAskMain){i&&i(`[Executing Tool] AskMain("${$}")...`);let P=await e.onAskMain($);i&&i(`[Tool Result]
781
+ Answer from Main Agent: ${P}
782
+ `),K+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${P}
783
+
784
+ `,await $t("toolSuccess")}else K+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
785
+
786
+ `;continue}if(!(o?o.some($=>$.toLowerCase()===F):!0)){let $=`ERROR: Tool [${D.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${D.toolName} - not allowed
787
+ `),K+=`${$}
788
+
789
+ `;continue}if(F==="exec_command"||F==="execcommand"||F==="run"){let $=L(D.args).command||"",P=S($);if(!P.allowed){let V=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${P.reason}`;i&&i(`[Blocked Command] ${$} - ${P.reason}
790
+ `),K+=`${V}
791
+
792
+ `;continue}}let Ee="";if(F==="web_search"||F==="websearch")Ee=`\u2714 \x1B[95mSearched\x1B[0m: ${L(D.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")Ee=`\u2714 \x1B[95mScraped\x1B[0m: ${L(D.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let $=L(D.args),P=$.keyword||"",V=$.path||"";Ee=`${P?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${P||"No Query"}${V?` \u2192 ${V.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")Ee=`\u2714 \x1B[95mRead\x1B[0m: ${(L(D.args).path||"").replaceAll("\\","/")}`;else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let $=L(D.args).path||null,P=L(D.args).recurse||0;Ee=`${$?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${$?`${$.replaceAll("\\","/")}${P>0?`${$.endsWith("/")?`*${P}`:`/*${P}`}`:`${$.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let $=L(D.args).path||null;Ee=`${$?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${$?`${$.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="update_file"||F==="updatefile"||F==="patchfile"||F==="patch_file"||F==="patchfile"||F==="updatefile"){let $=L(D.args).path||null,P=L(D.args).content||null;Ee=`${$?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${$?`${$.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let $=L(D.args).command||null;Ee=`${$?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${$?$.slice(0,100)+($.length>100?"...":""):"No Command"}`}else if(F==="file_map"||F==="filemap"){let $=L(D.args).path||"";Ee=`${$?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${$?`${$.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:$}=L(D.args),P=parseFloat($)||0;P<10&&(P=10),P>180&&(P=180),Ee=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(X=>{if(X>=60){let Pe=Math.floor(X/60),Le=X%60;return`${Pe}m${Le>0?` ${Le}s`:""}`}return`${X}s`})(P)}`}else{let $=or[F]||D.toolName,P=bs(F,D.args);Ee=`\u2714 \x1B[95m${$}\x1B[0m${P?`: ${P}`:""}`}e.onVisualFeedback&&Ee&&e.onVisualFeedback(Ee),i&&i(`[Executing Tool] ${D.toolName}(${D.args})...`);try{let $=await lo(D.toolName,D.args,{...e,mode:"Flux"});if(i&&i(`[Tool Result]
793
+ ${$}
794
+ `),K+=`[TOOL RESULT for ${D.toolName}]: ${$}
795
+
796
+ `,await $t("toolSuccess"),F==="patchfile"||F==="update_file"||F==="updatefile"||F==="patch_file"){if($){let P=$.split(`
797
+ `),V=0,X=0,Pe=!1;for(let Le of P){if(Le.includes("[DIFF_START]")){Pe=!0;continue}if(Le.includes("[DIFF_END]")){Pe=!1;continue}Pe&&(/^\+\d+/.test(Le)?V++:/^\-\d+/.test(Le)&&X++)}(V>0||X>0)&&(await Ht("linesAdded",V),await Ht("linesRemoved",X))}}else if((F==="writefile"||F==="write_file")&&$){let P=$.match(/- Stats: \[(\d+) lines/),V=P?parseInt(P[1]):0,X=0;if($.includes("Old File contents:")){let Pe=!1;for(let Le of $.split(`
798
+ `)){if(Le.includes("Old File contents:")){Pe=!0;continue}Pe&&(Le.trim()===""?Pe=!1:/^\d+ \|/.test(Le)&&X++)}}(V>0||X>0)&&(await Ht("linesAdded",V),await Ht("linesRemoved",X))}}catch($){let P=`ERROR: Execution failed for [${D.toolName}]: ${$.message}`;i&&i(`[Tool Error] ${P}
799
+ `),K+=`${P}
800
+
801
+ `,await $t("toolFailure")}}let Y="";if(e?.taskId&&typeof ze<"u"){let D=ze.find(F=>F.id===e.taskId);if(D&&D.pendingSteerMessages&&D.pendingSteerMessages.length>0){let F=[...D.pendingSteerMessages];D.pendingSteerMessages=[];for(let se of F)Y+=`
802
+
803
+ [STEERING INSTRUCTION FROM MAIN AGENT]: ${se}`,i&&i(`[Subagent Steered] ${se}`)}}let Se=(K.trim()+Y).trim();R.push({role:"user",text:Se}),A++}return w};export{mn as a,Jr as b,Qu as c,Zu as d,Kl as e,Qr as f,eh as g,sc as h,th as i,co as j,Na as k,qm as l,zm as m,L as n,xd as o,ai as p,Vs as q,Rd as r,kd as s,ct as t,cs as u,Zd as v,Ll as w,eu as x,tu as y,nu as z,su as A,ou as B,du as C,uu as D,Rn as E,Fl as F,Js as G,Ht as H,Ul as I,jr as J,fs as K,Ef as L,Tp as M,bp as N,Xm as O,Po as P,Jm as Q,Kf as R,Pg as S,Dg as T,fr as U,Fg as V,Ug as W,od as X,Bg as Y,Wg as Z,jg as _};