fluxflow-cli 4.49.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-33R46AFF.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-IMX3PWYO.js → chunk-GBH7XI5A.js} +1 -1
  14. package/dist/chunks/{chunk-ZCM4J7JT.js → chunk-J4J3F6BT.js} +1 -1
  15. package/dist/chunks/chunk-LQM3JK7N.js +1 -0
  16. package/dist/chunks/{chunk-AIWOSKP3.js → chunk-QESQR5GB.js} +1 -1
  17. package/dist/chunks/chunk-V36DXF56.js +13 -0
  18. package/dist/chunks/{chunk-TNA3R7TS.js → chunk-ZNO55RNG.js} +1 -1
  19. package/dist/chunks/{click-HMFVJIQN.js → click-AWHZCV2E.js} +2 -2
  20. package/dist/chunks/{computer_action-6AYM3W7D.js → computer_action-MO2JR2XH.js} +1 -1
  21. package/dist/chunks/{custom_openai-HY6EEQI2.js → custom_openai-K554R7Q5.js} +1 -1
  22. package/dist/chunks/{drag-H53TOSDP.js → drag-D2GVPIQB.js} +1 -1
  23. package/dist/chunks/{generate_image-JS7J4FLD.js → generate_image-45UQ6P2B.js} +1 -1
  24. package/dist/chunks/{invoke-WGWAIYZH.js → invoke-DVZUJJV3.js} +2 -2
  25. package/dist/chunks/{invokeSync-DCL3EMVV.js → invokeSync-NEZGW27B.js} +2 -2
  26. package/dist/chunks/{key_press-NF322TXF.js → key_press-AQNKL6UM.js} +1 -1
  27. package/dist/chunks/{keyboard_typing-OADL5LPA.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-NWY2XLYF.js → ollama-6WSZPCI5.js} +1 -1
  32. package/dist/chunks/{recapture_screen-IXVMQR5C.js → recapture_screen-PPXYK2YY.js} +1 -1
  33. package/dist/chunks/{screen_grid-DGIDOOQD.js → screen_grid-3RU324CV.js} +1 -1
  34. package/dist/chunks/{scroll-B3HCFDTS.js → scroll-TSU6MTGU.js} +1 -1
  35. package/dist/chunks/search_keyword-DZY4MWV7.js +8 -0
  36. package/dist/chunks/{secrets-NGDMM5RJ.js → secrets-TNMLVMST.js} +1 -1
  37. package/dist/chunks/{secrets_v2-R5GMXRT3.js → secrets_v2-OBRWR3UT.js} +1 -1
  38. package/dist/chunks/{settings-JME7GCEU.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-RJDE5QDZ.js → usageServer-RTK5N5KE.js} +1 -2
  42. package/dist/chunks/write_file-O6OF7Z2W.js +32 -0
  43. package/dist/cli.js +27 -24
  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-QEMKCYGG.js +0 -1
  49. package/dist/chunks/app-6TAUOS56.js +0 -333
  50. package/dist/chunks/chunk-2XQIWDKW.js +0 -1
  51. package/dist/chunks/chunk-2YDU2B2F.js +0 -13
  52. package/dist/chunks/chunk-36FKJWXK.js +0 -949
  53. package/dist/chunks/chunk-AMFNIFF3.js +0 -44
  54. package/dist/chunks/chunk-HTOLY3HR.js +0 -1
  55. package/dist/chunks/search_keyword-UXNKLCGC.js +0 -8
  56. package/dist/chunks/update_file-YXW37NRJ.js +0 -13
  57. package/dist/chunks/usage-URT2EC23.js +0 -1
  58. package/dist/chunks/write_file-WMLWKQKI.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:"",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-NGDMM5RJ.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-NGDMM5RJ.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-NGDMM5RJ.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-URT2EC23.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-2XQIWDKW.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};