fluxflow-cli 3.22.0 → 3.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/ai-7LT7T34E.js +1 -0
- package/dist/chunks/ai-NDNZ4XGW.js +1 -0
- package/dist/chunks/ai-O2AHKT2Q.js +1 -0
- package/dist/chunks/ai-OLHI3UWZ.js +1 -0
- package/dist/chunks/ai-T2SZGY7Y.js +1 -0
- package/dist/chunks/ai-VMV4EAEQ.js +1 -0
- package/dist/chunks/app-2BDYKT26.js +226 -0
- package/dist/chunks/app-4VRQVBXL.js +226 -0
- package/dist/chunks/app-AASWJUCP.js +226 -0
- package/dist/chunks/app-DLGENJXK.js +226 -0
- package/dist/chunks/app-OIIPCXZF.js +226 -0
- package/dist/chunks/app-ZUY2BADH.js +226 -0
- package/dist/chunks/chunk-3VSDH7DF.js +3 -0
- package/dist/chunks/chunk-77P7CACS.js +3 -0
- package/dist/chunks/chunk-IW2KLAXM.js +803 -0
- package/dist/chunks/chunk-O4A5T73D.js +801 -0
- package/dist/chunks/chunk-UKBUOJ3P.js +803 -0
- package/dist/chunks/chunk-VBKX2PU3.js +803 -0
- package/dist/chunks/chunk-Y2EZRWRZ.js +803 -0
- package/dist/chunks/chunk-ZQZIEF5I.js +803 -0
- package/dist/chunks/settings-57QAZRCP.js +1 -0
- package/dist/chunks/settings-DTH5C6BO.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/model_config.json +591 -0
- package/dist/package.json +3 -3
- package/model_config.json +591 -571
- package/package.json +3 -3
|
@@ -0,0 +1,803 @@
|
|
|
1
|
+
import{b as Ko}from"./chunk-7WH5DREO.js";import{c as dn,f as Ze,g as Kt}from"./chunk-77P7CACS.js";import{a as Ys,b as $s,c as V,d as re}from"./chunk-SIINYZWE.js";import{c as Mn,d as cn,e as go,f as Cs,g as Os,h as qo,i as qt,j as Mt,k as Vt,l as _n,m as Bn,n as tn,o as fn,p as as,q as Vo,r as Wn,s as ls}from"./chunk-SGZ2OI72.js";import{a as Ve,c as yo}from"./chunk-56EJGQU3.js";import{a as pl,b as Tr}from"./chunk-6DHFEWGX.js";var Xo=pl((wo,br)=>{(function(n,e){typeof wo=="object"&&typeof br<"u"?e(wo):typeof define=="function"&&define.amd?define(["exports"],e):e(n.WHATWGFetch={})})(wo,(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 b=w.shift();return{done:b===void 0,value:b}}};return t.iterable&&(T[Symbol.iterator]=function(){return T}),T}function c(w){this.map={},w instanceof c?w.forEach(function(T,b){this.append(b,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 b=this.map[w];this.map[w]=b?b+", "+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 b in this.map)this.map.hasOwnProperty(b)&&w.call(T,this.map[b],b,this)},c.prototype.keys=function(){var w=[];return this.forEach(function(T,b){w.push(b)}),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,b){w.push([b,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,b){w.onload=function(){T(w.result)},w.onerror=function(){b(w.error)}})}function u(w){var T=new FileReader,b=l(T);return T.readAsArrayBuffer(w),b}function h(w){var T=new FileReader,b=l(T),v=/charset=([A-Za-z0-9_-]+)/.exec(w.type),_=v?v[1]:"utf-8";return T.readAsText(w,_),b}function m(w){for(var T=new Uint8Array(w),b=new Array(T.length),v=0;v<T.length;v++)b[v]=String.fromCharCode(T[v]);return b.join("")}function p(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=p(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):t.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||i(w))?this._bodyArrayBuffer=p(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(m(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 E(w,T){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');T=T||{};var b=T.body;if(w instanceof E){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,!b&&w._bodyInit!=null&&(b=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 $=new AbortController;return $.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&b)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(b),(this.method==="GET"||this.method==="HEAD")&&(T.cache==="no-store"||T.cache==="no-cache")){var v=/([?&])_=[^&]*/;if(v.test(this.url))this.url=this.url.replace(v,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function x(w){var T=new FormData;return w.trim().split("&").forEach(function(b){if(b){var v=b.split("="),_=v.shift().replace(/\+/g," "),$=v.join("=").replace(/\+/g," ");T.append(decodeURIComponent(_),decodeURIComponent($))}}),T}function C(w){var T=new c,b=w.replace(/\r?\n[\t ]+/g," ");return b.split("\r").map(function(v){return v.indexOf(`
|
|
2
|
+
`)===0?v.substr(1,v.length):v}).forEach(function(v){var _=v.split(":"),$=_.shift().trim();if($){var G=_.join(":").trim();try{T.append($,G)}catch(ce){console.warn("Response "+ce.message)}}}),T}y.call(E.prototype);function A(w,T){if(!(this instanceof A))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(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new c(this.headers),url:this.url})},A.error=function(){var w=new A(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var R=[301,302,303,307,308];A.redirect=function(w,T){if(R.indexOf(T)===-1)throw new RangeError("Invalid status code");return new A(null,{status:T,headers:{location:w}})},n.DOMException=e.DOMException;try{new n.DOMException}catch{n.DOMException=function(T,b){this.message=T,this.name=b;var v=Error(T);this.stack=v.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function k(w,T){return new Promise(function(b,v){var _=new E(w,T);if(_.signal&&_.signal.aborted)return v(new n.DOMException("Aborted","AbortError"));var $=new XMLHttpRequest;function G(){$.abort()}$.onload=function(){var z={statusText:$.statusText,headers:C($.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&($.status<200||$.status>599)?z.status=200:z.status=$.status,z.url="responseURL"in $?$.responseURL:z.headers.get("X-Request-URL");var $e="response"in $?$.response:$.responseText;setTimeout(function(){b(new A($e,z))},0)},$.onerror=function(){setTimeout(function(){v(new TypeError("Network request failed"))},0)},$.ontimeout=function(){setTimeout(function(){v(new TypeError("Network request timed out"))},0)},$.onabort=function(){setTimeout(function(){v(new n.DOMException("Aborted","AbortError"))},0)};function ce(z){try{return z===""&&e.location.href?e.location.href:z}catch{return z}}if($.open(_.method,ce(_.url),!0),_.credentials==="include"?$.withCredentials=!0:_.credentials==="omit"&&($.withCredentials=!1),"responseType"in $&&(t.blob?$.responseType="blob":t.arrayBuffer&&($.responseType="arraybuffer")),T&&typeof T.headers=="object"&&!(T.headers instanceof c||e.Headers&&T.headers instanceof e.Headers)){var ge=[];Object.getOwnPropertyNames(T.headers).forEach(function(z){ge.push(r(z)),$.setRequestHeader(z,a(T.headers[z]))}),_.headers.forEach(function(z,$e){ge.indexOf($e)===-1&&$.setRequestHeader($e,z)})}else _.headers.forEach(function(z,$e){$.setRequestHeader($e,z)});_.signal&&(_.signal.addEventListener("abort",G),$.onreadystatechange=function(){$.readyState===4&&_.signal.removeEventListener("abort",G)}),$.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}k.polyfill=!0,e.fetch||(e.fetch=k,e.Headers=c,e.Request=E,e.Response=A),n.Headers=c,n.Request=E,n.Response=A,n.fetch=k,Object.defineProperty(n,"__esModule",{value:!0})}))});import Lf from"dotenv";import{GoogleGenAI as Ka,ThinkingLevel as rt,HarmBlockThreshold as Kn,HarmCategory as Xn}from"@google/genai";import Al,{promises as Rr}from"node:fs";import{resolve as kr}from"node:path";var ld=Tr(Xo(),1),Er="11434",xr=`http://127.0.0.1:${Er}`,ml="0.6.3",gl=Object.defineProperty,yl=(n,e,t)=>e in n?gl(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Jo=(n,e,t)=>(yl(n,typeof e!="symbol"?e+"":e,t),t),ei=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)}},ti=class{constructor(e,t,o){Jo(this,"abortController"),Jo(this,"itr"),Jo(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.")}},ni=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 ei(e,n.status)};function wl(){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 Sl(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 Tl=(n,e)=>n[e],si=async(n,e,t={})=>{let o={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${ml} (${wl()})`};t.headers=Sl(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?Tl(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)},Qo=async(n,e,t)=>{let o=await si(n,e,{headers:t?.headers});return await ni(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 si(n,e,{method:"POST",body:i,signal:o?.signal,headers:o?.headers});return await ni(r),r},bl=async(n,e,t,o)=>{let s=await si(n,e,{method:"DELETE",body:JSON.stringify(t),headers:o?.headers});return await ni(s),s},El=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)}},xl=n=>{if(!n)return xr;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=Er);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},Rl=Object.defineProperty,kl=(n,e,t)=>e in n?Rl(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Zo=(n,e,t)=>(kl(n,typeof e!="symbol"?e+"":e,t),t),oi=class{constructor(e){Zo(this,"config"),Zo(this,"fetch"),Zo(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=xl(e?.host??xr)),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=El(r.body),d=new ti(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 bl(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 Qo(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 Qo(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Qo(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()}},fd=new oi;var md=Tr(Xo(),1),zs=class extends oi{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(Al.existsSync(e)){let t=await Rr.readFile(kr(e));return Buffer.from(t).toString("base64")}}catch{}return e}async fileExists(e){try{return await Rr.access(e),!0}catch{return!1}}async create(e){if(e.from&&await this.fileExists(kr(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)}},gd=new zs;import{execSync as Cl}from"child_process";import{spawn as ii}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),m=h.trim(),p=m===""||/^,\s*\w+\s*=/.test(m)||m.startsWith(")")&&(m.length===1||/^\)\s*([,\]\s]|\[\[?tool:)/i.test(m));if(p&&h.startsWith(`
|
|
5
|
+
`)){let y=m.split(`
|
|
6
|
+
`)[0];if(!y.includes("=")&&!y.includes(")")){c=l+1;continue}}if(p){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 So=null;try{let n=await import("node-pty");So=n.default||n}catch{}var Ed=!!So,To=n=>typeof n!="string"?n:n.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),ri=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 m=0;m<o&&m<h.length;m++)h[m]=" ";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
|
+
`)},ht=null,qs=!1,xd=n=>{try{ht&&(qs&&typeof ht.write=="function"?ht.write(n):ht.stdin&&ht.stdin.writable&&ht.stdin.write(n))}catch{}},Rd=()=>{if(ht){try{qs&&typeof ht.destroy=="function"?ht.destroy():typeof ht.kill=="function"&&(process.platform==="win32"?ii("taskkill",["/pid",ht.pid,"/f","/t"]):ht.kill("SIGKILL"))}catch{}ht=null,qs=!1}},ai=(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 m=t[h];if([">",">>","<","&","&&","|","||",";"].includes(m))break;m!=="-p"&&m!=="--parents"&&m!=="-v"&&m!=="--verbose"&&u.push(m),h++}if(u.length>0){let m=u.map(p=>{let y=p.replace(/^['"]|['"]$/g,""),g=p;return r(y)&&(g=p.replace(/\//g,"\\")),g});a.push("New-Item","-ItemType","Directory","-Force","-Path",m.join(","))}else a.push("New-Item","-ItemType","Directory","-Force");f=h-1;continue}if(l==="rm"&&e&&Hn()){let u=[],h=!1,m=!1,p=f+1;for(;p<t.length;){let g=t[p];if([">",">>","<","&","&&","|","||",";"].includes(g))break;g==="-rf"||g==="-fr"?(h=!0,m=!0):g==="-r"||g==="-R"||g==="--recursive"?h=!0:g==="-f"||g==="--force"?m=!0:u.push(g),p++}let y=["Remove-Item"];if(h&&y.push("-Recurse"),m&&y.push("-Force"),u.length>0){let g=u.map(S=>{let E=S.replace(/^['"]|['"]$/g,""),x=S;return r(E)&&(x=S.replace(/\//g,"\\")),x});y.push("-Path",g.join(","))}a.push(...y),f=p-1;continue}if(l==="cp"&&e&&Hn()){let u=[],h=!1,m=!1,p=f+1;for(;p<t.length;){let g=t[p];if([">",">>","<","&","&&","|","||",";"].includes(g))break;g==="-r"||g==="-R"||g==="--recursive"?h=!0:g==="-f"||g==="--force"?m=!0:u.push(g),p++}let y=["Copy-Item"];if(h&&y.push("-Recurse"),m&&y.push("-Force"),u.length>0){let g=u.map(S=>{let E=S.replace(/^['"]|['"]$/g,""),x=S;return r(E)&&(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=p-1;continue}if(l==="touch"&&e&&Hn()){let u=[],h=f+1;for(;h<t.length;){let m=t[h];if([">",">>","<","&","&&","|","||",";"].includes(m))break;u.push(m),h++}if(u.length>0){let p=`(${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(p)}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,""),m=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(h);if(r(h)&&m){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 m=/^['"]|['"]$/.test(h),p=h.replace(/^['"]|['"]$/g,"");r(p)&&(h=h.replace(/\//g,"\\"));let y=h.replace(/^['"]|['"]$/g,"");return y.includes(" ")&&!m&&(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(" ")},li=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=ai(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 m=u,p=[...h];if(process.platform==="linux")u="unshare",h=["-n","-r",m,...p];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,m,...p]}}if(So)try{let m=So.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}});ht=m,qs=!0;let p="",y=!1;return m.onData(g=>{if(!y){p+=g,o&&o(g);let S=To(p);/(?: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))}}),m.onExit(({exitCode:g})=>{if(y)return;ht=null;let S=ri(p||""),E=To(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
|
+
${E}`:`SUCCESS: Command [${t}] completed.
|
|
21
|
+
|
|
22
|
+
${E}`)}),!0}catch(m){return s&&(c==="pwsh"||c==="powershell")&&m.code==="ENOENT"?!1:(bo(a,l,t,r,o,c,i),!0)}else return bo(a,l,t,r,o,c,i),!0};s?d("pwsh")||d("powershell")||d("cmd"):d("bash")})},bo=(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 p=c,y=[...f];if(process.platform==="linux")c="unshare",f=["-n","-r",p,...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,p,...y]}}let l=a?ii(c,f,{cwd:process.cwd(),env:{...process.env,...o}}):ii(c,f,{cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...o}});ht=l,qs=!1,l.stdin&&l.stdin.on("error",()=>{ht=null});let u="",h="",m=!1;l.stdout.on("data",p=>{if(!m){let y=p.toString();u+=y,s&&s(y);let g=To(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)&&(m=!0,setTimeout(()=>n(`SUCCESS: Dev server started successfully in background.
|
|
28
|
+
|
|
29
|
+
${g}`),500))}}),l.stderr.on("data",p=>{if(!m){let y=p.toString();h+=y,s&&s(y)}}),l.on("close",p=>{if(m)return;ht=null;let y=[],g=ri(u),S=ri(h);g&&y.push(`STDOUT:
|
|
30
|
+
${g}`),S&&y.push(`STDERR:
|
|
31
|
+
${S}`),p!==0&&y.push(`EXIT CODE: ${p}`);let E=y.join(`
|
|
32
|
+
|
|
33
|
+
`)||"Command executed with no output.",x=To(E).replace(/\n{3,}/g,`
|
|
34
|
+
|
|
35
|
+
`);n(p!==0?`ERROR: Command [${t}] failed with exit code [${p}].
|
|
36
|
+
|
|
37
|
+
${x}`:`SUCCESS: Command [${t}] completed.
|
|
38
|
+
|
|
39
|
+
${x}`)}),l.on("error",p=>{if(a&&p.code==="ENOENT"){if(i==="pwsh"){let g=ai(t,!0);return bo(n,g,t,o,s,"powershell",r)}else if(i==="powershell"){let g=ai(t,!1);return bo(n,g,t,o,s,"cmd",r)}}ht=null;let y=p instanceof Error?p.message:String(p);n(`ERROR: Failed to start command [${t}]: ${y}`)})};var Vs=null,Hn=()=>{if(process.platform!=="win32")return!1;if(Vs!==null)return Vs;try{Cl('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Vs=!0}catch{Vs=!1}return Vs},ci=null,Ar=(n,e,t,o,s=!1,i=!0)=>(ci===null&&(ci=s),`
|
|
40
|
+
-- TOOL DEFINITIONS --
|
|
41
|
+
TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' SYNTAX STRING IN CHAT \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 ALL 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
|
+
`:""}
|
|
51
|
+
- COMMUNICATION WITH USER -
|
|
52
|
+
- [tool:functions.Ask(question="...", optionA="title::description", ...MAX4)]. Ambiguity: MUST for path divergence, security risk. Ask, don't finish/guess. Keep titles short
|
|
53
|
+
|
|
54
|
+
- WEB TOOLS -
|
|
55
|
+
- [tool:functions.WebSearch(query="...", aiMode="bool", limit="integer 3-10 aiMode: exclude")]. Usage: unknown info/docs. aiMode: LLM search
|
|
56
|
+
- [tool:functions.WebScrape(url="...")]. Proactive use for specific webpage/docs/api
|
|
57
|
+
|
|
58
|
+
${n==="Flux"?`- WORKSPACE TOOLS (path = relative; FIRST ARGUMENT, path separator: '/') -
|
|
59
|
+
- [tool:functions.ReadFile(path="...", startLine="integer", endLine="integer")]. ${o!=="Google"?`${t?"Supports images/docs":""}`:"Supports images/docs"}
|
|
60
|
+
- [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. DIR Contents + File Size. Minimize recursion
|
|
61
|
+
- [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
|
|
62
|
+
- [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile
|
|
63
|
+
- [tool:functions.CodeSearch(keyword="...", path="dir/file/glob/regex, inclusion/exclusion ;-separated", fuzzy="bool default: false", regex="bool default: auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
|
|
64
|
+
- [tool:functions.Run(command="...")]. Runs ${e==="Windows"?Hn()?"POWERSHELL":"WINDOWS CMD":"BASH"} command. Destructive/Irreversible ops \u2192 Ask user
|
|
65
|
+
- [tool:functions.Todo(method="create/append/get", tasks=[STRING ARRAY], markDone=[TASK ID ARRAY])]. Analyze request: ONLY if long multi-task, break it down & create Todos BEFORE starting. Use \`get + markDone\` to mark complete. UPDATE EVERY TURN WHEN CREATED
|
|
66
|
+
${ci?'\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?`
|
|
67
|
+
- SUB AGENT TOOLS -
|
|
68
|
+
**PROACTIVE sub-agent use HIGHLY RECOMMENDED. Prefer for any task with even slight benefit, no user nudge needed**
|
|
69
|
+
Invocations:
|
|
70
|
+
\u2022 Invoke (async/background, \u22647 parallel). Parallelize long tasks. May take time
|
|
71
|
+
\u2022 InvokeSync (sync/blocking). Sequential, repetitive or delegated tasks. Saves tokens/cost
|
|
72
|
+
- [tool:functions.InvokeSync/Invoke(title="...", task="...")]. Task must be detailed: exact file paths, imports/exports, dependencies & folder structure
|
|
73
|
+
- [tool:functions.Await(id="...", timeout="integer seconds, default: 120")]. Event-driven wait
|
|
74
|
+
- [tool:functions.GetProgress(id="...")]. Poll \`getProgress\` sparingly; NO initial poll. Work or await. Never end while subagent runs
|
|
75
|
+
- [tool:functions.Steer(id="...", message="...")]. Inject additional instruction or redirection into active async subagent
|
|
76
|
+
- [tool:functions.Cancel(id="...")]. Cancel async task ONLY if stalled (2m+) or clearly incorrect`:""}`.trim():`- CREATIVE TOOLS (path = relative to CWD & WILL BE FIRST ARGUMENT, path separator: '/') -
|
|
77
|
+
- [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout, stable margins & headers/footers, NO WATERMARKS
|
|
78
|
+
- [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document, NO WATERMARKS, stable margins & headers/footers
|
|
79
|
+
- WORKSPACE & SUB AGENT TOOLS ARE NOT AVAILABLE IN FLOW`.trim()}`.trim());var Cr=(n=!0,e=!0)=>`
|
|
80
|
+
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
|
|
81
|
+
|
|
82
|
+
-- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS IN THIS TURN) --
|
|
83
|
+
- [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
|
|
84
|
+
- [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
|
|
85
|
+
|
|
86
|
+
${n?`-- User-specific long-term/permanent memory (USE BASED ON CONVERSATION CONTEXT, DO NOT RE-SAVE MEMORY WHICH IS ALREADY SAVED) --
|
|
87
|
+
- 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)
|
|
88
|
+
- Delete: [tool:functions.Memory(action="user", method="delete", id="<memory id>")]
|
|
89
|
+
- Update: [tool:functions.Memory(action="user", method="update", content-new="string to update", id="<memory id>")]
|
|
90
|
+
|
|
91
|
+
-- Memory Relevance Decay Tool --
|
|
92
|
+
- Score Adjustment: [tool:functions.addMemScore(id="<memory id>")]
|
|
93
|
+
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
|
|
94
|
+
|
|
95
|
+
Explicit Triggers for permanent memory:
|
|
96
|
+
- User explicitly asks to 'remember' something
|
|
97
|
+
- User mentions something important long-term that should be remembered
|
|
98
|
+
- User provides information that could be useful for long-term reference
|
|
99
|
+
- User shares personal information or preferences
|
|
100
|
+
|
|
101
|
+
Usage Rules:
|
|
102
|
+
- Frequency for 'user' action: Based on explicit triggers.
|
|
103
|
+
- IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT ADD
|
|
104
|
+
- Chat Title is MANDATORY
|
|
105
|
+
- TEMPORARY Memory is MANDATORY
|
|
106
|
+
- WHEN Called User Memory, STILL use Temporary Memory
|
|
107
|
+
- MUST NOT IGNORE ANY TOOL CALLS IN GIVEN CONTEXT OF CHAT BETWEEN USER & AGENT`:""}`.trim();var Eo={xHigh:`EFFORT: HIGH
|
|
108
|
+
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
|
|
109
|
+
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
110
|
+
MANDATORY: Full technical verification`,High:`EFFORT: HIGH
|
|
111
|
+
Rigorous thinking, prefer the simplest correct solution, assess architecture, performance & maintainability, verify error handling, assumptions, edge cases, dependencies & regressions, plan: files, functions, logic & interactions
|
|
112
|
+
Continuous analysis, verify from first principles, seek failure paths, verify imports, tool results & system stability; avoid syntax errors
|
|
113
|
+
MANDATORY: Full technical verification`,Medium:`EFFORT: MEDIUM
|
|
114
|
+
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
|
|
115
|
+
Logical, implementation-focused, efficient, deliberate, verify imports, tool results & system stability; avoid syntax errors
|
|
116
|
+
MANDATORY: Brief verification for technical tasks/greetings`,Minimal:`EFFORT: LOW
|
|
117
|
+
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
118
|
+
Brief thoughts, think only enough to avoid mistakes, verify imports, tool results & system stability; avoid syntax errors`,Off:`EFFORT: LOWEST
|
|
119
|
+
No thinking. Immediate response
|
|
120
|
+
Verify imports, tool results & system stability; avoid syntax errors`};import $r from"fs";var fi=null,Or=null,Ks=null,$l=(n,e)=>{if(!e)return"";if(n!==Or||Ks===null){Or=n;try{let t=V(Mt,[]);Array.isArray(t)&&t.length>0?Ks=t.map(o=>`- ${o.memory}`).join(`
|
|
121
|
+
`):Ks=""}catch(t){Ks="",$r.appendFileSync(`${cn}/memory/error.txt`,`${t.message}
|
|
122
|
+
-------------------------------------------------
|
|
123
|
+
|
|
124
|
+
`)}}return Ks},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) --
|
|
125
|
+
${n}`:"";return s?`${s}`:""},_r=(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 A=e;e==="Fast"&&(A="Off"),e==="Low"&&(A="Minimal"),e==="Standard"&&(A="Medium"),(e==="xHigh"||e==="Max")&&(A="xHigh"),l=Eo[A]||Eo.Medium}if(d||r!=="Google"){let A={Fast:"LOWEST",Low:"LOW",Medium:"MEDIUM",Standard:"MEDIUM",High:"HIGH",xHigh:"HIGH",Max:"HIGH"};l=Eo.xHigh,l=l.replace("EFFORT: HIGH",`EFFORT: ${A[e]}`).replace(`
|
|
126
|
+
MANDATORY: Full technical verification`,""),e==="Fast"?l=`EFFORT: LOWEST
|
|
127
|
+
No thinking. Immediate response
|
|
128
|
+
Verify imports, tool results & system stability; avoid syntax errors`:e==="Low"&&(l=`EFFORT: LOW
|
|
129
|
+
Quick, focused thinking, intent & complexity, required tools/files/actions, before acting
|
|
130
|
+
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}
|
|
131
|
+
|
|
132
|
+
`:"",m=n.nickname&&n.nickname?.length>0?`User Nickname: ${n.nickname}
|
|
133
|
+
${h.length?"":`
|
|
134
|
+
`}`:"",p=n.name&&n.name?.length>0?`User Name: ${n.name}
|
|
135
|
+
${m.length||h.length?"":`
|
|
136
|
+
`}`:"",y=process.cwd(),g=$l(c,s),S=g?.length>0?`--- SAVED MEMORIES ---
|
|
137
|
+
${g}
|
|
138
|
+
|
|
139
|
+
`:"",E=(()=>{let A=process.cwd().toLowerCase();if(process.platform==="win32"){let R=process.env.SystemRoot?.toLowerCase()||"c:\\windows",k=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",w=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return A.startsWith(R)||A.startsWith(k)||A.startsWith(w)}else return A==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(k=>A.startsWith(k))})(),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||fi===null){let A=x.filter(R=>$r.existsSync(R.name));fi=t==="Flux"&&A.length>0?`
|
|
140
|
+
-- PROJECT CONTEXT --
|
|
141
|
+
${A.map(R=>`- ${R.name}: ${R.desc}`).join(`
|
|
142
|
+
`)}
|
|
143
|
+
Check these first; These Files > Training Data. Safety rules apply
|
|
144
|
+
`:""}let C=fi;return`=== SYSTEM PROMPT ===
|
|
145
|
+
Identity: Flux Flow. Sassy, Friendly, Warm, Conversational, CLI Agent
|
|
146
|
+
${t==="Flux"?"Logical, task-driven. Prioritize scalable, modular architecture, clean abstractions, stepwise execution. Use latest practices/libraries, verify imports, run automated tests":`Mode: ${t}. Concise, Humorous, Sarcastic`}
|
|
147
|
+
|
|
148
|
+
- USE DIRECTORY STRUCTURE FOR FILE AVAILABILITY AND PATH RESOLUTION${s?`
|
|
149
|
+
- USE RELATIVE TIME REFERENCE eg. few mins ago`:""}
|
|
150
|
+
- Chat Context > Metadata
|
|
151
|
+
|
|
152
|
+
-- THINKING GUIDANCE --
|
|
153
|
+
${r==="Mistral"||r==="Google"&&!d?`${l}
|
|
154
|
+
${f||e!=="Fast"&&(r==="Mistral"||e!=="xHigh"&&!d)?`CRITICAL THINKING POLICY
|
|
155
|
+
- Use <think>...</think> for reasoning before responding any queries
|
|
156
|
+
`:""}`:`${l}
|
|
157
|
+
`}
|
|
158
|
+
${Ar(t,u,r.toLowerCase()==="deepseek"?!1:a,r,o?.advanceRollback,o?.subAgents!==!1)}
|
|
159
|
+
${C}${s?`
|
|
160
|
+
-- MEMORY RULES --
|
|
161
|
+
- Subtly Personalize with RELEVENT CONTEXTUAL MEMORIES. Auto Saves
|
|
162
|
+
`:""}
|
|
163
|
+
-- SECURITY POLICIES --
|
|
164
|
+
- Sensitive files? Ask before Read${E?`
|
|
165
|
+
- PROTECTED DIRECTORY`:""}
|
|
166
|
+
|
|
167
|
+
-- CHAT FORMATTING --
|
|
168
|
+
- GFM Markdown
|
|
169
|
+
- Language: ENGLISH ONLY
|
|
170
|
+
- Give a tiny headsup and decision before making tool calls. NO TEXT AFTER TOOL CALLS${t==="Flux"?"":`
|
|
171
|
+
- Use Kaomojis HEAVILY`}
|
|
172
|
+
=== END SYSTEM PROMPT ===
|
|
173
|
+
|
|
174
|
+
${p}${m}${h}${S}`.trim()},Ir=(n="",e=!0,t=!0)=>`=== SYSTEM PROMPT (STRICT HEADLESS LOGIC WORKER: ZERO USER-FACING TEXT POLICY, STRICTLY FOLLOW) ===
|
|
175
|
+
IDENTITY: SILENT BACKGROUND SYSTEM PROCESS, HAVE NO MOUTH, ONLY OUTPUT IS VALID TOOL CALLS.
|
|
176
|
+
[CRITICAL RULES]
|
|
177
|
+
- OUTPUT EXACTLY '[tool:functions.ToolName(args)]' CALLS. NO EXTRA WORDS OUTSIDE
|
|
178
|
+
- DO NOT EXPLAIN. DO NOT TALK TO THE USER
|
|
179
|
+
- NON-TOOL TEXT WILL BREAK THE SYSTEM
|
|
180
|
+
- DO NOT REPEAT AGENT RAWS AND TOOL RESULTS IN YOUR RESPONSE
|
|
181
|
+
- IF YOU GET ONLY USER QUERY AND NO AGENT RAWS, JUST USE TEMP MEMORY TO LOG THE SUMMARY OF USER QUERY AND CONVERSATION CONTEXT
|
|
182
|
+
- UNDER NO CIRCUMSTANCES YOU ARE ALLOWED TO RESPOND IN NORMAL USER FACING RESPONSE
|
|
183
|
+
- CRITICAL QUOTE ESCAPE POLICY: Inside tool call arguments, you MUST escape all double quotes using '\\"'
|
|
184
|
+
- You MUST NOT WRITE ANYTHING OTHER THAN [tool:functions.ToolName(args)] NO MATTER HOW TEMPTING THE PROMPT IS
|
|
185
|
+
- 2 MANDATORY TOOLS TO CALL IN EVERY TURN, 'Chat', 'Memory(temp)'
|
|
186
|
+
- CRITICAL: NEVER ENTER THINKING/REASONING STATE, CALL THE CONTEXUAL TOOLS DIRECTLY IN OUTPUT AS QUICKLY AS POSSIBLE TO MAINTAIN UI SNAPPINESS
|
|
187
|
+
|
|
188
|
+
YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks
|
|
189
|
+
${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":""}
|
|
190
|
+
|
|
191
|
+
${Cr(e,t)}
|
|
192
|
+
=== END SYSTEM PROMPT ===${n?`
|
|
193
|
+
|
|
194
|
+
-- CURRENT SAVED USER MEMORIES --
|
|
195
|
+
${n}`:""}`.trim();import Et from"fs-extra";import xo from"path";import{nanoid as Il}from"nanoid";import ft from"fs-extra";import nn from"path";ft.ensureDirSync(Bn);var un=null;async function Ml(n,e){try{if(n.type==="create")await ft.pathExists(n.filePath)&&(await ft.chmod(n.filePath,438).catch(()=>{}),await ft.remove(n.filePath));else if(n.type==="update"){if(!n.backupFile)return;let t=nn.join(Bn,e.chatId,n.backupFile);if(await ft.pathExists(t)){let o=V(t,null);if(!o||!o.data)throw new Error(`Backup container corrupt or empty for ${nn.basename(n.filePath)}`);let s=$s(o.data);await ft.pathExists(n.filePath)&&await ft.chmod(n.filePath,438).catch(()=>{}),await ft.writeFile(n.filePath,s,"utf8")}}}catch(t){throw new Error(`Restoration failed for ${nn.basename(n.filePath)}: ${t.message}`)}}async function _l(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 di=null,dt={async startTransaction(n,e){di=n,un={id:`tx_prompt_${Date.now()}`,chatId:n,timestamp:new Date().toISOString(),prompt:e.trim(),changes:[],reverted:!1},re(as,un)},async recordFileChange(n,e=null){try{if(!un){if(di){let r=V(tn,[]),a=[...r].reverse().find(d=>d.chatId===di);if(a){if(a.changes.some(u=>u.filePath===n))return;let f=await ft.pathExists(n)||e?"update":"create",l=null;if(f==="update"){let u=nn.basename(n);l=`${a.id}_${u}.bak`;let h=nn.join(Bn,a.chatId);await ft.ensureDir(h);let m=nn.join(h,l),p=e!==null?e:await ft.readFile(n,"utf8").catch(()=>null);p!==null?re(m,{data:Ys(p)}):(f="create",l=null)}a.changes.push({filePath:n,type:f,backupFile:l}),re(tn,r)}}return}if(un.changes.some(r=>r.filePath===n))return;let s=await ft.pathExists(n)||e?"update":"create",i=null;if(s==="update"){let r=nn.basename(n);i=`${un.id}_${r}.bak`;let a=nn.join(Bn,un.chatId);await ft.ensureDir(a);let d=nn.join(a,i),c=e!==null?e:await ft.readFile(n,"utf8").catch(()=>null);c!==null?re(d,{data:Ys(c)}):(s="create",i=null)}un.changes.push({filePath:n,type:s,backupFile:i}),re(as,un)}catch{}},async commitTransaction(){if(un)try{let n=V(tn,[]);if(n.push(un),n.length>512e3){let e=n.shift();if(e.changes)for(let t of e.changes)t.backupFile&&await ft.remove(nn.join(Bn,e.chatId,t.backupFile)).catch(()=>{})}re(tn,n),await ft.remove(as).catch(()=>{})}catch{}finally{un=null}},async recoverCrashedTransaction(){try{if(await ft.pathExists(as)){let n=V(as,null);if(n?.changes?.length>0){let e=V(tn,[]);e.some(t=>t.id===n.id)||(e.push(n),re(tn,e))}await ft.remove(as).catch(()=>{})}}catch{}},async rollbackToBefore(n){let e=V(tn,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 _l(a,r);for(let a of r.changes)if(a.backupFile){let d=nn.join(Bn,r.chatId,a.backupFile);await ft.remove(d).catch(()=>{})}e=e.filter(a=>a.id!==r.id),re(tn,e)}return{success:!0,chatId:o,targetPrompt:s}},async getChatHistory(n){try{return V(tn,[]).filter(t=>t.chatId===n&&!t.reverted)}catch{return[]}},async deleteChatBackups(n){try{await ft.remove(nn.join(Bn,n));let e=V(tn,[]),t=e.filter(o=>o.chatId!==n);e.length!==t.length&&re(tn,t)}catch{}}};var vr=Promise.resolve(),Ro=n=>{let e=vr.then(async()=>{try{return await n()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return vr=e.catch(()=>{}),e},cs=async()=>{await Et.ensureDir(Os);let n={};if(await Et.pathExists(Cs))try{n=V(Cs,{})}catch{n={}}for(let e in n){let t=xo.join(Os,`${e}.json`);Object.defineProperty(n[e],"messages",{get:()=>{if(Et.existsSync(t))try{return V(t,[])}catch{return[]}return[]},set:o=>{try{re(t,o)}catch{}},enumerable:!1,configurable:!0})}return n},Qd=async(n,e,t)=>Ro(async()=>{await Et.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 Kt()).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 E=S.split(/\s+/),x;return E.length>7?x=E.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)}`),m=xo.join(Os,`${n}.json`);re(m,i),o[n]={name:h,prompt:a||void 0,updatedAt:Date.now()};let p={};for(let y in o)p[y]={name:o[y].name,prompt:o[y].prompt||void 0,updatedAt:o[y].updatedAt};re(Cs,p)}),Lr=async(n,e)=>Ro(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};re(Cs,o)}),vl=async n=>Ro(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(re(Cs,t),await Et.pathExists(Wn))try{let r=V(Wn,[]);if(Array.isArray(r)){let a=r.filter(d=>Object.keys(d)[0]!==String(n));re(Wn,a)}}catch{}let o=V(Vt,{});o[n]&&(delete o[n],re(Vt,o));let s=V(_n,{});s[n]&&(delete s[n],re(_n,s)),await dt.deleteChatBackups(n);let i=xo.join(Os,`${n}.json`);if(await Et.pathExists(i))try{await Et.remove(i)}catch{}return e}),Zd=()=>`flow-${Il(6)}`,eu=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 vl(r),i++)}return i},Ll=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,m=0,p=0;if(i){let g=i.split(":").map(Number);h=g[0]||0,m=g[1]||0,p=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,m,p);return isNaN(y.getTime())?null:y.getTime()},Nl=async n=>{try{if(!await Et.pathExists(n))return;let e=await Et.readFile(n,"utf8");if(!e.trim())return;let t=e.split(`
|
|
196
|
+
`),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 m=l.header.match(c);if(m){let p=Ll(m[1]);if(p&&a-p>r)continue}}let h=l.header+(l.body.length>0?`
|
|
197
|
+
`+l.body.join(`
|
|
198
|
+
`):"");d.push(h)}let f=d.join(`
|
|
199
|
+
`).trim();f?await Et.writeFile(n,f+`
|
|
200
|
+
`,"utf8"):await Et.writeFile(n,"","utf8")}catch{}},tu=async n=>{try{if(!await Et.pathExists(n))return;let e=async t=>{let o=await Et.readdir(t);for(let s of o){let i=xo.join(t,s);(await Et.stat(i)).isDirectory()?(await e(i),(await Et.readdir(i)).length===0&&await Et.remove(i)):s.endsWith(".log")&&await Nl(i)}};await e(n)}catch{}},Nr=(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 nu=async(n,e,t)=>Ro(async()=>{let o=V(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}),re(Wn,o)}),su=async n=>{try{if(!await Et.pathExists(Wn))return{total:0,context:0};let e=V(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 pt from"fs-extra";import Pr from"path";var Pl=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),Z=null,Gn=null,Dr=0,Ms=!1,In={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:[]},_s=(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},ko=async()=>{let n=new Date().toISOString().split("T")[0];try{!await pt.exists(qt)&&await pt.exists(qo)&&(await pt.ensureDir(Pr.dirname(qt)),await pt.move(qo,qt))}catch{}let e=qt+".tmp",t=null;try{if(await pt.exists(e)){let s=(await pt.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 pt.rename(e,qt)}catch{}}else try{await pt.remove(e)}catch{}}}catch{try{await pt.remove(e)}catch{}}if(!t)try{if(await pt.exists(qt)){let s=(await pt.readFile(qt,"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||{...In},i={...In,...s};Array.isArray(i.imageCalls)||(i.imageCalls=[]);let r=o.history||{},a=_s(r,n);if(Object.keys(r).length!==Object.keys(a).length&&(Ms=!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:{...In},history:_s(f,n)}}}return{date:n,stats:{...In},history:{}}},ui=async()=>{if(!(!Ms||!Z))try{await pt.ensureDir(Pr.dirname(qt));let n=null;try{if(await pt.exists(qt)){let s=(await pt.readFile(qt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?n=JSON.parse(s):n=JSON.parse($s(s))}}catch{}if(n&&n.date===Z.date&&n.stats){for(let s in Z.stats)if(n.stats[s]!==void 0){if(Array.isArray(Z.stats[s])){let i=Array.isArray(n.stats[s])?n.stats[s]:[],r=Z.stats[s],a=new Map;for(let d of[...i,...r])d&&d.timestamp&&a.set(d.timestamp,d);Z.stats[s]=Array.from(a.values())}else if(typeof Z.stats[s]=="number")Z.stats[s]=Math.max(Z.stats[s],Number(n.stats[s])||0);else if(Z.stats[s]&&typeof Z.stats[s]=="object"){let i=n.stats[s]||{},r=Z.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={...Z.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];Z.history=_s(s,Z.date||today)}else if(Z&&Z.history){let s=new Date().toISOString().split("T")[0];Z.history=_s(Z.history,s)}Z.saveId=Pl();let e=qt+".tmp",t=Ys(JSON.stringify(Z,null,2));await pt.writeFile(e,t,"utf8");let o=await pt.open(e,"r+");await pt.fsync(o),await pt.close(o),await pt.rename(e,qt),Ms=!1,Dr=Date.now()}catch{}},Ao=()=>{if(Ms=!0,Gn)return;let n=Date.now(),e=Math.max(0,1500-(n-Dr));Gn=setTimeout(async()=>{await ui(),Gn=null},e),Gn.unref&&Gn.unref()},fu=async()=>{Z=await ko(),Ms&&Ao()},du=async()=>{Gn&&(clearTimeout(Gn),Gn=null),await ui()},En=async()=>{let n=new Date().toISOString().split("T")[0];if(!Z)Z=await ko();else if(Z.date!==n){let e=Z.date,t=Z.stats,o=Z.history||{};t&&(o[e]=t),Z={date:n,stats:{...In},history:_s(o,n)},Ms=!0,await ui()}return Z&&Z.stats&&!Array.isArray(Z.stats.imageCalls)&&(Z.stats.imageCalls=[]),Z.stats},Dl=async()=>{let n=new Date().toISOString().split("T")[0];Z||(Z=await ko()),Z.date!==n&&await En();let e=Z.history||{},t=_s(e,n);Z.history=t;let o=Z.stats||{...In},s={...In};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},Ut=async(n,e)=>{n==="toolSuccess"?Xs.toolSuccess++:n==="toolFailure"?Xs.toolFailure++:n==="toolDenied"&&Xs.toolDenied++;let t=await En();t[n]!==void 0&&t[n]++,e&&n==="agent"&&(t.providerRequests||(t.providerRequests={}),t.providerRequests[e]=(t.providerRequests[e]||0)+1),Ao()},Xs={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0},Bt=async(n,e,t,o)=>{n==="linesAdded"?Xs.linesAdded+=e:n==="linesRemoved"&&(Xs.linesRemoved+=e);let s=await En();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))}Ao()},Fl=async(n=1)=>{let e=new Date,t=e.toISOString().split("T")[0];Z||(Z=await ko()),Z.date!==t&&await En();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=Z.history||{},c=Z.stats||{...In},f={...In};f.imageCalls=[],f.models={};let l=(u,h)=>{for(let m in u)if(m==="imageCalls")u.imageCalls=[...u.imageCalls||[],...h.imageCalls||[]];else if(m==="models"){let p=h.models||{};for(let y in p){u.models[y]||(u.models[y]={});for(let g in p[y]){u.models[y][g]||(u.models[y][g]={tokens:0,cachedTokens:0,candidateTokens:0});let S=u.models[y][g],E=p[y][g];S.tokens+=E.tokens||0,S.cachedTokens+=E.cachedTokens||0,S.candidateTokens+=E.candidateTokens||0}}}else typeof u[m]=="number"&&(u[m]+=h[m]||0)};l(f,c);for(let u in d)u>=a&&u<t&&l(f,d[u]);return f},hi=async(n,e={})=>{let t=await Kt().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 En(),m;s.resetMode==="Custom"?m=await Fl(s.resetDay||1):m=await Dl();let p=0,y=0,g=0;if(d){p=h.providerRequests?.[a]||0;let S=h.models?.[a]||{};for(let x in S)y+=S[x]?.tokens||0;let E=m.models?.[a]||{};for(let x in E)g+=E[x]?.tokens||0}else p=h.agent||0,y=h.tokens||0,g=m.tokens||0;return o==="Free"&&h.agent+h.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:p>=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 En();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 En()).search<(s.searchLimit||100);return{allowed:l,reason:l?void 0:"Search Quota Exceeded"}}return{allowed:!0}},Fr=async(n,e={})=>(await hi(n,e)).allowed,pi=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},Ur=(n,e)=>{if(!n||n.length===0)return .025;let o=pi(n);if(o.length===0)return .025;let s=[];for(let l of o){let u=.025;if(s.length>0){let m=s[s.length-1],p=!1;if(s.length>=2){let y=s[s.length-2];m.ratio>=.8&&y.ratio>=.8&&(p=!0)}if(p)u=.015;else{let y=m.limit,g=m.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},Br=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 En();s.imageCalls||(s.imageCalls=[]);let i=Date.now(),r=pi(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=Ur(s.imageCalls,i);return a+o<=d},Wr=async()=>{let n=await En();n.imageCalls||(n.imageCalls=[]);let e=Date.now(),t=pi(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=Ur(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}},jr=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 En();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:o}),Ao()};import Yr from"puppeteer";import zr from"fs";import qr from"path";import Hr from"os";import Js from"path";import Is from"fs";import{createRequire as Ul}from"module";import{fileURLToPath as Bl}from"url";var Wl=Ul(import.meta.url),Gr=Js.dirname(Bl(import.meta.url));function fs(){let n=Hr.platform(),e=Hr.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=Js.resolve(Gr,"..","..",".puppeteerrc.cjs");if(Is.existsSync(i)||(i=Js.resolve(Gr,"..",".puppeteerrc.cjs")),!Is.existsSync(i))return{};try{let r=Wl(i),a=r.cacheDirectory,d=r.chrome?.version;if(a){if(process.env.PUPPETEER_CACHE_DIR=a,d){let l=Js.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 m of u){let p=Js.join(l,m),y;try{y=Is.statSync(p)}catch{continue}if(y.isDirectory())h.push(p);else if(m.toLowerCase()===o.toLowerCase()&&(!d||p.includes(d)))return p}if(d){for(let m of h)if(m.includes(d)){let p=c(m);if(p)return p}}for(let m of h)if(!d||!m.includes(d)){let p=c(m);if(p)return p}}catch{}return null},f=c(a);if(f)return{executablePath:f,cacheDirectory:a}}}catch{}return{}}var mi=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}
|
|
201
|
+
|
|
202
|
+
RESPONSE RULES:
|
|
203
|
+
- ANSWER CONCISELY WITH REQUIRED DETAILS UNDER 300 WORDS.
|
|
204
|
+
- DO NOT CITE, REFERENCE, OR MENTION SOURCES ANYWHERE BETWEEN THE MAIN RESPONSE.
|
|
205
|
+
- DO NOT USE MARKDOWN EXCEPT FOR THE SOURCES SECTION BELOW.
|
|
206
|
+
- END THE RESPONSE WITH EXACTLY:
|
|
207
|
+
|
|
208
|
+
Sources:
|
|
209
|
+
- <URL 1>
|
|
210
|
+
- <URL 2>
|
|
211
|
+
- <URL 3>
|
|
212
|
+
|
|
213
|
+
- LIST ONE RAW URL PER BULLET.
|
|
214
|
+
- DO NOT USE MARKDOWN LINKS.
|
|
215
|
+
- 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 Yr.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,m=45e3,p=Date.now();for(;Date.now()-p<m&&(h=await f.evaluate(()=>{let T=Array.from(document.querySelectorAll('.message:not(.user), .answer-text, .llm-content, [data-type="answer"]')),b="";if(T.length>0&&(b=T.map(z=>z.innerText.trim()).filter(Boolean).join(`
|
|
216
|
+
|
|
217
|
+
`)),b||(b=document.body.innerText),b.includes("anomaly"))throw new Error("ANOMALY_DETECTED");let v=!!document.querySelector('.spinner, .loading, .typing, .streaming, [data-streaming="true"], [data-state="loading"], svg.animate-spin, circle[cx], div[class*="spin"]'),_=T[0]||document.body,$=_?_.innerText.trim():"",G=/^(?:[✓✔]\s*)?Finished/i.test($)||!!(_&&_.querySelector(".status-finished, .finished")),ce=!v&&(G||b.includes("Sources:")&&!v),ge={};return document.querySelectorAll("a[href]").forEach(z=>{let $e=z.getAttribute("href")||z.href||"";if($e.includes("uddg=")&&($e=decodeURIComponent($e.split("uddg=")[1].split("&")[0])),$e.includes("url=")&&($e=decodeURIComponent($e.split("url=")[1].split("&")[0])),$e&&($e.startsWith("http://")||$e.startsWith("https://"))&&!$e.includes("search.brave.com")){let P=z.innerText.trim();P&&(ge[P]=$e),z.textContent=$e}}),{isFinished:ce,text:b,hrefMap:ge}}),!(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 E=y,x="";if(y.includes("Sources:")){let T=y.split("Sources:");E=T[0],x=T.slice(1).join("Sources:")}let C=[];for(let T of E.split(`
|
|
218
|
+
`)){let b=T.trim();b&&(/^(View all|Finished|Searching|Answering|Thinking)$/i.test(b)||/^[\+\-]?\d+$/.test(b)||b.includes("search.brave.com")||b.startsWith("https://www.youtube.com/watch")||b.startsWith("https://youtube.com/watch")||C.push(T))}let A=C.join(`
|
|
219
|
+
`).replace(/^(?:[\+\-]?\d+\s*)+/i,"").replace(/\n{3,}/g,`
|
|
220
|
+
|
|
221
|
+
`).trim(),R=T=>!T||T.includes("search.brave.com")||T.includes("youtube.com")||T.includes("youtu.be"),k="";if(x){let T=x.match(/https?:\/\/[^\s\)\>]+/g)||[],b=[];for(let _ of T){let $=_.replace(/[\.\,\;]+$/,""),G=Object.keys(g).find(ce=>ce.startsWith($)||$.startsWith(ce));G&&g[G]&&($=g[G]),R($)||b.push($)}Object.values(g).forEach(_=>{!R(_)&&!b.includes(_)&&b.push(_)});let v=Array.from(new Set(b));v.length>0&&(k=`Sources:
|
|
222
|
+
`+v.map(_=>`- ${_}`).join(`
|
|
223
|
+
`))}let w=A+(k?`
|
|
224
|
+
|
|
225
|
+
`+k:"");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}]:
|
|
226
|
+
|
|
227
|
+
${w}`}catch(c){if(i=c,zr.writeFileSync(qr.join(cn,"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 Yr.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(p=>setTimeout(p,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",(p,y)=>p.slice(0,y).map((g,S)=>{let E=g.querySelector(".result__a"),x=g.querySelector(".result__snippet"),C=E?E.href:"";C.includes("uddg=")&&(C=decodeURIComponent(C.split("uddg=")[1].split("&")[0]));let A=E?E.innerText.trim():"No Title",R=x?x.innerText.trim():"No Snippet";return`${S+1}. ${A}
|
|
228
|
+
Source: ${C}
|
|
229
|
+
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(`
|
|
230
|
+
|
|
231
|
+
`);return await a.close(),`${o?`AI Mode temporarily failed, used Standard search.
|
|
232
|
+
|
|
233
|
+
`:""}Search results for [${e}]:
|
|
234
|
+
|
|
235
|
+
${h}`}catch(d){if(i=d,a&&await a.close(),zr.writeFileSync(qr.join(cn,"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 jl from"puppeteer";import Hl from"turndown";import{gfm as Gl}from"turndown-plugin-gfm";var gi=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 jl.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(p=>setTimeout(p,c)),await d.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(p=>setTimeout(p,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 C=x.attributes;for(let A=C.length-1;A>=0;A--){let R=C[A].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(`
|
|
236
|
+
|
|
237
|
+
`))});let E=()=>{let x=!1;document.querySelectorAll("*").forEach(C=>{C.childNodes.length===0&&!C.innerText.trim()&&(C.remove(),x=!0)}),x&&E()};return E(),document.body.innerHTML});if(!f)throw new Error("EMPTY_RENDER_RESULT");let l=f.replace(/<br\s*\/?>/gi,`
|
|
238
|
+
|
|
239
|
+
`).replace(/[ \t]+/g," ").replace(/>[ \t]+</g,"><").replace(/\n\s+/g,`
|
|
240
|
+
`).replace(/\n{3,}/g,`
|
|
241
|
+
|
|
242
|
+
`).trim(),u=new Hl({headingStyle:"atx",codeBlockStyle:"fenced"});u.use(Gl);let h=u.turndown(l).replace(/\.\s*\n/g,`
|
|
243
|
+
`).replace(/ +/g," ").replace(/\t/g," ").replace(/\n\s+/g,`
|
|
244
|
+
`).replace(/\n{3,}/g,`
|
|
245
|
+
|
|
246
|
+
`),m=h.substring(0,5e4);return await r.close(),`Markdown parsed from [${t}]:
|
|
247
|
+
|
|
248
|
+
${m}${h.length>5e4?`
|
|
249
|
+
|
|
250
|
+
[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 Yl=4*(1024*2),yi=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"),m=n.match(h);return m?m[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=V(Vt,{});f[c]||(f[c]=[]),f[c].push(i),re(Vt,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=V(Mt,[]).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}]`,m=Yl,p=f.reduce((E,x)=>E+(x.memory?.length||0),0);for(;f.length>0&&p+h.length>m;){let E=f.shift();p-=E.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),re(Mt,f),`SUCCESS: Memory added with ID [${S.id}] and score [${S.score}]. (Vault Size: ${p+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 m=new Date,p=`${m.getDate()}/${m.getMonth()+1}/${m.getFullYear()}`,y=u.includes("[Saved on:")?u:`${u.trim()} [Saved on: ${p}]`;return f[h].memory=y,re(Mt,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(m=>m.id!==l);return h.length===u?`ERROR: Memory ID [${l}] not found.`:(re(Mt,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 wi=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 Lr(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 Co from"fs";import Vr from"path";var Qs=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,m=f||(c?c+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let p=Vr.resolve(process.cwd(),t);try{if(!Co.existsSync(p))return`ERROR: File [${t}] does not exist.`;if(Co.statSync(p).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let g=Vr.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 E={".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(E[g]){if(!(e.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let $=Co.readFileSync(p).toString("base64"),G=E[g];return{text:`[BINARY FILE]: ${t} (${G}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:$,mimeType:G}}}}let x=Co.readFileSync(p,"utf8");x.startsWith("\uFEFF")&&(x=x.slice(1)),x=x.replace(/\r\n/g,`
|
|
251
|
+
`).replace(/\r/g,`
|
|
252
|
+
`);let C=x.split(`
|
|
253
|
+
`),A=C.length;!l&&!u&&A>800&&(h=1,m=50);let R=Math.max(0,h-1),k=Math.min(A,m),w=C.slice(R,k),T=`File: [${t}] (Showing lines ${R+1}-${k} of ${A}).`,b=w.map((v,_)=>`${String(R+_+1).padStart(4)}: ${v.trimEnd()}`).join(`
|
|
254
|
+
`);return`${T}
|
|
255
|
+
|
|
256
|
+
${b}`}catch(y){let g=y instanceof Error?y.message:String(y);return`ERROR: Failed to read file [${t}]: ${g}`}};import vs from"fs";import Kr from"path";var Si=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,`
|
|
257
|
+
`).replace(/\r/g,`
|
|
258
|
+
`);let s=Kr.resolve(process.cwd(),t),i=Kr.dirname(s);try{await dt.recordFileChange(s);let r="";if(vs.existsSync(s))try{r=`Old File contents:
|
|
259
|
+
${vs.readFileSync(s,"utf8").split(/\r?\n/).map((C,A)=>`${A+1} | ${C}`).join(`
|
|
260
|
+
`)}
|
|
261
|
+
|
|
262
|
+
`}catch{r=`[Note: Could not read existing file for reversal reference]
|
|
263
|
+
|
|
264
|
+
`}vs.existsSync(i)||vs.mkdirSync(i,{recursive:!0});let d=(E=>E.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
265
|
+
`).replace(/\r/g,`
|
|
266
|
+
`))(o),c=d.endsWith(`
|
|
267
|
+
`)?d:d+`
|
|
268
|
+
`,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"),m=u.split(/\r?\n/),p=m.length;if(h===0&&l>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk!`;let y="";if(p<=100)y=m.join(`
|
|
269
|
+
`);else{let E=m.slice(0,50).join(`
|
|
270
|
+
`),x=m.slice(-50).join(`
|
|
271
|
+
`);y=`${E}
|
|
272
|
+
|
|
273
|
+
... [${p-100} lines truncated] ...
|
|
274
|
+
|
|
275
|
+
${x}`}u=null;let{systemSettings:g}=await Kt(),S=`SUCCESS: File [${t}] saved.
|
|
276
|
+
- Stats: [${p} lines, ${(h/1024).toFixed(1)} KB]
|
|
277
|
+
${r}- Content Preview:
|
|
278
|
+
|
|
279
|
+
${y}`;if(g?.compressToolResults&&p>60){let E=c.split(/\r?\n/),x=E.slice(0,25).join(`
|
|
280
|
+
`)===m.slice(0,25).join(`
|
|
281
|
+
`),C=E.slice(-25).join(`
|
|
282
|
+
`)===m.slice(-25).join(`
|
|
283
|
+
`);x&&C&&(S=`[[SAME]]
|
|
284
|
+
${S}`)}return S}catch(r){let a=r instanceof Error?r.message:String(r);return`ERROR: Failed to write file [${t}]: ${a}`}};import xi from"fs";import sc from"path";import zl from"os";var hn=n=>typeof n!="string"?n:n.length>12?(n+"").replace("",""):n,Xr=(n,e)=>{if(!n)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,o=n.split(`
|
|
285
|
+
`),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,m)=>{if(h.length===0)return;let p=i(h);if(f+p>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+=p}),(c.trimEnd().length>0||c===u)&&s.push(c.trimEnd())}),hn(s.join(`
|
|
286
|
+
`))},Ju=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()},Qu=(n,e=40)=>{let t=Mn.replaceAll("\\\\","\\");if(n=n.replace(zl.homedir(),"~").replace(t,"FluxFlow").replaceAll("\\","/"),!n||n.length<=e)return hn(n);let o=Math.floor((e-3)/2);return hn(n.substring(0,o)+"..."+n.substring(n.length-o).replaceAll("\\","/"))},Oo=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 m=d===1?[`${h}1`,h,`${h}_1`]:[`${h}${d}`,`${h}_${d}`];for(let p of m)if(n[p]!==void 0){l=n[p];break}if(l!==void 0)break}for(let h of f){let m=d===1?[`${h}1`,h,`${h}_1`]:[`${h}${d}`,`${h}_${d}`];for(let p of m)if(n[p]!==void 0){u=n[p];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}},ql=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===`
|
|
287
|
+
`)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]!==`
|
|
288
|
+
`&&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,`
|
|
289
|
+
`).replace(/\r/g,`
|
|
290
|
+
`),i=g=>g.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
291
|
+
`).replace(/\r/g,`
|
|
292
|
+
`),r=g=>g.match(/^\s*/)[0],a=g=>{let S=g.split(`
|
|
293
|
+
`).filter(x=>x.trim()!=="");if(S.length===0)return"";let E=r(S[0]);for(let x of S){let C=r(x);C.length<E.length&&(E=C)}return E},d=(g,S,E="")=>{if(!g||S===void 0)return g;let C=/^\t/m.test(S)?" ":" ",A=v=>v.split(`
|
|
294
|
+
`).find(_=>_.trim()!=="")??"",R=A(S).match(/^\s*/)[0].length,k=A(g).match(/^\s*/)[0].length,w=R-k,T=(E.match(/^\s*/)||[""])[0].length;return g.split(`
|
|
295
|
+
`).map((v,_)=>{if(v.trim()===""&&_!==0)return"";let $=v.match(/^\s*/)[0].length,G=Math.max(0,$+w);return _===0&&(G=Math.max(0,G-T)),C.repeat(G)+v.trimStart()}).join(`
|
|
296
|
+
`)},c=[];for(let g=0;g<e.length;g++){let S=e[g],E=(S.replace||"").trim(),x=i(S.new||"");if(E.startsWith("^LINE:")&&E.endsWith("$")){let T=E.slice(6,-1).trim().split(".."),b=parseInt(T[0]),v=T[1]!==void 0?parseInt(T[1]):b;if(!isNaN(b)&&!isNaN(v)){let _=s.split(`
|
|
297
|
+
`);if(b<1||b>_.length||v<b||v>_.length){c.push({index:g,success:!1,error:`Block ${g+1}: Line range ^LINE:${b}..${v}$ out of bounds (file has ${_.length} lines).`});continue}let G=_.slice(b-1,v).join(`
|
|
298
|
+
`),ce=0;for(let ge=0;ge<b-1;ge++)ce+=_[ge].length+1;c.push({index:g,success:!0,startPos:ce,firstMatchContent:G,content_to_add:x});continue}}let C=i(S.replace||"");if(C===""&&x===""){c.push({index:g,success:!1,error:`Block ${g+1}: Empty replace and add content.`});continue}let A=C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),R=null;if(C!==""&&s.includes(C))R=new RegExp(A,"g");else{let w=C.split(`
|
|
299
|
+
`).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(A,"g")}}else R=new RegExp(A,"g")}let k=[...s.matchAll(R)];if(k.length===0&&C!==""){let w=ql(C);w&&(k=[...s.matchAll(w)])}if(k.length===0){c.push({index:g,success:!1,error:`Block ${g+1}: Could not find match.`});continue}if(k.length>1&&!o){c.push({index:g,success:!1,error:`Block ${g+1}: Found ${k.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let w of k)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],E=f[g+1];S.startPos+S.firstMatchContent.length>E.startPos&&(S.success=!1,S.error=`Block ${S.index+1}: Overlaps with another block.`,E.success=!1,E.error=`Block ${E.index+1}: Overlaps with another block.`)}let l=new Map,u=s,h=0,m=0,p=c.filter(g=>g.success).sort((g,S)=>g.startPos-S.startPos);for(let g of p){let S=g.startPos,E=s.substring(0,S).split(`
|
|
300
|
+
`).length,x=S+h,C=E+m,A=u.lastIndexOf(`
|
|
301
|
+
`,x)+1,R=u.substring(A,x),k=d(g.content_to_add,g.firstMatchContent,R),w=u.split(`
|
|
302
|
+
`),T=[];for(let $=Math.max(0,C-4);$<C-1;$++)T.push({num:$+1,text:w[$]});let b=g.firstMatchContent.split(`
|
|
303
|
+
`),v=[],_=C+b.length-1;for(let $=_;$<Math.min(w.length,_+3);$++)v.push({num:$+1,text:w[$]});l.set(g,{success:!0,index:g.index,oldContent:g.firstMatchContent,newContent:k,originalStartLine:E,finalStartLine:C,contextBefore:T,contextAfter:v}),u=u.substring(0,x)+k+u.substring(x+g.firstMatchContent.length),h+=k.length-g.firstMatchContent.length,m+=k.split(`
|
|
304
|
+
`).length-g.firstMatchContent.split(`
|
|
305
|
+
`).length}let y=[];for(let g=0;g<e.length;g++){let S=p.filter(E=>E.index===g);if(S.length>0)for(let E of S)l.has(E)&&y.push(l.get(E));else{let E=c.find(x=>x.index===g);y.push({success:!1,error:E?E.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=p=>String(p).padStart(d," "),f=`[DIFF_START]
|
|
306
|
+
`,l="\u2550".repeat(88),u=0,h=null,m=t.filter(p=>p.success).sort((p,y)=>p.originalStartLine-y.originalStartLine);if(m.forEach((p,y)=>{let g=p.finalStartLine!==void 0?p.finalStartLine:p.originalStartLine;if(h===null)for(u=Math.max(0,g-4);u<g-1;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
|
|
307
|
+
`,u++;else{let k=h,w=k.originalStartLine+k.oldContent.split(`
|
|
308
|
+
`).length-1;if(p.originalStartLine-w-1>=o){let b=Math.min(r.length,u+3);for(;u<b;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
|
|
309
|
+
`,u++;for(f+=`[UI_CONTEXT] ${l}
|
|
310
|
+
`,u=Math.max(u,g-4);u<g-1;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
|
|
311
|
+
`,u++}else for(;u<g-1;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
|
|
312
|
+
`,u++}let S=p.originalStartLine-1,E=i[S]||"",x=p.oldContent.split(`
|
|
313
|
+
`),C=E.match(/^\s*/),A=C?C[0]:"";x.forEach((k,w)=>{let T=k;if(x.length===1&&E.trim().length>0&&E.includes(k.trim()))T=E;else if(w===0){let b=k.match(/^\s*/);(b?b[0]:"").length<A.length&&E.includes(k.trim())&&(T=A+k.trimStart())}f+=`-${c(p.originalStartLine+w)} |${T}
|
|
314
|
+
`});let R=u;if(p.finalStartLine!==void 0)R=p.finalStartLine-1+(p.newContent?p.newContent.split(`
|
|
315
|
+
`).length:0);else{let k=p.originalStartLine+x.length-1,w=i[k]||null;if(w!==null){let T=y<m.length-1?(m[y+1].originalStartLine||r.length)+10:r.length;for(let b=u;b<T;b++){if(r[b]===w){R=b;break}b===r.length-1&&(R=r.length)}}else R=r.length}for(;u<R;)f+=`+${c(u+1)} |${r[u]||""}
|
|
316
|
+
`,u++;h=p}),h!==null){let p=Math.min(r.length,u+3);for(;u<p;)f+=`[UI_CONTEXT] ${c(u+1)} |${r[u]||""}
|
|
317
|
+
`,u++}if(s){let p=`[DIFF_START]
|
|
318
|
+
`,y=f.substring(p.length),g=`[UI_CONTEXT] ${l}
|
|
319
|
+
`,E=y.split(g).map(x=>x.split(`
|
|
320
|
+
`).filter(A=>A.trim()!=="").length>45?`[[VERIFIED]]
|
|
321
|
+
${x}
|
|
322
|
+
[[/VERIFIED]]`:x);f=p+E.join(g)}return f+="[DIFF_END]",hn(f)},Vl=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?hn(s.substring(0,i).trim()):"",a=hn(i!==-1?s.substring(i+1):s);return{isR:t,isA:o,num:r,content:a}},Kl=(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 m=1;m<=a;m++)h===i[m-1]?c[m]=d[m-1]:c[m]=Math.min(d[m],c[m-1],d[m-1])+1;d.set(c)}let f=d[a],l=Math.max(t,o);return l===0?1:1-f/l},Jr=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]=Kl(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,m=i[f-1][l-1]+h,p=i[f-1][l],y=i[f][l-1];m>=p&&m>=y?(i[f][l]=m,r[f][l]="diag"):p>=y?(i[f][l]=p,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,Qr=200,Ti=6,Ei=(n,e)=>{e.set(n.key,n),n.type==="chunk"&&n.blocks&&n.blocks.forEach(t=>Ei(t,e))},Zu=(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=hn(nc(n.text||"",n.role==="think")),s=`${n.id}-${e}`,i=new Map;if(n.isStreaming){let m=ds.get(s);m&&o.startsWith(m.text)&&(i=m.blocksMap)}let r=(m,p,y,g={})=>{let S=i.get(m);if(S&&S.text===y&&S.type===p&&!!S.isActiveBlock==!!g.isActiveBlock&&!!S.isStreaming==!!g.isStreaming&&S.pairContent===g.pairContent)return S;let E=hn(y),x={...g};return typeof x.pairContent=="string"&&(x.pairContent=hn(x.pairContent)),Array.isArray(x.wrappedLines)&&(x.wrappedLines=x.wrappedLines.map(hn)),{key:m,isStreamingMsg:!!n.isStreaming,workedDuration:n.workedDuration,type:p,text:E,msg:p==="full-message"?n:void 0,...x}};if(o.includes("- Content Preview:")){let m="",p=o.match(/File\s+\[(.*?)\]/i);p&&(m=p[1].split(".").pop().toLowerCase());let x=((o.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
|
|
323
|
+
`).map(b=>b.replace(/\r$/,"")),C=String(x.length).length,A=[],R=null,k=[],w=()=>{if(!k.length)return;let b=k;k=[],A.push(b.length===1?b[0]:{key:`${b[0].key}-chunk`,type:"chunk",blocks:b})},T=e-(C+6);return x.forEach((b,v)=>{let _=v===x.length-1,$=Xr(b,T).split(`
|
|
324
|
+
`),G=r(`${n.id||Date.now()}-write-line-${v}`,"write-line",b,{gutterWidth:C,lineNum:v+1,isFirstLine:v===0,isLastLine:_,extension:m,wrappedLines:$});_&&n.isStreaming?(w(),R=G):(k.push(G),k.length>=Ti&&w())}),w(),{completed:A,active:R?[R]:[]}}if(o.includes("[DIFF_START]")){let m=o.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),y=(m?m[1].trim():"").split(`
|
|
325
|
+
`).map(R=>R.replace(/\r$/,"")),g=y.map(R=>({line:R,parsed:Vl(R),pairContent:null})),S=[];for(let R=0;R<g.length;R++){let k=g[R];k.parsed&&(k.parsed.isR||k.parsed.isA)?S.push(k):S.length>0&&(Jr(S),S=[])}S.length>0&&Jr(S);let E=[],x=null,C=[],A=()=>{if(!C.length)return;let R=C;C=[],E.push(R.length===1?R[0]:{key:`${R[0].key}-chunk`,type:"chunk",blocks:R})};return y.forEach((R,k)=>{let w=k===y.length-1,T=g[k].parsed,b=null;T&&(b=Xr(T.content,e-17).split(`
|
|
326
|
+
`));let v=r(`${n.id||Date.now()}-diff-${k}`,"diff-line",R,{isFirstLine:k===0,isLastLine:w,pairContent:g[k].pairContent,wrappedLines:b});w&&n.isStreaming?(A(),x=v):(C.push(v),C.length>=Ti&&A())}),A(),{completed:E,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 m={completed:[],active:[]};return Yn.set(t,m),m}let a=[],d=null,c=[],f=null,l=()=>{if(!c.length)return;let m=c;c=[],f=null,a.push(m.length===1?m[0]:{key:`${n.id||"x"}-chunk-${m[0].key}`,type:"chunk",blocks:m})},u=(m,p=!1)=>{if(f!==null&&f!==m.type&&l(),c.push(m),f=m.type,c.length>=Ti){if(n.isStreaming&&p)return;l()}};if(n.role==="think"){a.push(r(`${n.id}-header`,"think-header",""));let m=o.split(`
|
|
327
|
+
`);m.forEach((p,y)=>{let g=y===m.length-1;u(r(`${n.id}-${y}`,"think-line",p,{}),g)}),n.isStreaming||(l(),a.push({key:`${n.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let m=o.split(`
|
|
328
|
+
`),p=!1,y=[],g=!1,S="",E=0,x=0;m.forEach((C,A)=>{let R=A===m.length-1,k=C.trim().startsWith("|"),w=C.trim().startsWith("```");g?w?(g=!1,u(r(`${n.id}-code-close-${x}`,"code-fence-close","",{}),R)):(E++,u(r(`${n.id}-code-line-${A}`,"code-line",C,{lineNum:E,lang:S}),R)):w?(g=!0,x=A,E=0,S=C.trim().replace(/^```/,"").trim(),u(r(`${n.id}-code-open-${A}`,"code-fence-open",S,{}),R)):k?(p=!0,y.push(C),R&&(l(),n.isStreaming?d=r(`${n.id}-table-${A}`,"table",y.join(`
|
|
329
|
+
`),{isStreaming:!0}):a.push(r(`${n.id}-table-${A}`,"table",y.join(`
|
|
330
|
+
`),{isStreaming:!1})))):(p&&(l(),a.push(r(`${n.id}-table-${A}`,"table",y.join(`
|
|
331
|
+
`),{isStreaming:!1})),p=!1,y=[]),u(r(`${n.id}-${A}`,"agent-line",C,{}),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 m=new Map;if(a.forEach(p=>Ei(p,m)),d&&Ei(d,m),ds.set(s,{text:o,blocksMap:m}),ds.size>Qr){let p=ds.keys().next().value;ds.delete(p)}}else{if(Yn.set(t,h),Yn.size>Qr){let m=Yn.keys().next().value;Yn.delete(m)}ds.delete(s)}return h},Xl={},Jl=/<\/think>(\r?\n){2}/gi,Ql=/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|agent:generalist|agent\.generalist|\s*turn\s*:))/gi,bi=(n,e)=>{let t=!1;for(let o=0;o<e;o++)n[o]==="`"&&(t=!t);return t},Zl=/\[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,ec=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,tc=/\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,nc=(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(Jl,"</think>").replace(Ql,(i,r,a,d)=>!Ls&&bi(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&&bi(t,c)){let g=c+d.length,S=i.indexOf(o,g),E=i.indexOf(s,g);if(S===-1&&E===-1)break;let x=-1,C=0;for(;;){let A=i.indexOf(o,C),R=i.indexOf(s,C),k=-1,w=o;if(A===-1&&R===-1)break;if(A===-1||R!==-1&&R<A?(k=R,w=s):k=A,!bi(t,k)){x=k,d=w;break}C=k+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,m=!1,p=null,y=c;for(;y<t.length;){let g=t[y];if(!p&&(g==="'"||g==='"'||g==="`")?p=g:p&&g===p&&t[y-1]!=="\\"&&(p=null),p||(g==="("?(h++,m=!0):g===")"&&h--),m&&h===0&&!p){let S=y;if(l){let E=y+1;for(;E<t.length&&/\s/.test(t[E]);)E++;E<t.length&&t[E]==="]"&&(S=E)}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(Zl,""),t=t.replace(ec,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(tc,i=>Xl[i.toLowerCase()]||i),t.trim()},eh=()=>{Yn.clear(),ds.clear()};var Ri=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}=Oo(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=sc.resolve(process.cwd(),o);try{if(!xi.existsSync(d))return`ERROR: File [${o}] does not exist. Use WriteFile instead.`;let c=e.forcedContent||xi.readFileSync(d,"utf8");c.startsWith("\uFEFF")&&(c=c.slice(1));let f=c.replace(/\r\n/g,`
|
|
332
|
+
`).replace(/\r/g,`
|
|
333
|
+
`),{content:l,results:u}=$o(f,s,{allowMultiple:a}),h=u.filter(g=>!g.success),m=u.filter(g=>g.success);if(m.length===0)return`ERROR: Patch Failed to apply to [${o}].
|
|
334
|
+
${h.map(g=>` \u2022 ${g.error}`).join(`
|
|
335
|
+
`)}`;await dt.recordFileChange(d,f),xi.writeFileSync(d,l,"utf8");let{systemSettings:p}=await Kt(),y=Mo(f,l,u,12,p?.compressToolResults);return h.length>0?`SUCCESS: File [${o}] updated with some blocks failed. [${m.length}/${s.length}] blocks applied.
|
|
336
|
+
|
|
337
|
+
Failures:
|
|
338
|
+
${h.map(g=>` \u2022 ${g.error}`).join(`
|
|
339
|
+
`)}
|
|
340
|
+
|
|
341
|
+
${y}`:`SUCCESS: File [${o}] updated. [${u.length}/${s.length}] blocks applied.
|
|
342
|
+
|
|
343
|
+
${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 ki from"path";var oc=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"]),ic=n=>oc.has(n)||n.startsWith(".pnpm"),rc=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"}},Ai=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=ki.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 p=us.readdirSync(s),y=p.length,g=150,S=p.slice(0,g),E=[];for(let A of S){let R=ki.join(s,A),k={name:A,type:"unknown",size:"N/A",mtime:"N/A"};try{let w=us.statSync(R);k={name:A,type:w.isDirectory()?"directory":"file",size:(w.size/1024).toFixed(1)+"KB",mtime:rc(w.mtime)}}catch{k.type="inaccessible"}E.push(k)}let x=E.map(A=>A.type==="directory"?`${A.name}/`:`${A.name} (${A.size}, ${A.mtime})`).join(`
|
|
344
|
+
`),C=`
|
|
345
|
+
|
|
346
|
+
(Total items in folder: ${y})`;return y>g&&(C=`
|
|
347
|
+
|
|
348
|
+
TRUNCATED: Showing first ${g} of ${y} items.`),p.length=0,S.length=0,E.length=0,`Detailed folder stats for [${t}]:
|
|
349
|
+
|
|
350
|
+
${x}${C}`}let r=0,a=0,d=0,c=500,f=!1,l=(p,y,g=1)=>{if(y>o||f)return[];let S=[];try{S=us.readdirSync(p)}catch{return[`${" ".repeat(g-1)}[Inaccessible Directory]`]}let E=[],x=[];for(let k of S){let w=ki.join(p,k),T=!1;try{T=us.statSync(w).isDirectory()}catch{}T?E.push({name:k,fullPath:w}):x.push({name:k,fullPath:w})}E.sort((k,w)=>k.name.localeCompare(w.name)),x.sort((k,w)=>k.name.localeCompare(w.name));let C=[],A=" ".repeat(g-1);for(let k of E){if(d>=c){f=!0,C.push(`${A}[Truncated - Maximum item limit reached (${c})]`);break}if(d++,r++,C.push(`${A}${k.name}/`),y<o&&!ic(k.name)){let w=l(k.fullPath,y+1,g+1);C.push(...w)}}let R=[];for(let k of x){if(d>=c){f=!0,C.push(`${A}[Truncated - Maximum item limit reached (${c})]`);break}d++,a++;let w="N/A";try{w=(us.statSync(k.fullPath).size/1024).toFixed(1)+"KB"}catch{}R.push(`${k.name} (${w})`)}return R.length>0&&C.push(`${A}${R.join("; ")}`),C},h=l(s,1,1).join(`
|
|
351
|
+
`),m=`
|
|
352
|
+
|
|
353
|
+
(Total items scanned: ${d}, Directories: ${r}, Files: ${a})`;return f&&(m=`
|
|
354
|
+
|
|
355
|
+
TRUNCATED: Scan capped at ${c} items. (Directories: ${r}, Files: ${a})`),`Detailed directory tree for [${t}] (recursive depth: ${o}):
|
|
356
|
+
|
|
357
|
+
${h}${m}`}catch(i){let r=i instanceof Error?i.message:String(i);return`ERROR: Failed to read folder [${t}]: ${r}`}};var Ci=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 ac from"puppeteer";import Ns from"path";import hs from"fs-extra";import{PDFDocument as lc}from"pdf-lib";var Oi=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 dt.recordFileChange(i);let a=fs();r=await ac.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 k=Ns.resolve(process.cwd(),R);if(await hs.pathExists(k)){let w=Ns.extname(k).toLowerCase().replace(".","")||"png",T=w==="jpg"?"jpeg":w==="svg"?"svg+xml":w,b=await hs.readFile(k,"base64");return`data:image/${T};base64,${b}`}}catch{}return null},u=/<link[^>]+href=["']([^"']+)["']/gi,h={},m;for(;(m=u.exec(t))!==null;){let R=m[1],k=m[0];if(R&&k.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[k]=`<style>${T}</style>`}}catch{}}for(let[R,k]of Object.entries(h))c=c.split(R).join(k);let p=/<img[^>]+src=["']([^"']+)["']/gi;for(;(m=p.exec(c))!==null;){let R=m[1];if(R&&!f[R]){let k=await l(R);k&&(f[R]=k)}}let y=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(m=y.exec(c))!==null;){let R=m[1].trim();if(R&&!f[R]){let k=await l(R);k&&(f[R]=k)}}for(let[R,k]of Object.entries(f)){let w=R.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),T=new RegExp(`(src=["'])(${w})(["'])`,"gi");c=c.replace(T,`$1${k}$3`);let b=new RegExp(`url\\(\\s*(['"]?)(${w})\\1\\s*\\)`,"gi");c=c.replace(b,`url($1${k}$1)`)}let g=`
|
|
358
|
+
<style>
|
|
359
|
+
@page {
|
|
360
|
+
margin: ${s};
|
|
361
|
+
}
|
|
362
|
+
body {
|
|
363
|
+
margin: 0;
|
|
364
|
+
padding: 0;
|
|
365
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
366
|
+
}
|
|
367
|
+
* { box-sizing: border-box; }
|
|
368
|
+
.watermark {
|
|
369
|
+
position: fixed;
|
|
370
|
+
top: 50%;
|
|
371
|
+
left: 50%;
|
|
372
|
+
transform: translate(-50%, -50%) rotate(-50deg);
|
|
373
|
+
font-size: 52px;
|
|
374
|
+
font-weight: bold;
|
|
375
|
+
color: rgba(0, 0, 0, 0.005);
|
|
376
|
+
pointer-events: none;
|
|
377
|
+
z-index: -1000;
|
|
378
|
+
text-align: center;
|
|
379
|
+
width: 150%;
|
|
380
|
+
white-space: nowrap;
|
|
381
|
+
text-transform: uppercase;
|
|
382
|
+
letter-spacing: 5px;
|
|
383
|
+
}
|
|
384
|
+
</style>
|
|
385
|
+
<div class="watermark">Generated by FluxFlow CLI (AI)</div>
|
|
386
|
+
${c}
|
|
387
|
+
`;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}),E=await lc.load(S),x=Ns.basename(e);E.setTitle(`FluxFlow_${x}`),E.setAuthor("FluxFlow CLI"),E.setSubject("Generated with Agentic AI System"),E.setKeywords(["FluxFlow","AI","Agentic","Automated"]),E.setCreator("FluxFlow PDF Engine"),E.setProducer("FluxFlow (Generative AI)");let C=await E.save();await hs.writeFile(i,C);let A=await hs.stat(i);return`SUCCESS: PDF generated successfully at [${e}] (${(A.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 Zr from"fs-extra";import $i from"path";import cc 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 Zr.ensureDir($i.dirname(o)),await dt.recordFileChange(o);let s=$i.basename(e),i=t.includes("<html")?t:`
|
|
388
|
+
<!DOCTYPE html>
|
|
389
|
+
<html lang="en">
|
|
390
|
+
<head>
|
|
391
|
+
<meta charset="UTF-8">
|
|
392
|
+
<title>FluxFlow Document</title>
|
|
393
|
+
</head>
|
|
394
|
+
<body>
|
|
395
|
+
${t}
|
|
396
|
+
</body>
|
|
397
|
+
</html>
|
|
398
|
+
`,r=await cc(i,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await Zr.writeFile(o,r),`SUCCESS: Word document [${e}] generated successfully.
|
|
399
|
+
- 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 Ui from"fs/promises";import ms from"path";import Fi from"fast-glob";var _i=(n,e,t)=>{let o=n instanceof RegExp?ea(n,t):n,s=e instanceof RegExp?ea(e,t):e,i=o!==null&&s!=null&&fc(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)}},ea=(n,e)=>{let t=e.match(n);return t?t[0]:null},fc=(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 ta="\0SLASH"+Math.random()+"\0",na="\0OPEN"+Math.random()+"\0",Li="\0CLOSE"+Math.random()+"\0",sa="\0COMMA"+Math.random()+"\0",oa="\0PERIOD"+Math.random()+"\0",dc=new RegExp(ta,"g"),uc=new RegExp(na,"g"),hc=new RegExp(Li,"g"),pc=new RegExp(sa,"g"),mc=new RegExp(oa,"g"),gc=/\\\\/g,yc=/\\{/g,wc=/\\}/g,Sc=/\\,/g,Tc=/\\\./g,bc=1e5,Ec=4e6;function Ii(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function xc(n){return n.replace(gc,ta).replace(yc,na).replace(wc,Li).replace(Sc,sa).replace(Tc,oa)}function Rc(n){return n.replace(dc,"\\").replace(uc,"{").replace(hc,"}").replace(pc,",").replace(mc,".")}function ia(n){if(!n)return[""];let e=[],t=_i("{","}",n);if(!t)return n.split(",");let{pre:o,body:s,post:i}=t,r=o.split(",");r[r.length-1]+="{"+s+"}";let a=ia(i);return i.length&&(r[r.length-1]+=a.shift(),r.push.apply(r,a)),e.push.apply(e,r),e}function ra(n,e={}){if(!n)return[];let{max:t=bc,maxLength:o=Ec}=e;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),vi(xc(n),t,o,!0).map(Rc)}function kc(n){return"{"+n+"}"}function Ac(n){return/^-?0\d/.test(n)}function Cc(n,e){return n<=e}function Oc(n,e){return n>=e}function Zs(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=Ii(s[0]),a=Ii(s[1]),d=Math.max(s[0].length,s[1].length),c=s.length===3&&s[2]!==void 0?Math.max(Math.abs(Ii(s[2])),1):1,f=Cc;a<r&&(c*=-1,f=Oc);let u=s.some(Ac),h=0;for(let m=r;f(m,a)&&i.length<t;m+=c){let p;if(e)p=String.fromCharCode(m),p==="\\"&&(p="");else if(p=String(m),u){let y=d-p.length;if(y>0){let g=new Array(y+1).join("0");m<0?p="-"+g+p.slice(1):p=g+p}}if(h+p.length>o)break;i.push(p),h+=p.length}return i}function vi(n,e,t,o){let s=[""],i=!1,r=!0;for(;;){let a=_i("{","}",n);if(!a)return Zs(s,n,[""],e,t,i);let d=a.pre;if(/\$$/.test(d)){if(s=Zs(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+Li+a.post,o=!0;continue}return Zs(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 m=ia(a.body);if(m.length===1&&m[0]!==void 0&&(m=vi(m[0],e,t,!1).map(kc),m.length===1)){if(s=Zs(s,d+m[0],[""],e,t,i&&!a.post.length),!a.post.length)break;n=a.post;continue}let p=i&&!a.post.length&&!d;for(let g=0;p&&g<s.length;g++)s[g]&&(p=!1);h=[];let y=0;e:for(let g=0;g<m.length;g++){let S=vi(m[g],e,t,!1);for(let E=0;E<S.length;E++){let x=S[E];if(!(p&&!x)){if(h.length>=e||y+x.length>t)break e;h.push(x),y+=x.length}}}}if(s=Zs(s,d,h,e,t,i&&!a.post.length),!a.post.length)break;n=a.post}return s}var eo=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]},to=n=>n.replace(/[[\]\\-]/g,"\\$&"),_c=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),aa=n=>n.join(""),la=(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 p=n.charAt(i);if((p==="!"||p==="^")&&i===t+1){c=!0,i++;continue}if(p==="]"&&r&&!d){f=i+1;break}if(r=!0,p==="\\"&&!d){d=!0,i++;continue}if(p==="["&&!d){for(let[y,[g,S,E]]of Object.entries(Mc))if(n.startsWith(y,i)){if(l)return["$.",!1,n.length-t,!0];i+=y.length,E?s.push(g):o.push(g),a=a||S;continue e}}if(d=!1,l){p>l?o.push(to(l)+"-"+to(p)):p===l&&o.push(to(p)),l="",i++;continue}if(n.startsWith("-]",i+1)){o.push(to(p+"-")),i+=2;continue}if(n.startsWith("-",i+1)){l=p,i+=2;continue}o.push(to(p)),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 p=o[0].length===2?o[0].slice(-1):o[0];return[_c(p),!1,f-t,!1]}let u="["+(c?"^":"")+aa(o)+"]",h="["+(c?"":"^")+aa(s)+"]";return[o.length&&s.length?"("+u+"|"+h+")":o.length?u:h,a,f-t,!0]};var zn=(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 Wt,Ic=new Set(["!","?","+","*","@"]),Ni=n=>Ic.has(n),ca=n=>Ni(n.type),vc=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),Lc=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),Nc=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),fa=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),Pc="(?!(?:^|/)\\.\\.?(?:$|/))",_o="(?!\\.)",Dc=new Set(["[","."]),Fc=new Set(["..","."]),Uc=new Set("().*{}+?[]^$\\!"),Bc=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Pi="[^/]",da=Pi+"*?",ua=Pi+"+?",Wc=0,ps=class{type;#n;#s;#o=!1;#e=[];#t;#a;#c;#l=!1;#i;#r;#f=!1;id=++Wc;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 Wt&&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 Wt&&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 Wt(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 p=o,y="";for(;p<e.length;){let g=e.charAt(p++);if(a||g==="\\"){a=!a,y+=g;continue}if(d){p===c+1?(g==="^"||g==="!")&&(f=!0):g==="]"&&!(p===c+2&&f)&&(d=!1),y+=g;continue}else if(g==="["){d=!0,c=p,f=!1,y+=g;continue}if(!s.noext&&Ni(g)&&e.charAt(p)==="("&&i<=r){t.push(y),y="";let E=new Wt(g,t);p=Wt.#d(e,E,p,s,i+1),t.push(E);continue}y+=g}return t.push(y),p}let l=o+1,u=new Wt(null,t),h=[],m="";for(;l<e.length;){let p=e.charAt(l++);if(a||p==="\\"){a=!a,m+=p;continue}if(d){l===c+1?(p==="^"||p==="!")&&(f=!0):p==="]"&&!(l===c+2&&f)&&(d=!1),m+=p;continue}else if(p==="["){d=!0,c=l,f=!1,m+=p;continue}if(!s.noext&&Ni(p)&&e.charAt(l)==="("&&(i<=r||t&&t.#u(p))){let g=t&&t.#u(p)?0:1;u.push(m),m="";let S=new Wt(p,u);u.push(S),l=Wt.#d(e,S,l,s,i+g);continue}if(p==="|"){u.push(m),m="",h.push(u),u=new Wt(null,t);continue}if(p===")")return m===""&&t.#e.length===0&&(t.#f=!0),u.push(m),m="",t.push(...h,u),l;m+=p}return t.type=null,t.#s=void 0,t.#e=[e.substring(o-1)],l}#w(e){return this.#p(e,Lc)}#p(e,t=vc){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=Nc){return!!t.get(this.type)?.includes(e)}#S(e,t){let o=e.#e[0],s=new Wt(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!!fa.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=fa.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 Wt(null,void 0,t);return Wt.#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()),!ca(this)){let d=this.isStart()&&this.isEnd()&&!this.#e.some(h=>typeof h!="string"),c=this.#e.map(h=>{let[m,p,y,g]=typeof h=="string"?Wt.#x(h,this.#s,d):h.toRegExpSource(e);return this.#s=this.#s||y,this.#o=this.#o||g,m}).join(""),f="";if(this.isStart()&&typeof this.#e[0]=="string"&&!(this.#e.length===1&&Fc.has(this.#e[0]))){let m=Dc,p=t&&m.has(c.charAt(0))||c.startsWith("\\.")&&m.has(c.charAt(2))||c.startsWith("\\.\\.")&&m.has(c.charAt(4)),y=!t&&!e&&m.has(c.charAt(0));f=p?Pc:y?_o:""}let l="";return this.isEnd()&&this.#n.#l&&this.#t?.type==="!"&&(l="(?:$|\\/)"),[f+c+l,zn(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,zn(this.toString()),!1,!1]}let r=!o||e||t||!_o?"":this.#g(!0);r===i&&(r=""),r&&(i=`(?:${i})(?:${r})*?`);let a="";if(this.type==="!"&&this.#f)a=(this.isStart()&&!t?_o:"")+ua;else{let d=this.type==="!"?"))"+(this.isStart()&&!t&&!e?_o:"")+da+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&r?")":this.type==="*"&&r?")?":`)${this.type}`;a=s+i+d}return[a,zn(i),this.#s=!!this.#s,this.#o]}#h(){if(ca(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+=(Uc.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,i+=o&&/^[*]+$/.test(e)?ua:da,t=!0;continue}else a=!1;if(c==="\\"){d===e.length-1?i+="\\\\":s=!0;continue}if(c==="["){let[f,l,u,h]=la(e,d);if(u){i+=f,r=r||l,d+=u-1,t=t||h;continue}}if(c==="?"){i+=Pi,t=!0;continue}i+=Bc(c)}return[i,zn(e),!!t,r]}};Wt=ps;var Di=(n,{windowsPathsNoEscape:e=!1,magicalBraces:t=!1}={})=>t?e?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var _t=(n,e,t={})=>(eo(e),!t.nocomment&&e.charAt(0)==="#"?!1:new vn(e,t).match(n)),jc=/^\*+([^+@!?*[(]*)$/,Hc=n=>e=>!e.startsWith(".")&&e.endsWith(n),Gc=n=>e=>e.endsWith(n),Yc=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),zc=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),qc=/^\*+\.\*+$/,Vc=n=>!n.startsWith(".")&&n.includes("."),Kc=n=>n!=="."&&n!==".."&&n.includes("."),Xc=/^\.\*+$/,Jc=n=>n!=="."&&n!==".."&&n.startsWith("."),Qc=/^\*+$/,Zc=n=>n.length!==0&&!n.startsWith("."),ef=n=>n.length!==0&&n!=="."&&n!=="..",tf=/^\?+([^+@!?*[(]*)?$/,nf=([n,e=""])=>{let t=ma([n]);return e?(e=e.toLowerCase(),o=>t(o)&&o.toLowerCase().endsWith(e)):t},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=ga([n]);return e?o=>t(o)&&o.endsWith(e):t},rf=([n,e=""])=>{let t=ma([n]);return e?o=>t(o)&&o.endsWith(e):t},ma=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},ga=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},ya=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ha={win32:{sep:"\\"},posix:{sep:"/"}},af=ya==="win32"?ha.win32.sep:ha.posix.sep;_t.sep=af;var At=Symbol("globstar **");_t.GLOBSTAR=At;var lf="[^/]",cf=lf+"*?",ff="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",df="(?:(?!(?:\\/|^)\\.).)*?",uf=(n,e={})=>t=>_t(t,n,e);_t.filter=uf;var sn=(n,e={})=>Object.assign({},n,e),hf=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return _t;let e=_t;return Object.assign((o,s,i={})=>e(o,s,sn(n,i)),{Minimatch:class extends e.Minimatch{constructor(s,i={}){super(s,sn(n,i))}static defaults(s){return e.defaults(sn(n,s)).Minimatch}},AST:class extends e.AST{constructor(s,i,r={}){super(s,i,sn(n,r))}static fromGlob(s,i={}){return e.AST.fromGlob(s,sn(n,i))}},unescape:(o,s={})=>e.unescape(o,sn(n,s)),escape:(o,s={})=>e.escape(o,sn(n,s)),filter:(o,s={})=>e.filter(o,sn(n,s)),defaults:o=>e.defaults(sn(n,o)),makeRe:(o,s={})=>e.makeRe(o,sn(n,s)),braceExpand:(o,s={})=>e.braceExpand(o,sn(n,s)),match:(o,s,i={})=>e.match(o,s,sn(n,i)),sep:e.sep,GLOBSTAR:At})};_t.defaults=hf;var wa=(n,e={})=>(eo(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:ra(n,{max:e.braceExpandMax}));_t.braceExpand=wa;var pf=(n,e={})=>new vn(n,e).makeRe();_t.makeRe=pf;var mf=(n,e,t={})=>{let o=new vn(e,t);return n=n.filter(s=>o.match(s)),o.options.nonull&&!n.length&&n.push(e),n};_t.match=mf;var pa=/[?*]|[+@!]\(.*?\)|\[|\]/,gf=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vn=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){eo(e),t=t||{},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||ya,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]==="?"||!pa.test(i[2]))&&!pa.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,m]=[e[l],t[u]];h.toLowerCase()===m.toLowerCase()&&(t[u]=h,i=u,s=l)}}let{optimizationLevel:r=1}=this.options;return r>=2&&(e=this.levelTwoFileOptimize(e)),t.includes(At)?this.#n(e,t,o,s,i):this.#o(e,t,o,s,i)}#n(e,t,o,s,i){let r=t.indexOf(At,i),a=t.lastIndexOf(At),[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 E=s;E<e.length-l;E++){let x=String(e[E]);if(S=!0,x==="."||x===".."||!this.options.dot&&x.startsWith("."))return!1}return o||S}let u=[[[],0]],h=u[0],m=0,p=[0];for(let S of c)S===At?(p.push(m),h=[[],0],u.push(h)):(h[0].push(S),m++);let y=u.length-1,g=e.length-l;for(let S of u)S[1]=g-(p[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===At)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 wa(this.pattern,this.options)}parse(e){eo(e);let t=this.options;if(e==="**")return At;if(e==="")return"";let o,s=null;(o=e.match(Qc))?s=t.dot?ef:Zc:(o=e.match(jc))?s=(t.nocase?t.dot?zc:Yc:t.dot?Gc:Hc)(o[1]):(o=e.match(tf))?s=(t.nocase?t.dot?sf:nf:t.dot?of:rf)(o):(o=e.match(qc))?s=t.dot?Kc:Vc:(o=e.match(Xc))&&(s=Jc);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?cf:t.dot?ff:df,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"?gf(l):l===At?At:l._src});c.forEach((l,u)=>{let h=c[u+1],m=c[u-1];l!==At||m===At||(m===void 0?h!==void 0&&h!==At?c[u+1]="(?:\\/|"+o+"\\/)?"+h:c[u]=o:h===void 0?c[u-1]=m+"(?:\\/|\\/"+o+")?":h!==At&&(c[u-1]=m+"(?:\\/|\\/"+o+"\\/)"+h,c[u+1]=At))});let f=c.filter(l=>l!==At);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 _t.defaults(e).Minimatch}};_t.AST=ps;_t.Minimatch=vn;_t.escape=Di;_t.unescape=zn;async function no(n,e,t=n,o=1){if(o>12)return[];let s=[],i;try{i=await Ui.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(m=>m===h||m.startsWith(".pnpm"))}))if(r.isDirectory()){let u=await no(a,e,t,o+1);s=s.concat(u)}else r.isFile()&&s.push({fullPath:a,relativePath:d})}return s}function yf(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 wf(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&&yf(r,d,a)<=a)return!0;return!1})}var so=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=p=>p===!0||p==="true"||p===1||p==="1"||p==="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(p){if(c)return`ERROR: Invalid regex pattern "${r}": ${p.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"],m=150;try{let p=[],y=process.cwd(),g=null;if(t){let _=t.split(";").map(ce=>ce.trim()).filter(Boolean),$=_.some(ce=>ce.startsWith("!"));if(_.some(ce=>Fi.isDynamicPattern(ce)||/[*?{}[\]()|+]/.test(ce))){g="glob";let ce=t.replace(/\\/g,"/"),ge=_.map(P=>P.replace(/\\/g,"/")),z=h.map(P=>P.startsWith(".")?`**/*${P}`:`**/${P}/**`);if($&&!_.some(P=>!P.startsWith("!"))){let P=await no(y,h,y),F=O=>O.endsWith("/")?O+"**":O,he=ge.filter(O=>O.startsWith("!")).map(O=>F(O.slice(1))),ye=ge.filter(O=>!O.startsWith("!")).map(F);p=P.filter(O=>{let D=O.relativePath.replace(/\\/g,"/"),ne=ye.length===0||ye.some(Me=>{try{return new vn(Me).match(D)}catch{return!1}}),q=he.some(Me=>{try{return new vn(Me).match(D)}catch{return!1}});return ne&&!q})}else{let P=ge.some(he=>/[\(\)\|]|\.\*/.test(he)),F=[];if(!P)try{F=await Fi(ge,{cwd:y,ignore:z,dot:!0,onlyFiles:!0,absolute:!1})}catch{F=[]}if(F.length===0&&(P||Fi.isDynamicPattern(ce))){let he=ce.match(/^([^\*\?\(\)\|\[\]\s]+)\//),ye=he&&!/[\*\?\(\)\|\[\]]/.test(he[1])?ms.resolve(y,he[1]):y,O=await no(ye,h,y);try{let D=ce.replace(/^\.\//,"");D=D.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!D.startsWith("^")&&!D.startsWith(".*")&&(D=`.*${D}`);let ne=new RegExp(D.endsWith("$")?D:`${D}$`,"i");p=O.filter(q=>{let Me=q.relativePath.replace(/\\/g,"/");return ne.test(Me)})}catch{p=[]}}else p=F.map(he=>({fullPath:ms.resolve(y,he),relativePath:he}))}}else{let ce=t.replace(/[\/\\]+$/,""),ge=ms.resolve(y,ce);try{let z=await Ui.stat(ge);if(z.isDirectory())g="dir",p=await no(ge,h,y);else if(z.isFile())g="file",p.push({fullPath:ge,relativePath:ms.relative(y,ge)});else return`ERROR: Path is neither a file nor a directory: ${t}`}catch{return`ERROR: Path not found: ${t}`}}}else p=await no(y,h);let S=p.map(async _=>{try{let $=await Ui.readFile(_.fullPath,"utf-8");if($.includes("\0"))return[];let G=$.split(/\r?\n/),ce=[];for(let z=0;z<G.length;z++)(f?G[z].toLowerCase().includes(r.toLowerCase())||wf(G[z],r):d?u&&u.test(G[z]):l&&l.test(G[z])||u&&u.test(G[z]))&&ce.push({line:z+1,content:G[z].trim()});return ce.length===0?null:{path:_.relativePath.replace(/\\/g,"/"),matches:ce}}catch{return[]}}),E=await Promise.all(S),x=[],C=0;for(let _ of E){if(!_||!_.matches)continue;if(C>=m)break;let $=m-C,G=_.matches.slice(0,$);x.push({path:_.path,matches:G}),C+=G.length}typeof global.gc=="function"&&global.gc();let A=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",$=g==="dir"?"[DIR]":g==="glob"?"[GLOB]":"";return`${$}${$?" ":""}Found 0 matches of '${r}'${_}${A?` ${A}`:""}`}let R=A?` ${A}`:"",k=`${x.length} file${x.length===1?"":"s"}`,w=`${C} match${C===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 ${k}${R}:`:T=`Found ${w} of '${r}' across ${k}${R}:`;let b=g==="dir"?"[DIR]":g==="glob"?"[GLOB]":"",v=`${b}${b?" ":""}${T}
|
|
400
|
+
|
|
401
|
+
`;for(let _ of x){v+=`${_.path}
|
|
402
|
+
`;for(let $ of _.matches)v+=` ${$.line}: ${$.content}
|
|
403
|
+
`;v+=`
|
|
404
|
+
`}return v.trimEnd()}catch(p){return`ERROR: ${p.message}`}};import Sa from"fs-extra";import Bi from"path";var Sf=(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}},Wi=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 Kt();if(!await Br(c))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await Wr()).nextResetMin||60}m).`;let l=c.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},u=l.keyType==="Custom"&&l.apiKey?l.apiKey:FALLBACK_IMAGE_KEY,m={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[l.quality]||"zimage",p=1024,y=1024;if(i){let $=i.replace(/\s+/g,"");$==="16:9"?(p=1024,y=576):$==="9:16"?(p=576,y=1024):$==="4:3"?(p=1024,y=768):$==="3:4"?(p=768,y=1024):$==="1:1"&&(p=1024,y=1024)}let g=Math.floor(Math.random()*1e7),E=`https://gen.pollinations.ai/image/${encodeURIComponent(o)}?model=${m}&width=${p}&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(E,{method:"GET",headers:{Authorization:`Bearer ${u}`}});if(!x.ok){let $=x.status,G="";try{G=await x.text()}catch{}return $===402||G.includes("Insufficient balance")||G.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${$}]: ${G||"Unknown API Error"}`}if((x.headers.get("content-type")||"").includes("application/json")){let $=await x.json();return $.status===402||$.error&&$.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${$.error?.message||JSON.stringify($)}`}let A=await x.arrayBuffer(),R=Buffer.from(A),k={Title:o,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:o,Model:`Fluxflow:${m}`,Ratio:i||"1:1",Seed:String(g)};R=Sf(R,k);let w=Bi.resolve(process.cwd(),s);await Sa.ensureDir(Bi.dirname(w)),await dt.recordFileChange(w),await Sa.writeFile(w,R),await jr(c);let T=Bi.extname(s).toLowerCase(),v={".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:v}}}:`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 oo=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=V(Vt,{}),r=V(_n,{});return r[o]=s,delete i[o],re(_n,r),re(Vt,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=V(Mt,[]),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(re(Mt,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 Hi from"fs-extra";import ys from"path";import{createRequire as Ef}from"module";import gs from"fs-extra";import ji from"path";import Tf from"https";var Ta={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 bf(n,e=null){let t=e||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${n}`,o=ji.join(ls,n);return await gs.ensureDir(ls),new Promise((s,i)=>{let r={headers:{"User-Agent":"FluxFlow-Agent"}};Tf.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}`}bf(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 Sp(n){let e=ji.join(ls,n);return gs.existsSync(e)}async function Tp(n){let e=ji.join(ls,n);gs.existsSync(e)&&await gs.unlink(e)}var xa=Ef(import.meta.url),ba=xa("web-tree-sitter"),Ea=!1,Ra=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"]),ka=new Set(["export_statement","lexical_declaration","variable_declaration","variable_declarator","pair","assignment_expression"]);function pn(n,e=50){if(!n)return"";let t=n.replace(/\s+/g," ").trim();return t.length>e?t.substring(0,e-3)+"...":t}function Aa(n){let e=n.type;if(e==="if_statement"){let o=n.childForFieldName("condition");return o?`if (${pn(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?pn(o.text,40):""})`}if(e==="for_statement"||e==="for_in_statement"||e==="for_of_statement"){let s=n.text.split(`
|
|
405
|
+
`)[0].match(/for\s*(?:await\s*)?\((.*)\)/);return s?`for (${pn(s[1],40)})`:"for"}if(e==="switch_statement"){let o=n.childForFieldName("value");return`switch (${o?pn(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?`<${pn(s.text,30)}>`:null}if(["import_declaration","import_from_statement","import_statement","preproc_include"].includes(e))return pn(n.text.split(`
|
|
406
|
+
`)[0],60);if(e==="pair"){let o=n.childForFieldName("key");return o?pn(o.text.replace(/["']/g,""),40):null}if(e==="assignment_expression"){let o=n.childForFieldName("left");return o?`${pn(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?pn(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 pn(o.text,40)}return pn(t.text,40)}if(["arrow_function","function_expression","function_declaration"].includes(e)){let o=n.parent;for(;o&&o.type!=="program";){let s=Aa(o);if(s)return s;if(!ka.has(o.type))break;o=o.parent}}return null}function xf(n){let e=[];function t(o){for(let s of o.children)Ra.has(s.type)?e.push(s):t(s)}return t(n),e}function Rf(n){return n.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Ca(n,e=0,t=!0,o="",s=null,i=12){let r=n.type,a=Aa(n),d=Ra.has(r)||e===0,c=xf(n),f=d&&e>0&&(ka.has(r)&&c.length>0||a!==null&&a===s&&c.length>0),l="",u=o,h=e,m=s;if(d&&!f){let p=n.startPosition.row+1,y=n.endPosition.row+1,g=Rf(r),S=a?`${g} [${a}]`:g;e===0?(l+=`\u{1F4C1} ROOT (Lines: ${p}-${y})
|
|
407
|
+
`,u=o):(l+=`${o}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${S} (Lines: ${p}-${y})
|
|
408
|
+
`,u+=t?" ":"\u2502 "),h=e+1,m=a}return h>i&&c.length>0?l+=`${u}\u2514\u2500\u2500 ... depth exceeded ...
|
|
409
|
+
`:c.forEach((p,y)=>{let g=y===c.length-1;l+=Ca(p,h,f?t&&g:g,u,m,i)}),l}var Gi=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(!Hi.existsSync(t))return`ERROR: File not found: ${e}`;let o=ys.extname(t).slice(1).toLowerCase(),s=Ta[o];if(!s)return`ERROR: Unsupported file extension: .${o}`;let i=ys.resolve(ls,s);if(!Hi.existsSync(i))return`ERROR: Parser for .${o} not found. Please download it in Settings > Other.`;try{let r=ba.Parser;if(!Ea){let m;try{m=ys.join(ys.dirname(xa.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{m=ys.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await r.init({locateFile:p=>p==="tree-sitter.wasm"||p.endsWith("tree-sitter.wasm")?m:p}),Ea=!0}let a=new r,d=await ba.Language.load(i);a.setLanguage(d);let c=await Hi.readFile(t,"utf8"),f=c.split(`
|
|
410
|
+
`).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=Ca(u.rootNode,0,!0," ",null,l);return`\u{1F4C4} File Map for: ${e}
|
|
411
|
+
${h}`}catch(r){let a=r instanceof Error?r.message:typeof r=="object"?JSON.stringify(r):String(r),d=r instanceof Error?`
|
|
412
|
+
Stack: ${r.stack}`:"";return`ERROR: Failed to map file: ${a}${d}`}};import qn from"fs";import Oa 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=Oa.join(Mn,"plan",i),a=Oa.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(m=>m.slice(1,-1).replace(/\\(.)/g,"$1")):u.slice(1,-1).split(",").map(m=>m.trim()).filter(Boolean)}return l},c=l=>{let u=d(l);return u?(Array.isArray(u)?u:String(u).split(`
|
|
413
|
+
`)).map(m=>{let p=String(m).trim();return p?p.startsWith("- [ ]")||p.startsWith("- [x]")||p.startsWith("- [X]")?p:`- [ ] ${p}`:null}).filter(Boolean).join(`
|
|
414
|
+
`)+`
|
|
415
|
+
`:""},f=(l,u)=>{if(!u)return{content:l,markedCount:0};let h=d(u),m=(Array.isArray(h)?h:[h]).map(S=>String(S).replace(/^- \[[xX ]\]\s*/i,"").trim()).filter(Boolean),p=l.split(`
|
|
416
|
+
`),y=0,g=!1;for(let S of m){let E=!1;for(let x=0;x<p.length;x++)if(p[x].includes(S)&&/^- \[\s\]/.test(p[x].trim())){p[x]=p[x].replace("- [ ]","- [x]"),E=!0,g=!0,y++;break}if(!E){for(let x=0;x<p.length;x++)if(p[x].toLowerCase().includes(S.toLowerCase())&&/^- \[\s\]/.test(p[x].trim())){p[x]=p[x].replace("- [ ]","- [x]"),E=!0,g=!0,y++;break}}}return{content:g?p.join(`
|
|
417
|
+
`):l,markedCount:y}};try{if(qn.existsSync(r)||qn.mkdirSync(r,{recursive:!0}),t==="create"){if(!o)return'ERROR: Missing "tasks" for create method.';let l=c(o),u=0;if(s){let m=f(l,s);l=m.content,u=m.markedCount}await dt.recordFileChange(a),qn.writeFileSync(a,l,"utf8");let h=l.split(/\r?\n/).map(m=>m.trim()).filter(m=>m.startsWith("- [ ]")||m.startsWith("- [x]")||m.startsWith("- [X]")).length;if(u>0){let m=l.split(/\r?\n/).map(p=>p.trim()).filter(p=>p.startsWith("- [x]")||p.startsWith("- [X]")).length;return`SUCCESS: TASK LIST CREATED (${u} marked done, ${m} completed, ${h-m} left)
|
|
418
|
+
${l}`}return`SUCCESS: TASK LIST CREATED (${h} total)
|
|
419
|
+
${l}`}if(t==="append"){if(!o)return'ERROR: Missing "tasks" for append method.';let l=c(o);await dt.recordFileChange(a),qn.appendFileSync(a,l,"utf8");let u=qn.readFileSync(a,"utf8"),h=u.split(/\r?\n/).map(g=>g.trim()),m=h.filter(g=>g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")).length,p=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 (${p} completed, ${m-p} left, ${y} added)
|
|
420
|
+
${u}`}if(t==="get"){if(!qn.existsSync(a))return"TODO GET: No task list found for this session.";let l=qn.readFileSync(a,"utf8"),u=0;if(s){let g=f(l,s);g.markedCount>0&&(l=g.content,u=g.markedCount,await dt.recordFileChange(a),qn.writeFileSync(a,l,"utf8"))}let h=l.split(/\r?\n/).map(g=>g.trim()),m=h.filter(g=>g.startsWith("- [ ]")||g.startsWith("- [x]")||g.startsWith("- [X]")).length,p=h.filter(g=>g.startsWith("- [x]")||g.startsWith("- [X]")).length;return`${u>0?`SUCCESS: ${u} TASK(S) MARKED DONE`:"TODO GET"}: ${p} Completed, ${m-p} left
|
|
421
|
+
${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 Yi=async(n,e={})=>{let{runSubagent:t}=await import("./ai-T2SZGY7Y.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]
|
|
422
|
+
`),c}catch(c){let{isTerminationSignaled:f}=await import("./ai-T2SZGY7Y.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}
|
|
423
|
+
`)}return`ERROR: Subagent execution failed: ${c.message}`}};var Ma=async(n,e={})=>{let{runSubagent:t}=await import("./ai-T2SZGY7Y.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:[]},m={chunks:[],totalWords:0};Ve.push(h),e.onSubagentUpdate&&e.onSubagentUpdate();let p=[],y={...e,taskId:c,onAskMain:async g=>{let S=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,E=null,x=new Promise(R=>{E=R}),C={id:S,question:g,answered:!1,answer:null,askedAt:Date.now(),_resolve:E};return h.questions.push(C),h.status="waiting",e.onSubagentUpdate&&e.onSubagentUpdate(),yo(`[SYSTEM] Background subagent "${h.title}" is WAITING FOR YOUR INPUT: "${g}"
|
|
424
|
+
Respond using tool: [tool:functions.Answer(id="${c}", answer="...")]
|
|
425
|
+
[/SYSTEM]`),await x},onVisualFeedback:g=>{h.lastChunkTime=Date.now();let S=g.replace(/\x1b\[[0-9;]*m/g,""),E=S.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);E?h.currentTool=E[1].trim():h.currentTool=S,e.onSubagentUpdate&&e.onSubagentUpdate()},onTokenChunk:(g,S)=>{let E=Date.now();if(h.lastChunkTime=E,h.currentTool="Thinking",typeof S=="number"&&S>0){m.totalWords+=S,m.chunks.push({time:E,words:S});let x=E-400;if(m.chunks=m.chunks.filter(C=>C.time>=x),m.chunks.length>0){let C=m.chunks.reduce((k,w)=>k+w.words,0),A=m.chunks[0].time,R=Math.max(.4,(E-A)/1e3);h.wps=Math.round(C/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")&&p.length>0&&(h.progress.push([...p]),p=[]),g.includes("[Executing Tool]")){let E=g.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);E&&(!h.currentTool||h.currentTool==="Thinking")&&(h.currentTool=E[1])}let S=g;if(S.startsWith("[Tool Result]")){let E=S.split(`
|
|
426
|
+
`);E.length>5&&(S=E.slice(0,4).join(`
|
|
427
|
+
`)+`
|
|
428
|
+
... [Content/Diff Truncated from Logs] ...`)}p.push(S),e.onSubagentUpdate&&e.onSubagentUpdate()},!0).then(g=>{if(h.status==="cancelled"){h._resolveCompletion&&h._resolveCompletion(g);return}p.length>0&&(h.progress.push([...p]),p=[]),h.status="completed",h.finalAnswer=g,e.onSubagentUpdate&&e.onSubagentUpdate(),yo(`[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-T2SZGY7Y.js");if(g.message==="Subagent task was cancelled."||h.status==="cancelled"||S()){h.status="cancelled",p.push("[SUBAGENT CANCELLED] Task was cancelled."),h.progress.push([...p]),e.onSubagentUpdate&&e.onSubagentUpdate(),h._resolveCompletion&&h._resolveCompletion(null);return}p.push(`[SUBAGENT FAILURE] Error: ${g.message}`),h.progress.push([...p]),h.status="failed",h.error=g.message,e.onSubagentUpdate&&e.onSubagentUpdate(),yo(`[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=Ve.find(a=>a.id===o);if(!s)return`ERROR: Subagent task with ID [${o}] not found.`;let i=`Subagent Task Status: ${s.status.toUpperCase()}
|
|
429
|
+
`;if(i+=`Title: ${s.title}
|
|
430
|
+
`,i+=`Task: ${s.task}
|
|
431
|
+
`,s.startedAt){let a=Math.floor((Date.now()-s.startedAt)/1e3);i+=`Elapsed Time: ${a}s
|
|
432
|
+
`}if(i+=`Turns Completed: ${s.progress.length}
|
|
433
|
+
`,(s.status==="running"||s.status==="waiting")&&(s.currentTool&&(i+=`Current Tool: ${s.currentTool}
|
|
434
|
+
`),s.wps>0&&(i+=`TPS: ${s.wps}
|
|
435
|
+
`)),s.questions&&s.questions.length>0){let a=s.questions.filter(d=>!d.answered);a.length>0&&(i+=`
|
|
436
|
+
**PENDING QUESTION**
|
|
437
|
+
`,a.forEach(d=>{i+=`"${d.question}"
|
|
438
|
+
`}),i+=`Respond using tool: [tool:functions.Answer(id="${s.id}", answer="...")]
|
|
439
|
+
|
|
440
|
+
`)}return i+=`
|
|
441
|
+
Progress Log:
|
|
442
|
+
`,s.progress.forEach((a,d)=>{i+=`--- Turn ${d+1} ---
|
|
443
|
+
`;let f=a.filter(l=>!l.startsWith("[SUBAGENT SUCCESS]")).map(l=>{if(l.startsWith("[Subagent Response]")){let u="[Subagent Response]",m=l.substring(u.length),p="tool:functions.";for(;;){let g=m.toLowerCase().indexOf(p);if(g===-1)break;let S=g,E=!1,x=g-1;for(;x>=0&&/\s/.test(m[x]);)x--;x>=0&&m[x]==="["&&(S=x,E=!0);let C=0,A=!1,R=null,k=g;for(;k<m.length;){let w=m[k];if(!R&&(w==="'"||w==='"'||w==="`")?R=w:R&&w===R&&m[k-1]!=="\\"&&(R=null),R||(w==="("?(C++,A=!0):w===")"&&C--),A&&C===0&&!R){let T=k;if(E){let b=k+1;for(;b<m.length&&/\s/.test(m[b]);)b++;b<m.length&&m[b]==="]"&&(T=b)}m=m.substring(0,S)+m.substring(T+1);break}if(k++,k===m.length){m=m.substring(0,S);break}}}return u+`
|
|
444
|
+
`+m.trim()}return l.startsWith("[Executing Tool]")&&l.length>256?l.substring(0,256)+"...[truncated from logs]":l});i+=f.join(`
|
|
445
|
+
`)+`
|
|
446
|
+
|
|
447
|
+
`}),s.status==="completed"&&s.finalAnswer?i+=`Final Answer:
|
|
448
|
+
${s.finalAnswer}
|
|
449
|
+
`:s.status==="failed"&&s.error&&(i+=`Failure Error: ${s.error}
|
|
450
|
+
`),i.replace(/\r\n/g,`
|
|
451
|
+
`).replace(/\n{3,}/g,`
|
|
452
|
+
|
|
453
|
+
`).trim().replace(/\[TOOL RESULT\]/gi,"TOOL RESULT:")};var _a=async(n,e={})=>{let o=L(n).id;if(!o)return'ERROR: Missing "id" argument for cancel.';let s=Ve.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 mt from"fs-extra";import wt from"path";var kf=["node_modules","dist","bin","logs",".git",".fluxflow","secret",".gemini",".agents","tmp","temp","build","out","snapshots"];async function io(n,e=n){let t={},o=await mt.readdir(n,{withFileTypes:!0}).catch(()=>[]);for(let s of o){if(kf.includes(s.name))continue;let i=wt.join(n,s.name),r=wt.relative(e,i).replace(/\\/g,"/");if(s.isDirectory()){let a=await io(i,e);Object.assign(t,a)}else{let a=await mt.stat(i).catch(()=>null);a&&(t[r]={size:a.size,mtime:a.mtimeMs})}}return t}async function Ia(n,e){await mt.ensureDir(n);for(let t of Object.keys(e)){let o=wt.join(process.cwd(),t),s=wt.join(n,t);await mt.ensureDir(wt.dirname(s)),await mt.copyFile(o,s).catch(()=>{})}}async function qi(n,e,t=null,o=null){if(!await mt.pathExists(n))return;o||(o=n);let s=await mt.readdir(n,{withFileTypes:!0}).catch(()=>[]);for(let i of s){let r=wt.join(n,i.name),a=wt.join(e,i.name);if(i.isDirectory())await qi(r,a,t,o);else{let d=wt.relative(o,r).replace(/\\/g,"/"),c=await mt.pathExists(a);c&&await mt.chmod(a,438).catch(()=>{}),await mt.ensureDir(wt.dirname(a));let f=await mt.copyFile(r,a).then(()=>!0).catch(()=>!1);await mt.chmod(a,438).catch(()=>{}),t&&(f?c?t.replaced++:t.restored++:t.failed.push(d))}}}var Vn={async takeInitialSnapshot(n){try{let e=wt.join(Mn,"snapshots",n);await mt.remove(e).catch(()=>{}),await mt.ensureDir(e);let t=await io(process.cwd());await Ia(wt.join(e,"initial"),t);let o=V(fn,{});o[n]={initialManifest:t,currentManifest:t,checkpoints:[{id:"initial",timestamp:new Date().toISOString(),newFiles:[],modifiedFiles:[],deletedFiles:[],toolsUsed:[]}]},re(fn,o)}catch{}},async recordTurnDelta(n,e,t=[]){try{let o=V(fn,{}),s=o[n];if(!s)return;let i=s.currentManifest||s.initialManifest,r=await io(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=wt.join(Mn,"snapshots",n,`turn_${e}`);await Ia(u,l)}s.checkpoints.push({id:`turn_${e}`,timestamp:new Date().toISOString(),newFiles:a,modifiedFiles:d,deletedFiles:c,toolsUsed:t}),s.currentManifest=r,re(fn,o)}catch{}},async getCheckpoints(n){try{let t=V(fn,{})[n];return t?t.checkpoints||[]:[]}catch{return[]}},async rollbackToCheckpoint(n,e){try{let t=V(fn,{}),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=wt.join(Mn,"snapshots",n),a={restored:0,replaced:0,failed:[]},d=await io(process.cwd());for(let f of Object.keys(d)){let l=wt.join(process.cwd(),f);await mt.chmod(l,438).catch(()=>{}),await mt.remove(l).catch(()=>{})}let c=wt.join(r,"initial");await qi(c,process.cwd(),a,c);for(let f=1;f<=i;f++){let l=s[f],u=wt.join(r,l.id);if(await qi(u,process.cwd(),a,u),l.deletedFiles&&l.deletedFiles.length>0)for(let h of l.deletedFiles){let m=wt.join(process.cwd(),h);await mt.chmod(m,438).catch(()=>{}),await mt.remove(m).catch(()=>{})}}return o.checkpoints=s.slice(0,i+1),o.currentManifest=await io(process.cwd()),re(fn,t),{checkpointId:e,stats:a}}catch(t){throw new Error(`Rollback failed: ${t.message}`)}},async getLatestFileChanges(n){try{let t=V(fn,{})[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=wt.join(Mn,"snapshots",n);await mt.remove(e).catch(()=>{});let t=V(fn,{});t[n]&&(delete t[n],re(fn,t))}catch{}}};var Vi=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:
|
|
454
|
+
|
|
455
|
+
`;for(let l of a)if(l.id==="initial")f+=`--- Initial State (id: initial) ---
|
|
456
|
+
Tools Used: User Prompted for task
|
|
457
|
+
|
|
458
|
+
`;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}) ---
|
|
459
|
+
Tools Used: ${h}
|
|
460
|
+
|
|
461
|
+
`}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}].
|
|
462
|
+
|
|
463
|
+
`;return l+=`Stats:
|
|
464
|
+
`,l+=` Restored : ${c.restored} file${c.restored!==1?"s":""} (new to workspace)
|
|
465
|
+
`,l+=` Replaced : ${c.replaced} file${c.replaced!==1?"s":""} (overwritten)
|
|
466
|
+
`,l+=` Failed : ${c.failed.length} file${c.failed.length!==1?"s":""}`,c.failed.length>0&&(l+=`
|
|
467
|
+
${c.failed.join(`
|
|
468
|
+
`)}`),l+=`
|
|
469
|
+
\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-
|
|
470
|
+
`,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=Ve.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.
|
|
471
|
+
Final Answer:
|
|
472
|
+
${i.finalAnswer||"(No output)"}`;if(i.status==="failed")return`ERROR: Subagent task [${o}] failed.
|
|
473
|
+
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.
|
|
474
|
+
Final Answer:
|
|
475
|
+
${i.finalAnswer||"(No output)"}`:i.status==="failed"?`ERROR: Subagent task [${o}] failed.
|
|
476
|
+
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=Ve.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 ro=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=Ve.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 Af={web_search:mi,web_scrape:gi,memory:yi,chat:wi,view_file:Qs,write_file:Si,update_file:Ri,exec_command:li,read_folder:Ai,write_pdf:Oi,write_docx:Mi,search_keyword:so,generate_image:Wi,saveSummary:oo,addMemScore:Ps,file_map:Gi,todo:$a,invokeSync:Yi,invoke:Ma,getProgress:zi,cancel:_a,awaitSubagent:Ds,answerSubagent:Fs,steerSubagent:ro,invoke_sync:Yi,get_progress:zi,await_subagent:Ds,answer_subagent:Fs,steer_subagent:ro,steer:ro,Steer:ro,ask:Ci,Ask:Ci,WebSearch:mi,WebScrape:gi,ReadFile:Qs,ReadFolder:Ai,WriteFile:Si,PatchFile:Ri,WritePDF:Oi,WriteDoc:Mi,Run:li,SearchKeyword:so,CodeSearch:so,code_search:so,Memory:yi,Chat:wi,GenerateImage:Wi,saveSumary:oo,SaveSummary:oo,SaveSumary:oo,add_mem_score:Ps,AddMemScore:Ps,addMemoryScore:Ps,AddMemoryScore:Ps,FileMap:Gi,answer:Fs,Answer:Fs,AnswerSubagent:Fs,await:Ds,Await:Ds,AwaitSubagent:Ds,EmergencyRollback:Vi,emergency_rollback:Vi},ao=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=Af[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 K from"path";import Oe from"fs";import Cf from"gradient-string";var Ki=["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 va=[{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"]}],lo={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 Io=null;var La=(n="Dark")=>{let e;n==="Mystery"||n==="Chaos"?(Io||(Io=va[Math.floor(Math.random()*va.length)]),e={...Io,id:"Mystery"}):(Io=null,lo[n]?e=lo[n]:n==="GitHub"?e=lo["GitHub Dark"]:n==="Transparent"?e=lo["Transparent Dark"]:e=lo.Dark);let t=e.codeText||e.secondary||e.info||e.logoGradient&&e.logoGradient[0]||"cyan";return{...e,codeText:t}};var Of=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ym=(n=2)=>{let e=Of();return e==="wt"?" ".repeat(Math.max(1,n-1)):" ".repeat(n)},zm=(n="...",e="Loading...",t="Dark")=>{let o=Ki[Math.floor(Math.random()*Ki.length)],s=La(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=Cf(f).multiline(c.join(`
|
|
477
|
+
`)).split(`
|
|
478
|
+
`),u=h=>`${a}${h}${d}`;return`${l[0]}
|
|
479
|
+
${l[1]} ${i}Selected Provider: ${e}${d}
|
|
480
|
+
${l[2]}
|
|
481
|
+
${l[3]} ${i}FluxFlow ${u("v"+n)}${d}
|
|
482
|
+
${l[4]}
|
|
483
|
+
${l[5]} ${r}See /help for additional commands.${d}
|
|
484
|
+
${l[6]} ${u(o)}
|
|
485
|
+
${l[7]}`};import{WebSocket as vo}from"ws";var jt=null,Us=!1,$f="ws://localhost:56832",Xi=[],Bs=null,Ji=null,Na="2.0.0",Km=n=>{Na=n,Pa()},Qi=n=>{Ji=n},Pa=()=>{if(jt||Us)return;Us=!0;let n=new vo($f);n.on("open",()=>{for(jt=n,Us=!1,jt.send(JSON.stringify({command:"version",version:Na,pid:process.pid,ppid:process.ppid}));Xi.length>0;)jt.send(JSON.stringify(Xi.shift()))}),n.on("message",e=>{try{let t=JSON.parse(e.toString());t.command==="contextResponse"&&Bs?(Bs(t.data),Bs=null):t.command==="securityResponse"&&Ji&&Ji(t.result)}catch{}}),n.on("error",()=>{Us=!1,jt=null}),n.on("close",()=>{Us=!1,jt=null})},Lo=n=>{jt&&jt.readyState===vo.OPEN?jt.send(JSON.stringify(n)):(Xi.push(n),Us||Pa())},No=()=>jt!==null&&jt.readyState===vo.OPEN,Xm=n=>{Lo({command:"status",status:n})},ws=()=>new Promise(n=>{if(!jt||jt.readyState!==vo.OPEN){n({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}Bs=n,jt.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{Bs===n&&(n({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),Bs=null)},1e3)}),Da=n=>{Lo({command:"open",filePath:n})},Zi=(n,e,t)=>{Lo({command:"showDiff",filePath:n,originalContent:e,modifiedContent:t})},Fa=(n,e)=>{Lo({command:"closeDiff",filePath:n,result:e})};import Ua from"path";import Mf from"fs";var _f=n=>{try{return Mf.readdirSync(n,{withFileTypes:!0})}catch{return[]}},er=(n,e,t=1,o=_f,s=[],i=null)=>{let r=i||o(n),a=" ".repeat(t-1);if(r.length>100)return`${a}${Ua.basename(n)}/ (>100 files)
|
|
486
|
+
`;let d="",c=s,f=r.filter(m=>!c.includes(m.name)&&!m.name.startsWith(".")),l=r.filter(m=>c.includes(m.name)||m.name.startsWith(".")).map(m=>m.name).sort();l.length>0&&(d+=`${a}[ignored: ${l.map(m=>m+"/").join(", ")}]
|
|
487
|
+
`);let u=f.filter(m=>m.isDirectory()).sort((m,p)=>m.name.localeCompare(p.name)),h=f.filter(m=>!m.isDirectory()).map(m=>m.name).sort();for(let m of u){let p=Ua.join(n,m.name);if(t>e)d+=`${a}${m.name}/ (max depth)
|
|
488
|
+
`;else{let y=o(p);y.length>80?d+=`${a}${m.name}/ (>80 files)
|
|
489
|
+
`:(d+=`${a}${m.name}/
|
|
490
|
+
`,d+=er(p,e,t+1,o,s,y))}}return h.length>0&&(d+=`${a}${h.join("; ")}
|
|
491
|
+
`),d};import tr from"path";import If from"fs";var vf=n=>{try{return If.readdirSync(n,{withFileTypes:!0})}catch{return[]}},nr=(n,e,t="",o=1,s=vf,i=[])=>{let r=s(n),a=tr.sep;if(r.length>100)return`${t}\u2514\u2500\u2500 ${tr.basename(n)}${a} ...100+ files...
|
|
492
|
+
`;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,m)=>h.isDirectory()&&!m.isDirectory()?-1:!h.isDirectory()&&m.isDirectory()?1:h.name.localeCompare(m.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,m)=>{let p=m===u.length-1,y=tr.join(n,h.name),g=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",S=t+(p?" ":"\u2502 ");if(h.isCollapsed){d+=`${t}${g}${h.name}${a}...
|
|
493
|
+
`;return}h.isDir?o>e?d+=`${t}${g}${h.name}${a} ...depth exceeded...
|
|
494
|
+
`:s(y).length>80?d+=`${t}${g}${h.name}${a} ...80+ files...
|
|
495
|
+
`:(d+=`${t}${g}${h.name}${a}
|
|
496
|
+
`,d+=nr(y,e,S,o+1,s,i)):d+=`${t}${g}${h.name}
|
|
497
|
+
`}),d};Lf.config({quiet:!0});var Nf=/```[\s\S]*?```/g,Pf=/```[\s\S]*$/g,Df=/`[^`]+`/g,Ff=/^\|.*\|$/gm,Uf=/^[^\w]+|[^\w]+$/g,Bf=/[^a-z0-9]/gi,co=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,Wf=/\[\s*(?:tool:functions\.|agent:generalist\.)([a-z0-9_]+)\s*\(/gi,jf=/(?:path|targetFile|TargetFile|directory|keyword|id|taskId|title|task)\s*=\s*\\?["']?([^\\"' \),]+)/,Ss=/["']/g,Ba=/\\/g,Hf=/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,Gf=/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*$/gi,Wa=/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,ja=/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,Xa=/`[^`]*`/g,Ja=/`[^`]*$/,Ha=/<\|\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,Yf=/"([^"]+)"\s*:\s*(?:"([^"]*)"|(\d+)|true|false|null)/g,Ga=/<\|\s*tool_calls_section_begin\s*\|>/gi,Ya=/<\|\s*tool_calls_section_end\s*\|>/gi,zf=/```(?:tool|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,za=/<(\w+)(?:[^>]*)>\r?\n?/gi,qa=/\r?\n?<\/\w+(?:[^>]*)>/gi,or=null,Po={},Ts={key:null,value:null},mn=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`),qf=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"))})})}}},Ct=!1;var Vf=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},Kf=n=>typeof n!="string"?n:n.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Fo=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},ir=async function*(n,e,t,o,s,i,r,a,d=.99){let c=[];o&&c.push({role:"system",content:o});for(let E of t){let x=E.role==="user"?"user":"assistant",C=[];if(Array.isArray(E.parts)){for(let A of E.parts)if(A.text)C.push({type:"text",text:A.text});else if(A.inlineData&&r){let R=A.inlineData.mimeType,k=A.inlineData.data;R.startsWith("image/")&&C.push({type:"image_url",image_url:{url:`data:${R};base64,${k}`}})}}else{let A=E.text||"";A&&C.push({type:"text",text:A})}c.push({role:x,content:C.length===1&&C[0].type==="text"?C[0].text:C})}let f={model:e,messages:c,stream:!0,stream_options:{include_usage:!0},temperature:d};if(s!=="Fast"){let E={Low:"high",Medium:"high",Standard:"high",High:"max",xHigh:"max"};f.reasoning_effort=E[s]||"high",f.extra_body={thinking:{type:"enabled"}}}else f.extra_body={thinking:{type:"disabled"}};let l=await Fo("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 E=await l.json().catch(()=>({}));throw new Error(`DeepSeek Error (${l.status}): ${E.error?.message||l.statusText}`)}let u=l.body.getReader(),h=new TextDecoder,m="",p=[],y=null,g=Date.now(),S=!1;for(;;){let{done:E,value:x}=await u.read();if(E){S&&(p.length>0||y)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:y});break}m+=h.decode(x,{stream:!0});let C=m.split(`
|
|
498
|
+
`);m=C.pop();for(let A of C){let R=A.trim();if(!R||!R.startsWith("data: "))continue;let k=!1;if(R==="data: [DONE]")k=!0;else try{let w=JSON.parse(R.substring(6)),T=w.choices?.[0]?.delta,b=w.usage;if(w.choices?.[0]?.finish_reason&&(k=!0),b&&(y={totalTokenCount:b.total_tokens||b.prompt_tokens+b.completion_tokens,promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:b.completion_tokens_details?.reasoning_tokens||0},S=!0),T){let v=T.reasoning_content||null;v&&(p.push({text:v,thought:!0}),S=!0),T.content&&(p.push({text:T.content}),S=!0)}}catch{}if((k||Date.now()-g>=150)&&S&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],g=Date.now(),S=!1),k)break}Date.now()-g>=150&&S&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],g=Date.now(),S=!1)}},rr=async function*(n,e,t,o,s,i,r,a,d=.99){let c=[];o&&c.push({role:"system",content:o});for(let E of t){let x=E.role==="user"?"user":"assistant",C=[];if(Array.isArray(E.parts)){for(let A of E.parts)if(A.text)C.push({type:"text",text:A.text});else if(A.inlineData&&r){let R=A.inlineData.mimeType,k=A.inlineData.data;R.startsWith("image/")&&C.push({type:"image_url",image_url:`data:${R};base64,${k}`})}}else{let A=E.text||"";A&&C.push({type:"text",text:A})}C.length>0&&c.push({role:x,content:C.length===1&&C[0].type==="text"?C[0].text:C})}let f={model:e,messages:c,stream:!0,temperature:d,prompt_cache_key:"flux-flow-session"},l=await Fo("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(f),signal:a});if(!l.ok){let E=await l.text().catch(()=>""),x=l.statusText;try{let C=JSON.parse(E);x=C.error?.message||C.message||JSON.stringify(C.detail||C)}catch{E&&(x=E)}throw new Error(`Mistral Error (${l.status}): ${x}`)}let u=l.body.getReader(),h=new TextDecoder,m="",p=[],y=null,g=Date.now(),S=!1;for(;;){let{done:E,value:x}=await u.read();if(E){S&&(p.length>0||y)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:y});break}m+=h.decode(x,{stream:!0});let C=m.split(`
|
|
499
|
+
`);m=C.pop();for(let A of C){let R=A.trim();if(!R||!R.startsWith("data: "))continue;let k=!1;if(R==="data: [DONE]")k=!0;else try{let w=JSON.parse(R.substring(6)),T=w.choices?.[0]?.delta,b=w.usage;w.choices?.[0]?.finish_reason&&(k=!0),b&&(y={totalTokenCount:b.total_tokens||(b.prompt_tokens||0)+(b.completion_tokens||0),promptTokenCount:b.prompt_tokens||0,candidatesTokenCount:b.completion_tokens||0,cachedContentTokenCount:b.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:0},S=!0),T&&(T.thinking&&(p.push({text:T.thinking,thought:!0}),S=!0),T.content&&(p.push({text:T.content}),S=!0))}catch{}if((k||Date.now()-g>=150)&&S&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],g=Date.now(),S=!1),k)break}Date.now()-g>=150&&S&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],g=Date.now(),S=!1)}},ar=async function*(n,e,t,o,s,i,r=!1,a,d=.99){let c=[];o&&c.push({role:"system",content:o}),t.forEach(P=>{let F=P.role==="model"?"assistant":"user",he=[];Array.isArray(P.parts)&&P.parts.forEach(ye=>{if(ye.text)he.push({type:"text",text:ye.text});else if(ye.inlineData&&r){let O=ye.inlineData.mimeType,D=ye.inlineData.data;O.startsWith("image/")&&dn(e)&&he.push({type:"image_url",image_url:{url:`data:${O};base64,${D}`}})}}),c.push({role:F,content:he.length===1&&he[0].type==="text"?he[0].text:he})});let l={Fast:"Fast",Low:"Fast",Medium:"Standard",Standard:"Standard",High:"High",xHigh:"High"}[s]||"High",u=l!=="Fast",h=e.includes("kimi"),m=e.includes("gemma"),p=e.includes("deepseek"),y=e.includes("glm"),g=e.includes("mistral"),S=e.includes("minimax"),E=e.includes("gpt"),x=e.includes("qwen"),C=e.includes("nemotron"),A=e.includes("llama-3"),R=e.includes("seed"),k=e.includes("poolside"),w=e.includes("thinkingmachines"),T={Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},b={Fast:"64",Low:"64",Medium:"4096",Standard:"4096",High:"16384",xHigh:"16384"},v={Fast:"none",Low:"minimal",Medium:"medium",Standard:"medium",High:"max",xHigh:"max"},_=S||p||k||w?16384:32768;_=process.env.NVIDIA_BASE_URL?1024:_;let $={model:e,messages:c,max_tokens:_,stream:!0,stream_options:{include_usage:!0},temperature:d,...E&&{thinking:T[s]||"high"}};if(!process.env.NVIDIA_BASE_URL){if(!A)if(h)$.chat_template_kwargs={thinking:u};else if(m)$.chat_template_kwargs={enable_thinking:u};else if(p)if(u){let P=l==="High"?"max":"high";$.chat_template_kwargs={thinking:!0,reasoning_effort:P}}else $.chat_template_kwargs={thinking:!1};else y?$.chat_template_kwargs={enable_thinking:u,clear_thinking:!u}:g?$.reasoning_effort=u?"high":"none":S&&e.includes("minimax-m3")?$.chat_template_kwargs={thinking_mode:u?"enabled":"disabled"}:x?$.chat_template_kwargs={enable_thinking:u}:C?l==="High"?($.reasoning_budget=12e3,$.chat_template_kwargs={enable_thinking:!0}):l==="Standard"?($.reasoning_budget=12e3,$.chat_template_kwargs={enable_thinking:!0,medium_effort:!0}):$.chat_template_kwargs={enable_thinking:!1}:R?u&&($.extra_body={thinking_budget:parseInt(b[l]??"4096")}):k?$.chat_template_kwargs={enable_thinking:u}:w&&($.reasoning_effort=v[l]||"0.7")}let G=0,ce=6,ge=!1,z=process.env.NVIDIA_BASE_URL||"https://integrate.api.nvidia.com/v1/chat/completions",$e=process.env.NVIDIA_API_KEY&&process.env.NVIDIA_BASE_URL?process.env.NVIDIA_API_KEY:n;for(z.endsWith("/chat/completions")||(z=z.replace(/\/+$/,"")+"/chat/completions");G<ce;){G++;try{let P=await Fo(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$e}`},body:JSON.stringify($),signal:a});if(!P.ok){let Me=await P.text().catch(()=>""),Ne=P.statusText;try{let He=JSON.parse(Me);Ne=He.error?.message||He.message||JSON.stringify(He.detail||He)}catch{Me&&(Ne=Me)}let Fe=new Error(`NVIDIA API Error (${P.status}): ${Ne}`);throw Fe.status=P.status,Fe}let F=P.body.getReader(),he=new TextDecoder,ye="",O=[],D=null,ne=Date.now(),q=!1;for(;;){let{done:Me,value:Ne}=await F.read();if(Me){q&&(O.length>0||D)&&(yield{candidates:O.length>0?[{content:{parts:O}}]:[],usageMetadata:D},ge=!0);break}ye+=he.decode(Ne,{stream:!0});let Fe=ye.split(`
|
|
500
|
+
`);ye=Fe.pop();let He=!1;for(let nt of Fe){let It=nt.trim();if(It){if(It==="data: [DONE]"){He=!0;break}if(It.startsWith("data: ")){let et;try{et=JSON.parse(It.substring(6))}catch{continue}if(et.error)throw new Error(`NVIDIA Stream Error: ${et.error.message||JSON.stringify(et.error)}`);et.choices?.[0]?.finish_reason&&(He=!0);try{let Ue=et.usage;Ue&&(D={totalTokenCount:Ue.total_tokens||Ue.prompt_tokens+Ue.completion_tokens,promptTokenCount:Ue.prompt_tokens||0,candidatesTokenCount:Ue.completion_tokens||0,cachedContentTokenCount:Ue.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:(Ue.completion_tokens_details?.reasoning_tokens||0)+(Ue.completion_tokens_details?.thoughts_tokens||0)},q=!0);let Xt=et.choices?.[0]?.delta?.reasoning||et.choices?.[0]?.delta?.reasoning_content||"",Nn=et.choices?.[0]?.delta?.content||"";Xt&&(O.push({text:Xt,thought:!0}),q=!0),Nn&&(O.push({text:Nn}),q=!0)}catch{}}}}if((He||Date.now()-ne>=350)&&q&&(yield{candidates:O.length>0?[{content:{parts:[...O]}}]:[],usageMetadata:D},ge=!0,O=[],ne=Date.now(),q=!1),He)break}break}catch(P){if(ge||G>=ce)throw P;await new Promise(F=>setTimeout(F,3500))}}},Xf=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 m=h.queues[0].queueDepth;c||r({value:{type:"status",content:`Queue ${m||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:m}=await u.next();if(m)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)}},lr=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 C of t){let A=C.role==="user"?"user":"assistant",R=[];if(Array.isArray(C.parts)){for(let k of C.parts)if(k.text)R.push({type:"text",text:k.text});else if(k.inlineData&&r){let w=k.inlineData.mimeType,T=k.inlineData.data;w.startsWith("image/")?R.push({type:"image_url",image_url:{url:`data:${w};base64,${T}`}}):R.push({type:"file",file:{filename:k.filename||"file",file_data:`data:${w};base64,${T}`}})}}else{let k=C.text||"";k&&R.push({type:"text",text:k})}c.push({role:A,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 Fo("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 C=await h.json().catch(()=>({}));throw new Error(`OpenRouter Error (${h.status}): ${C.error?.message||h.statusText}`)}let m=h.body.getReader(),p=new TextDecoder,y="",g=[],S=null,E=Date.now(),x=!1;for(;;){let{done:C,value:A}=await m.read();if(C){x&&(g.length>0||S)&&(yield{candidates:g.length>0?[{content:{parts:g}}]:[],usageMetadata:S});break}y+=p.decode(A,{stream:!0});let R=y.split(`
|
|
501
|
+
`);y=R.pop();for(let k of R){let w=k.trim();if(!w||!w.startsWith("data: "))continue;let T=!1;if(w==="data: [DONE]")T=!0;else try{let b=JSON.parse(w.substring(6)),v=b.choices?.[0]?.delta,_=b.usage;if(b.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),v){let $=v.reasoning||(v.reasoning_details?v.reasoning_details.map(G=>G.text).join(""):null);$&&(g.push({text:$,thought:!0}),x=!0),v.content&&(g.push({text:v.content}),x=!0)}}catch{}if((T||Date.now()-E>=150)&&x&&(yield{candidates:g.length>0?[{content:{parts:[...g]}}]:[],usageMetadata:S},g=[],E=Date.now(),x=!1),T)break}}},Qa=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 k=R.role==="user"?"user":"assistant",w="",T=[];if(Array.isArray(R.parts)){w=R.parts.map(b=>b.text||"").filter(Boolean).join(`
|
|
502
|
+
`);for(let b of R.parts)b.inline_data&&b.inline_data.data&&T.push(b.inline_data.data)}else w=R.text||"";if(w||T.length>0){let b={role:k,content:w};T.length>0&&(b.images=T),f.push(b)}}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 m=new zs(h),p=[],y=null,g=Date.now(),S=!1,E={Fast:!1,Low:"medium",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},x=E[s]!==void 0?E[s]:!0,C={model:e,messages:f,stream:!0,think:x,keep_alive:"10m",options:{temperature:d}},A=await m.chat(C);for await(let R of A){if(a?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(R.message?.thinking&&(p.push({text:R.message.thinking,thought:!0}),S=!0),R.message?.content&&(p.push({text:R.message.content}),S=!0),R.done){let k=R.prompt_cached_count||0;if(!k&&R.prompt_eval_count){let w=R.prompt_eval_duration||0;w>0&&w<75e6&&(k=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:k,thoughtsTokenCount:0},S=!0}(R.done||Date.now()-g>=150&&S)&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y},p=[],g=Date.now(),S=!1)}S&&(p.length>0||y)&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:y})},vg=()=>{Ct=!0},Lg=()=>Ct,sr={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?K.basename(s.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},cr=n=>n?new Ka({apiKey:n}):or,Ng=async(n,e,t,o,s={})=>{let{onStatus:a,onMemoryUpdated:d,onBackgroundIncrement:c}=s,{profile:f,thinkingLevel:l,mode:u,janitorModel:h,chatId:m,systemSettings:p,sessionStats:y,aiProvider:g="Google",apiKey:S}=n,E=process.env.NVIDIA_BASE_URL||g==="Ollama"?!1:p?.memory!==!1,C=V(Mt,[]).map(O=>`- [${O.id}]: ${O.memory}`).join(`
|
|
503
|
+
`),A=o.slice(0,-1).filter(O=>O.text&&!O.text.includes("[TOOL RESULT]")&&!O.text.includes("OBSERVATION:")&&!O.text.startsWith("[TERMINAL_RECORD]")&&!O.isTerminalRecord&&!O.isMeta&&!O.isLogo&&!String(O.id).startsWith("welcome")&&!String(O.id).startsWith("logo")).slice(-14).map(O=>{let D=Kf(O.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ne,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,`
|
|
504
|
+
`).replace(/\n\n/g,`
|
|
505
|
+
`).replace(/\\n\\n/g,"").trim(),ne=O.role==="user"?8192:32768,q=D.substring(0,ne);D.length>ne&&(q+=`
|
|
506
|
+
... (truncated) ...`);let Me=O.role==="user"?q.startsWith("[USER]")?"":"[USER]: ":q.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:O.role==="user"?"user":"model",parts:[{text:`${Me}${q}`}]}}),R=o.filter(O=>O.role==="user").length===1,k=e.includes("[TITLE-UPDATE]"),w=Math.random()<.8,T=R||k||w,b=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),v=Ir(C,E,T),_=`${b.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&&(_+=`
|
|
507
|
+
... (truncated) ...`);let $=e.replace(/\[Prompted on:.*?\]/g,"").trim();_=_.replace(/\r?\n\r?\n/g,`
|
|
508
|
+
`).replace(/\n\n/g,`
|
|
509
|
+
`).replace(/\\n\\n/g,"").trim();let G=new Date,ge=`[METADATA] Current date and Time: ${`${G.getFullYear()}-${G.toLocaleString("en-US",{month:"short"}).toUpperCase()}-${String(G.getDate()).padStart(2,"0")}, ${G.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`}
|
|
510
|
+
|
|
511
|
+
[USER]: ${$.substring(0,8192)}
|
|
512
|
+
${$.length>8192?`... (truncated) ...
|
|
513
|
+
|
|
514
|
+
`:""}
|
|
515
|
+
[AGENT (current turn)]: ${_}`;A.push({role:"user",parts:[{text:ge}]});let z=await Ko("NVIDIA"),P=(await Kt()).quotas?.providerTiers?.NVIDIA==="Free",F="",he=0,ye=E?12:-1;for(;he<=ye;)try{if(!await Fr("background",n))return;let O="",D=null,ne=!1,q=g;try{let Fe=new Promise((vt,at)=>setTimeout(()=>at(new Error("JANITOR_TIMEOUT")),1e4)),He=g==="Google"&&he>=0&&he<6&&z&&P,nt=g==="DeepSeek"&&he<4&&z&&P;ne=He||nt,q=ne?"NVIDIA":g;let It=(async()=>{if(g==="OpenRouter"){let vt=Ze("janitor_open_router"),fe=lr(S,vt,A,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),Ht=await fe.next();return{iterator:fe,firstResult:Ht}}else if(g==="DeepSeek"&&!ne){let at=ir(S,Ze("deepseek_fast_fallback"),A,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),fe=await at.next();return{iterator:at,firstResult:fe}}else if(g==="Mistral"&&!ne){let at=rr(S,Ze("mistral_janitor_fallback"),A,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),fe=await at.next();return{iterator:at,firstResult:fe}}else if(g==="NVIDIA"||ne){let at=ar(ne?z:S,Ze("nvidia_janitor_fallback"),A,v,"Fast",u,!1,null,.6)[Symbol.asyncIterator](),fe=await at.next();return{iterator:at,firstResult:fe}}else{let fe=(await cr(S).models.generateContentStream({model:h||(he===ye?Ze("janitor_default"):Ze("gemma_janitor_fallback_google")),contents:A,config:{systemInstruction:v,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:rt.MINIMAL}}}))[Symbol.asyncIterator](),Ht=await fe.next();return{iterator:fe,firstResult:Ht}}})();if(process.stdout.isTTY){let fe=(await cs())[m]?.name||"",Ht=fe&&!fe.startsWith("flow-")&&!fe.startsWith("Session ")?fe:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${Ht}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Ht}\x07`)}let{iterator:et,firstResult:Ue}=await Promise.race([It,Fe]),{value:Xt,done:Nn}=Ue;if(!Nn&&Xt){let vt=Xt.candidates?.[0]?.content?.parts,at=vt?q==="Google"?vt[1]?.text||vt[0]?.text||"":vt.filter(fe=>fe.text&&!fe.thought).map(fe=>fe.text).join(""):typeof Xt.text=="function"?Xt.text():"";at&&(O+=at),D=Xt.usageMetadata;for await(let fe of{[Symbol.asyncIterator]:()=>et}){let Ht=fe.candidates?.[0]?.content?.parts,Jn=Ht?q==="Google"?Ht[1]?.text||Ht[0]?.text||"":Ht.filter(Qn=>Qn.text&&!Qn.thought).map(Qn=>Qn.text).join(""):typeof fe.text=="function"?fe.text():"";Jn&&(O+=Jn),D=fe.usageMetadata}}}catch(Fe){throw Fe}if(O){if(F=O,D){let Fe=D.totalTokenCount||0,He=D.cachedContentTokenCount||0,nt=(D.candidatesTokenCount||0)+(D.thoughtsTokenCount||0),It=ne?Ze("nvidia_janitor_fallback"):q==="DeepSeek"?Ze("deepseek_fast_fallback"):q==="OpenRouter"?Ze("janitor_open_router"):h||(he===ye?Ze("janitor_default"):Ze("gemma_janitor_fallback_google"));await Bt("tokens",Fe,q,It),He>0&&await Bt("cachedTokens",He,q,It),nt>0&&await Bt("candidateTokens",nt,q,It)}}else throw new Error("No synthesis generated by Janitor.");c&&(c(),await Ut("background"));let Me=Uo(F),Ne=!1;for(let Fe of Me){let He=Fe.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(He)&&(Ne=!0);let nt={chatId:m,sessionId:m,history:o},It=await ao(He,Fe.args,nt);He.toLowerCase()==="memory"&&(Fe.args.includes("action='user'")||Fe.args.includes('action="user"'))&&!It.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(Ue=>setTimeout(Ue,3e3)))}if(!Ne)try{let Fe=V(Mt,[]);if(Fe.length>0){let He=[];for(let nt of Fe)nt.score===void 0&&(nt.score=.5),nt.score*=.99995,nt.score<.05&&(nt.score=0),nt.score=Math.round(nt.score*1e5)/1e5,nt.score>0&&He.push(nt);re(Mt,He)}}catch{}break}catch(O){he++;let D=new Date().toLocaleString(),ne=O instanceof Error?(()=>{try{return JSON.parse(JSON.parse(O.message).error.message).error.message}catch{return String(O)}})():String(O);await new Promise(Ne=>setTimeout(Ne,1e3));let q=K.join(cn,"janitor");if(Oe.existsSync(q)||Oe.mkdirSync(q,{recursive:!0}),Oe.appendFileSync(K.join(q,"error.log"),`ERROR [Attempt ${he}/${ye+1}] [${D}]: ${ne}
|
|
516
|
+
|
|
517
|
+
`),he>ye)break;let Me=Math.min(750*Math.pow(2,he-1),5e3);await new Promise(Ne=>setTimeout(Ne,Me))}if(he){let O=K.join(cn,"janitor");Oe.appendFileSync(K.join(O,"error.log"),`-----------------------------------------------------------------------------
|
|
518
|
+
|
|
519
|
+
`)}if(process.stdout.isTTY)try{let ne=(await cs())[m]?.name||"",q=ne&&!ne.startsWith("flow-")&&!ne.startsWith("Session ")?ne:"FluxFlow | Idle";process.stdout.write(`\x1B]0;${q}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${q}\x07`)}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}},Jf=n=>{let e=n.replace(Hf,"").replace(Gf,""),t=Ls?e:e.replace(Xa,s=>" ".repeat(s.length)).replace(Ja,s=>" ".repeat(s.length));co.lastIndex=0;let o;for(;(o=co.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,co.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}},Za=(n,e=!0)=>{let t=co;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(Wa,""):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 m=l-1;m>=0&&n[m]==="\\";m--)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(Wa,""):n.substring(s)),o},Qf=(n,e,t)=>{let o=co;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 m=0;for(let p=u-1;p>=0&&n[p]==="\\";p--)m++;m%2===0&&(f=null)}}else if(h==='"'||h==="'"||h==="`")f=h;else if(h==="(")c++;else if(h===")"&&(c--,c===0)){let m=u+1;for(;m<n.length&&/\s/.test(n[m]);)m++;if(m<n.length&&n[m]==="]"){l=m;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},Va=n=>Za(n,!0),Zf=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("");Ha.lastIndex=0;let o=n.replace(Ha,(s,i,r)=>{let a="";try{let f=JSON.parse(r.trim());f&&typeof f=="object"&&(a=Object.entries(f).map(([u,h])=>{let m=typeof h=="string"?h:JSON.stringify(h);return`${u}=${JSON.stringify(m)}`}).join(", "))}catch{let l=[],u=Yf;u.lastIndex=0;let h;for(;(h=u.exec(r))!==null;){let m=h[1],p=h[2]!==void 0?h[2]:h[0].split(":").slice(1).join(":").trim();l.push(`${m}=${JSON.stringify(p)}`)}l.length>0?a=l.join(", "):a=r.trim()}let d=i.toLowerCase().replace(/_/g,"");return`[tool:functions.${e[d]||t(i)}(${a})]`});return Ga.lastIndex=0,Ya.lastIndex=0,o=o.replace(Ga,""),o=o.replace(Ya,""),o},ed=/(?:path|query|url|keyword|command|method|title|task|id)\s*=\s*['"`]?\s*\.\.\.\s*['"`]?/i,td=/^['"`]?\s*\.\.\.\s*['"`]?$/,Ln=n=>{if(n==null)return!1;let e=String(n).trim();return e==="..."||e==="\u2026"||td.test(e)},Uo=n=>{if(!n)return[];let e=Zf(n);ja.lastIndex=0;let t=e.replace(ja,""),o=[],s=Ls?t:t.replace(Xa,a=>" ".repeat(a.length)).replace(Ja,a=>" ".repeat(a.length)),i=Wf;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 m=t[h];if(f){if(m===f){let p=0;for(let y=h-1;y>=0&&t[y]==="\\";y--)p++;p%2===0&&(f=null)}}else if(m==='"'||m==="'"||m==="`")f=m;else if(m==="(")c++;else if(m===")"&&(c--,c===0)){u=h;let p=h+1;for(;p<s.length&&/\s/.test(s[p]);)p++;if(p<s.length&&s[p]==="]"){l=p;break}}}if(l!==-1){let h=t.substring(d+1,u),m=t.substring(r.index,l+1),p=L(h);Ln(p.path)||Ln(p.query)||Ln(p.url)||Ln(p.keyword)||Ln(p.command)||Ln(p.method)||Ln(p.title)||Ln(p.task)||Ln(p.id)||ed.test(h)||o.push({fullMatch:m,toolName:a.trim(),args:h.trim()}),i.lastIndex=l+1}}return o},Pg=(n,e={})=>{if(!n)return null;if(Po=e,or=new Ka({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}}}},Do=async(n,e,t,o,s="Fast",i=.75,r="agent")=>qf(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,m=h.signal,p=setInterval(()=>{Ct&&(h.abort(),clearInterval(p))},100);try{let y;a==="Ollama"?y=Qa(d,e,u,o,s,c,dn(e),m,i,systemSettings?.ollamaEndpoint||"Cloud"):a==="OpenRouter"?y=lr(d,e,u,o,s,c,dn(e),m,i):a==="DeepSeek"?y=ir(d,e,u,o,s,c,dn(e),m,i):a==="Mistral"?y=rr(d,e,u,o,s,c,dn(e),m,i):a==="NVIDIA"?y=ar(d,e,u,o,s,c,dn(e),m,i):y=await cr(d).models.generateContentStream({model:e,contents:u,config:{systemInstruction:o,temperature:i,thinkingConfig:(()=>{let E=(e||"").toLowerCase(),x=E.includes("gemma-4")||E.startsWith("gemma"),C=E.includes("gemini-3");if(x||C)return x?s.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:rt.MINIMAL}:{includeThoughts:!0,thinkingLevel:rt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:E.includes("pro")?rt.LOW:rt.MINIMAL,Low:rt.LOW,Medium:rt.MEDIUM,Standard:rt.MEDIUM,High:rt.HIGH,xHigh:rt.HIGH}[s]||rt.MEDIUM};{let A={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[s]||2048;return A===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:A}}})()}},{signal:m});for await(let g of y){if(Ct)throw new Error("Subagent task was cancelled.");if(n?.taskId&&typeof Ve<"u"){let x=Ve.find(C=>C.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 E=S?S.trim().split(/\s+/).filter(Boolean).length:0;n&&typeof n.onTokenChunk=="function"&&n.onTokenChunk(S,E),g.usageMetadata&&(l=g.usageMetadata)}}finally{clearInterval(p)}if(l){let y=l.totalTokenCount||0,g=l.cachedContentTokenCount||0,S=(l.candidatesTokenCount||0)+(l.thoughtsTokenCount||0);await Bt("tokens",y,a,e),g>0&&await Bt("cachedTokens",g,a,e),S>0&&await Bt("candidateTokens",S,a,e),n&&typeof n.onUsage=="function"&&n.onUsage({totalTokenCount:y,cachedContentTokenCount:g,candidatesTokenCount:S})}return await Ut("agent",a),{text:f,usageMetadata:l}}),nd=async(n,e,t=null)=>{t=t||V(Vt,{});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.
|
|
520
|
+
Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
|
|
521
|
+
For each Chat ID provided, you must output a tool call to save the consolidated summary.
|
|
522
|
+
|
|
523
|
+
The tool call format MUST be:
|
|
524
|
+
[tool:functions.saveSummary(id="<chat-id>", summary="<updated summary string, max 400 words>")]
|
|
525
|
+
|
|
526
|
+
Guidelines:
|
|
527
|
+
- 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.
|
|
528
|
+
- Focus on key goals, preferences, modified files, and technical decisions.
|
|
529
|
+
- Under no circumstances write normal conversational text. Output ONLY the tool calls.
|
|
530
|
+
- You can stack multiple tool calls for multiple chats.
|
|
531
|
+
|
|
532
|
+
Chats to process:
|
|
533
|
+
|
|
534
|
+
`,a=V(_n,{});for(let u of i){let m=t[u].map(y=>`- ${y}`).join(`
|
|
535
|
+
`),p=a[u];r+=`[Chat ID: ${u}]
|
|
536
|
+
`,p?(r+=`- Existing Summary: "${p}"
|
|
537
|
+
`,r+=`
|
|
538
|
+
-- New Memories to integrate:
|
|
539
|
+
${m}
|
|
540
|
+
|
|
541
|
+
`):r+=`-- Individual Memories:
|
|
542
|
+
${m}
|
|
543
|
+
|
|
544
|
+
`}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 Do(e,l,r,null,"Fast",.75,"background")).text||"",m=Uo(h);if(m.length===0)throw new Error("No tool calls detected in synthesis response");for(let p of m){let y=p.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(y)&&await ao(y,p.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=K.join(cn,"janitor");Oe.existsSync(i)||Oe.mkdirSync(i,{recursive:!0}),Oe.appendFileSync(K.join(i,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${s}
|
|
545
|
+
`)}},sd=async(n,e,t=!1)=>{let{chatId:o,aiProvider:s="Google"}=n,i=K.join(go,"chat-summaries.json"),r=h=>h.filter(m=>(m.role==="user"||m.role==="agent"||m.role==="system")&&m.role!=="think"&&!m.isVisualFeedback&&!m.isMeta&&!m.isTerminalRecord&&!(m.text&&m.text.includes("[TERMINAL_RECORD]"))&&!String(m.id).startsWith("welcome")).map(m=>{let p=m.fullText||m.text||"",y=m.role==="system"||p.startsWith("[TOOL RESULT]:")||m.text&&m.text.startsWith("[TOOL RESULT]:"),g=p;return y&&(p.includes("[TOOL RESULT]:")||m.text&&m.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":m.role==="agent"?"AGENT":"USER"}]: ${g}`}).join(`
|
|
546
|
+
|
|
547
|
+
`),a=async(h,m)=>{let p="You are an expert context summarizer. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details, chat messages, file changes. Under no circumstances exceed MAX 2000 words.",y=m?`Here is the previous summary:
|
|
548
|
+
${m}
|
|
549
|
+
|
|
550
|
+
Here is the new conversation history:
|
|
551
|
+
${h}
|
|
552
|
+
|
|
553
|
+
Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
|
|
554
|
+
${h}
|
|
555
|
+
|
|
556
|
+
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,E=!1,x=null;for(;S<=3&&!E;){S++;try{x=await Do(n,g,y,p,"Fast"),E=!0}catch{if(S>3){if(s==="Google")try{let A=Ze("general_fallback");return(await Do(n,A,y,p,"Fast")).text||""}catch{return""}return""}}}return x&&x.text||""},d=r(e),c=V(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=Vf(e);return t?f.historyLength=(f.historyLength||0)+h:f.historyLength=h,c[o]=f,re(i,c),u}return null},Dg=n=>{try{let e=K.join(go,"chat-summaries.json");if(Oe.existsSync(e)){let t=V(e,{});t[n]&&(delete t[n],re(e,t))}}catch{}},Fg=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:m,wildcardTooling:p}=t,y=dn(n);if(!or&&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,E=K.join(go,"chat-summaries.json"),x=!1,C=e.filter(T=>T.role==="user").length===1,A=S.includes("[TITLE-UPDATE]"),R=C||A,k=S.replace(/\[TITLE-UPDATE\]/g,"").trim();k=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),yield{type:"status",content:"[start]"},yield{type:"status",content:"Gathering Context"},await dt.startTransaction(c,k),l?.advanceRollback&&await Vn.takeInitialSnapshot(c),Ct=!1;let w=null;try{let T=new AbortController;w=setInterval(()=>{Ct&&(T.abort(),w&&(clearInterval(w),w=null))},400);let b=[...e.slice(0,-1)];{let Ae=V(E,{})[c]||{summary:"",historyLength:0};if(Ae.summary&&Ae.historyLength>0){let Jt=0,_e=[];for(let Je=0;Je<b.length;Je++){let Be=b[Je];(Be.role==="user"||Be.role==="agent"||Be.role==="system")&&!String(Be.id).startsWith("welcome")&&!Be.isMeta&&Jt++,Jt>Ae.historyLength&&_e.push(Be)}b=_e}}b=b.map(B=>{if(B.role==="user"&&B.text){let Ae=B.text.match(/\[USER\]([\s\S]*?)\[\/USER\]/);if(Ae)return{...B,text:Ae[1].trim()}}return{...B}});let v=process.env.HIGH_CONTEXT,_=255e3,$=26e4;if(v&&v!=="false"){let B=parseInt(v,10);!isNaN(B)&&B>=256e3&&B<=1e6&&($=B,_=Math.round(B*.85))}if((h==="NVIDIA"&&(n?.includes("glm")||n?.includes("gpt")||n?.includes("qwen")||n?.includes("medium"))||h==="Mistral")&&(_=122e3,$=126e3),h!=="Ollama"&&(u?.tokens||0)>_&&(yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."},await sd(t,b,!0)&&(b=[],x=!0)),C&&g){let B=V(Vt,{});Object.values(B).flat().length>5&&(yield{type:"status",content:"Condensing past chat memories"},await nd(c,t,B))}let G=V(Vt,{}),ce=V(_n,{}),ge=Object.entries(G).filter(([B])=>B!==c).flatMap(([B,Ae])=>Ae),$e=[...Object.entries(ce).filter(([B])=>B!==c).slice(-20).map(([B,Ae])=>`[Chat Summary]: ${Ae}`),...ge].map(B=>`- ${B}`).join(`
|
|
557
|
+
`),F=V(Mt,[]).map(B=>`- ${B.memory}`).join(`
|
|
558
|
+
`),he=(u?.tokens||0)>=1e4,ye=Mr($e,F,g,he),O=new Date,D=O.getFullYear(),ne=O.toLocaleString("en-US",{month:"short"}).toUpperCase(),q=String(O.getDate()).padStart(2,"0"),Me=O.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}),Ne=`${D}-${ne}-${q}, ${Me}`,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"],He=B=>{try{return Oe.readdirSync(B,{withFileTypes:!0})}catch{return[]}},nt=(B,Ae={value:0},Jt=1)=>{if(Ae.value>6200||Jt>7)return Ae.value;let _e=He(B);for(let Je of _e){if(Ae.value>6200)break;Fe.includes(Je.name)||Je.name.startsWith(".")||Je.isDirectory()&&(Ae.value++,nt(K.join(B,Je.name),Ae,Jt+1))}return Ae.value},It=(B,Ae)=>l?.indentationTree!==!1?er(B,Ae,1,He,Fe):nr(B,Ae,"",1,He,Fe),et=nt(process.cwd()),Ue=12;et>3072?Ue=1:et>2304?Ue=2:et>1536?Ue=3:et>768?Ue=4:et>384?Ue=6:et>192?Ue=7:et>96?Ue=8:et>48?Ue=9:et>24&&(Ue=10);let Xt=V(Vo,{}),Nn=Xt[c],vt=Nn?Nn!==process.cwd():!1;Xt[c]=process.cwd(),re(Vo,Xt);let at=V(E,{}),fe=at[c]||{summary:"",historyLength:0};typeof fe=="string"&&(fe={summary:fe,historyLength:0});let Ht=e.filter(B=>(B.role==="user"||B.role==="agent"||B.role==="system")&&!String(B.id).startsWith("welcome")&&!B.isMeta).length;fe.historyLength&&Ht<fe.historyLength&&(fe.summary="",fe.historyLength=0,at[c]=fe,re(E,at));let Jn=typeof fe=="object"?fe.summary||"":fe||"",Qn=b.length>0;Qn&&Jn&&b[0]&&(b[0].role==="user"||b[0].role==="system")&&(b[0].text.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")||(b[0].text=`[SYSTEM METADATA]
|
|
559
|
+
**CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: DYNAMIC)**
|
|
560
|
+
${Jn}
|
|
561
|
+
|
|
562
|
+
[USER] ${b[0].text}`,yield{type:"summary_injected",content:{id:b[0].id,text:b[0].text}}));let fr=Jn&&!Qn?`
|
|
563
|
+
[SYSTEM METADATA]
|
|
564
|
+
**CONTEXT SUMMARY OF PREVIOUS TURNS**
|
|
565
|
+
${Jn}
|
|
566
|
+
`:"",dr=!!l?.dynamicDirAwareness,el=`${c}|${h}|${r}|${n}|${i}|${dr}`,ur=!dr&&Ts.key===el&&Ts.value?"":`
|
|
567
|
+
**DIRECTORY STRUCTURE**
|
|
568
|
+
CWD: `+process.cwd()+`${f?" [PLAYGROUND MODE]":""}
|
|
569
|
+
`+It(process.cwd(),Ue),gt=await ws(),Pn="";if(No()&>.file_focused!=="none"){Pn=`
|
|
570
|
+
[ADDITIONAL IDE CONTEXT]
|
|
571
|
+
`;let B=K.relative(process.cwd(),gt.file_focused),Ae=(gt.opened_editors||[]).map(_e=>{let Je=K.relative(process.cwd(),_e);return Je.startsWith("..")?`[External] ${K.basename(_e)}`:Je});if(Pn+=`Focused File: ${B}
|
|
572
|
+
Cursor Line: ${gt.cursor_line}
|
|
573
|
+
`,gt.selected){let _e=gt.selected,Je=_e.split(`
|
|
574
|
+
`);Je.length>256&&(_e=Je.slice(0,240).join(`
|
|
575
|
+
`)+`
|
|
576
|
+
... [truncated] ...
|
|
577
|
+
`+Je.slice(-16).join(`
|
|
578
|
+
`)),_e.length>2048&&(_e=_e.slice(0,1920)+`
|
|
579
|
+
... [truncated] ...
|
|
580
|
+
`+_e.slice(-128)),Pn+=`Current Selection: "${_e}"
|
|
581
|
+
`}if(gt.manual_edits){let Je=gt.manual_edits.split(`
|
|
582
|
+
`),Be=[],Ke=null;for(let j of Je)j.trim()&&(j.startsWith(" Line ")?Ke&&Ke.edits.push(j):(Ke={path:j.endsWith(":")?j.slice(0,-1):j,edits:[]},Be.push(Ke)));for(let j of Be)j.edits.length>80&&(j.edits=j.edits.slice(-80)),j.originalEditsCount=j.edits.length;let se=(j,J)=>J.reduce((We,on)=>{let yn=gt.file_focused&&(on.path===gt.file_focused||K.resolve(process.cwd(),on.path)===K.resolve(gt.file_focused))?Math.ceil(j*1.2):j;return We+Math.min(on.edits.length,yn)},0),Lt=80;if(se(80,Be)>300){let j=!1;for(let J=80;J>=10;J--)if(se(J,Be)<=300){Lt=J,j=!0;break}j||(Lt=10)}let Xe=[...Be];if(Lt===10&&se(10,Xe)>500)for(;Xe.length>0&&se(10,Xe)>500;){let j=0,J=Xe[0].originalEditsCount;for(let We=1;We<Xe.length;We++)Xe[We].originalEditsCount<J&&(J=Xe[We].originalEditsCount,j=We);Xe.splice(j,1)}for(let j of Xe){let We=gt.file_focused&&(j.path===gt.file_focused||K.resolve(process.cwd(),j.path)===K.resolve(gt.file_focused))?Math.ceil(Lt*1.2):Lt;j.edits.length>We&&(j.edits=j.edits.slice(-We))}for(let j of Xe){let J=`${j.path}:
|
|
583
|
+
${j.edits.join(`
|
|
584
|
+
`)}`;for(;j.edits.length>0&&J.length>4*768;)j.edits.shift(),J=`${j.path}:
|
|
585
|
+
${j.edits.join(`
|
|
586
|
+
`)}`;J.length>4*768?j.stringRepresentation="... "+J.slice(-(4*768-4)):j.stringRepresentation=J}let Qt=Xe.map(j=>j.stringRepresentation).join(`
|
|
587
|
+
`);for(;Xe.length>0&&Qt.length>4*2048;){Xe[0].edits.length>0?Xe[0].edits.shift():Xe.shift();for(let j of Xe){let J=`${j.path}:
|
|
588
|
+
${j.edits.join(`
|
|
589
|
+
`)}`;J.length>4*768?j.stringRepresentation="... "+J.slice(-(4*768-4)):j.stringRepresentation=J}Qt=Xe.map(j=>j.stringRepresentation).join(`
|
|
590
|
+
`)}Qt.length>4*2048&&(Qt="... "+Qt.slice(-(4*2048-4))),Pn+=`Recent Manual Edits:
|
|
591
|
+
${Qt}
|
|
592
|
+
`}Ae.length>0&&(Pn+=`All Opened Editors: ${Ae.join(", ")}`),gt.diagnostics&&(Pn+=`
|
|
593
|
+
**ACTIVE FILE ERRORS**:
|
|
594
|
+
${gt.diagnostics}
|
|
595
|
+
`),(k.toLowerCase().includes("lint")||k.toLowerCase().includes("warning"))&>.warnings&&(Pn+=`
|
|
596
|
+
**LINT WARNINGS**:
|
|
597
|
+
${gt.warnings}
|
|
598
|
+
`)}let hr=k.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),pr=/(?:\\)?@\[([^\]]+)\]/g,Bo,Wo=[];for(pr.lastIndex=0;(Bo=pr.exec(hr))!==null;){let B=Bo[0].startsWith("\\");Wo.push({tag:Bo[1],isEscaped:B})}let jo=[],fo=null;for(let B=0;B<Wo.length;B++){let{tag:Ae,isEscaped:Jt}=Wo[B];if(!Jt)try{let _e=Ae.trim().replace(/^["']|["']$/g,""),Je=/[:#]L?(\d+)(?:-L?(\d+))?$/i,Be=_e.match(Je),Ke=_e,se=null,Lt=null;Be&&(se=parseInt(Be[1],10),Lt=Be[2]?parseInt(Be[2],10):se,Ke=_e.slice(0,Be.index));let Xe=K.resolve(process.cwd(),Ke);if(Oe.existsSync(Xe)&&Oe.statSync(Xe).isFile()){let j=Ke.toLowerCase(),J=j.endsWith(".pdf"),We=j.endsWith(".docx")||j.endsWith(".doc")||j.endsWith(".ppt")||j.endsWith(".pptx")||j.endsWith(".xls")||j.endsWith(".xlsx"),on=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(j),Nt=on||J||We,yn=h==="Google"||dn(n);if(Nt&&!yn){let Pe=`\u2718 Unsupported Modality: ${K.basename(Ke)}`,Ce=115;process.stdout.isTTY&&(Ce=process.stdout.columns-5||120);let ut=[Pe],Dn=Math.max(...ut.map(kn=>kn.length)),Fn=Math.min(Dn+4,Ce),ts=ut.map(kn=>`${kn.padEnd(Fn-2).substring(0,Fn-2)}`).join(`
|
|
599
|
+
`);yield{type:"visual_feedback",content:mn(`${ts}
|
|
600
|
+
`)};continue}if(se===null&&!Nt){let Pe=0;try{Pe=Oe.readFileSync(Xe,"utf8").split(/\r\n|\r|\n/).length}catch{}if(Pe>300){let Ce=`\u21B7 Skipped (Too Large): ${K.basename(Ke)}`,ut=115;process.stdout.isTTY&&(ut=process.stdout.columns-5||120);let Dn=Math.min(Ce.length+4,ut),Fn=Ce.padEnd(Dn-2).substring(0,Dn-2);yield{type:"visual_feedback",content:mn(`${Fn}
|
|
601
|
+
`)};continue}}let Rn=se!==null?se:1,Zn=Lt!==null?Lt:se!==null?se:Rn+299;Zn-Rn>300&&(Zn=Rn+300);let ho=`path=${JSON.stringify(Ke)}, startLine=${Rn}, endLine=${Zn}`,tt=await Qs(ho,{isMultiModal:yn}),Ge=!1,Pt="",es=null;if(typeof tt=="string"?tt.trim().startsWith("ERROR")?Ge=!0:Pt=tt:tt&&typeof tt=="object"&&tt.binaryPart?(es=tt.binaryPart,Pt=tt.text||""):Ge=!0,!Ge){let Pe="";if(on?(Pe=`\u2714 Processed: ${K.basename(Ke)}`,fo=es):J||We?(Pe=`\u2714 Auto-Analysed: ${K.basename(Ke)}`,fo=es):(Pe=`\u2714 Auto-Read: ${K.basename(Ke)}`,jo.push(Pt)),Pe){let Ce=115;process.stdout.isTTY&&(Ce=process.stdout.columns-5||120);let ut=[Pe],Dn=Math.max(...ut.map(kn=>kn.length)),Fn=Math.min(Dn+4,Ce),ts=ut.map(kn=>`${kn.padEnd(Fn-2).substring(0,Fn-2)}`).join(`
|
|
602
|
+
`);yield{type:"visual_feedback",content:mn(`${ts}
|
|
603
|
+
`)}}}}}catch{}}let mr="";jo.length>0&&(mr=`[TAGGED FILE CONTENTS] Auto Read User Tagged files by System, No need to re-read
|
|
604
|
+
`+jo.join(`
|
|
605
|
+
|
|
606
|
+
`)+`
|
|
607
|
+
[/TAGGED FILE CONTENTS]
|
|
608
|
+
`);let tl=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",nl=hr.replace(/\\(@\[[^\]]+\])/g,"$1"),sl=p?`**You cannot execute tools
|
|
609
|
+
Instead in chat, output the exact string you WOULD have produced & wait for system response**
|
|
610
|
+
`:"",gr=`[SYSTEM METADATA]
|
|
611
|
+
Time: ${Ne}
|
|
612
|
+
OS: ${tl}${l?.dynamicDirAwareness?ur:""}${vt?`
|
|
613
|
+
WARNING: CWD Changed from previous: "${Nn}" to current: "${process.cwd()}", write change in chat to avoid future path mismatches
|
|
614
|
+
`:""}${ye}${Pn}
|
|
615
|
+
[/METADATA]
|
|
616
|
+
${fr}${r!=="Fast"&&(h==="Mistral"||r!=="xHigh"&&h==="Google")?`${h==="Mistral"||n.toLowerCase().startsWith("gemma")?`[SYSTEM] STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think> [/SYSTEM]
|
|
617
|
+
`:""}`:""}[SYSTEM] EXACT STRING SYNTAX '[tool:functions.ToolName(arg="value")]' IN CHAT [/SYSTEM]
|
|
618
|
+
${mr}${sl}[USER PROMPT] ${nl.trim()} [/USER PROMPT]`.trim(),yr={role:"user",text:gr};fo&&(yr.binaryPart=fo),b.forEach(B=>{B.text&&B.role==="agent"&&(B.text=B.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,""),B.text=B.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[^\[\n]*/gi,"").trim())}),b.push(yr),fr&&e[e.length-1]?.id&&(yield{type:"summary_injected",content:{id:e[e.length-1].id,text:gr}});let xn=null,Ho=a==="Flux"?100:10,gn=16;yield{type:"status",content:"Connecting"},Ct=!1;let wr=[],uo=!1;for(let B=0;B<=Ho;B++){let Ae=await hi("agent",t);if(!Ae.allowed)throw new Error(Ae.reason||`Budget Exhausted for Provider (${h||"Agent"})`);let Jt=[];if(uo=!1,l?.compression===0&&(u?.tokens||0)>$&&(b=Nr(b,6)),B>0&&(yield{type:"status",content:"Working"}),Ct){try{let{clearPendingNudges:Te}=await import("./subagent_state-3D5ZJCLX.js");Te()}catch{}yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
619
|
+
|
|
620
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}try{let{consumePendingNudges:Te}=await import("./subagent_state-3D5ZJCLX.js"),Ye=Te();if(Ye&&Ye.length>0){let ie=Ye.join(`
|
|
621
|
+
|
|
622
|
+
`);b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
623
|
+
|
|
624
|
+
${ie}`:b.push({role:"user",text:ie}),yield{type:"status",content:"Subagent Update"}}}catch{}if(o){let Te=await o();Te&&(Te.startsWith("/btw")?b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
625
|
+
|
|
626
|
+
[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
|
|
627
|
+
[QUESTION] ${Te.replace("/btw","").trim()} [/QUESTION]`:b.push({role:"user",text:`${r!=="Fast"&&(h==="Mistral"||r!=="xHigh"&&h==="Google")?`${h==="Mistral"||n.toLowerCase().startsWith("gemma")?`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY
|
|
628
|
+
**STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
|
|
629
|
+
`:""}`:""}[QUESTION] ${Te.replace("/btw","").trim()} [/QUESTION]`}):b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
|
|
630
|
+
|
|
631
|
+
[STEERING HINT] ${Te.trim()} [/STEERING HINT]`:b.push({role:"user",text:`${r!=="Fast"&&(h==="Mistral"||r!=="xHigh"&&h==="Google")?`${h==="Mistral"||n.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
|
|
632
|
+
`:""}`:""}[STEERING HINT] ${Te.trim()} [/STEERING HINT]`}),yield{type:"status",content:`${Te.startsWith("/btw")?"Question Forwarded...":"Steering Hint Injected..."}`})}let _e,Je=!1,Be=1,Ke=1,se="",Lt=null,Xe=null,Qt=null,j=0,J=[],We=0,on=!1,Nt=!1,yn=!1,Rn=!1,Zn=!0,ho=0,tt="",Ge="",Pt=!1,es=!1,Pe=!0,Ce=n,ut="";for(;Be<=gn&&Ke<=gn&&!Je&&!Ct;){let Te=!1;try{se="",Zn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},Zn=!1,Ke===1&&(tt=""));let Ye=N=>{if(!N||!N.includes("[tool:"))return N;let Q="___THINK_OPEN_TAG___",U="___THINK_CLOSE_TAG___";N=N.replace("<think>",Q).replace("</think>",U),N=N.replace(zf,(de,De)=>De.includes("[tool:")?De.trim():de);let W="",Ee=0;for(;Ee<N.length;){let de=N.indexOf("[tool:",Ee);if(de===-1){W+=N.substring(Ee).replace(za,"").replace(qa,"");break}let De=N.substring(Ee,de);W+=De.replace(za,"").replace(qa,"");let St=N.indexOf("]",de);if(St===-1){W+=N.substring(de);break}W+=N.substring(de,St+1),Ee=St+1}return N=W,N=N.replaceAll(Q,"<think>").replaceAll(U,"</think>"),N},ie=b.filter(N=>(N.role==="user"||N.role==="agent"||N.role==="system")&&!String(N.id).startsWith("welcome")&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.startsWith("[TERMINAL_RECORD]"))).map((N,Q,U)=>{let W=N.text||"";g||(W=W.replace(/\s*\n*\s*\[Prompted on:.*?\]/gi,"").trim()),N.role==="agent"&&(W=Ye(W),W=W.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim(),W=W.replaceAll("\x1B[33m\u24D8 Request Cancelled\x1B[0m","*User Cancelled Response Generation*"));let Ee=[{text:W}];return N.binaryPart&&dn(Ce)&&U.slice(Q+1).filter(De=>De.role==="user"&&!De.text?.startsWith("[TOOL RESULT]")).length<=2&&Ee.push(N.binaryPart),{role:N.role==="user"||N.role==="system"?"user":"model",parts:Ee}});for(let N=0;N<ie.length;N++){let Q=ie[N],U=Q.parts?.[0]?.text||"";if(Q.role==="model"&&/\[tool:/i.test(U)){let W=-1;for(let Ee=N+1;Ee<ie.length;Ee++){let de=ie[Ee],De=de.parts?.[0]?.text||"";if(de.role==="user"&&De.startsWith("[TOOL RESULT]")){W=Ee;break}}if(W!==-1&&W!==N+1){let[Ee]=ie.splice(W,1);ie.splice(N+1,0,Ee)}}}for(let N=ie.length-2;N>=0;N--){let Q=ie[N],U=ie[N+1];Q.role==="user"&&U.role==="user"&&(U.parts?.[0]?.text||"").trim().startsWith("[SYSTEM")&&ie.splice(N,1)}let rn=[];for(let N=0;N<ie.length;N++){let Q=ie[N];if(rn.length===0)rn.push(Q);else{let U=rn[rn.length-1];U.role===Q.role?(U.parts[0].text+=`
|
|
633
|
+
|
|
634
|
+
`+(Q.parts?.[0]?.text||""),Q.parts?.length>1&&U.parts.push(...Q.parts.slice(1))):rn.push(Q)}}ie.length=0,ie.push(...rn),Ce=n;let Zt=`${c}|${h}|${r}|${Ce}|${JSON.stringify(i)}|${!!l?.dynamicDirAwareness}|${!!l?.subAgents}`;Ts.key===Zt&&Ts.value?ut=Ts.value:(ut=_r(i,((Ce||"gemma").toLowerCase().startsWith("gemma"),r),a,l,g,C,h,h==="Google"?!0:y,!(Ce||"gemma").toLowerCase().startsWith("gemma"),c),l?.dynamicDirAwareness||(ut+=`
|
|
635
|
+
${ur.replace(`
|
|
636
|
+
**DIRECTORY STRUCTURE**`,`
|
|
637
|
+
**DIRECTORY STRUCTURE**`)}`),Ts.key=Zt,Ts.value=ut);let xt=ie[ie.length-1];if(No()&B>0){await new Promise(U=>setTimeout(U,2500)),yield{type:"status",content:"Verifying"};let N=await ws(),Q=N?N.diagnostics:null;Q&&xt&&xt.role==="user"&&xt.parts?.[0]?.text&&(xt.parts[0].text+=`
|
|
638
|
+
${Q} [/ERROR]`),yield{type:"status",content:"Working"}}if(h==="Mistral"||h==="Google"&&n?.toLowerCase().startsWith("gemma")){let U=`
|
|
639
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn${r!=="Fast"&&(h==="Mistral"||r!=="xHigh")?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>**":""} [/SYSTEM]`;xt&&xt.role==="user"&&xt.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(xt.parts[0].text+=U)}if(l?.advanceRollback&&xt&&xt.role==="user"&&xt.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 Q=`
|
|
640
|
+
[SYSTEM] File Changes:
|
|
641
|
+
`;for(let W of N.newFiles)Q+=`* ${W} (created)
|
|
642
|
+
`;for(let W of N.modifiedFiles)Q+=`* ${W} (modified)
|
|
643
|
+
`;for(let W of N.deletedFiles)Q+=`* ${W} (deleted)
|
|
644
|
+
`;Q+="[/SYSTEM]",xt.parts[0].text+=Q;let U=-1;for(let W=b.length-1;W>=0;W--)if(b[W].role==="user"&&b[W].text?.startsWith("[TOOL RESULT]")){U=W;break}U!==-1&&(b[U].text+=Q)}}catch{}let en=Math.floor(Ho*(a==="Flux"?.98:.8)),Ot=B+1;Ot>=en&&xt&&xt.parts?.[0]&&(xt.parts[0].text+=`
|
|
645
|
+
[SYSTEM] WARNING, Turn Limit Impending: Step ${Ot}/${Ho}. Wrap up quickly/prompt user to continue. [/SYSTEM]`);let $t=new Promise((N,Q)=>{T.signal.aborted&&Q(new DOMException("The user aborted a request.","AbortError")),T.signal.addEventListener("abort",()=>{Q(new DOMException("The user aborted a request.","AbortError"))})});$t.catch(()=>{});let an=ie;if(h==="Ollama")_e=Qa(t.apiKey,Ce,an,ut,r,a,y,T.signal,1,l?.ollamaEndpoint||"Cloud");else if(h==="OpenRouter")_e=lr(t.apiKey,Ce,an,ut,r,a,y,T.signal,1);else if(h==="DeepSeek")_e=ir(t.apiKey,Ce,an,ut,r,a,y,T.signal,1.05);else if(h==="Mistral")_e=rr(t.apiKey,Ce,an,ut,r,a,y,T.signal,1);else if(h==="NVIDIA"){let N=ar(t.apiKey,Ce,an,ut,r,a,y,T.signal,1.05);_e=Xf(N,Ce)}else{let Q=cr(t?.apiKey).models.generateContentStream({model:Ce||"gemini-3-flash-preview",contents:an,config:{systemInstruction:ut,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(),W=U.includes("gemma-4")||U.startsWith("gemma"),Ee=U.includes("gemini-3");if(W||Ee)return W?r.toLowerCase()!=="xhigh"?{includeThoughts:!1,thinkingLevel:rt.MINIMAL}:{includeThoughts:!0,thinkingLevel:rt.HIGH}:{includeThoughts:!0,thinkingLevel:{Fast:U.includes("pro")?rt.LOW:rt.MINIMAL,Low:rt.LOW,Medium:rt.MEDIUM,Standard:rt.MEDIUM,High:rt.HIGH,xHigh:rt.HIGH}[r]||rt.MEDIUM};{let de={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[r]||2048;return de===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:de}}})()}},{signal:T.signal});_e=await Promise.race([Q,$t])}se="",Lt=null,Qt=null,J=[],We=0,yield{type:"model_update",content:null},Ge="",Pt=tt.length>0;let wn="",Go=Date.now(),os=async function*(){if(h==="Google"&&wn){let N=Ws(wn);for(let Q of N)yield Q;wn="",Go=Date.now()}},Sr=!0,is="",Es=!1,lt=null,Ws=N=>{let Q=[],U=N;for(;U.length>0;)if(Es){let W=is+U;if(lt==="tool"||lt==="agent"){let De=lt==="tool"?"[tool:functions.":"[agent:generalist.",St=lt==="tool"?"[tool":"[agent";if(!W.startsWith(St)||W.length>=De.length&&!W.startsWith(De)){Q.push({type:"text",content:W}),is="",Es=!1,lt=null,U="";break}}let Ee=-1,de="]";if(lt==="tool"||lt==="agent"){let De=0,St=null,Y=0,ae=!1;for(let ze=0;ze<W.length;ze++){let M=W[ze];if(St){if(M===St){let yt=0;for(let Ie=ze-1;Ie>=0&&W[Ie]==="\\";Ie--)yt++;yt%2===0&&(St=null)}}else if(M==='"'||M==="'"||M==="`")St=M;else if(M==="(")De++,ae=!0;else if(M===")")De--;else if(M==="[")Y++;else if(M==="]"){if(ae&&De===0&&Y===1){Ee=ze;break}Y--}}}else lt==="end"?de="[[END]]":lt==="kimi_section"?de="<|tool_calls_section_end|>":lt==="kimi_call"&&(de="<|tool_call_end|>"),Ee=W.indexOf(de);if(Ee!==-1){let De=de.length;if(!lt.startsWith("kimi")){let St=W.substring(0,Ee+De);Q.push({type:"text",content:St})}is="",Es=!1,lt=null,U=W.substring(Ee+De)}else{let De=lt.startsWith("kimi")?8192:512;W.length>De?(lt.startsWith("kimi")||Q.push({type:"text",content:W}),is="",Es=!1):is=W,U="";break}}else{let W=U.indexOf("[tool"),Ee=U.indexOf("[agent"),de=U.indexOf("[[END]]"),De=U.indexOf("<|tool_calls_section_begin|>"),St=U.indexOf("<|tool_call_begin|>"),Y=[{type:"tool",idx:W,start:"[tool",end:"]"},{type:"agent",idx:Ee,start:"[agent",end:"]"},{type:"end",idx:de,start:"[[END]]",end:"[[END]]"},{type:"kimi_section",idx:De,start:"<|tool_calls_section_begin|>",end:"<|tool_calls_section_end|>"},{type:"kimi_call",idx:St,start:"<|tool_call_begin|>",end:"<|tool_call_end|>"}].filter(ae=>ae.idx!==-1).sort((ae,ze)=>ae.idx-ze.idx);if(Y.length>0){let ae=Y[0];ae.idx>0&&Q.push({type:"text",content:U.substring(0,ae.idx)}),Es=!0,lt=ae.type,is="",U=U.substring(ae.idx)}else{let ae=["[tool","[agent","[[END]]","<|tool_calls_section_begin|>","<|tool_call_begin|>"],ze=-1;for(let M of ae){for(let yt=M.length-1;yt>0;yt--)if(U.endsWith(M.substring(0,yt))){ze=U.length-yt;let Ie=ae.indexOf(M);Ie===0?lt="tool":Ie===1?lt="agent":Ie===2?lt="end":Ie===3?lt="kimi_section":lt="kimi_call";break}if(ze!==-1)break}if(ze!==-1)ze>0&&Q.push({type:"text",content:U.substring(0,ze)}),Es=!0,is=U.substring(ze),U="";else{Q.push({type:"text",content:U});break}}}return Q},rl=_e[Symbol.asyncIterator]();for(;;){let{value:N,done:Q}=await Promise.race([rl.next(),$t]);if(Q)break;if(N&&N.type==="status"){yield N;continue}let U="",W=N.candidates?.[0]?.content?.parts;if(W&&W.length>0)for(let de of W)de.thought?de.text&&(Te||(U+="<think>",Te=!0),U+=de.text):de.text&&(Te&&(U+="</think>",Te=!1),U+=de.text);else{let de=N.text||"";de&&Te&&(U+="</think>",Te=!1),U+=de}let Ee=U?U.trim().split(/\s+/).filter(Boolean).length:0;if(t&&typeof t.onTokenChunk=="function"&&t.onTokenChunk(U,Ee),Sr&&(yield{type:"status",content:"Thinking"},Sr=!1),Ct){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
646
|
+
|
|
647
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(U){if(Pt){if(Ge+=U,Ge.length>=64){let Y=0,ae=Math.min(tt.length,Ge.length);for(let M=ae;M>=10;M--)if(tt.endsWith(Ge.substring(0,M))){Y=M;break}let ze=Ge.substring(Y);if(ze){let yt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?ze.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):ze.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");if(yt)if(se+=yt,h==="Google")wn+=yt;else{yield*os();let Ie=Ws(yt);for(let ue of Ie)yield ue}}Pt=!1,Ge=""}continue}else if(se+=U,h==="Google")wn+=U;else{yield*os();let Y=Ws(U);for(let ae of Y)yield ae}let de=Jf(se);if(de.inside){es=!0,Qt||(Qt=Date.now());let ae={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"}[de.toolName]||de.toolName,ze=de.args||"",M=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(ae)){let Ie=L(ze),ue=Ie.path||Ie.targetFile||Ie.TargetFile||Ie.directory,Sn=Ie.keyword,rs=Ie.title||Ie.task,Un=Ie.id||Ie.taskId,be=Ie.timeout||Ie.time;if(Sn!=null)M=String(Sn).replace(Ss,"");else if(ue)M=K.basename(String(ue).replace(Ss,"").replace(Ba,"/"));else if(rs&&(ae==="invoke"||ae==="invoke_sync"))M=String(rs).replace(Ss,"").substring(0,30);else if(Un&&ae==="get_progress")M=String(Un).replace(Ss,"");else if(be&&ae==="await"){let Dt=parseFloat(String(be).replace(Ss,""));isNaN(Dt)?M=String(be).replace(Ss,""):(Dt<5&&(Dt=5),Dt>120&&(Dt=120),M=(Cn=>{if(Cn>=60){let zo=Math.floor(Cn/60),xs=Cn%60;return`${zo}m${xs>0?` ${xs}s`:""}`}return`${Cn}s`})(Dt))}else{let Dt=ze.match(jf);if(Dt){let Gt=Dt[1].replace(Ss,"");ae==="invoke"||ae==="invoke_sync"||ae==="get_progress"?M=Gt.substring(0,30):M=ae==="search_keyword"||ae==="file_map"?Gt:K.basename(Gt.replace(Ba,"/"))}}}let yt=`${sr[ae]||ae}${M?` ${M}`:""}`;if((ae!==Lt||M!==Xe)&&(Lt=ae,Xe=M,yield{type:"status",content:`${yt}`},process.stdout.isTTY)){let ue={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"}[ae]||"Working";process.stdout.write(`\x1B]0;${ue}...\x07`)}}if(se.length-ho>150){ho=se.length;let Y=Za(se,!1),ze=(Y.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),M=ze.split(/[.!?]\s+/),yt=new Set(M),Ie=M.length>10?(M.length-yt.size)/M.length:0,ue=ze.split(/\s+/).filter(xe=>xe.length>0).length,Sn=.6,rs=.8,Un=!1;if((h.toLowerCase().includes("google")||h.toLowerCase().includes("mistral"))&&((Ce||"").toLowerCase().startsWith("gemma")||(Ce||"").toLowerCase().includes("stral"))){let I={low:256,medium:768,high:8192,max:16384,xhigh:16384}[r?.toLowerCase()]||2500;Un=ue>I}if(Ie>Sn||Un){yield{type:"status",content:`${Ie>Sn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},Nt=!0,await new Promise(I=>setTimeout(I,3e3));break}let Gt=Va(se).trim().split(/[.!?]\s+/),Cn=new Set(Gt);if((Gt.length>10?(Gt.length-Cn.size)/Gt.length:0)>rs){yield{type:"status",content:"Response Loop Detected. Re-centering..."},Nt=!1,Rn=!0,await new Promise(xe=>setTimeout(xe,3e3));break}let xs=Y.replace(Nf,"").replace(Pf,"").replace(Df,"").replace(Ff,""),Ft=xs.toLowerCase().split(/\s+/).map(xe=>xe.replace(Uf,"")).filter(xe=>xe.length>0),On=!1;if(Ft.length>=10)for(let xe=1;xe<=15;xe++){let I=Math.max(3,Math.ceil(10/xe));if(Ft.length<xe*I)continue;let H=Ft.slice(Ft.length-xe),ee=H.join(" ");if(xe>1&&ee===H.slice(0,Math.floor(xe/2)).join(" ").repeat(2).trim())continue;let le=!0;for(let pe=1;pe<I;pe++)if(Ft.slice(Ft.length-xe*(pe+1),Ft.length-xe*pe).join(" ")!==ee){le=!1;break}if(le){On=!0;break}}if(!On){let xe=xs.toLowerCase().replace(Bf,"");if(xe.length>=20)for(let I=1;I<=10;I++){let H=Math.max(5,Math.ceil(16/I));if(xe.length<I*H)continue;let ee=xe.substring(xe.length-I),le=!0;for(let pe=1;pe<H;pe++)if(xe.substring(xe.length-I*(pe+1),xe.length-I*pe)!==ee){le=!1;break}if(le){On=!0;break}}}if(On){yield{type:"status",content:"Stuttering Detected. Re-centering..."},Nt=!1,yn=!0,await new Promise(xe=>setTimeout(xe,3e3));break}}let De=se.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),St=Uo(De);for(;St.length>We;){yield*os();let Y=St[We],ae=Date.now(),M={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"}[Y.toolName]||Y.toolName,yt=sr[M]||Y.toolName,Ie=bs(M,Y.args);yield{type:"status",content:`${yt}${Ie?` ${Ie}`:""}`};let ue="";if(M==="web_search"){let{query:I,limit:H=10,aiMode:ee=!1}=L(Y.args);ue=`${I?"\u2714":"\u2718"} ${ee?"AI Search":"Searched"}: ${I?`${I}`:"No Search Query"}${ee===!1&&I?` \u2192 ${H}`:""}`}else if(M==="web_scrape"){let I=L(Y.args).url||null;ue=`${I?"\u2714":"\u2718"} Visited: ${I||"No Source"}`}else if(M==="view_file"){let{path:I,StartLine:H,EndLine:ee,start_line:le,end_line:pe,startLine:je,endLine:ke}=L(Y.args),we=H||le||je,X=ee||pe||ke,oe=parseInt(we)||1,te=parseInt(X)||(we?oe+800:800),Le="...",Qe=te;try{let qe=K.resolve(process.cwd(),I);if(Oe.existsSync(qe)){let Tt=Oe.readFileSync(qe,"utf8").split(`
|
|
648
|
+
`).length;Le=Tt,!we&&!X&&Tt>800?Qe=Math.min(50,Tt):Qe=Math.min(te,Tt)}}catch{}let me=(I||"").toLowerCase(),ve=me.endsWith(".pdf"),st=me.endsWith(".docx")||me.endsWith(".doc")||me.endsWith(".ppt")||me.endsWith(".pptx")||me.endsWith(".xls")||me.endsWith(".xlsx"),Re=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(me);ve||st?ue=`${I.length>0?"\u2714":"\u2718"} ${I?`Analyzed: ${K.basename(I)}`:"Analyzed: File Not Found"}`:Re?ue=`${I.length>0?"\u2714":"\u2718"} ${I?`Processed: ${K.basename(I)}`:"Processed: File Not Found"}`:ue=`${Le!=="..."?"\u2714":"\u2718"} Read: ${I?`${K.basename(I)} \u2192 ${Le!=="..."?`Lines ${oe} - ${Qe} of ${Le}`:"File Not Found"}`:"File Not Found"}`}else if(M==="list_files"||M==="read_folder"){let I=M==="list_files"?"List":"Browsed",H=L(Y.args).path||null,ee=L(Y.args).recurse||1;ue=`${H?"\u2714":"\u2718"} ${I}: ${H?`${H==="."?`./${ee>1?"*":""}`:`${H.replaceAll("\\","/")}${ee>1?`${H.endsWith("/")?"*":"/*"}`:`${H.endsWith("/")?"":"/"}`}`}`:"No Folder Selected"}`}else if(M==="write_file"||M==="update_file"){let I=M==="write_file"?"Created":"Edited",H=L(Y.args).path||null;ue=`${H?"\u2714":"\u2718"} ${I}: ${H.replaceAll("\\","/")||"No File Changes"}`}else if(M==="write_pdf"){let I=L(Y.args).path||null;ue=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No PDF Generated"}`}else if(M==="write_docx"){let I=L(Y.args).path||null;ue=`${I?"\u2714":"\u2718"} Generated: ${I.replaceAll("\\","/")||"No Docx Generated"}`}else if(M==="file_map"){let I=L(Y.args).path;ue=`${I?"\u2714":"\u2718"} Indexed: ${I.replaceAll("\\","/")?""+I:"File Not Found"}`}else if(M.toLowerCase()==="search_keyword"||M.toLowerCase()==="todo")ue="";else if(M.toLowerCase()==="generate_image"){let{path:I,outputPath:H,output:ee}=L(Y.args);ue=`\u2714 Generated: ${I||H||ee||"generated_image.png"}`}else if(M==="invoke_sync"||M==="InvokeSync"){let I=bs(M,Y.args);ue=`\u2714 Called Generalist${I?`: ${I}`:""}`}else if(M==="Invoke"||M==="InvokeAsync"||M==="invoke"){let I=bs(M,Y.args);ue=`\u2714 Started Generalist${I?`: ${I}`:""}`}else if(M==="get_progress"||M==="GetProgress"){let I=bs(M,Y.args);ue=`\u2714 Checked${I?`: ${I}`:""}`}else if(M==="cancel"){let I=bs(M,Y.args);ue=`\u{1F6C7} Cancelled${I?`: ${I}`:""}`}else if(M==="steer"||M==="Steer"){let I=bs(M,Y.args);ue=`\u2714 Steered${I?`: ${I}`:""}`}else if(M==="EmergencyRollback"){let{method:I}=L(Y.args);ue=I==="forceRevert"?"":"\u2714 Rollback Point Checked"}else if(M==="await"||M==="Await"){let{time:I,timeout:H}=L(Y.args),ee=parseFloat(H||I)||0;ee||(ee=120);let le=ke=>{if(ke>=60){let we=Math.floor(ke/60),X=ke%60;return`${we}m${X>0?` ${X}s`:""}`}return`${ke}s`},pe=["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"];ue=`\u2714 ${pe[Math.floor(Math.random()*pe.length)]} \u2192 ${le(ee)}`}else M==="Answer"||M==="answer"?ue="\u2714 Resolved Sub-Agent Query":M==="exec_command"||M==="ask"?ue="":ue=`Executed: ${Y.toolName}`;if(yield*os(),M==="exec_command"){let{command:I}=L(Y.args);if(I&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let H=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],ee=K.resolve(process.cwd()).substring(0,3).toLowerCase(),le=X=>{let oe=[],te="",Le=null;for(let Qe=0;Qe<X.length;Qe++){let me=X[Qe];Le?(me===Le&&(Le=null),te+=me):me==='"'||me==="'"?(Le=me,te+=me):me==="&"&&X[Qe+1]==="&"||me==="|"&&X[Qe+1]==="|"?(te.trim()&&(oe.push(te.trim()),te=""),Qe++):me===";"||me==="|"||me==="&"?te.trim()&&(oe.push(te.trim()),te=""):te+=me}return te.trim()&&oe.push(te.trim()),oe},pe=X=>{let oe=[],te="",Le=null;for(let Qe=0;Qe<X.length;Qe++){let me=X[Qe];Le?(me===Le&&(Le=null),te+=me):me==='"'||me==="'"?(Le=me,te+=me):/\s/.test(me)?te&&(oe.push(te),te=""):te+=me}return te&&oe.push(te),oe},je=X=>{let oe=X.replace(/^['"]|['"]$/g,"").trim();return!oe||process.platform==="win32"&&/^\/[a-zA-Z0-9?]+$/.test(oe)?!1:H.some(te=>{if(te.source==="[a-zA-Z]:[\\\\\\/]"){let Le=oe.match(/[a-zA-Z]:[\\\/]/i);return Le&&Le[0].toLowerCase()!==ee}return te.test(oe)})};if(le(I).some(X=>{let oe=pe(X);if(oe.length===0)return!1;let te=oe[0].replace(/^['"]|['"]$/g,"").toLowerCase();if(["echo","printf","write-output"].includes(te)){let Qe=!1;return oe.some(me=>{let ve=me.replace(/^['"]|['"]$/g,"");if(ve===">"||ve===">>"||ve==="<")return Qe=!0,!1;if(ve.startsWith(">")||ve.startsWith("<")){let st=ve.replace(/^[><]+/,"");return je(st)}return Qe?(Qe=!1,je(me)):!1})}return oe.some(Qe=>je(Qe))})){let X='Access Denied. Prohibited from accessing external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"},await new Promise(oe=>setTimeout(oe,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${X}`),await new Promise(oe=>setTimeout(oe,50)),t.onExecEnd&&t.onExecEnd(),J.push({role:"user",text:`[TOOL RESULT]: ERROR: ${X}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${X}`},We++;continue}}t.onExecStart&&t.onExecStart(I||"No Command"),yield{type:"exec_start"}}let Sn=L(Y.args),rs=Sn.path||Sn.targetPath||null;if(rs){let I=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,H=K.resolve(rs),ee=K.resolve(process.cwd());if(I&&!H.startsWith(ee)){let le="Access Denied. You are not allowed to access files outside the current workspace.";if(M==="write_file"||M==="update_file"){let je=`\u2718 ${M==="write_file"?"Write Canceled":"Edit Canceled"}: ${Sn.path||"..."}`,ke=115;process.stdout.isTTY&&(ke=process.stdout.columns-5||120);let we=Math.min(je.length+4,ke),X=`${je.padEnd(we-2).substring(0,we-2)}`;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
649
|
+
`:""}${X}
|
|
650
|
+
`)},Pe=!1}J.push({role:"user",text:`[TOOL RESULT]: ERROR: ${le}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${le}`},We++;continue}}if(t.onToolApproval&&(M==="write_file"||M==="update_file"||M==="exec_command")){let H=t.systemSettings||{},ee=H.autoExec,le=null,pe=!1,je=!1,ke=!1;if(M==="exec_command"){let{command:ve}=L(Y.args),st=(ve||"").trim(),Re=(Tt,Yt)=>{if(!Yt)return!1;let ln=Yt.split(",").map(zt=>zt.trim().toLowerCase()).filter(Boolean),ot=Tt.toLowerCase();return ln.some(zt=>ot.startsWith(zt))},qe=Re(st,H.alwaysAskCommands),Se=Re(st,H.autoApproveCommands);if(je=Re(st,H.autoDisallowCommands),qe?pe=!0:(Se||H.autoApproveGit&&/^git\s+commit\b/i.test(st))&&(le="allow"),!pe&&!le){if(H.networkAccess===!1){let Yt=st.trim().replace(/\s+/g," ").replace(/^['"]+|['"]+$/g,"").toLowerCase().split(" "),ot=Yt[0].split("/").pop().split("\\").pop().replace(/\.exe$/,""),zt=new Set(["curl","wget","httpie","xh","ssh","scp","sftp","rsync","ftp","lftp","tftp","telnet","nc","netcat","socat","ping","traceroute","tracert","dig","nslookup","host","whois","nmap","docker","podman","kubectl","helm","gcloud","aws","az","terraform","ansible-playbook","nix","nix-env","apt","apt-get","dpkg","yum","dnf","pacman","zypper","brew","apk","choco","scoop","conda","mamba","aria2c","axel","smbclient","lynx","w3m","links","elinks","heroku","netlify","vercel","firebase","supabase","wrangler","flyctl","powershell","pwsh","certutil","bitsadmin","cloudflared","ngrok","tailscale","zerotier","rclone"]),it=!1;zt.has(ot)&&(it=!0);let ct=Tn=>Yt.slice(1).some(bn=>Tn.includes(bn)),Rt=Tn=>{let bn=Yt.findIndex($n=>Tn.includes($n)),Rs=Yt.findIndex($n=>["run","exec","test"].includes($n));return bn!==-1&&!(Rs!==-1&&Rs<bn)};ot==="git"&&ct(["clone","pull","push","fetch"])&&(it=!0),ot==="go"&&ct(["get","install"])&&(it=!0),ot==="npm"&&Rt(["install","i","update","add"])&&(it=!0),ot==="yarn"&&Rt(["add","install","upgrade"])&&(it=!0),ot==="pnpm"&&Rt(["add","install","update"])&&(it=!0),ot==="bun"&&Rt(["add","install","update"])&&(it=!0),ot==="deno"&&ct(["install","add"])&&(it=!0),ot==="pip"&&ct(["install","download"])&&(it=!0),ot==="pip3"&&ct(["install","download"])&&(it=!0),ot==="cargo"&&ct(["install","add"])&&(it=!0),["bash","sh","zsh","fish"].includes(ot)&&ct(["-c"])&&(it=!0),ot==="cmd"&&ct(["/c"])&&(it=!0),it&&(le="deny",ke=!0)}!le&&je&&(le="deny")}!pe&&!le&&ee&&(le="allow")}else ee&&(le="allow");let we=le,X="";le==="deny"&&(ke?X="network":je?X="settings":X="prohibited");let oe=!1,te="",Le=[],Qe=0,me=!1;if(!we){if(M==="write_file"||M==="update_file")try{let Re=L(Y.args),{path:qe}=Re;if(qe){let Se=K.resolve(process.cwd(),qe),Tt=ct=>ct?ct.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,Rt=>Rt.toUpperCase()):"",Yt=Tt(Se),ln="",ot=!1,zt=await ws(),it=Tt(zt?.file_focused);if(zt&&it===Yt&&zt.full_content?(ln=zt.full_content,ot=!0):Oe.existsSync(Se)&&(ln=Oe.readFileSync(Se,"utf8"),ot=!0),te=ln,await dt.recordFileChange(Se,ln),ot){let ct=ln;if(M==="write_file")ct=Re.content||Re.newContent||"";else{let{patchPairs:Rt,allowMultiple:Tn,error:bn}=Oo(Re);if(bn){let bt=`[TOOL RESULT]: ERROR: ${bn}`;J.push({role:"user",text:bt}),await Ut("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:bt,toolName:M},We++;continue}let Rs=Re.allowMultiple!==void 0?Re.allowMultiple===!0||String(Re.allowMultiple).toLowerCase()==="true":Tn;Qe=Rt.length;let $n=$o(ln,Rt,{allowMultiple:Rs});ct=$n.content,Le=$n.results;let po=Le.filter(bt=>bt.success),kt=Le.filter(bt=>!bt.success);if(po.length===0){let bt=`[TOOL RESULT]: ERROR: Failed to apply patches to [${K.basename(Se)}].
|
|
651
|
+
${kt.map(Gs=>` \u2022 ${Gs.error}`).join(`
|
|
652
|
+
`)}`,ks=`\u2714 Edited: ${K.basename(Se.replaceAll("\\","/"))}`,Hs=115;process.stdout.isTTY&&(Hs=process.stdout.columns-5||120);let As=Math.min(ks.length+4,Hs),mo=`${ks.padEnd(As-2).substring(0,As-2)}`;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
653
|
+
`:""}${mo}`)},Pe=!1,J.push({role:"user",text:bt}),await Ut("toolFailure"),t.onToolResult&&t.onToolResult("failure",M),yield{type:"tool_result",content:bt,toolName:M},We++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${K.basename(Se)}`},Zi(Se,ln,ct),oe=!0,await new Promise(Rt=>setTimeout(Rt,50))}else if(M==="write_file"){let ct=Re.content||Re.newContent||"",Rt=ct.endsWith(`
|
|
654
|
+
`)?ct:ct+`
|
|
655
|
+
`;Oe.existsSync(Se)||(me=!0,Oe.mkdirSync(K.dirname(Se),{recursive:!0}),Oe.writeFileSync(Se,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${K.basename(Se)}`},Zi(Se,"",Rt),oe=!0,await new Promise(Tn=>setTimeout(Tn,50))}}}catch(Re){console.error("Simulation/Diff Error:",Re)}let ve=null;Qi(Re=>{ve=Re});let st=t.onToolApproval;if(we=await new Promise(async Re=>{let qe=setInterval(()=>{ve&&(Po.onIDEApproval&&Po.onIDEApproval(ve),clearInterval(qe),Re(ve))},100);try{let Se=await st(M,Y.args);clearInterval(qe),Re(Se)}catch{clearInterval(qe),Re("deny")}}),Qi(null),M==="write_file"||M==="update_file"){let{path:Re}=L(Y.args);if(Re){let qe=K.resolve(process.cwd(),Re);if(Fa(qe,we),we==="deny"&&me&&Oe.existsSync(qe))try{Oe.unlinkSync(qe)}catch{}}}we==="deny"&&(X="user")}if(we==="allow"&&oe&&No()){let{path:ve}=L(Y.args),st=K.resolve(process.cwd(),ve),Re=kt=>kt?K.resolve(kt).replace(/\\/g,"/").toLowerCase():"",qe=await ws(),Se="";qe&&qe.file_focused&&Re(qe.file_focused)===Re(st)&&qe.full_content&&(Se=qe.full_content),!Se&&Oe.existsSync(st)&&(Se=Oe.readFileSync(st,"utf8"),Se||(await new Promise(kt=>setTimeout(kt,100)),Se=Oe.readFileSync(st,"utf8")));let Tt=Se.split(/\r?\n/),Yt=Tt.length,ln=Buffer.byteLength(Se,"utf8"),ot="";te&&(ot=`Old File contents:
|
|
656
|
+
${te.split(/\r?\n/).map((bt,ks)=>`${ks+1} | ${bt}`).join(`
|
|
657
|
+
`)}
|
|
658
|
+
|
|
659
|
+
`);let zt="";if(Yt<=100)zt=Tt.join(`
|
|
660
|
+
`);else{let kt=Tt.slice(0,50).join(`
|
|
661
|
+
`),bt=Tt.slice(-50).join(`
|
|
662
|
+
`);zt=`${kt}
|
|
663
|
+
|
|
664
|
+
... [${Yt-100} lines truncated for history stability] ...
|
|
665
|
+
|
|
666
|
+
${bt}`}let it="";if(M==="update_file"){let kt=Mo(te,Se,Le,12,t?.compressToolResults||Po?.systemSettings?.compressToolResults);it=`SUCCESS: File [${ve}] updated via IDE Companion (May have user edits). [${Le.length}/${Qe}] blocks applied.
|
|
667
|
+
|
|
668
|
+
${kt}`}else{let kt=Se.split(/\r?\n/),bt=kt.length,ks=Buffer.byteLength(Se,"utf8"),Hs="";te&&(Hs=`Old File contents:
|
|
669
|
+
${te.split(/\r?\n/).map((Gs,hl)=>`${hl+1} | ${Gs}`).join(`
|
|
670
|
+
`)}
|
|
671
|
+
|
|
672
|
+
`);let As="";if(bt<=100)As=kt.join(`
|
|
673
|
+
`);else{let mo=kt.slice(0,50).join(`
|
|
674
|
+
`),Gs=kt.slice(-50).join(`
|
|
675
|
+
`);As=`${mo}
|
|
676
|
+
|
|
677
|
+
... [${bt-100} lines truncated] ...
|
|
678
|
+
|
|
679
|
+
${Gs}`}it=`SUCCESS: File [${ve}] saved via IDE Companion (May have user edits).
|
|
680
|
+
- Stats: [${bt} lines, ${(ks/1024).toFixed(1)} KB]
|
|
681
|
+
${Hs}- Content Preview:
|
|
682
|
+
|
|
683
|
+
${As}`}let Rt=`${ve?"\u2714":"\u2718"} ${M==="write_file"?"Created":"Edited"}: ${ve.replaceAll("\\","/")||"No File Changes"}`,Tn=115;process.stdout.isTTY&&(Tn=process.stdout.columns-5||120);let bn=Math.min(Rt.length+4,Tn),Rs=`${Rt.padEnd(bn-2).substring(0,bn-2)}`;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
684
|
+
`:""}${Rs}`)},Pe=!1;let $n=Date.now();j=$n,yield{type:"tool_time",content:$n-ae};let po=`[TOOL RESULT]: ${it}`;J.push({role:"user",text:po}),on=!0,await Ut("toolSuccess"),t.onToolResult&&t.onToolResult("success",M),yield{type:"tool_result",content:it,aiContent:po,toolName:M},We++;continue}if(we==="deny"){let ve=`Permission Denied: Prohibited ${M==="exec_command"?"Command":"file edit"}.`;if(X==="user"?ve="Permission Denied by User":X==="settings"?ve="Permission Denied by User Policy":X==="network"?ve="Permission Denied: Sandbox Network Access Disabled by User Policy.":X==="prohibited"&&M==="exec_command"&&(ve="Permission Denied: Prohibited Command in User Policy"),M==="write_file"||M==="update_file"){let Re=`\u2718 ${M==="write_file"?"Write Cancelled":"Edit Denied"}: ${L(Y.args).path.replaceAll("\\","/")||"..."}`,qe=115;process.stdout.isTTY&&(qe=process.stdout.columns-5||120);let Se=Math.min(Re.length+4,qe),Tt=`${Re.padEnd(Se-2).substring(0,Se-2)}`,Yt=` ${" ".repeat(Se)} `;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
685
|
+
`:""}${Tt}
|
|
686
|
+
`)},Pe=!1}M==="exec_command"&&(await new Promise(st=>setTimeout(st,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${ve}`),await new Promise(st=>setTimeout(st,50)),t.onExecEnd&&t.onExecEnd()),J.push({role:"user",text:`[TOOL RESULT]: DENIED: ${ve}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${ve}`},await Ut("toolDenied"),t.onToolResult&&t.onToolResult("denied",M),We++;continue}}if(ue){let I=115;process.stdout.isTTY&&(I=process.stdout.columns-5||120);let H=Math.min(ue.length+4,I),ee=`${ue.padEnd(H-2).substring(0,H-2)}`;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
687
|
+
`:""}${ee}${ue.includes("\u2714")&&(ue.includes("Created")||ue.includes("Edited"))?"":`
|
|
688
|
+
`}`)},Pe=!1}if(j>0){let I=Date.now()-j,H=Math.max(0,1e3-I);H>0&&await new Promise(ee=>setTimeout(ee,H))}let Un={chatId:c,history:e,onChunk:I=>t.onExecChunk?t.onExecChunk(I):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:a,isMultiModal:dn(Ce),onVisualFeedback:t.onVisualFeedback,onSubagentUpdate:t.onSubagentUpdate,onTokenChunk:t.onTokenChunk,modelName:Ce,aiProvider:t.aiProvider,apiKey:t.apiKey,onUsage:t.onUsage};if(M==="write_file"||M==="update_file")try{let{path:I}=L(Y.args);if(I){let H=K.resolve(process.cwd(),I),ee=await ws();ee&&ee.file_focused===H&&ee.full_content&&(Un.forcedContent=ee.full_content)}}catch{}Jt.push(M);let be=await ao(M,Y.args,Un);if((M==="write_file"||M==="update_file")&&be.startsWith("SUCCESS")){let{path:I}=L(Y.args);if(I){let H=K.resolve(process.cwd(),I);Da(H)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let Dt=Date.now();j=Dt,yield{type:"tool_time",content:Dt-ae},Qt=Dt;let Gt=null;if(typeof be=="object"&&be.binaryPart&&(Gt=be.binaryPart,be=be.text),M==="search_keyword"){let{keyword:I,path:H}=L(Y.args),ee=typeof be=="string"&&be.startsWith("[GLOB]");ee&&(be=be.slice(6).trimStart());let le=typeof be=="string"&&be.startsWith("[DIR]");le&&(be=be.slice(5).trimStart());let pe=0;if(be){let Le=be.match(/Found (\d+) match/i);Le&&(pe=parseInt(Le[1]))}let je=H?H.replace(/[\/\\]+$/,""):null,ke=je&&je!=="."?`"${ee?H:le?`${je}/*`:je}"`:"./",we=`${I?"\u2714":"\u2718"} Searched: "${I||""}" in ${ke.replaceAll("\\","/")} \u2192 ${pe} Match${pe===1?"":"es"}`,X=115;process.stdout.isTTY&&(X=process.stdout.columns-5||120);let oe=Math.min(we.length+4,X),te=`${we.padEnd(oe-2).substring(0,oe-2)}`;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
689
|
+
`:""}${te}
|
|
690
|
+
`)},Pe=!1}if(M==="EmergencyRollback"){let{method:I}=L(Y.args);if(I==="forceRevert"){let H=0;if(be){let we=be.match(/Total\s*:\s*(\d+)/i);we&&(H=parseInt(we[1]))}let le=be&&be.startsWith("ERROR:")?"\u2718 Emergency Rollback Failed":`\u2714 Emergency Rollback \u2192 ${H} file${H===1?"":"s"} processed`,pe=115;process.stdout.isTTY&&(pe=process.stdout.columns-5||120);let je=Math.min(le.length+4,pe),ke=`${le.padEnd(je-2).substring(0,je-2)}`;yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
691
|
+
`:""}${ke}
|
|
692
|
+
`)},Pe=!1}}if(M==="todo"){let{method:I,tasks:H,markDone:ee}=L(Y.args),le="",pe=[],je=ke=>{if(!ke)return[];let we=Array.isArray(ke)?ke:[];if(we.length===0&&typeof ke=="string"){let X=ke.trim();if(X.startsWith("[")&&X.endsWith("]")){let oe=X.match(/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g);oe?we=oe.map(te=>te.slice(1,-1).replace(/\\(.)/g,"$1")):we=X.slice(1,-1).split(",").map(te=>te.trim()).filter(Boolean)}else we=ke.split(`
|
|
693
|
+
`)}return we.filter(X=>String(X).trim()).map(X=>{let oe=String(X).trim();return oe.startsWith("- [")?oe.substring(6).trim():oe})};if(I==="create"?(le="\x1B[32m\u2192\x1B[0m Created Plan",pe=je(H).map(ke=>`\x1B[90m\u25CB\x1B[0m ${ke}`)):I==="append"?(le="\x1B[34m\u2795\x1B[0m Added Plan",pe=je(H).map(ke=>`\x1B[90m\u25CB\x1B[0m ${ke}`)):I==="get"&&(le=ee?"\x1B[36m\u21BB\x1B[0m Updated Plan":"\x1B[35m\u2022\x1B[0m Reviewed Plan",pe=(be||"").split(`
|
|
694
|
+
`).slice(1).join(`
|
|
695
|
+
`).split(`
|
|
696
|
+
`).filter(we=>we.trim().startsWith("- [")).map(we=>{let X=we.trim(),oe=X.startsWith("- [x]");return`${oe?"\x1B[32m\u2714\x1B[0m":"\x1B[90m\u25CB\x1B[0m"} ${oe?"\x1B[90m":"\x1B[37m"}${X.substring(6).trim()}\x1B[0m`})),le&&pe.length>0){let ke=[`${le}`,...pe.map(we=>` ${we}`)].join(`
|
|
697
|
+
`);yield{type:"visual_feedback",content:mn(`${Pe?`
|
|
698
|
+
`:""}${ke}
|
|
699
|
+
`)},Pe=!1}}M==="exec_command"&&t.onExecEnd&&(await new Promise(I=>setTimeout(I,800)),t.onExecEnd());let Cn=be&&be.startsWith("DENIED:");be&&!be.startsWith("ERROR:")&&!Cn?(await Ut("toolSuccess"),t.onToolResult&&t.onToolResult("success",M)):Cn||(await Ut("toolFailure"),t.onToolResult&&t.onToolResult("failure",M));let Ft=(be||"").toString().replaceAll("[UI_CONTEXT]","");Ft.includes("[[VERIFIED]]")&&(Ft=Ft.replace(/\[\[VERIFIED\]\][\s\S]*?\[\[\/VERIFIED\]\]/g,`[SYSTEM NOTE]: Patch Block matched & applied successfully. Large Block omitted to conserve context.
|
|
700
|
+
`));let On;if(Ft.startsWith("[[SAME]]")){let H=Ft.replace(/^\[\[SAME\]\]\s*\r?\n?/,"").split(/\r?\n/),ee=H.filter(pe=>pe.startsWith("SUCCESS:")||pe.trim().startsWith("- Stats:"));On=`[TOOL RESULT]: ${ee.length>0?ee.join(`
|
|
701
|
+
`):H.slice(0,2).join(`
|
|
702
|
+
`)}
|
|
703
|
+
[SYSTEM NOTE]: Content verified and persisted to disk. Full preview omitted to conserve context.`}else On=`[TOOL RESULT]: ${Ft}`;J.push({role:"user",text:On,binaryPart:Gt}),on=!0;let xe=`[TOOL RESULT]: ${be.replaceAll(`[[VERIFIED]]
|
|
704
|
+
`,"").replaceAll(`
|
|
705
|
+
[[/VERIFIED]]`,"")||""}`;(M==="view_file"||M==="web_scrape"||M==="file_map")&&(xe=`[TOOL RESULT]: ${ue} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:xe,aiContent:On,binaryPart:Gt,toolName:M},M==="memory"&&be.includes("SUCCESS")&&(yield{type:"memory_updated"}),We++}if(h==="Google"&&wn&&Date.now()-Go>=150){yield*os();let Y=Ws(wn);for(let ae of Y)yield ae;wn="",Go=Date.now()}}N.usageMetadata&&(xn=N.usageMetadata),xn&&(yield{type:"liveTokens",content:xn.totalTokenCount})}if(Te&&(Te=!1,Pt?Ge+="</think>":(se+="</think>",h==="Google"?wn+="</think>":yield{type:"text",content:"</think>"})),Pt&&Ge.length>0){let N=0,Q=Math.min(tt.length,Ge.length);for(let W=Q;W>0;W--)if(tt.endsWith(Ge.substring(0,W))){N=W;break}let U=Ge.substring(N);if(U){let Ee=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?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(Ee)if(se+=Ee,h==="Google")wn+=Ee;else{yield*os();let de=Ws(Ee);for(let De of de)yield De}}Pt=!1,Ge=""}if(yield*os(),Ct)break;let js=(se||"").trim(),al=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(js.toLowerCase())||/\[\[END\]\]/i.test(js.toLowerCase()),ll=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(js.toLowerCase()),cl=J.length>0||Lt!==null,Yo=js.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),fl=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Yo),dl=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Yo.trim()),ul=/[.!?}"'`’“”]$|```$/s.test(Yo)||dl||fl;!al&&!ll&&!cl&&js.length>0,Je=!0,await Ut("agent",h)}catch(Ye){if(Ct){yield{type:"status",content:"Request Cancelled"},yield{type:"text",content:`
|
|
706
|
+
|
|
707
|
+
\x1B[33m\u24D8 Request Cancelled\x1B[0m`};break}if(String(Ye).includes("Incomplete JSON segment at the end")){Te&&(Te=!1,Pt?Ge+="</think>":(se+="</think>",yield{type:"text",content:"</think>"})),Je=!0,await Ut("agent",h);break}if(Te&&(Te=!1,Pt?Ge+="</think>":se+="</think>"),Pt&&Ge.length>0){let ss=0,en=Math.min(tt.length,Ge.length);for(let $t=en;$t>0;$t--)if(tt.endsWith(Ge.substring(0,$t))){ss=$t;break}let Ot=Ge.substring(ss);if(Ot){let an=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(tt)?Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):Ot.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");an&&(se+=an)}Pt=!1,Ge=""}let ie=Ye instanceof Error?(()=>{try{return JSON.parse(JSON.parse(Ye.message).error.message).error.message}catch{return String(Ye)}})():String(Ye),rn=new Date().toLocaleString(),Zt=K.join(cn,"agent");Oe.existsSync(Zt)||Oe.mkdirSync(Zt,{recursive:!0}),Oe.appendFileSync(K.join(Zt,"error.log"),`ERROR [${rn}]: ${ie}
|
|
708
|
+
|
|
709
|
+
----------------------------------------------------------------------
|
|
710
|
+
|
|
711
|
+
`);let An=Ye.status||Ye.statusCode||Ye.code;if(!(An&&(An>=500&&An<600||An===408||An===429)||!An&&(/status[ :]+(5\d\d|408|429)/i.test(String(Ye))||/code[ :]+(5\d\d|408|429)/i.test(String(Ye))||/(500|503|408|429)/.test(String(Ye))))){if(Be<gn-3)throw Ye;yield{type:"text",content:ie},yield{type:"status",content:"Error Occured"}}if(se.trim().length>0||Ke>1)if(Ke<=gn){Ke++;let ss=Math.min(1e3*Math.pow(2,Ke-1),24e3);if(se.trim().length>0){b.push({role:"agent",text:se});let en=`[SYSTEM]
|
|
712
|
+
- SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
|
|
713
|
+
- NO REPETITION: Do not repeat any text already written
|
|
714
|
+
- NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block </think> BEFORE CHAT OUTPUT
|
|
715
|
+
- MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
|
|
716
|
+
- STEALTH: Do not mention/apologize for cutoff [/SYSTEM]`;J.length>0?J.forEach((Ot,$t)=>{$t===J.length-1?b.push({...Ot,text:`${Ot.text}
|
|
717
|
+
|
|
718
|
+
${en}`}):b.push(Ot)}):b.push({role:"user",text:en}),tt+=se}for(let en=ss/1e3;en>0&&!Ct;en--)yield{type:"status",content:`Error Occured. Recovering Stream (${Ke}/${gn}) [Retrying in ${en.toFixed(0)}s]...`},await new Promise(Ot=>setTimeout(Ot,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${gn} times)
|
|
719
|
+
Error log can be found in \`/export logs\``);else if(Be<=gn){Be++,Ke=1,tt="";let ss=Math.min(1e3*Math.pow(2,Be-1),32e3),en=.8+Math.random()*.4,Ot=Math.round(ss*en);Zn=!0,yield{type:"status",content:`Trying to reach ${n} (${Be}/${gn}) [Retrying in ${(Ot/1e3).toFixed(0)}s]`};for(let $t=Ot/1e3;$t>0&&!Ct;$t--)yield{type:"status",content:`Trying to reach ${n} (${Be}/${gn}) [Retrying in ${$t.toFixed(0)}s]`},await new Promise(an=>setTimeout(an,1e3));yield{type:"status",content:`Trying to reach ${n}`}}else throw new Error(`Model ${n} cannot be reached. (Failed ${gn} times)
|
|
720
|
+
Error log can be found in \`/export logs\``)}}if(xn){let Te=xn.totalTokenCount||0,Ye=xn.cachedContentTokenCount||0,ie=(xn.candidatesTokenCount||0)+(xn.thoughtsTokenCount||0);await Bt("tokens",Te,h,Ce),Ye>0&&await Bt("cachedTokens",Ye,h,Ce),ie>0&&await Bt("candidateTokens",ie,h,Ce),yield{type:"usage",content:xn}}wr.push(se);let Dn=se;se.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Dn=se.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let ts=Va(se),kn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(ts.toLowerCase())||/\[\[END\]\]/i.test(ts.toLowerCase())||!0,id=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(ts.toLowerCase()),rd=We>0;yield{type:"status",content:"Thinking"};let ol=Qf(se,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),ns=(kn||J.length===0)&&!Nt&&!yn&&!Rn;if(ns=J.length===0?ns:!1,ns=es||uo?!1:ns,se&&se.trim().endsWith('")]')&&J.length===0&&(ns=!1),ns){let Te=wr.join(`
|
|
721
|
+
`),Ye=Te.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:k,fullAgentTextRaw:Te,history:[...b],needTitle:R}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=Ye:b.push({role:"agent",text:Ye}),b.forEach(ie=>{if(ie.role==="user"&&ie.text&&(ie.text=ie.text.replace(/\n\[COMPILE ERROR\][\s\S]*?\[\/ERROR\]/g,""),ie.text=ie.text.replaceAll(`
|
|
722
|
+
|
|
723
|
+
[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY [/SYSTEM]
|
|
724
|
+
`,"").replaceAll(`[SYSTEM] USER QUESTION. RESOLVE THIS SPECIFIC QUERY WITHIN '[ANSWER] ... [/ANSWER]' CONCISELY, NATURALLY
|
|
725
|
+
**STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
|
|
726
|
+
`,"").replaceAll(`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS HIGH PRIORITY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]
|
|
727
|
+
`,"").replaceAll(/\n\[SYSTEM\] WARNING, Turn Limit Impending: Step \d+\/\d+\. Wrap up quickly\/prompt user to continue & use \[\[END\]\] quickly\. \[\/SYSTEM\]/g,""),ie.text=ie.text.replaceAll(/\n\[SYSTEM\] File Changes:\n(?:\* .+ \(created|modified|deleted\)\n)*\[\/SYSTEM\]/g,""),(h==="Mistral"||h==="Google"&&n?.toLowerCase().startsWith("gemma"))&&ie.text.startsWith("[TOOL RESULT]"))){let Zt=`
|
|
728
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn [/SYSTEM]`,An=`
|
|
729
|
+
[SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think>...</think>** [/SYSTEM]`;ie.text=ie.text.replaceAll(An,"").replaceAll(Zt,"").trim()}}),yield{type:"status",content:"[end]"}}if(ns)break;let il=ol.trim()||"*Working...*";if(b.push({role:"agent",text:il}),J.length>0||on){if(J.length>0){let Te=J.map(Zt=>Zt.text).join(`
|
|
730
|
+
|
|
731
|
+
`),ie=(se.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,"").match(/\[tool:functions/g)||[]).length;J.length<ie&&(Te+=`
|
|
732
|
+
|
|
733
|
+
[SYSTEM] Only ${J.length} out of ${ie} attempted tool calls were executed. Verify proper schema compliance & try failed calls again [/SYSTEM]`);let rn=J.find(Zt=>Zt.binaryPart)?.binaryPart||null;b.push({role:"user",text:Te,binaryPart:rn})}}else uo||es?b.push({role:"user",text:"[SYSTEM] Failed to execute some tools. Verify proper schema compliance & try again [/SYSTEM]"}):b.push({role:"user",text:`[SYSTEM] ${yn&&!Nt?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${Nt?" OVER THINKING":" LOOP"} DETECTED by Internal System${Nt?" for current EFFORT_LEVEL":""}. ${Nt?"If you have planned the task, prioritize execution/output":"If you have finished your task provide a simple summary and end"}`} [/SYSTEM]`}),Nt=!1,yn=!1,Rn=!1;l?.advanceRollback&&await Vn.recordTurnDelta(c,B+1,Jt),uo=We>0||on}}catch(T){let v=(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(),$=K.join(cn,"agent");yield{type:"text",content:`\u2726 CRITICAL ERROR: ${v.includes("fetch failed")?"Failed to Connect. Check your Internet Connection or Wait a moment":v}
|
|
734
|
+
\u2800`},Oe.existsSync($)||Oe.mkdirSync($,{recursive:!0}),Oe.appendFileSync(K.join($,"error.log"),`CRITICAL ERROR [${_}]: ${T}
|
|
735
|
+
|
|
736
|
+
----------------------------------------------------------------------
|
|
737
|
+
|
|
738
|
+
`),typeof flushGoogleBuffer=="function"&&(yield*flushGoogleBuffer()),yield{type:"tool_result",content:`ERROR: [INTERNAL CRITICAL] ${v}`}}finally{w&&(clearInterval(w),w=null),typeof performance<"u"&&performance.clearMeasures&&(performance.clearMeasures(),performance.clearMarks()),await dt.commitTransaction(),l?.advanceRollback&&await Vn.cleanup(c),await ws()}yield{type:"status",content:null}},Ug=async(n,e,t=null,o=null,s=50,i=null,r=!1)=>{let a=await Kt(),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(":","-")}`,m=(T=>{if(!T)return null;let b=T.toLowerCase();return b==="google"?"Google":b==="deepseek"?"DeepSeek":b==="openrouter"?"OpenRouter":b==="nvidia"?"NVIDIA":b==="mistral"?"Mistral":b==="ollama"?"Ollama":null})(f),p=d?.systemSettings?.CustomSubAgent?d?.systemSettings?.SubAgentModel:null,y=d?.systemSettings?.CustomSubAgent?d?.systemSettings?.SubAgentProvider:null,g=null;if(p==="ENV"?(g=c,c&&m&&(d.aiProvider=m)):p&&p!=="Default"?(g=p,y&&(d.aiProvider=y)):c&&m&&(d.aiProvider=m),d.aiProvider){let T=await Ko(d.aiProvider);T&&(d.apiKey=T)}let S=T=>{if(!T||typeof T!="string")return{allowed:!0};let b=[/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 v of b)if(v.test(T))return{allowed:!1,reason:`Blocked potentially destructive or unsafe command pattern: "${v.source}"`};return{allowed:!0}},E=t||g||e?.modelName||e?.activeModel||a.activeModel,x=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",C=`-- TOOL DEFINITIONS (path = relative to CWD, path separator: '/') --
|
|
739
|
+
TO USE TOOLS, MUST OUTPUT EXACTLY '[tool:functions.ToolName(arg1="value1")]' SYNTAX STRING IN CHAT \u2190 MANDATORY
|
|
740
|
+
TOOL RULES:
|
|
741
|
+
- JSON ESCAPE ALL LITERAL ESCAPE SEQUENCES IN TOOL ARGUMENTS
|
|
742
|
+
- SAME file, MULTIPLE edits? ONE PatchFile (\u226415 blocks) \u2190 PRIORITY
|
|
743
|
+
- Need text or huge files? CodeSearch > Full Read
|
|
744
|
+
- MUST AVOID UNNECESSARY LARGE-FILE CHUNK READS
|
|
745
|
+
- Restricted Shell Access, No Deletion
|
|
746
|
+
- DONT HALLUCINATE TOOL RESULTS, VERIFY, FIX ERRORS
|
|
747
|
+
- ONLY valid tools and syntax defined below are allowed
|
|
748
|
+
|
|
749
|
+
**PROVIDED TOOLS**
|
|
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 default: false", regex="bool default: auto")]. Find definitions, logic, relevant code, standard junk auto-excluded
|
|
760
|
+
- [tool:functions.ReadFolder(path="...", recurse="integer 1-3")]. DIR Contents + File Size. 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(),A=`=== START SYSTEM PROMPT ===
|
|
765
|
+
You are a subagent helping the main FluxFlow CLI agent
|
|
766
|
+
Your task is: "${n}"
|
|
767
|
+
|
|
768
|
+
${C.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}`}],k=0,w="";for(;k<s;){if(Ct){if(e?.taskId&&typeof Ve<"u"){let P=Ve.find(F=>F.id===e.taskId);P&&(P.status="cancelled")}throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}if(e?.taskId&&typeof Ve<"u"){let P=Ve.find(F=>F.id===e.taskId);if(P&&P.status==="cancelled")throw i&&i("[SUBAGENT CANCELLED] Subagent task was cancelled."),new Error("Subagent task was cancelled.")}let T=R.map(P=>({role:P.role==="user"?"user":"model",parts:[{text:P.text}]}));i&&i(`[Subagent Turn ${k+1}]...`);let _=((await Do(d,E,T,A,"Fast")).text||"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim();w=_,i&&i(`[Subagent Response]
|
|
778
|
+
${_}
|
|
779
|
+
`),R.push({role:"agent",text:_});let $=Uo(_);if($.length===0)break;let G=$.filter(P=>P.toolName.toLowerCase()==="askmain"||P.toolName.toLowerCase()==="ask_main"),ce=!1,ge="";for(let P of $){if(Ct){if(e?.taskId&&typeof Ve<"u"){let O=Ve.find(D=>D.id===e.taskId);O&&(O.status="cancelled")}throw new Error("Subagent task was cancelled.")}if(e?.taskId&&typeof Ve<"u"){let O=Ve.find(D=>D.id===e.taskId);if(O&&O.status==="cancelled")throw new Error("Subagent task was cancelled.")}let F=P.toolName.toLowerCase();if(F==="askmain"||F==="ask_main"){if(ce)continue;ce=!0;let O="";if(G.length===1?O=L(G[0].args).question||G[0].args:O=G.map((D,ne)=>{let q=L(D.args);return`Q${ne+1}: ${q.question||D.args}`}).join(`
|
|
780
|
+
`),e.onAskMain){i&&i(`[Executing Tool] AskMain("${O}")...`);let D=await e.onAskMain(O);i&&i(`[Tool Result]
|
|
781
|
+
Answer from Main Agent: ${D}
|
|
782
|
+
`),ge+=`[TOOL RESULT for AskMain]: Answer from Main Agent: ${D}
|
|
783
|
+
|
|
784
|
+
`,await Ut("toolSuccess")}else ge+=`[TOOL RESULT for AskMain]: ERROR: Main agent communication channel not available.
|
|
785
|
+
|
|
786
|
+
`;continue}if(!(o?o.some(O=>O.toLowerCase()===F):!0)){let O=`ERROR: Tool [${P.toolName}] is not in the allowed tools list for this subagent.`;i&&i(`[Blocked Tool Call] ${P.toolName} - not allowed
|
|
787
|
+
`),ge+=`${O}
|
|
788
|
+
|
|
789
|
+
`;continue}if(F==="exec_command"||F==="execcommand"||F==="run"){let O=L(P.args).command||"",D=S(O);if(!D.allowed){let ne=`ERROR: [SECURITY RESTRICTION] Subagent execution blocked command: ${D.reason}`;i&&i(`[Blocked Command] ${O} - ${D.reason}
|
|
790
|
+
`),ge+=`${ne}
|
|
791
|
+
|
|
792
|
+
`;continue}}let ye="";if(F==="web_search"||F==="websearch")ye=`\u2714 \x1B[95mSearched\x1B[0m: ${L(P.args).query||""}`;else if(F==="web_scrape"||F==="webscrape")ye=`\u2714 \x1B[95mScraped\x1B[0m: ${L(P.args).url||""}`;else if(F==="search_keyword"||F==="searchkeyword"||F==="codesearch"||F==="code_search"){let O=L(P.args),D=O.keyword||"",ne=O.path||"";ye=`${D?"\u2714":"\u2718"} \x1B[95mSearched\x1B[0m: ${D||"No Query"}${ne?` \u2192 ${ne.replaceAll("\\","/")}`:""}`}else if(F==="view_file"||F==="viewfile"||F==="readfile")ye=`\u2714 \x1B[95mRead\x1B[0m: ${(L(P.args).path||"").replaceAll("\\","/")}`;else if(F==="list_files"||F==="read_folder"||F==="readfolder"){let O=L(P.args).path||null,D=L(P.args).recurse||0;ye=`${O?"\u2714":"\u2718"} \x1B[95mBrowsed\x1B[0m: ${O?`${O.replaceAll("\\","/")}${D>0?`${O.endsWith("/")?`*${D}`:`/*${D}`}`:`${O.endsWith("/")?"":"/"}`}`:""}`}else if(F==="write_file"||F==="writefile"){let O=L(P.args).path||null;ye=`${O?"\u2714":"\u2718"} \x1B[95mCreated\x1B[0m: ${O?`${O.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="update_file"||F==="updatefile"||F==="patchfile"||F==="patch_file"||F==="patchfile"||F==="updatefile"){let O=L(P.args).path||null,D=L(P.args).content||null;ye=`${O?"\u2714":"\u2718"} \x1B[95mEdited\x1B[0m: ${O?`${O.replaceAll("\\","/")}`:"No File Changes"}`}else if(F==="exec_command"||F==="execcommand"||F==="run"){let O=L(P.args).command||null;ye=`${O?"\u2714":"\u2718"} \x1B[95mExecuted\x1B[0m: ${O?O.slice(0,100)+(O.length>100?"...":""):"No Command"}`}else if(F==="file_map"||F==="filemap"){let O=L(P.args).path||"";ye=`${O?"\u2714":"\u2718"} \x1B[95mIndexed\x1B[0m: ${O?`${O.replaceAll("\\","/")}`:"File Not Found"}`}else if(F==="await"){let{time:O}=L(P.args),D=parseFloat(O)||0;D<10&&(D=10),D>180&&(D=180),ye=`\u2714 \x1B[95mAwaiting\x1B[0m \u2192 ${(q=>{if(q>=60){let Me=Math.floor(q/60),Ne=q%60;return`${Me}m${Ne>0?` ${Ne}s`:""}`}return`${q}s`})(D)}`}else{let O=sr[F]||P.toolName,D=bs(F,P.args);ye=`\u2714 \x1B[95m${O}\x1B[0m${D?`: ${D}`:""}`}e.onVisualFeedback&&ye&&e.onVisualFeedback(ye),i&&i(`[Executing Tool] ${P.toolName}(${P.args})...`);try{let O=await ao(P.toolName,P.args,{...e,mode:"Flux"});if(i&&i(`[Tool Result]
|
|
793
|
+
${O}
|
|
794
|
+
`),ge+=`[TOOL RESULT for ${P.toolName}]: ${O}
|
|
795
|
+
|
|
796
|
+
`,await Ut("toolSuccess"),F==="patchfile"||F==="update_file"||F==="updatefile"||F==="patch_file"){if(O){let D=O.split(`
|
|
797
|
+
`),ne=0,q=0,Me=!1;for(let Ne of D){if(Ne.includes("[DIFF_START]")){Me=!0;continue}if(Ne.includes("[DIFF_END]")){Me=!1;continue}Me&&(/^\+\d+/.test(Ne)?ne++:/^\-\d+/.test(Ne)&&q++)}(ne>0||q>0)&&(await Bt("linesAdded",ne),await Bt("linesRemoved",q))}}else if((F==="writefile"||F==="write_file")&&O){let D=O.match(/- Stats: \[(\d+) lines/),ne=D?parseInt(D[1]):0,q=0;if(O.includes("Old File contents:")){let Me=!1;for(let Ne of O.split(`
|
|
798
|
+
`)){if(Ne.includes("Old File contents:")){Me=!0;continue}Me&&(Ne.trim()===""?Me=!1:/^\d+ \|/.test(Ne)&&q++)}}(ne>0||q>0)&&(await Bt("linesAdded",ne),await Bt("linesRemoved",q))}}catch(O){let D=`ERROR: Execution failed for [${P.toolName}]: ${O.message}`;i&&i(`[Tool Error] ${D}
|
|
799
|
+
`),ge+=`${D}
|
|
800
|
+
|
|
801
|
+
`,await Ut("toolFailure")}}let z="";if(e?.taskId&&typeof Ve<"u"){let P=Ve.find(F=>F.id===e.taskId);if(P&&P.pendingSteerMessages&&P.pendingSteerMessages.length>0){let F=[...P.pendingSteerMessages];P.pendingSteerMessages=[];for(let he of F)z+=`
|
|
802
|
+
|
|
803
|
+
[STEERING INSTRUCTION FROM MAIN AGENT]: ${he}`,i&&i(`[Subagent Steered] ${he}`)}}let $e=(ge.trim()+z).trim();R.push({role:"user",text:$e}),k++}return w};export{hn as a,Xr as b,Ju as c,Qu as d,Vl as e,Jr as f,Zu as g,nc as h,eh as i,lo as j,La as k,Ym as l,zm as m,L as n,Ed as o,ri as p,qs as q,xd as r,Rd as s,dt as t,cs as u,Qd as v,vl as w,Zd as x,eu as y,tu as z,nu as A,su as B,fu as C,du as D,En as E,Dl as F,Xs as G,Bt as H,Fl as I,Wr as J,fs as K,bf as L,Sp as M,Tp as N,Km as O,No as P,Xm as Q,Vf as R,vg as S,Lg as T,cr as U,Ng as V,Pg as W,sd as X,Dg as Y,Fg as Z,Ug as _};
|