fluxflow-cli 4.50.0 → 5.0.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.
Files changed (58) hide show
  1. package/ARCHITECTURE.md +7 -16
  2. package/README.md +1 -4
  3. package/TOOLS.md +0 -9
  4. package/UI_FEATURES.md +1 -2
  5. package/dist/chunks/ai-WBRHU7IH.js +1 -0
  6. package/dist/chunks/app-ML5GKD3A.js +325 -0
  7. package/dist/chunks/{auto_completion-5WD4TTIP.js → auto_completion-UG6IEWD2.js} +1 -1
  8. package/dist/chunks/{chat-BA72I6O3.js → chat-ISCVWNVN.js} +1 -1
  9. package/dist/chunks/chunk-24LJKH4G.js +847 -0
  10. package/dist/chunks/chunk-7SGZ66KT.js +44 -0
  11. package/dist/chunks/chunk-B4UKMX5E.js +1 -0
  12. package/dist/chunks/{chunk-Z5D4VQSG.js → chunk-EXT42EJZ.js} +1 -1
  13. package/dist/chunks/{chunk-6JMPGZPV.js → chunk-GBH7XI5A.js} +1 -1
  14. package/dist/chunks/{chunk-5KSNFTQN.js → chunk-J4J3F6BT.js} +1 -1
  15. package/dist/chunks/chunk-LQM3JK7N.js +1 -0
  16. package/dist/chunks/{chunk-ZURGYQ4L.js → chunk-QESQR5GB.js} +1 -1
  17. package/dist/chunks/chunk-V36DXF56.js +13 -0
  18. package/dist/chunks/{chunk-TRVRMCHV.js → chunk-ZNO55RNG.js} +1 -1
  19. package/dist/chunks/{click-F4M4FVLQ.js → click-AWHZCV2E.js} +2 -2
  20. package/dist/chunks/{computer_action-72ZORSKW.js → computer_action-MO2JR2XH.js} +1 -1
  21. package/dist/chunks/{custom_openai-BLC4CWOL.js → custom_openai-K554R7Q5.js} +1 -1
  22. package/dist/chunks/{drag-OT2BJZ4P.js → drag-D2GVPIQB.js} +1 -1
  23. package/dist/chunks/{generate_image-V4OMOT7Z.js → generate_image-45UQ6P2B.js} +1 -1
  24. package/dist/chunks/{invoke-L2V4QMJG.js → invoke-DVZUJJV3.js} +2 -2
  25. package/dist/chunks/{invokeSync-7NWIYBX5.js → invokeSync-NEZGW27B.js} +2 -2
  26. package/dist/chunks/{key_press-IVB7R7CK.js → key_press-AQNKL6UM.js} +1 -1
  27. package/dist/chunks/{keyboard_typing-A6VFLI7Q.js → keyboard_typing-QSBPTZJ6.js} +1 -1
  28. package/dist/chunks/{mistral-YTTOZB2J.js → mistral-ON6RQMK7.js} +1 -1
  29. package/dist/chunks/{model_config-JTMSQGKH.js → model_config-QRYAVWHF.js} +1 -1
  30. package/dist/chunks/{nvidia-ON4Q6Q26.js → nvidia-I6DPWP6U.js} +2 -2
  31. package/dist/chunks/{ollama-DIFOZ4PM.js → ollama-6WSZPCI5.js} +1 -1
  32. package/dist/chunks/{recapture_screen-TVTRNE7C.js → recapture_screen-PPXYK2YY.js} +1 -1
  33. package/dist/chunks/{screen_grid-AEHMTXP3.js → screen_grid-3RU324CV.js} +1 -1
  34. package/dist/chunks/{scroll-KFID5QKZ.js → scroll-TSU6MTGU.js} +1 -1
  35. package/dist/chunks/search_keyword-DZY4MWV7.js +8 -0
  36. package/dist/chunks/{secrets-JMSL57D2.js → secrets-TNMLVMST.js} +1 -1
  37. package/dist/chunks/{secrets_v2-U7JR7ZO6.js → secrets_v2-OBRWR3UT.js} +1 -1
  38. package/dist/chunks/{settings-3VSVCZDF.js → settings-PUFSRWT3.js} +1 -1
  39. package/dist/chunks/update_file-TGEB5UWK.js +13 -0
  40. package/dist/chunks/usage-EBE2OVES.js +1 -0
  41. package/dist/chunks/{usageServer-4X7T4FDJ.js → usageServer-RTK5N5KE.js} +1 -2
  42. package/dist/chunks/write_file-O6OF7Z2W.js +32 -0
  43. package/dist/cli.js +25 -22
  44. package/dist/model_config.json +2 -30
  45. package/dist/package.json +2 -2
  46. package/model_config.json +2 -30
  47. package/package.json +2 -2
  48. package/dist/chunks/ai-EWDCEXLL.js +0 -1
  49. package/dist/chunks/app-C7G3NWAQ.js +0 -333
  50. package/dist/chunks/chunk-HTOLY3HR.js +0 -1
  51. package/dist/chunks/chunk-OB2V6ZNC.js +0 -951
  52. package/dist/chunks/chunk-PACSPBDP.js +0 -1
  53. package/dist/chunks/chunk-T5CUPXCW.js +0 -13
  54. package/dist/chunks/chunk-TX3H7HDF.js +0 -44
  55. package/dist/chunks/search_keyword-666PL7YG.js +0 -8
  56. package/dist/chunks/update_file-RG5QSLR2.js +0 -13
  57. package/dist/chunks/usage-AJDMLXTH.js +0 -1
  58. package/dist/chunks/write_file-AQJXPIUV.js +0 -32
@@ -1 +0,0 @@
1
- import{e as m,f as c}from"./chunk-P5HBJA23.js";import{b as s}from"./chunk-26BQ45XP.js";import n from"fs-extra";import p from"path";var o={mode:"Flux",display:0,thinkingLevel:"Medium",aiProvider:"",activeModel:"",activeKeyIndex:{},showFullThinking:!0,apiTier:"Free",quotas:{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0,providerTiers:{Google:"Free",DeepSeek:"Free",NVIDIA:"Free",OpenRouter:"Free",InferX:"Free",SenseNova:"Free",Poolside:"Free",ExpLabs:"Free",TokenHarbor:"Free",Infron:"Free",APInex:"Free",xKiro:"Free",c_openai:"Free"}},systemSettings:{customOpenAIBaseUrl:"",memory:!1,theme:"Dark",compression:0,autoExec:!0,allowExternalAccess:!1,advanceRollback:!1,autoDeleteHistory:"7d",useExternalData:!1,externalDataPath:"",preserveThinking:!0,loadingPhrases:!1,progressiveRendering:!0,showTPMEstimate:!0,subAgents:!1,CustomSubAgent:!1,SubAgentModel:"Default",SubAgentProvider:"",commitMessageModel:"Default",commitMessageProvider:"",dynamicDirAwareness:!1,indentationTree:!0,ollamaEndpoint:"Cloud",compressToolResults:!1,autoTruncateResults:!0,agentFinishSound:!1,imageHistoryCU:"Standard",contextLength:"256k",keepReasoningContext:!1,autoExcludeMetadata:!1,disableTodo:!1,preferBash:!1,clipboardContext:!1,cacheCalculateMode:"Session",alwaysAskFiles:".env, .env.*, *.env",loopLimits:"Default",overwriteProtection:!0},profileData:{preset:"Default",name:null,nickname:null,instructions:null},imageSettings:{keyType:"Default",quality:"Low-High",apiKey:""},autoCompletion:{enabled:!1,model:"Default",provider:"",baseUrl:""}},I={Mistral:"https://api.mistral.ai/v1/chat/completions",DeepSeek:"https://api.deepseek.com/chat/completions",OpenRouter:"https://openrouter.ai/api/v1/chat/completions",NVIDIA:"https://integrate.api.nvidia.com/v1",Ollama:"https://ollama.com/v1",InferX:"https://model.inferx.net/endpoints/v1/chat/completions",SenseNova:"https://token.sensenova.ai/v1/chat/completions",Poolside:"https://inference.poolside.ai/v1/chat/completions",ExpLabs:"https://api.experientiallabs.ai/v1/chat/completions",TokenHarbor:"https://tokenharbor.ai/v1/chat/completions",Infron:"https://llm.onerouter.pro/v1/chat/completions",APInex:"https://api.apinex.bond/v1/chat/completions",xKiro:"https://api.xkiro.com/v1/chat/completions",AIHubMix:"https://aihubmix.com/v1/chat/completions",Google:"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"},g=async()=>{let t={...o};try{if(await n.exists(s)){let e=m(s);if(e.imageSettings&&e.imageSettings.apiKey)try{let a=e.imageSettings.apiKey,{saveSecret:i}=await import("./secrets-JMSL57D2.js");await i("POLLINATIONS_API_KEY",a),e.imageSettings.apiKey="",c(s,e)}catch{}t={...o,...e,quotas:{...o.quotas,...e.quotas,providerTiers:{...o.quotas.providerTiers,...e.quotas?.providerTiers||{}}},systemSettings:{...o.systemSettings,...e.systemSettings},profileData:{...o.profileData,...e.profileData},imageSettings:{...o.imageSettings,...e.imageSettings},autoCompletion:{...o.autoCompletion,...e.autoCompletion}}}}catch(e){console.error("Failed to load settings:",e)}try{let{getSecret:e}=await import("./secrets-JMSL57D2.js"),a=await e("POLLINATIONS_API_KEY");a&&(t.imageSettings.apiKey=a)}catch{}if(t.showFullThinking===!1){t.showFullThinking=!0;try{c(s,t)}catch{}}return t},d=async t=>{let{FLUXFLOW_DIR:e}=await import("./paths-RQRI2XRY.js"),a=["logs","secret"];for(let i of a){let l=p.join(e,i),r=p.join(t,i);try{await n.exists(l)&&(await n.ensureDir(r),await n.copy(l,r,{overwrite:!0}))}catch(u){console.error(`Migration failed for ${i}:`,u)}}},D=async t=>{try{let e=await g();if(!e.systemSettings.useExternalData&&t.systemSettings?.useExternalData&&t.systemSettings?.externalDataPath&&await d(t.systemSettings.externalDataPath),t.imageSettings&&t.imageSettings.apiKey!==void 0){let{saveSecret:i,removeSecret:l}=await import("./secrets-JMSL57D2.js"),r=t.imageSettings.apiKey;r?await i("POLLINATIONS_API_KEY",r):await l("POLLINATIONS_API_KEY")}let a={...e,...t};a.systemSettings&&(a.systemSettings.dynamicDirAwareness=!1),a.imageSettings&&(a.imageSettings={...a.imageSettings,apiKey:""}),await n.ensureDir(p.dirname(s)),c(s,a);try{let{invalidateCachedBaseUrl:i}=await import("./usage-AJDMLXTH.js");i()}catch{}return!0}catch(e){return console.error("Failed to save settings:",e),!1}};export{I as a,g as b,D as c};
@@ -1,13 +0,0 @@
1
- import{b as z}from"./chunk-PACSPBDP.js";import{p as ut}from"./chunk-HTOLY3HR.js";import{a as mt,b as W}from"./chunk-P5HBJA23.js";import{d as J,h as Z,i as M,j as b}from"./chunk-26BQ45XP.js";import S from"fs-extra";import U from"path";import bt from"http";import N from"fs-extra";import et from"path";import{spawn as vt}from"child_process";import{fileURLToPath as Ft}from"url";var $=52991,Rt=15e3,ft=et.join(J,"usage","usage_error.txt"),ht=async(e,t)=>{let o=t?.stack||t?.message||String(t);console.error(`[Usage Daemon Error] [${e}]:`,t);try{await N.ensureDir(et.dirname(ft));let s=`[${new Date().toISOString()}] [Daemon:${e}] ${o}
2
- -------------------------------------
3
-
4
- `;await N.appendFile(ft,s,"utf8")}catch{}},B={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,cost:0,imageCalls:[]},tt=(e,t)=>{if(!e)return{};let o=Object.keys(e),i=new Date(new Date(t).getTime()-720*60*60*1e3),s={};for(let n of o)new Date(n)>=i&&(s[n]=e[n]);return s};async function Ut(){let e=new Date().toISOString().split("T")[0],t=null;try{if(await N.exists(M)){let o=(await N.readFile(M,"utf8")).trim();o.startsWith("{")||o.startsWith("[")?t=JSON.parse(o):t=JSON.parse(W(o))}}catch(o){await ht("loadUsageFromDisk",o)}if(t){let o={...B,...t.stats||{}};Array.isArray(o.imageCalls)||(o.imageCalls=[]);let i=t.history||{},s=tt(i,e);if(t.date===e)return{...t,stats:o,history:s};{let n=t.date,c={...s};return n&&(c[n]=o),{date:e,stats:{...B},history:tt(c,e)}}}return{date:e,stats:{...B},history:{}}}async function Ot(e=$){let t=await Ut(),o=!1,i=!1,s=Date.now(),n=null,c=async()=>{if(t)try{await N.ensureDir(et.dirname(M));let l=new Date().toISOString().split("T")[0];t.history=tt(t.history||{},t.date||l),t.saveId=Math.random().toString(36).substring(2)+Date.now().toString(36);let a=mt(JSON.stringify(t,null,2));await N.writeFile(M,a,"utf8"),i=!1}catch(l){await ht("flushToDisk",l)}},r=async()=>{n&&clearInterval(n),await c(),m.close(()=>{process.exit(0)}),setTimeout(()=>process.exit(0),1e3).unref()};n=setInterval(async()=>{if(o)return;Date.now()-s>Rt&&await r()},5e3),n.unref&&n.unref();let m=bt.createServer(async(l,a)=>{let u=l.url||"";if(l.method==="POST"&&u==="/heartbeat"){o||(s=Date.now()),a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify({ok:!0}));return}if((l.method==="GET"||l.method==="POST")&&u==="/finalize"){o=!0,n&&clearInterval(n),await c(),a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify({success:!0,message:"Finalized and written to disk"})),setTimeout(()=>{m.close(()=>process.exit(0)),setTimeout(()=>process.exit(0),500).unref()},3e3);return}if(l.method==="POST"&&u==="/flush"){o||(s=Date.now(),await c()),a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify({success:!0}));return}if(l.method==="POST"&&u==="/write"){if(o){a.writeHead(403,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:"Daemon finalized. Writes locked."}));return}s=Date.now();let d="";l.on("data",p=>{d+=p}),l.on("end",async()=>{try{let p=JSON.parse(d||"{}"),C=new Date().toISOString().split("T")[0];if(t.date!==C){let y=t.date;y&&(t.history||(t.history={}),t.history[y]={...t.stats}),t.date=C,t.stats={...B}}t.stats||(t.stats={...B});let{key:h,amount:f=1,provider:w,model:T}=p;if(h&&t.stats[h]!==void 0&&(h==="cost"?t.stats.cost=Number(((t.stats.cost||0)+Number(f)).toFixed(6)):typeof t.stats[h]=="number"&&(t.stats[h]+=Math.floor(f))),h==="agent"&&w&&(t.stats.providerRequests||(t.stats.providerRequests={}),t.stats.providerRequests[w]=(t.stats.providerRequests[w]||0)+Math.floor(f)),w&&T&&(h==="tokens"||h==="cachedTokens"||h==="candidateTokens"||h==="ttft"||h==="cost")){t.stats.models||(t.stats.models={}),t.stats.models[w]||(t.stats.models[w]={}),t.stats.models[w][T]||(t.stats.models[w][T]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0,cost:0});let y=t.stats.models[w][T];h==="tokens"&&(y.tokens+=Math.floor(f)),h==="cachedTokens"&&(y.cachedTokens+=Math.floor(f)),h==="candidateTokens"&&(y.candidateTokens+=Math.floor(f)),h==="cost"&&(y.cost=Number(((y.cost||0)+Number(f)).toFixed(6))),h==="ttft"&&(y.ttftSum=(y.ttftSum||0)+Math.floor(f),y.ttftCalls=(y.ttftCalls||0)+1)}i=!0,await c(),a.writeHead(200,{"Content-Type":"application/json"}),a.end(JSON.stringify({success:!0}))}catch(p){a.writeHead(400,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:p.message}))}});return}a.writeHead(404,{"Content-Type":"text/plain"}),a.end("Not Found")});m.listen(e,"127.0.0.1",()=>{s=Date.now()}),m.on("error",l=>{l.code==="EADDRINUSE"&&process.exit(0)})}async function At(e=$){try{if((await fetch(`http://127.0.0.1:${e}/heartbeat`,{method:"POST",signal:AbortSignal.timeout(300)})).ok)return!0}catch{}try{let t=Ft(import.meta.url);vt(process.execPath,[t,"--usage-daemon-worker",`--port=${e}`],{detached:!0,stdio:"ignore",windowsHide:!0}).unref();for(let i=0;i<10;i++){await new Promise(s=>setTimeout(s,100));try{if((await fetch(`http://127.0.0.1:${e}/heartbeat`,{method:"POST",signal:AbortSignal.timeout(300)})).ok)return!0}catch{}}}catch{}return!1}async function st(e,t=$){try{await At(t),await fetch(`http://127.0.0.1:${t}/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(1e3)})}catch{}}async function It(e=$){try{await fetch(`http://127.0.0.1:${e}/heartbeat`,{method:"POST",signal:AbortSignal.timeout(600)})}catch{}}async function Et(e=$){try{await fetch(`http://127.0.0.1:${e}/finalize`,{method:"GET",signal:AbortSignal.timeout(1e3)})}catch{}}if(process.argv.includes("--usage-daemon-worker")){let e=process.argv.find(o=>o.startsWith("--port=")),t=e?parseInt(e.split("=")[1],10):$;Ot(t)}var pt=U.join(J,"usage","usage_error.txt"),H=new Map,Nt=(e,t)=>{let o=`${e}:${t}`;if(H.has(o))return H.get(o);try{let i=yt();if(S.existsSync(i)){let n=S.readFileSync(i,"utf8").split(`
5
- `).filter(Boolean),c=t?t.trim().toLowerCase():"",r=e?e.trim().toLowerCase():"";for(let m=n.length-1;m>=0;m--)try{let l=JSON.parse(n[m]),a=l.provider&&l.provider.trim().toLowerCase()===r,u=l.model&&l.model.trim().toLowerCase()===c;if(a&&u&&l.cached!==void 0){let d=Number(l.cached)||0;return H.set(o,d),d}}catch{}}}catch{}return H.set(o,0),0},$t=(e,t,{input:o=0,cached:i=0,output:s=0})=>{let n=ut(e,t);if(!n)return{cost:0,uncachedInput:Math.max(0,o-i),estimatedCacheWrite:0,pricing:null};let c=Math.max(0,o-i),r=`${e}:${t}`,m=Nt(e,t);H.set(r,i);let l=i>m?i-m:0,a=c/1e6*n.IN,u=s/1e6*n.OUT,d=i/1e6*n.CR,p=l/1e6*n.CW,C=a+u+d+p;return{cost:Number(C.toFixed(6)),uncachedInput:c,estimatedCacheWrite:l,breakdown:{inputCost:Number(a.toFixed(6)),outputCost:Number(u.toFixed(6)),cacheReadCost:Number(d.toFixed(6)),cacheWriteCost:Number(p.toFixed(6))},pricing:n}},Q=null,oe=()=>{Q=null},it=async e=>{if(e!=="c_openai")return e;if(Q)return Q;try{let o=(await z())?.systemSettings?.customOpenAIBaseUrl||"";if(o=o.trim().replace(/\/+$/,""),o){let i=o.indexOf("/v1");return i!==-1&&(o=o.substring(0,i+3)),Q=o,o}}catch{}return"c_openai"},X=async(e,t)=>{let o=t?.stack||t?.message||String(t);console.error(`[Usage Error] [${e}]:`,t);try{await S.ensureDir(U.dirname(pt));let s=`[${new Date().toISOString()}] [${e}] ${o}
6
- -------------------------------------
7
-
8
- `;await S.appendFile(pt,s,"utf8")}catch{}},g=null,v={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,cost:0,imageCalls:[]},Y=(e,t)=>{if(!e)return{};let o=Object.keys(e),i=new Date(new Date(t).getTime()-720*60*60*1e3),s={};for(let n of o)new Date(n)>=i&&(s[n]=e[n]);return s},j=async()=>{let e=new Date().toISOString().split("T")[0];try{!await S.exists(M)&&await S.exists(Z)&&(await S.ensureDir(U.dirname(M)),await S.move(Z,M))}catch{}let t=null;try{if(await S.exists(M)){let i=(await S.readFile(M,"utf8")).trim();i.startsWith("{")||i.startsWith("[")?t=JSON.parse(i):t=JSON.parse(W(i))}}catch(i){await X("loadUsageFromFile",i)}let o=t;if(o){let i=o.stats||{...v},s={...v,...i};Array.isArray(s.imageCalls)||(s.imageCalls=[]);let n=o.history||{},c=Y(n,e);if(o.date===e)return{...o,stats:s,history:c};{let r=o.date,m=s,l={...c};return r&&(l[r]=m),{date:e,stats:{...v},history:Y(l,e)}}}return{date:e,stats:{...v},history:{}}},Pt=async()=>{},ot=500,gt=0,yt=()=>{let t=new Date().toISOString().split("T")[0];return U.join(b,`${t}.jsonl`)},ie=async e=>{try{await S.ensureDir(b);let t=await it(e.provider),o=Number(e.prompt)||0,i=Number(e.cached)||0,s=Number(e.output)||0,n=$t(e.provider,e.model,{input:o,cached:i,output:s}),c={time:new Date().toISOString(),provider:t||"unknown",model:e.model||"unknown",input:o,cached:i,output:s,reasoning:Number(e.reasoning)||0,ttft:Number(e.ttft)||0,cost:n.cost,estimatedCacheWrite:n.estimatedCacheWrite};n.breakdown&&(c.costBreakdown=n.breakdown),await S.appendFile(yt(),JSON.stringify(c)+`
9
- `,"utf8"),n.cost>0&&await qt("cost",n.cost,e.provider,e.model),++gt>=10&&(gt=0,await wt())}catch{}},wt=async()=>{try{if(!await S.exists(b))return;let e=(await S.readdir(b)).filter(s=>s.endsWith(".jsonl")).sort(),t=[];for(let s of e)try{let n=await S.readFile(U.join(b,s),"utf8");for(let c of n.split(`
10
- `))c.trim()&&t.push({file:s,line:c})}catch{}if(t.length<=ot)return;let o=t.slice(-ot),i=new Map;for(let s of o)i.has(s.file)||i.set(s.file,[]),i.get(s.file).push(s.line);for(let s of e){let n=i.get(s);!n||n.length===0?await S.remove(U.join(b,s)):await S.writeFile(U.join(b,s),n.join(`
11
- `)+`
12
- `,"utf8")}}catch{}},ne=async(e=30)=>{let t=[];try{if(!await S.exists(b))return t;let i=(await S.readdir(b)).filter(s=>s.endsWith(".jsonl")).sort().slice(-Math.max(1,e));for(let s of i)try{let n=await S.readFile(U.join(b,s),"utf8");for(let c of n.split(`
13
- `))if(c.trim())try{t.push(JSON.parse(c))}catch(r){await X(`getTimedUsage:parseLine (${s})`,r)}}catch(n){await X(`getTimedUsage:readFile (${s})`,n)}}catch(o){await X("getTimedUsage",o)}return t.slice(-ot)},ae=async()=>{g=await j(),await wt()},F=async()=>{let e=new Date().toISOString().split("T")[0];if(!g)g=await j();else if(g.date!==e){let t=g.date,o=g.stats,i=g.history||{};o&&(i[t]=o),g={date:e,stats:{...v},history:Y(i,e)},await Pt()}return g&&g.stats&&!Array.isArray(g.stats.imageCalls)&&(g.stats.imageCalls=[]),g.stats},kt=async()=>{let e=new Date().toISOString().split("T")[0];g||(g=await j()),g.date!==e&&await F();let t=g.history||{},o=Y(t,e);g.history=o;let i=g.stats||{...v},s={...v};s.imageCalls=[],s.models={},s.providerRequests={};let n=(c,r)=>{for(let m in c)if(m==="imageCalls")c.imageCalls=[...c.imageCalls||[],...r.imageCalls||[]];else if(m==="providerRequests"){let l=r.providerRequests||{};for(let a in l)c.providerRequests[a]=(c.providerRequests[a]||0)+(l[a]||0)}else if(m==="models"){let l=r.models||{};for(let a in l){c.models[a]||(c.models[a]={});for(let u in l[a]){c.models[a][u]||(c.models[a][u]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0,cost:0});let d=c.models[a][u],p=l[a][u];d.tokens+=p.tokens||0,d.cachedTokens+=p.cachedTokens||0,d.candidateTokens+=p.candidateTokens||0,d.cost=Number(((d.cost||0)+(p.cost||0)).toFixed(6)),d.ttftSum=(d.ttftSum||0)+(p.ttftSum||0),d.ttftCalls=(d.ttftCalls||0)+(p.ttftCalls||0)}}}else m==="cost"?c.cost=Number(((c.cost||0)+(r.cost||0)).toFixed(6)):typeof c[m]=="number"&&(c[m]+=r[m]||0)};n(s,i);for(let c in o)n(s,o[c]);return s},re=async(e,t)=>{t=await it(t),e==="toolSuccess"?R.toolSuccess++:e==="toolFailure"?R.toolFailure++:e==="toolDenied"&&R.toolDenied++;let o=await F();o[e]!==void 0&&o[e]++,t&&e==="agent"&&(o.providerRequests||(o.providerRequests={}),o.providerRequests[t]=(o.providerRequests[t]||0)+1),await st({key:e,amount:1,provider:t})},R={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0,cost:0},qt=async(e,t,o,i)=>{o=await it(o),e==="linesAdded"?R.linesAdded+=t:e==="linesRemoved"?R.linesRemoved+=t:e==="cost"&&(R.cost=Number(((R.cost||0)+Number(t)).toFixed(6)));let s=await F();if(s[e]!==void 0&&(e==="cost"?s.cost=Number(((s.cost||0)+Number(t)).toFixed(6)):s[e]+=Math.floor(t)),o&&i&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens"||e==="ttft"||e==="cost")){s.models||(s.models={}),s.models[o]||(s.models[o]={}),s.models[o][i]||(s.models[o][i]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0,cost:0});let n=s.models[o][i];e==="tokens"&&(n.tokens+=Math.floor(t)),e==="cachedTokens"&&(n.cachedTokens+=Math.floor(t)),e==="candidateTokens"&&(n.candidateTokens+=Math.floor(t)),e==="cost"&&(n.cost=Number(((n.cost||0)+Number(t)).toFixed(6))),e==="ttft"&&(n.ttftSum=(n.ttftSum||0)+Math.floor(t),n.ttftCalls=(n.ttftCalls||0)+1)}await st({key:e,amount:t,provider:o,model:i})},Ct=async(e=1)=>{let t=new Date,o=t.toISOString().split("T")[0];g||(g=await j()),g.date!==o&&await F();let i=t.getFullYear(),s=t.getMonth();t.getDate()<e&&(s-=1,s<0&&(s=11,i-=1));let r=new Date(i,s,e).toISOString().split("T")[0],m=g.history||{},l=g.stats||{...v},a={...v};a.imageCalls=[],a.models={},a.providerRequests={};let u=(d,p)=>{for(let C in d)if(C==="imageCalls")d.imageCalls=[...d.imageCalls||[],...p.imageCalls||[]];else if(C==="providerRequests"){let h=p.providerRequests||{};for(let f in h)d.providerRequests[f]=(d.providerRequests[f]||0)+(h[f]||0)}else if(C==="models"){let h=p.models||{};for(let f in h){d.models[f]||(d.models[f]={});for(let w in h[f]){d.models[f][w]||(d.models[f][w]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0});let T=d.models[f][w],y=h[f][w];T.tokens+=y.tokens||0,T.cachedTokens+=y.cachedTokens||0,T.candidateTokens+=y.candidateTokens||0,T.ttftSum=(T.ttftSum||0)+(y.ttftSum||0),T.ttftCalls=(T.ttftCalls||0)+(y.ttftCalls||0)}}}else typeof d[C]=="number"&&(d[C]+=p[C]||0)};u(a,l);for(let d in m)d>=r&&d<o&&u(a,m[d]);return a},_t=async(e,t={})=>{let o=await z().catch(()=>({})),i=t.apiTier||o.apiTier||"Free",s=t.quotas||t.systemSettings?.quotas||o.quotas||{},n=s.providerBudgets||{},c=!!n.__useProvider,r=t.aiProvider||o.aiProvider||"Google",m=c&&!!n[r],l=()=>{if(m){let a=n[r];return{agentLimit:typeof a.agentLimit=="number"&&a.agentLimit>0?a.agentLimit:99999999,tokenLimit:typeof a.tokenLimit=="number"&&a.tokenLimit>0?a.tokenLimit:99999999999999,monthlyTokenLimit:typeof a.monthlyTokenLimit=="number"&&a.monthlyTokenLimit>0?a.monthlyTokenLimit:99999999999999,dailyCostLimit:typeof a.dailyCostLimit=="number"&&a.dailyCostLimit>0?a.dailyCostLimit:99999999999999,monthlyCostLimit:typeof a.monthlyCostLimit=="number"&&a.monthlyCostLimit>0?a.monthlyCostLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999,dailyCostLimit:typeof s.dailyCostLimit=="number"&&s.dailyCostLimit>0?s.dailyCostLimit:99999999999999,monthlyCostLimit:typeof s.monthlyCostLimit=="number"&&s.monthlyCostLimit>0?s.monthlyCostLimit:99999999999999}};if(e==="agent"){let{agentLimit:a,tokenLimit:u,monthlyTokenLimit:d,dailyCostLimit:p,monthlyCostLimit:C}=l(),h=await F(),f;s.resetMode==="Custom"?f=await Ct(s.resetDay||1):f=await kt();let w=0,T=0,y=0,O=0,L=0;if(m){w=h.providerRequests?.[r]||0;let D=h.models?.[r]||{};for(let x in D)T+=D[x]?.tokens||0,O+=D[x]?.cost||0;let k=f.models?.[r]||{};for(let x in k)y+=k[x]?.tokens||0,L+=k[x]?.cost||0}else w=h.agent||0,T=h.tokens||0,y=f.tokens||0,O=h.cost||0,L=f.cost||0;return i==="Free"&&h.agent+h.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:w>=a?{allowed:!1,reason:m?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:T>=u?{allowed:!1,reason:m?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:y>=d?{allowed:!1,reason:m?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:O>=p?{allowed:!1,reason:m?`Daily Cost Budget Exhausted for ${r} ($${O.toFixed(4)} >= $${p.toFixed(4)})`:`Daily Cost Budget Exhausted ($${O.toFixed(4)} >= $${p.toFixed(4)})`}:L>=C?{allowed:!1,reason:m?`Monthly Cost Budget Exhausted for ${r} ($${L.toFixed(4)} >= $${C.toFixed(4)})`:`Monthly Cost Budget Exhausted ($${L.toFixed(4)} >= $${C.toFixed(4)})`}:{allowed:!0}}if(e==="background"){let a=await F();if(i==="Free"&&a.agent+a.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let u=a.background<(s.backgroundLimit||999999);return{allowed:u,reason:u?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let u=(await F()).search<(s.searchLimit||100);return{allowed:u,reason:u?void 0:"Search Quota Exceeded"}}return{allowed:!0}},ce=async(e,t={})=>(await _t(e,t)).allowed,nt=e=>{if(!e||e.length===0)return[];let o=[...e].sort((s,n)=>s.timestamp-n.timestamp),i=[];for(let s of o){if(i.length>0){let n=i[i.length-1];if(s.timestamp>=n.start&&s.timestamp<n.end){n.calls.push(s),n.spent+=s.cost;continue}}i.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return i},Tt=(e,t)=>{if(!e||e.length===0)return .025;let i=nt(e);if(i.length===0)return .025;let s=[];for(let u of i){let d=.025;if(s.length>0){let C=s[s.length-1],h=!1;if(s.length>=2){let f=s[s.length-2];C.ratio>=.8&&f.ratio>=.8&&(h=!0)}if(h)d=.015;else{let f=C.limit,w=C.ratio;w>=.8?d=f===.015?.015:f:w<.4?d=Math.min(.025,f+.005):w>=.4&&w<.6?d=Math.min(.025,f+.004):d=Math.min(.025,f+.002)}}let p=d>0?u.spent/d:0;s.push({limit:d,spent:u.spent,ratio:p})}let n=i[i.length-1];if(t<n.end)return s[s.length-1].limit;let c=s[s.length-1].limit,r=c,m=s[s.length-1].ratio,l=n.end,a=0;for(let u=s.length-1;u>=0&&s[u].ratio>=.8;u--)a++;for(;l<=t;){let u=.025;a>=2?u=.015:m>=.8?u=r===.015?.015:r:m<.4?u=Math.min(.025,r+.005):m>=.4&&m<.6?u=Math.min(.025,r+.004):u=Math.min(.025,r+.002),r=u,m=0,a=0,l+=36e5,c=u}return c},le=async e=>{let t=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(t.keyType!=="Default")return!0;let i={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[t.quality]||.002,s=await F();s.imageCalls||(s.imageCalls=[]);let n=Date.now(),c=nt(s.imageCalls),r=0;if(c.length>0){let l=c[c.length-1];n>=l.start&&n<l.end&&(r=l.spent)}let m=Tt(s.imageCalls,n);return r+i<=m},de=async()=>{let e=await F();e.imageCalls||(e.imageCalls=[]);let t=Date.now(),o=nt(e.imageCalls),i=[],s=0,n=0;if(o.length>0){let l=o[o.length-1];t>=l.start&&t<l.end&&(i=l.calls,s=l.spent,n=Math.max(0,Math.ceil((l.end-t)/(60*1e3))))}let c=Tt(e.imageCalls,t),r=Math.max(0,c-s),m=s;return{totalSpent:s,remaining:r,activeCallsCount:i.length,nextResetMin:n,reclaimCost:m,limit:c}},me=async e=>{let t=e.imageSettings||{keyType:"Default",quality:"Low-High"},i={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[t.quality]||.002,s=await F();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:i}),queueFlush()},ue=async()=>{let e=new Date().toISOString().split("T")[0];g||(g=await j()),g.date!==e&&await F();let t=g.stats||{...v},o=g.history||{},i=new Set(Object.keys(o));i.add(e);let n=Array.from(i).sort().map(L=>{let D=L===e?t:o[L]||{},k={...v,...D},x=k.tokens||0,P=k.cachedTokens||0,q=k.candidateTokens||0,G=Math.max(0,x-q),_=Math.max(0,G-P),A=k.agent||0,I=k.background||0,E=k.search||0,St=A+I+E,V=k.toolSuccess||0,at=k.toolFailure||0,rt=k.toolDenied||0,K=V+at+rt,Lt=K>0?(V/K*100).toFixed(1):"100.0",ct=k.linesAdded||0,lt=k.linesRemoved||0,dt=Array.isArray(k.imageCalls)?k.imageCalls:[],Dt=dt.reduce((xt,Mt)=>xt+(Mt.cost||0),0);return{date:L,tokens:x,cachedTokens:P,candidateTokens:q,promptTokens:G,uncachedPromptTokens:_,agent:A,background:I,search:E,totalRequests:St,toolSuccess:V,toolFailure:at,toolDenied:rt,totalTools:K,toolSuccessRate:parseFloat(Lt),linesAdded:ct,linesRemoved:lt,netLines:ct-lt,duration:k.duration||0,cost:k.cost||0,imageCallsCount:dt.length,imageCost:Dt,models:k.models||{},providerRequests:k.providerRequests||{}}}),c=await z().catch(()=>({})),r=c.quotas||{},m=c.apiTier||"Free",l=await kt().catch(()=>({tokens:0,agent:0})),a=null;r.resetMode==="Custom"&&(a=await Ct(r.resetDay||1).catch(()=>({tokens:0})));let u=r.tokenLimit||0,d=r.monthlyTokenLimit||0,p=r.agentLimit||0,C=r.resetMode||"Daily",h=r.resetDay||1,f=r.providerBudgets||{},w=!!f.__useProvider,T=["Google","Anthropic","OpenAI","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside"];Object.keys(f).forEach(L=>{L!=="__useProvider"&&!T.includes(L)&&T.push(L)});let y=[];for(let L of T){let D=f[L];if(D&&(D.agentLimit||D.tokenLimit||D.monthlyTokenLimit)){let k=0,x=t.models?.[L]||{};for(let E in x)k+=x[E]?.tokens||0;let P=0,q=(r.resetMode==="Custom"?a?.models:l?.models)?.[L]||{};for(let E in q)P+=q[E]?.tokens||0;let G=t.providerRequests?.[L]||0,_=D.tokenLimit||0,A=D.monthlyTokenLimit||0,I=D.agentLimit||0;y.push({provider:L,dailyTokens:k,dailyTokenLimit:_,isDailyUnlimited:_>=9999999999999||_===0,monthlyTokens:P,monthlyTokenLimit:A,isMonthlyUnlimited:A>=9999999999999||A===0,dailyRequests:G,dailyAgentLimit:I,isRequestsUnlimited:I>=9999999||I===0})}}let O={apiTier:m,resetMode:C,resetDay:h,quotas:r,usingProviderBudgets:w&&y.length>0||y.length>0,providerBudgetsList:y,daily:{tokensUsed:t.tokens||0,tokenLimit:u,cost:t.cost||0,costLimit:r.dailyCostLimit||0,agentRequests:t.agent||0,agentLimit:p,isUnlimitedTokens:u>=9999999999999||u===0,isUnlimitedCost:!r.dailyCostLimit||r.dailyCostLimit>=9999999999999||r.dailyCostLimit===0,isUnlimitedRequests:p>=9999999||p===0},monthly:{tokensUsed:(r.resetMode==="Custom"?a?.tokens:l?.tokens)||0,tokenLimit:d,cost:(r.resetMode==="Custom"?a?.cost:l?.cost)||0,costLimit:r.monthlyCostLimit||0,isUnlimitedTokens:d>=9999999999999||d===0,isUnlimitedCost:!r.monthlyCostLimit||r.monthlyCostLimit>=9999999999999||r.monthlyCostLimit===0},providerBudgets:f};return{currentDate:e,todayStats:t,history:o,timeline:n,budget:O,runtimeSession:{...R}}};export{It as a,Et as b,$t as c,oe as d,Pt as e,ie as f,wt as g,ne as h,ae as i,F as j,kt as k,re as l,R as m,qt as n,Ct as o,_t as p,ce as q,nt as r,Tt as s,le as t,de as u,me as v,ue as w};
@@ -1,44 +0,0 @@
1
- import{c as U}from"./chunk-26BQ45XP.js";import G from"os";import{structuredPatch as V}from"diff";var R=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,D=(e,o)=>{if(!e)return"";let d=/\x1B\[[0-?]*[ -/]*[@-~]/g,g=e.split(`
2
- `),c=[];if(o<=5)return e;let l=t=>t<32||t>=127&&t<160||t>=768&&t<=879||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65056&&t<=65071?0:t>=4352&&t<=4447||t>=9001&&t<=9002||t>=11904&&t<=12350||t>=12352&&t<=42191||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=128591||t>=128640&&t<=128767||t>=131072&&t<=262141?2:1,w=t=>{let i=t.replace(d,""),n=0;for(let r=0;r<i.length;r++){let h=i.codePointAt(r);h>65535&&r++,n+=l(h)}return n},I=(t,i)=>{let n=0,r=t.length,h=!1;for(let p=0;p<t.length;p++){if(t[p]==="\x1B"&&t[p+1]==="["&&(h=!0),h){(t[p]==="m"||t[p]>="@"&&t[p]<="~"&&t[p]!=="[")&&(h=!1);continue}let L=t.codePointAt(p);L>65535&&p++;let y=l(L);if(n+y>i){r=L>65535?p-1:p;break}if(n+=y,n>=i){r=p+1;break}}return{head:t.substring(0,r),tail:t.substring(r)}};return g.forEach(t=>{if(w(t)<=o){c.push(t);return}let n=t.split(/(\s+)/),r="",h=0,p=t.match(/^(\s*)/),L=p?p[1]:"";n.forEach(y=>{if(y.length===0)return;let a=y;for(;a.length>0;){let F=w(a);if(h+F<=o){r+=a,h+=F;break}r.trim().length>0&&(c.push(r.trimEnd()),r=L.substring(0,Math.min(L.length,8)),h=w(r));let s=Math.max(1,o-h);if(w(a)>s){let{head:f,tail:u}=I(a,s);c.push((r+f).trimEnd()),r=L.substring(0,Math.min(L.length,8)),h=w(r),a=u}else r+=a,h+=w(a),a=""}}),(r.trimEnd().length>0||r===L)&&c.push(r.trimEnd())}),R(c.join(`
3
- `))},oe=e=>{if(!e)return 0;let o=0,d=e.match(/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g);d&&(o+=d.length*.55);let g=e.replace(/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g," "),c=g.match(/[<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}-]+/g);c&&(o+=c.length);let l=g.split(/[\s<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}-]+/g).filter(Boolean);return o+=l.length,Math.max(.1,o)},le=e=>e?e.match(/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]|\s+|[<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}-]+|[^\s<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}\-\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]+/g)||[e]:[],ce=e=>{if(!e&&e!==0)return"0.0k";let o=typeof e=="string"?parseFloat(e):e;return o>=1e6?`${(o/1e6).toFixed(1)}m`:o>=1e3?`${(o/1e3).toFixed(1)}k`:o.toString()},ae=(e,o=40)=>{let d=U.replaceAll("\\\\","\\");if(e=e.replace(G.homedir(),"~").replace(d,"FluxFlow").replaceAll("\\","/"),!e||e.length<=o)return R(e);let g=Math.floor((o-3)/2);return R(e.substring(0,g)+"..."+e.substring(e.length-g).replaceAll("\\","/"))},fe=e=>{let o=[],d=new Set,g=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(t=>{let i=t.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(i){let n=i[2]?parseInt(i[2],10):1;d.add(n)}});let c=Array.from(d).sort((t,i)=>t-i),l=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],w=["newContent","new_content","content_to_add","newBlock","new_block"],I=(t,i,n)=>{let r,h;for(let p of i){let L=t===1?[`${p}1`,p,`${p}_1`]:[`${p}${t}`,`${p}_${t}`];for(let y of L)if(e[y]!==void 0){r=e[y];break}if(r!==void 0)break}for(let p of n){let L=t===1?[`${p}1`,p,`${p}_1`]:[`${p}${t}`,`${p}_${t}`];for(let y of L)if(e[y]!==void 0){h=e[y];break}if(h!==void 0)break}return{r,n:h}};for(let t of c){let{r:i,n}=I(t,l,w);if(i!==void 0&&n!==void 0)o.push({replace:i,new:n});else if(i!==void 0||n!==void 0)return{error:`Mismatched replacement pair for index ${t}. Both replacement and new content must be provided.`,allowMultiple:g}}return{patchPairs:o,allowMultiple:g}},Z=e=>{if(!e)return null;let o="",d=0,g=e.length;for(;d<g;){let c=e[d];if(c==="\\"){for(;d<g&&e[d]==="\\";)d++;o+="\\\\*"}else if(c===`
4
- `)o+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",d++;else if(c==="\r")o+="(?:\\r|\\\\*r)?",d++;else if(c===" ")o+="(?:\\t|\\\\*t|\\s*)",d++;else if(c==='"'||c==="'"||c==="`")o.endsWith("\\\\*")||(o+="\\\\*"),o+=c,d++;else if(/[.*+?^${}()|[\]]/.test(c))o+="\\"+c,d++;else if(/\s/.test(c)){for(;d<g&&/\s/.test(e[d])&&e[d]!==`
5
- `&&e[d]!=="\r"&&e[d]!==" ";)d++;o+="\\s*"}else o+=c,d++}if(!o)return null;try{return new RegExp(o,"g")}catch{return null}},ue=(e,o,d={})=>{let g=typeof d=="boolean"?d:!!(d&&d.allowMultiple),c=e.replace(/\r\n/g,`
6
- `).replace(/\r/g,`
7
- `),l=s=>s.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
8
- `).replace(/\r/g,`
9
- `),w=s=>s.match(/^\s*/)[0],I=s=>{let f=s.split(`
10
- `).filter($=>$.trim()!=="");if(f.length===0)return"";let u=w(f[0]);for(let $ of f){let m=w($);m.length<u.length&&(u=m)}return u},t=(s,f,u="")=>{if(!s||f===void 0)return s;let m=/^\t/m.test(f)?" ":" ",b=S=>S.split(`
11
- `).find(C=>C.trim()!=="")??"",E=b(f).match(/^\s*/)[0].length,x=b(s).match(/^\s*/)[0].length,k=E-x,A=(u.match(/^\s*/)||[""])[0].length;return s.split(`
12
- `).map((S,C)=>{if(S.trim()===""&&C!==0)return"";let _=S.match(/^\s*/)[0].length,M=Math.max(0,_+k);return C===0&&(M=Math.max(0,M-A)),m.repeat(M)+S.trimStart()}).join(`
13
- `)},i=[];for(let s=0;s<o.length;s++){let f=o[s],u=(f.replace||"").trim(),$=l(f.new||"");if(u.startsWith("^LINE:")&&u.endsWith("$")){let A=u.slice(6,-1).trim().split(".."),T=parseInt(A[0]),S=A[1]!==void 0?parseInt(A[1]):T;if(!isNaN(T)&&!isNaN(S)){let C=c.split(`
14
- `);if(T<1||T>C.length||S<T||S>C.length){i.push({index:s,success:!1,error:`Block ${s+1}: Line range ^LINE:${T}..${S}$ out of bounds (file has ${C.length} lines).`});continue}let M=C.slice(T-1,S).join(`
15
- `),B=0;for(let P=0;P<T-1;P++)B+=C[P].length+1;i.push({index:s,success:!0,startPos:B,firstMatchContent:M,content_to_add:$});continue}}let m=l(f.replace||"");if(m===""&&$===""){i.push({index:s,success:!1,error:`Block ${s+1}: Empty replace and add content.`});continue}let b=m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),E=null;if(m!==""&&c.includes(m))E=new RegExp(b,"g");else{let k=m.split(`
16
- `).map(A=>A.trim()).filter(A=>A.length>0).map(A=>A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(k.length>0){let A=k.join("\\s*");try{E=new RegExp(A,"g")}catch{E=new RegExp(b,"g")}}else E=new RegExp(b,"g")}let x=[...c.matchAll(E)];if(x.length===0&&m!==""){let k=Z(m);k&&(x=[...c.matchAll(k)])}if(x.length===0){i.push({index:s,success:!1,error:`Block ${s+1}: Could not find match.`});continue}if(x.length>1&&!g){i.push({index:s,success:!1,error:`Block ${s+1}: Found ${x.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let k of x)i.push({index:s,success:!0,startPos:k.index,firstMatchContent:k[0],content_to_add:$})}let n=i.filter(s=>s.success).sort((s,f)=>s.startPos-f.startPos);for(let s=0;s<n.length-1;s++){let f=n[s],u=n[s+1];f.startPos+f.firstMatchContent.length>u.startPos&&(f.success=!1,f.error=`Block ${f.index+1}: Overlaps with another block.`,u.success=!1,u.error=`Block ${u.index+1}: Overlaps with another block.`)}let r=new Map,h=c,p=0,L=0,y=i.filter(s=>s.success).sort((s,f)=>s.startPos-f.startPos);for(let s of y){let f=s.startPos,u=c.substring(0,f).split(`
17
- `).length,$=f+p,m=u+L,b=h.lastIndexOf(`
18
- `,$)+1,E=h.substring(b,$),x=t(s.content_to_add,s.firstMatchContent,E),k=h.split(`
19
- `),A=[];for(let _=Math.max(0,m-4);_<m-1;_++)A.push({num:_+1,text:k[_]});let T=s.firstMatchContent.split(`
20
- `),S=[],C=m+T.length-1;for(let _=C;_<Math.min(k.length,C+3);_++)S.push({num:_+1,text:k[_]});r.set(s,{success:!0,index:s.index,oldContent:s.firstMatchContent,newContent:x,originalStartLine:u,finalStartLine:m,contextBefore:A,contextAfter:S}),h=h.substring(0,$)+x+h.substring($+s.firstMatchContent.length),p+=x.length-s.firstMatchContent.length,L+=x.split(`
21
- `).length-s.firstMatchContent.split(`
22
- `).length}let a=[];for(let s=0;s<o.length;s++){let f=y.filter(u=>u.index===s);if(f.length>0)for(let u of f)r.has(u)&&a.push(r.get(u));else{let u=i.find($=>$.index===s);a.push({success:!1,error:u?u.error:`Block ${s+1}: Unknown error.`})}}let F=a.filter(s=>!s.success&&s.error&&s.error.includes("Could not find match"));if(F.length===1)F[0].error+=" (Use Line Anchor or Run tool safely if search string fails)";else if(F.length>1){let s=F[F.length-1];s.error+=`
23
- (Tip: Use Line Anchor or Run tool safely if search string fails)`}return{content:h,results:a}},he=(e,o,d,g=8,c=!1)=>{if(e===o)return"";let l=(e||"").split(/\r?\n/),w=(o||"").split(/\r?\n/),I=Math.max(l.length,w.length,1),t=Math.max(4,String(I).length),i=p=>String(p).padStart(t," "),n=`[DIFF_START]
24
- `,r="\u2550".repeat(88),h=V("","",e||"",o||"","","",{context:3});if(!h||!h.hunks||h.hunks.length===0)return"";if(h.hunks.forEach((p,L)=>{let y=0,a=0;for(let $ of p.lines)$[0]==="+"?y++:$[0]==="-"&&a++;let F=[];y>0&&F.push(`+${y}`),a>0&&F.push(`-${a}`);let s=`@@ ${F.join(" ")} @@`;n+=`[UI_CONTEXT] ${s}
25
- `;let f=p.oldStart,u=p.newStart;for(let $ of p.lines){let m=$[0],b=$.slice(1);m===" "?(n+=`[UI_CONTEXT] ${i(u)} |${b}
26
- `,f++,u++):m==="-"?(n+=`-${i(f)} |${b}
27
- `,f++):m==="+"&&(n+=`+${i(u)} |${b}
28
- `,u++)}}),c){let p=`[DIFF_START]
29
- `,L=n.substring(p.length),y=`[UI_CONTEXT] ${r}
30
- `,F=L.split(y).map(s=>s.split(`
31
- `).filter(u=>u.trim()!=="").length>120?`[[VERIFIED]]
32
- ${s}
33
- [[/VERIFIED]]`:s);n=p+F.join(y)}return n+="[DIFF_END]",R(n)},K=e=>{if(!e)return null;let o=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),d=o.startsWith("-"),g=o.startsWith("+"),c=d||g?o.substring(1):o,l=c.indexOf("|"),w=l!==-1?R(c.substring(0,l).trim()):"",I=R(l!==-1?c.substring(l+1):c);return{isR:d,isA:g,num:w,content:I}},Y=(e,o)=>{if(!e&&!o)return 1;if(!e||!o)return 0;let d=e.length,g=o.length,c=e,l=o;d<g&&(c=o,l=e);let w=c.length,I=l.length,t=new Int32Array(I+1),i=new Int32Array(I+1);for(let h=0;h<=I;h++)t[h]=h;for(let h=1;h<=w;h++){i[0]=h;let p=c[h-1];for(let L=1;L<=I;L++)p===l[L-1]?i[L]=t[L-1]:i[L]=Math.min(t[L],i[L-1],t[L-1])+1;t.set(i)}let n=t[I],r=Math.max(d,g);return r===0?1:1-n/r},H=e=>{let o=[],d=[];e.forEach((n,r)=>{n.parsed.isR?o.push({index:r,content:n.parsed.content}):n.parsed.isA&&d.push({index:r,content:n.parsed.content})});let g=o.length,c=d.length;if(g===0||c===0)return;let l=Array.from({length:g+1},()=>Array(c+1).fill(0)),w=Array.from({length:g+1},()=>Array(c+1).fill(""));for(let n=1;n<=g;n++)w[n][0]="up";for(let n=1;n<=c;n++)w[0][n]="left";let I=Array.from({length:g},()=>Array(c).fill(0));for(let n=0;n<g;n++)for(let r=0;r<c;r++)I[n][r]=Y(o[n].content.trim(),d[r].content.trim());for(let n=1;n<=g;n++)for(let r=1;r<=c;r++){let h=I[n-1][r-1],p=h>=.2?h:-10,L=l[n-1][r-1]+p,y=l[n-1][r],a=l[n][r-1];L>=y&&L>=a?(l[n][r]=L,w[n][r]="diag"):y>=a?(l[n][r]=y,w[n][r]="up"):(l[n][r]=a,w[n][r]="left")}let t=g,i=c;for(;t>0||i>0;)if(w[t][i]==="diag"){if(I[t-1][i-1]>=.2){let r=o[t-1].index,h=d[i-1].index;e[r].pairContent=e[h].parsed.content,e[h].pairContent=e[r].parsed.content}t--,i--}else w[t][i]==="up"?t--:i--},N=new Map,W=new Map,X=200,j=5,z=(e,o)=>{o.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(d=>z(d,o))},de=(e,o)=>{if(!e)return{completed:[],active:[]};let d=`${e.id}-${e.text?.length||0}-${o}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&N.has(d))return N.get(d);let g=R(ne(e.text||"",e.role)),c=`${e.id}-${o}`,l=new Map;if(e.isStreaming){let a=W.get(c);a&&g.startsWith(a.text)&&(l=a.blocksMap)}let w=(a,F,s,f={})=>{let u=l.get(a);if(u&&u.text===s&&u.type===F&&!!u.isActiveBlock==!!f.isActiveBlock&&!!u.isStreaming==!!f.isStreaming&&u.pairContent===f.pairContent)return u;let $=R(s),m={...f};return typeof m.pairContent=="string"&&(m.pairContent=R(m.pairContent)),Array.isArray(m.wrappedLines)&&(m.wrappedLines=m.wrappedLines.map(R)),{key:a,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:F,text:$,msg:F==="full-message"?e:void 0,...m}};if(g.includes("- Content Preview:")){let a="",F=g.match(/File\s+\[(.*?)\]/i);F&&(a=F[1].split(".").pop().toLowerCase());let m=((g.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
34
- `).map(S=>S.replace(/\r$/,"")),b=String(m.length).length,E=[],x=null,k=[],A=()=>{if(!k.length)return;let S=k;k=[],E.push(S.length===1?S[0]:{key:`${S[0].key}-chunk`,type:"chunk",blocks:S})},T=o-(b+6);return m.forEach((S,C)=>{let _=C===m.length-1,M=D(S,T).split(`
35
- `),B=w(`${e.id||Date.now()}-write-line-${C}`,"write-line",S,{gutterWidth:b,lineNum:C+1,isFirstLine:C===0,isLastLine:_,extension:a,wrappedLines:M});_&&e.isStreaming?(A(),x=B):(k.push(B),k.length>=j&&A())}),A(),{completed:E,active:x?[x]:[]}}if(g.includes("[DIFF_START]")){let a=g.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),s=(a?a[1].trim():"").split(`
36
- `).map(x=>x.replace(/\r$/,"")),f=s.map(x=>({line:x,parsed:K(x),pairContent:null})),u=[];for(let x=0;x<f.length;x++){let k=f[x];k.parsed&&(k.parsed.isR||k.parsed.isA)?u.push(k):u.length>0&&(H(u),u=[])}u.length>0&&H(u);let $=[],m=null,b=[],E=()=>{if(!b.length)return;let x=b;b=[],$.push(x.length===1?x[0]:{key:`${x[0].key}-chunk`,type:"chunk",blocks:x})};return s.forEach((x,k)=>{let A=k===s.length-1,T=f[k].parsed,S=null;T&&(S=D(T.content,o-17).split(`
37
- `));let C=w(`${e.id||Date.now()}-diff-${k}`,"diff-line",x,{isFirstLine:k===0,isLastLine:A,pairContent:f[k].pairContent,wrappedLines:S});A&&e.isStreaming?(E(),m=C):(b.push(C),b.length>=j&&E())}),E(),{completed:$,active:m?[m]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user"){if(!g&&!e.isLogo&&!e.isHelpRecord&&!e.isTerminalRecord&&!e.isHomeWarning&&!e.isImageStats&&!e.isAskRecord&&!e.isAboutRecord&&!e.isUpdateNotification){let a={completed:[],active:[]};return N.set(d,a),a}return{completed:[w(`${e.id||Date.now()}-full`,"full-message",g)],active:[]}}if(!g&&!e.isStreaming){let a={completed:[],active:[]};return N.set(d,a),a}let I=[],t=null,i=[],n=null,r=()=>{if(!i.length)return;let a=i;i=[],n=null,I.push(a.length===1?a[0]:{key:`${e.id||"x"}-chunk-${a[0].key}`,type:"chunk",blocks:a})},h=(a,F=!1)=>{if(n!==null&&n!==a.type&&r(),i.push(a),n=a.type,i.length>=j){if(e.isStreaming&&F)return;r()}},p=Math.max(20,(o||80)-6),L=Math.max(20,(o||80)-8);if(e.role==="think"){I.push(w(`${e.id}-header`,"think-header","",{duration:e.duration}));let a=g.split(`
38
- `),F=[];a.forEach(s=>{D(s,L).split(`
39
- `).forEach(u=>F.push(u))}),F.forEach((s,f)=>{let u=f===F.length-1;h(w(`${e.id}-${f}`,"think-line",s,{}),u)}),e.isStreaming||(r(),I.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let a=g.split(`
40
- `),F=!1,s=[],f=!1,u="",$=0,m=0,b=[];a.forEach(E=>{let x=E.trim();x.startsWith("```")?(f=!f,b.push(E)):f||x.startsWith("|")?b.push(E):D(E,p).split(`
41
- `).forEach(A=>b.push(A))}),f=!1,b.forEach((E,x)=>{let k=x===b.length-1,A=E.trim().startsWith("|"),T=E.trim().startsWith("```");if(f)T?(f=!1,h(w(`${e.id}-code-close-${m}`,"code-fence-close","",{}),k)):($++,h(w(`${e.id}-code-line-${x}`,"code-line",E,{lineNum:$,lang:u}),k));else if(T)f=!0,m=x,$=0,u=E.trim().replace(/^```/,"").trim(),h(w(`${e.id}-code-open-${x}`,"code-fence-open",u,{}),k);else if(A){if(F||(F=!0,s=[]),s.push(E),s.length===2){let S=s[0],C=S.split("|");C[0]!==void 0&&C[0].trim()===""&&C.shift(),C.length>0&&C[C.length-1].trim()===""&&C.pop();let _=C.map(M=>M.trim());h(w(`${e.id}-table-hdr-${x}`,"table-header",S,{colHeaders:_,colCount:_.length}),k)}else if(s.length>2){let S=E.split("|");S[0]!==void 0&&S[0].trim()===""&&S.shift(),S.length>0&&S[S.length-1].trim()===""&&S.pop();let C=S.map(P=>P.trim()),_=s[0].split("|");_[0]!==void 0&&_[0].trim()===""&&_.shift(),_.length>0&&_[_.length-1].trim()===""&&_.pop();let M=_.map(P=>P.trim()),B=Math.max(1,M.length);h(w(`${e.id}-table-row-${x}`,"table-row",E,{cells:C,colHeaders:M,colCount:B,rowIndex:s.length-3}),k)}k&&!e.isStreaming&&(r(),h(w(`${e.id}-table-end-${x}`,"table-close","",{}),!0))}else F&&(h(w(`${e.id}-table-end-${x}`,"table-close","",{}),k),F=!1,s=[]),h(w(`${e.id}-${x}`,"agent-line",E,{}),k)}),!e.isStreaming&&e.workedDuration&&(r(),I.push(w(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&i.length>0?t=i.length===1?i[0]:{key:`${e.id||"x"}-chunk-active-${i[0].key}`,type:"chunk",blocks:i}:r();let y={completed:I,active:t?[t]:[]};if(e.isStreaming){let a=new Map;if(I.forEach(F=>z(F,a)),t&&z(t,a),W.set(c,{text:g,blocksMap:a}),W.size>X){let F=W.keys().next().value;W.delete(F)}}else{if(N.set(d,y),N.size>X){let a=N.keys().next().value;N.delete(a)}W.delete(c)}return y},q={},J=/(\r?\n){2}(?=\[?(?:tool:(?:functions\.)?|tool\.functions|action:(?:functions\.)?|action:|action\.functions|\s*turn\s*:))/gi,O=(e,o)=>{let d=!1,g=!1,c=0;for(;c<o;){if(e.startsWith("```",c)){d=!d,c+=3;continue}if(d){c++;continue}if(e[c]===`
42
- `){g=!1,c++;continue}e[c]==="`"&&(c===0||e[c-1]!=="\\")&&(g=!g),c++}if(d)return!0;if(g){let l=e.indexOf(`
43
- `,o),w=l===-1?e.length:l;if(e.substring(o,w).includes("`"))return!0}return!1},Q=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[(?:TOOL|ACTION) RESULTS?\]:?\s*|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL|ACTION).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,ee=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,te=/\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,v=!1,ne=(e,o="agent")=>{if(!e)return e;let d=o===!0||o==="think",g=o===!1||o==="agent",c=e.replace(/<\|channel>thought/gi,"<think_fluxflow>").replace(/<channel\|>/gi,"</think_fluxflow>");if(d)return c.replace(/^<think_fluxflow>/gi,"").replace(/<\/think_fluxflow>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let l=c;if(c.trimStart().startsWith("ERROR: [INTERNAL CRITICAL] "))return"";g&&(l=l.replace(/<\/?think_fluxflow>/gi,(i,n,r)=>O(r,n)?i:""),l=l.replace(J,(i,n,r,h)=>!v&&O(h,r)?i:""),l&&(l.includes("[tool:")||l.includes("[action:"))&&(l=l.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[(?:tool|action):[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(i,n,r)=>r&&(r.includes("[tool:")||r.includes("[action:"))?r.trim():i),v&&(l=l.replace(/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(i,n)=>n.includes("[tool:")||n.includes("[action:")?n.trim():i))));let w="tool:",I="action:";if(g&&(l.toLowerCase().includes(w)||l.toLowerCase().includes(I)))for(;;){let i=l.toLowerCase(),n=i.indexOf(w),r=i.indexOf(I),h=w,p=n;if((n===-1||r!==-1&&r<n)&&(h=I,p=r),p===-1)break;if(!v&&O(l,p)){let $=-1,m=0;for(;;){let b=i.indexOf(w,m),E=i.indexOf(I,m),x=-1,k=w;if(b===-1&&E===-1)break;if(b===-1||E!==-1&&E<b?(x=E,k=I):x=b,!O(l,x)){$=x,h=k;break}m=x+k.length}if($===-1)break;p=$}let L=p,y=!1,a=p-1;for(;a>=0&&/\s/.test(l[a]);)a--;a>=0&&l[a]==="["&&(L=a,y=!0);let F=0,s=!1,f=null,u=p;for(;u<l.length;){let $=l[u];if(!f&&($==="'"||$==='"'||$==="`")?f=$:f&&$===f&&l[u-1]!=="\\"&&(f=null),f||($==="("?(F++,s=!0):$===")"&&F--),s&&F===0&&!f){let m=u;if(y){let b=u+1;for(;b<l.length&&/\s/.test(l[b]);)b++;b<l.length&&l[b]==="]"&&(m=b)}l=l.substring(0,L)+l.substring(m+1);break}if(u++,u===l.length){l=l.substring(0,L);break}}}g&&(l=l.replace(/\[\s*(?:tool|action):[a-zA-Z0-9_.]*\s*\([\s\S]*?\)\s*\]/gi,(i,n,r)=>!v&&O(r,n)?i:""),l=l.replace(/\[\s*(?:tool|action):[a-zA-Z0-9_.]*[\s\S]*$/gi,(i,n,r)=>!v&&O(r,n)?i:""),l=l.replace(/^(?:\s*=\s*["'][^"'\n]*["']|\s*[a-zA-Z0-9_]+\s*=\s*(?:["'][^"'\n]*["']|\d+|true|false))(?:\s*,\s*[a-zA-Z0-9_]+\s*=\s*(?:["'][^"'\n]*["']|\d+|true|false))*\s*\)?\]\s*/gm,(i,n,r)=>!v&&O(r,n)?i:""),l=l.replace(/(?:\r?\n|^)\s*=\s*["'][^"'\n]*["'][\s\S]*?\s*\)?\]\s*/g,(i,n,r)=>!v&&O(r,n)?i:`
44
- `));let t=o==="tool_result"||o==="tool"||o==="action"||o==="action_result";return l=l.replace(Q,(i,n,r,h)=>{if(/^\[(?:TOOL|ACTION) RESULTS?\]:?\s*/i.test(i)||/^\[\s*(?:TOOL|ACTION).*?$/i.test(i)){if(t||O(h,r))return i}else if(O(h,r))return i;return""}),l=l.replace(ee,i=>{let n=i.toLowerCase();return n.includes("leftrightarrow")?"\u2194":n.includes("rightarrow")?"\u2192":n.includes("leftarrow")?"\u2190":n.includes("uparrow")?"\u2191":n.includes("downarrow")?"\u2193":i}),l=l.replace(te,i=>q[i.toLowerCase()]||i),l.trim()},pe=()=>{N.clear(),W.clear()};export{R as a,D as b,oe as c,le as d,ce as e,ae as f,fe as g,ue as h,he as i,K as j,H as k,de as l,ne as m,pe as n};
@@ -1,8 +0,0 @@
1
- import{a as Y}from"./chunk-Y5JU726N.js";import{b as Q}from"./chunk-PACSPBDP.js";import"./chunk-HTOLY3HR.js";import"./chunk-P5HBJA23.js";import{w as V,x as q,y as J}from"./chunk-26BQ45XP.js";import K from"fs/promises";import E from"path";import j from"fast-glob";import{Minimatch as tt}from"minimatch";async function A(f,o,n=f,p=1){if(p>12)return[];let h=[],s;try{s=await K.readdir(f,{withFileTypes:!0})}catch{return[]}for(let t of s){let a=E.join(f,t.name),y=E.relative(n,a),L=y.split(E.sep).map(w=>w.toLowerCase()),O=t.name.toLowerCase();if(!o.some(w=>{let F=w.toLowerCase();return F.startsWith(".")&&O.endsWith(F)?!0:L.some(M=>M===F||M.startsWith(".pnpm"))}))if(t.isDirectory()){let w=await A(a,o,n,p+1);h=h.concat(w)}else t.isFile()&&h.push({fullPath:a,relativePath:y})}return h}function rt(f,o,n=1/0){if(f===o)return 0;if(f.length===0)return o.length;if(o.length===0)return f.length;if(Math.abs(f.length-o.length)>n)return n+1;let p=Array.from({length:o.length+1},(h,s)=>s);for(let h=1;h<=f.length;h++){let s=[h],t=h;for(let a=1;a<=o.length;a++){let y=f[h-1]===o[a-1]?0:1,L=Math.min(s[a-1]+1,p[a]+1,p[a-1]+y);s.push(L),L<t&&(t=L)}if(p=s,t>n)return n+1}return p[o.length]}function nt(f,o){if(!f||!o)return!1;let n=f.toLowerCase(),p=o.toLowerCase();if(n.includes(p))return!0;let h=n.split(/[^a-z0-9]+/).filter(t=>t.length>0),s=p.split(/[^a-z0-9]+/).filter(t=>t.length>1||p.length===1&&t.length>0);return s.length===0?!1:s.every(t=>{let a=t.length<=2?0:t.length<=5?1:2;for(let y of h)if(y.includes(t)||t.length>=3&&y.length>=3&&Math.abs(y.length-t.length)<=a&&rt(t,y,a)<=a)return!0;return!1})}var gt=async f=>{let{keyword:o,path:n,fuzzy:p,subString:h,regex:s}=Y(f);if(o==null)return'ERROR: Missing "keyword" argument.';let t=String(o);if(n){let e=n.trim().toLowerCase();if(e==="#docs"||e==="#doc"||e==="#documentation"||e.includes("#skill/global/fluxflow")||e.startsWith("#skill"))return"ERROR: Cannot search in reserved VFS '#skill' namespace. Use 'ReadFile' to read specific skills."}let a=e=>e===!0||e==="true"||e===1||e==="1"||e==="yes",y=s===!1||s==="false"||s===0||s==="0"||s==="no",L=s===!0||s==="true"||s===1||s==="1"||s==="yes",O=a(p)||a(h),G=null,w=null;if(y)O||(w=new RegExp(`(?<![\\w])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i"));else{try{G=new RegExp(t,"i")}catch(e){if(L)return`ERROR: Invalid regex pattern "${t}": ${e.message}`}w=new RegExp(`(?<![\\w])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w])`,"i")}let F=Array.from(new Set([...V,...q(process.cwd())])),M=150;try{let e=[],P=process.cwd(),u=null;if(n){let i=r=>r.startsWith("!")||!r.startsWith("-")?r:"!"+r.replace(/^-+/,""),g=n.split(";").map(r=>r.trim()).filter(Boolean).map(i).filter(r=>r!=="!"),c=g.some(r=>r.startsWith("!"));if(g.some(r=>j.isDynamicPattern(r)||/[*?{}[\]()|+]/.test(r))){u="glob";let r=n.replace(/\\/g,"/"),l=g.map(m=>m.replace(/\\/g,"/")),z=F.map(m=>m.startsWith(".")?`**/*${m}`:`**/${m}/**`);if(c&&!g.some(m=>!m.startsWith("!"))){let m=await A(P,F,P),R=$=>$.endsWith("/")?$+"**":$,d=l.filter($=>$.startsWith("!")).map($=>R($.slice(1))),v=l.filter($=>!$.startsWith("!")).map(R);e=m.filter($=>{let x=$.relativePath.replace(/\\/g,"/"),_=v.length===0||v.some(b=>{try{return new tt(b).match(x)}catch{return!1}}),Z=d.some(b=>{try{return new tt(b).match(x)}catch{return!1}});return _&&!Z})}else{let m=l.some(d=>/[\(\)\|]|\.\*/.test(d)),R=[];if(!m)try{R=await j(l,{cwd:P,ignore:z,dot:!0,onlyFiles:!0,absolute:!1})}catch{R=[]}if(R.length===0&&(m||j.isDynamicPattern(r))){let d=r.match(/^([^\*\?\(\)\|\[\]\s]+)\//),v=d&&!/[\*\?\(\)\|\[\]]/.test(d[1])?E.resolve(P,d[1]):P,$=await A(v,F,P);try{let x=r.replace(/^\.\//,"");x=x.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!x.startsWith("^")&&!x.startsWith(".*")&&(x=`.*${x}`);let _=new RegExp(x.endsWith("$")?x:`${x}$`,"i");e=$.filter(Z=>{let b=Z.relativePath.replace(/\\/g,"/");return _.test(b)})}catch{e=[]}}else e=R.map(d=>({fullPath:E.resolve(P,d),relativePath:d}))}}else{let r=[],l=!1,z=!1;for(let k of g){let m=k.replace(/[\/\\]+$/,""),R=E.resolve(P,m);try{let d=await K.stat(R);if(d.isDirectory()){z=!0;let v=await A(R,F,P);r.push(...v)}else if(d.isFile())l=!0,r.push({fullPath:R,relativePath:E.relative(P,R)});else return`ERROR: Path is neither a file nor a directory: ${k}`}catch{return`ERROR: Path not found: ${k}`}}e=r,l&&!z?u="file":u="dir"}}else e=await A(P,F);let et=e.map(async i=>{try{let g=await K.readFile(i.fullPath,"utf-8");if(g.includes("\0"))return[];let c=g.split(/\r?\n/),W=[];for(let l=0;l<c.length;l++)(O?c[l].toLowerCase().includes(t.toLowerCase())||nt(c[l],t):y?w&&w.test(c[l]):G&&G.test(c[l])||w&&w.test(c[l]))&&W.push({line:l+1,content:c[l].trim()});return W.length===0?null:{path:i.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),st=await Promise.all(et),S=[],D=0;for(let i of st){if(!i||!i.matches)continue;if(D>=M)break;let g=M-D,c=i.matches.slice(0,g);S.push({path:i.path,matches:c}),D+=c.length}typeof global.gc=="function"&&global.gc();let I=null;if(S.length===0){let i=u==="file"?` in '${n}'`:u==="dir"||u==="glob"?` in '${n}'`:". Try to specify files",g=u==="dir"?"[DIR]":u==="glob"?"[GLOB]":"";return`${g}${g?" ":""}Found 0 matches of '${t}'${i}${I?` ${I}`:""}`}let B=I?` ${I}`:"",T=`${S.length} file${S.length===1?"":"s"}`,U=`${D} match${D===1?"":"es"}`,N;u==="file"?N=`Found ${U} of '${t}' in '${n}'${B}:`:u==="dir"||u==="glob"?N=`Found ${U} of '${t}' in '${n}' across ${T}${B}:`:N=`Found ${U} of '${t}' across ${T}${B}:`;let X=u==="dir"?"[DIR]":u==="glob"?"[GLOB]":"",C=`${X}${X?" ":""}${N}
2
-
3
- `,H="";try{let i=await Q();i?.systemSettings?.alwaysAskFiles&&(H=i.systemSettings.alwaysAskFiles)}catch{}for(let i of S)if(C+=`${i.path}:
4
- `,J(i.path,H)){let c=i.matches.map(W=>`Line ${W.line}`).join(", ");C+=` ${c}. Line snapshot not available due to file restriction policy. ReadFile if needed
5
-
6
- `}else{for(let c of i.matches)C+=` Line ${c.line}: ${c.content}
7
- `;C+=`
8
- `}return C.trimEnd()}catch(e){return`ERROR: ${e.message}`}};export{gt as search_keyword};
@@ -1,13 +0,0 @@
1
- import{g as h,h as m,i as R}from"./chunk-TX3H7HDF.js";import{a as F}from"./chunk-6EYQQ7GQ.js";import{a as $}from"./chunk-Y5JU726N.js";import{b as g}from"./chunk-PACSPBDP.js";import"./chunk-HTOLY3HR.js";import"./chunk-P5HBJA23.js";import"./chunk-26BQ45XP.js";import c from"fs";import P from"path";var j=async(w,y={})=>{let n=$(w),t=n.path;if(!t)return'ERROR: Missing "path" argument for PatchFile.';let{patchPairs:o,allowMultiple:E,error:p}=h(n);if(p)return`ERROR: ${p}`;if(o.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let M=n.allowMultiple!==void 0?n.allowMultiple===!0||String(n.allowMultiple).toLowerCase()==="true":E,i=P.resolve(process.cwd(),t);try{if(!c.existsSync(i))return`ERROR: File [${t}] does not exist. Use WriteFile instead.`;let e=y.forcedContent||c.readFileSync(i,"utf8");e.startsWith("\uFEFF")&&(e=e.slice(1));let s=e.replace(/\r\n/g,`
2
- `).replace(/\r/g,`
3
- `),{content:u,results:l}=m(s,o,{allowMultiple:M}),a=l.filter(r=>!r.success),f=l.filter(r=>r.success);if(f.length===0)return`ERROR: Patch Failed to apply to [${t}].
4
- ${a.map(r=>` \u2022 ${r.error}`).join(`
5
- `)}`;await F.recordFileChange(i,s),c.writeFileSync(i,u,"utf8");let{systemSettings:C}=await g(),d=R(s,u,l,12,C?.compressToolResults);return a.length>0?`File [${t}] updated with some blocks failed. [${f.length}/${o.length}] blocks applied.
6
-
7
- Failures:
8
- ${a.map(r=>` \u2022 ${r.error}`).join(`
9
- `)}
10
-
11
- ${d}`:`File [${t}] updated. [${l.length}/${o.length}] blocks applied.
12
-
13
- ${d}`}catch(e){let s=e instanceof Error?e.message:String(e);return`ERROR: Failed to update file [${t}]: ${s}`}};export{j as update_file};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w}from"./chunk-T5CUPXCW.js";import"./chunk-PACSPBDP.js";import"./chunk-HTOLY3HR.js";import"./chunk-P5HBJA23.js";import"./chunk-26BQ45XP.js";export{n as addToUsage,c as calculateTokenCost,t as checkImageQuota,q as checkQuota,p as checkQuotaDetailed,e as forceFlushUsage,w as getAllUsageData,o as getCustomPeriodUsage,j as getDailyUsage,r as getImageQuotaBuckets,s as getImageQuotaLimit,u as getImageQuotaStats,k as getMonthlyUsage,h as getTimedUsage,l as incrementUsage,i as initUsage,d as invalidateCachedBaseUrl,g as purgeTimedUsage,v as recordImageGeneration,f as recordTimedUsage,m as runtimeSession,b as sendUsageFinalize,a as sendUsageHeartbeat};
@@ -1,32 +0,0 @@
1
- import{a as C}from"./chunk-6EYQQ7GQ.js";import{a as j}from"./chunk-Y5JU726N.js";import{b as w}from"./chunk-PACSPBDP.js";import"./chunk-HTOLY3HR.js";import"./chunk-P5HBJA23.js";import{c as F}from"./chunk-26BQ45XP.js";import e from"fs";import f from"path";var T=async(k,b={})=>{let{path:i,content:p}=j(k);if(!i)return'ERROR: Missing "path" argument for WriteFile.';if(p===void 0)return'ERROR: Missing "content" argument for WriteFile.';p=p.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
2
- `).replace(/\r/g,`
3
- `);let n=f.resolve(process.cwd(),i),y=f.dirname(n);try{await C.recordFileChange(n);let{systemSettings:r}=await w(),m=r?.overwriteProtection!==!1,a="";if(e.existsSync(n))try{let o=e.readFileSync(n,"utf8").split(/\r?\n/);if(!m)a="";else if(o.length<=50)a=`Old File contents:
4
- ${o.map((c,l)=>`${l+1} | ${c}`).join(`
5
- `)}
6
-
7
- `;else{let c=f.parse(n),l=f.join(F,"OverwriteBackups");e.existsSync(l)||e.mkdirSync(l,{recursive:!0});let O=`${c.name}-old-${Date.now()}${c.ext}.bak`,v=f.join(l,O);e.copyFileSync(n,v),a=`Old File contents:
8
- - Renamed old file as ${v} and written requested content in ${i}. For reversal use Run
9
-
10
- `}}catch{a=`[Note: Could not read existing file for reversal reference]
11
-
12
- `}e.existsSync(y)||e.mkdirSync(y,{recursive:!0});let $=(t=>t.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
13
- `).replace(/\r/g,`
14
- `))(p),d=$.endsWith(`
15
- `)?$:$+`
16
- `,E=d.split(/\r?\n/).length,x=Buffer.byteLength(d,"utf8");e.writeFileSync(n,d,"utf8");let u=e.readFileSync(n,"utf8"),S=Buffer.byteLength(u,"utf8"),s=u.split(/\r?\n/),g=s.length;if(S===0&&x>0)return u=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${i}] is empty on disk!`;let h="";if(g<=690)h=s.join(`
17
- `);else{let t=s.slice(0,300).join(`
18
- `),o=s.slice(-300).join(`
19
- `);h=`${t}
20
-
21
- ... [${g-100} lines truncated] ...
22
-
23
- ${o}`}u=null;let R=`File [${i}] saved.
24
- - Stats: [${g} lines, ${(S/1024).toFixed(1)} KB]
25
- ${a}- Content Preview:
26
-
27
- ${h}`;if(r?.compressToolResults&&g>6e3){let t=d.split(/\r?\n/),o=t.slice(0,25).join(`
28
- `)===s.slice(0,25).join(`
29
- `),c=t.slice(-25).join(`
30
- `)===s.slice(-25).join(`
31
- `);o&&c&&(R=`[[SAME]]
32
- ${R}`)}return R}catch(r){let m=r instanceof Error?r.message:String(r);return`ERROR: Failed to write file [${i}]: ${m}`}};export{T as write_file};