fluxflow-cli 5.5.0 → 5.6.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 (48) hide show
  1. package/dist/chunks/{ai-6AZZQUJJ.js → ai-XPXVNDUQ.js} +1 -1
  2. package/dist/chunks/{apinex-COGJR7W4.js → apinex-BN3E62ML.js} +1 -1
  3. package/dist/chunks/{app-SKIGDYWL.js → app-PTS5SZLA.js} +168 -168
  4. package/dist/chunks/ask_user-RJTHGJNS.js +1 -0
  5. package/dist/chunks/{auto_completion-ZYVGXNQC.js → auto_completion-4ADVOCVI.js} +1 -1
  6. package/dist/chunks/chunk-3PZTWZTT.js +1 -0
  7. package/dist/chunks/chunk-3WV6FIZV.js +1 -0
  8. package/dist/chunks/{chunk-YI3O7C3D.js → chunk-BD6HA64O.js} +1 -1
  9. package/dist/chunks/{chunk-ZPSNXBWW.js → chunk-KTD4WQBO.js} +1 -1
  10. package/dist/chunks/{chunk-H2EXH5PL.js → chunk-KWSISKDF.js} +196 -198
  11. package/dist/chunks/{chunk-5MJKHQVE.js → chunk-KYIMFUZS.js} +1 -1
  12. package/dist/chunks/{chunk-5KBOEKGE.js → chunk-LTNOPF2E.js} +2 -2
  13. package/dist/chunks/chunk-MS7BITZ6.js +1 -0
  14. package/dist/chunks/{chunk-3SMC2C3F.js → chunk-QN4UHB5C.js} +1 -1
  15. package/dist/chunks/{click-M5D2RARW.js → click-R6CYDOMM.js} +2 -2
  16. package/dist/chunks/coarena-SGBBHWAP.js +2 -0
  17. package/dist/chunks/{computer_action-N7WIG3L4.js → computer_action-WRT67RP2.js} +1 -1
  18. package/dist/chunks/{custom_openai-JUCNWDKV.js → custom_openai-MM5T6QBQ.js} +1 -1
  19. package/dist/chunks/{drag-K5ITERVW.js → drag-4JO6XSNT.js} +1 -1
  20. package/dist/chunks/{exec_command-QBBSYF2H.js → exec_command-PIC3AFGH.js} +1 -1
  21. package/dist/chunks/{generate_image-53KQ3EDL.js → generate_image-NDIBDL5E.js} +1 -1
  22. package/dist/chunks/{infron-KCX7Z3RE.js → infron-4M36NBSA.js} +1 -1
  23. package/dist/chunks/{invoke-GUW4734N.js → invoke-ZLCJZ4KB.js} +2 -2
  24. package/dist/chunks/{invokeSync-2PXPUJSJ.js → invokeSync-FEPQMT4S.js} +2 -2
  25. package/dist/chunks/{key_press-RQ32VDHR.js → key_press-KJNHQOI7.js} +1 -1
  26. package/dist/chunks/{keyboard_typing-BH4JHUQO.js → keyboard_typing-M4UZB3TK.js} +1 -1
  27. package/dist/chunks/{ollama-BJHC4S6H.js → ollama-X7ARM2CC.js} +1 -1
  28. package/dist/chunks/recapture_screen-IYOK5JYN.js +1 -0
  29. package/dist/chunks/{screen_grid-Z5JHZZKA.js → screen_grid-PHZTVWOJ.js} +1 -1
  30. package/dist/chunks/{scroll-IQUZ3QLU.js → scroll-DXOBGF4W.js} +1 -1
  31. package/dist/chunks/{search_keyword-2JQ75HEQ.js → search_keyword-ZAEFTMSC.js} +1 -1
  32. package/dist/chunks/{secrets-OHIQHB63.js → secrets-6RUMHIWR.js} +1 -1
  33. package/dist/chunks/{secrets_v2-W4225MDM.js → secrets_v2-5NIKKQXX.js} +1 -1
  34. package/dist/chunks/{settings-Y7ODX5TH.js → settings-UL5E3OYC.js} +1 -1
  35. package/dist/chunks/{tokenharbor-2TAFOMPU.js → tokenharbor-KKGRGQXG.js} +1 -1
  36. package/dist/chunks/{update_file-2EZILIMQ.js → update_file-OD5V45KN.js} +1 -1
  37. package/dist/chunks/{usage-3CNTEZUA.js → usage-MKFPGZUK.js} +1 -1
  38. package/dist/chunks/{usageServer-7NPU35BP.js → usageServer-JFFFEUMY.js} +8 -2
  39. package/dist/chunks/{write_file-O3LLIRLR.js → write_file-AUCXXODD.js} +1 -1
  40. package/dist/chunks/{xkiro-GN4FCYYQ.js → xkiro-3R4IOLSP.js} +1 -1
  41. package/dist/cli.js +5 -5
  42. package/dist/package.json +1 -1
  43. package/package.json +1 -1
  44. package/dist/chunks/ask_user-4KTNP4MZ.js +0 -1
  45. package/dist/chunks/chunk-3HGLLXBK.js +0 -1
  46. package/dist/chunks/chunk-IWIVGFAT.js +0 -1
  47. package/dist/chunks/chunk-KQNW7DK5.js +0 -1
  48. package/dist/chunks/recapture_screen-YJNK64KL.js +0 -1
@@ -1,4 +1,4 @@
1
- import{b as z}from"./chunk-KQNW7DK5.js";import{q as ht}from"./chunk-Y6O7SAPD.js";import{a as ft,b as W}from"./chunk-ZGORMZE5.js";import{d as J,h as Z,i as M,j as b}from"./chunk-NPXJIGAI.js";import S from"fs-extra";import U from"path";import Ft from"http";import N from"fs-extra";import et from"path";import{spawn as Rt}from"child_process";import{fileURLToPath as Ut}from"url";var $=52991,Ot=15e3,gt=et.join(J,"usage","usage_error.txt"),pt=async(e,t)=>{let o=t?.stack||t?.message||String(t);console.error(`[Usage Daemon Error] [${e}]:`,t);try{await N.ensureDir(et.dirname(gt));let s=`[${new Date().toISOString()}] [Daemon:${e}] ${o}
1
+ import{b as z}from"./chunk-MS7BITZ6.js";import{q as ht}from"./chunk-Y6O7SAPD.js";import{a as ft,b as W}from"./chunk-ZGORMZE5.js";import{d as J,h as Z,i as M,j as b}from"./chunk-NPXJIGAI.js";import S from"fs-extra";import U from"path";import Ft from"http";import N from"fs-extra";import et from"path";import{spawn as Rt}from"child_process";import{fileURLToPath as Ut}from"url";var $=52991,Ot=15e3,gt=et.join(J,"usage","usage_error.txt"),pt=async(e,t)=>{let o=t?.stack||t?.message||String(t);console.error(`[Usage Daemon Error] [${e}]:`,t);try{await N.ensureDir(et.dirname(gt));let s=`[${new Date().toISOString()}] [Daemon:${e}] ${o}
2
2
  -------------------------------------
3
3
 
4
4
  `;await N.appendFile(gt,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 At(){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 pt("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 It(e=$){let t=await At(),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=ft(JSON.stringify(t,null,2));await N.writeFile(M,a,"utf8"),i=!1}catch(l){await pt("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>Ot&&await r()},5e3),n.unref&&n.unref();let m=Ft.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",g=>{d+=g}),l.on("end",async()=>{try{let g=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}=g;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(g){a.writeHead(400,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:g.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 Et(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=Ut(import.meta.url);Rt(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 Et(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 Nt(e=$){try{await fetch(`http://127.0.0.1:${e}/heartbeat`,{method:"POST",signal:AbortSignal.timeout(600)})}catch{}}async function $t(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):$;It(t)}var yt=U.join(J,"usage","usage_error.txt"),H=new Map,Pt=(e,t)=>{let o=`${e}:${t}`;if(H.has(o))return H.get(o);try{let i=kt();if(S.existsSync(i)){let n=S.readFileSync(i,"utf8").split(`
@@ -22,11 +22,11 @@ Default to using subagents whenever helpful, no user nudge needed
22
22
  Invocations:
23
23
  \u2022 Invoke, async/background, \u22647 parallel. Parallelize tasks
24
24
  \u2022 InvokeSync, sync/blocking. Sequential, repetitive or delegated tasks
25
- - InvokeSync/Invoke(title=string, task=string, id?=string). task: detailed steps & file paths. id: unique=new subagent, existing=resume subagent
25
+ - InvokeSync/Invoke(title=string, task=string, id?=string). task: detailed steps & file paths. id: unique=new, existing=resume subagent
26
26
  - Await(id=string, timeout?=int[..180])
27
27
  - GetProgress(id=string). Poll sparingly; Work or await
28
28
  - Steer(id=string, message=string). Inject additional instruction into active async subagent
29
- - Cancel(id=string). Cancel async task ONLY if stalled for 2m+ or incorrect`:""}`,S=`**Creative Actions (path = relative; first argument, path separator: '/')**
29
+ - Cancel(id=string). Cancel async task ONLY if stalled or incorrect`:""}`,S=`**Creative Actions (path = relative; first argument, path separator: '/')**
30
30
  - WritePDF(path=string, content=string, orientation="landscape/portrait"). Proactive A4 page breaks must in css. HTML/CSS for premium layout, stable margins & headers/footers, no watermarks
31
31
  - WriteDoc(path=string, content=string). A4 Word document, no watermarks, stable margins & headers/footers`,m=`**Computer Use (Desktop Automation)**
32
32
  - Click(gridId=int, type="single/double", button="left/middle/right", intendedClickText?=string, ocrCorrection=bool). Click target grid number, intendedClickText: literal text on screen (OCR scannable, upto 3 words). Double click desktop icons, clicking text? set ocrCorrection=true
@@ -0,0 +1 @@
1
+ import{e as m,f as c}from"./chunk-ZGORMZE5.js";import{b as s}from"./chunk-NPXJIGAI.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",CoArena:"Free",c_openai:"Free"}},systemSettings:{customOpenAIBaseUrl:"",memory:!1,theme:"Dark",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",CoArena:"https://coarena.ai/api/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-6RUMHIWR.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-6RUMHIWR.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-4NQOSFLK.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-6RUMHIWR.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-MKFPGZUK.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};
@@ -2,4 +2,4 @@ import{screen as j}from"@nut-tree-fork/nut-js";import P from"screenshot-desktop"
2
2
  <rect x="${p+1}" y="${o+1}" width="${i-2}" height="${c-2}" fill="rgba(0, 255, 255, 0.015)" stroke="rgba(255, 255, 0, 0.3)" stroke-width="1.1" rx="2"/>
3
3
  `;let w=s.some(t=>t!==a&&t.startY+t.cellH>=o-6&&t.startY<o&&Math.max(0,Math.min(p+i,t.startX+t.cellW)-Math.max(p,t.startX))>10),C=s.some(t=>t!==a&&t.startY<=o+c+6&&t.startY>o&&Math.max(0,Math.min(p+i,t.startX+t.cellW)-Math.max(p,t.startX))>10),g;if(a.isCustomY)g=u,!w&&g<o+11&&(g=Math.max(10,Math.min(g,o+4)));else{let t=a.yOffset!==void 0?a.yOffset:3;!w&&t<0&&(t=Math.min(t,-12));let Y=u+t,I=!w&&(t<0||Y<o+11)?Math.max(10,o+4):o+11,S=!C&&(t>0||Y>o+c-2)?Math.min(n-2,o+c+6):o+c+3;g=Math.max(I,Math.min(S,Y))}x+=`
4
4
  <text x="${r}" y="${g}" font-family="'Segoe UI', Roboto, sans-serif" font-size="14" font-weight="600" fill="#FFFF00" stroke="#000000" stroke-width="2" paint-order="stroke fill" stroke-linejoin="round" opacity="0.8" text-anchor="middle">${M}</text>
5
- `}return`<svg width="${e}" height="${n}" xmlns="http://www.w3.org/2000/svg">${x}</svg>`}var ot=1,J=e=>new Promise(n=>setTimeout(n,e));async function st(){try{let{loadSettings:e}=await import("./settings-Y7ODX5TH.js"),n=await e();return Number(n.display||0)}catch{return 0}}async function at(){let e=await st();try{let n=await P.listDisplays();if(n&&n.length>0)return{format:"png",screen:(n[e]||n[0]).id}}catch{}return{format:"png"}}async function it(){let e=0,n=await at();for(;e<2;){let f=await P(n);await J(500);let m=await P(n);if(f.equals(m))return m;e++,e<2&&await J(3e3)}return await J(3e3),await P(n)}function ft(e=[],n=[]){if(!e||e.length===0)return n||[];if(!n||n.length===0)return e;let f=[...e],m=typeof e.getModelConfidence=="function"?e.getModelConfidence.bind(e):null;for(let s of n){if(m&&m(s.startX,s.startY,s.cellW,s.cellH)<.01)continue;let h=s.startX,y=s.startX+s.cellW,x=s.startY,a=s.startY+s.cellH;for(let M of e){let w=M.startX,C=M.startY,g=M.startX+M.cellW,t=M.startY+M.cellH;if(Math.max(0,Math.min(a,t)-Math.max(x,C))>s.cellH*.4&&w<y&&g>h){let I=(w+g)/2,S=(h+y)/2;I<=S?h=Math.max(h,g):y=Math.min(y,w)}}let l=y-h;if(l<18)continue;let d=h,p=x,o=y,i=a,c=Math.floor(h+l/2),r=s.cy,u=!1;for(let M of e){let w=M.startX,C=M.startY,g=M.startX+M.cellW,t=M.startY+M.cellH;if(c>=w&&c<=g&&r>=C&&r<=t){u=!0;break}let Y=Math.max(d,w),I=Math.max(p,C),S=Math.min(o,g),G=Math.min(i,t),X=Math.max(0,S-Y)*Math.max(0,G-I),T=(o-d)*(i-p);if(X/(T||1)>=.25){u=!0;break}}u||f.push({...s,startX:d,cellW:l,cx:c})}return f.sort((s,h)=>Math.abs(s.startY-h.startY)>18?s.startY-h.startY:s.startX-h.startX),f.forEach((s,h)=>{s.badgeId=h+1}),f}function ht(e,n,f,m){let s=e/f,h=n/m,y="";for(let a=0;a<=f;a++){let l=a*s;y+=`<line x1="${l}" y1="0" x2="${l}" y2="${n}" stroke="rgba(255, 255, 255, 0.28)" stroke-width="1.2"/>`}for(let a=0;a<=m;a++){let l=a*h;y+=`<line x1="0" y1="${l}" x2="${e}" y2="${l}" stroke="rgba(255, 255, 255, 0.28)" stroke-width="1.2"/>`}let x=1;for(let a=0;a<m;a++)for(let l=0;l<f;l++){let d=Math.floor(l*s+s/2),p=Math.floor(a*h+h/2)+5;y+=`<text x="${d}" y="${p}" font-family="'Segoe UI', Roboto, sans-serif" font-size="14" font-weight="700" fill="#FFFF00" stroke="#000000" stroke-width="2" paint-order="stroke fill" stroke-linejoin="round" opacity="0.95" text-anchor="middle">${x}</text>`,x++}return`<svg width="${e}" height="${n}" xmlns="http://www.w3.org/2000/svg">${y}</svg>`}async function pt(e={}){let n=typeof e=="boolean"?e:e?.canvasMode===!0||e?.canvas_mode===!0;try{let f=await it(),m=null,s="";if(n){U=!0;let d=q.COLS,p=q.ROWS,o=H.TARGET_WIDTH/d,i=H.TARGET_HEIGHT/p,c=[],r=1;for(let u=0;u<p;u++)for(let M=0;M<d;M++){let w=Math.floor(M*o),C=Math.floor(u*i);c.push({badgeId:r,cellNum:r,startX:w,startY:C,cellW:o,cellH:i,cx:Math.floor(w+o/2),cy:Math.floor(C+i/2)}),r++}_=c,m=c,s=ht(H.TARGET_WIDTH,H.TARGET_HEIGHT,d,p)}else{if(U=!1,rt){let d=(async()=>{try{let{detectUIBoxesONNX:p}=await import("./ui_detector_onnx-XRKXFWLG.js");return await p(f,H.TARGET_WIDTH,H.TARGET_HEIGHT)}catch{return null}})();if(lt)m=await d||[];else{let p=Z(f,!0),[o,i]=await Promise.all([d,p]);m=o&&o.length>0?ft(o,i):await Z(f,!1)}}else m=await Z(f,!1);_=m,s=ct(H.TARGET_WIDTH,H.TARGET_HEIGHT,H.COLS,H.ROWS,m)}let h=await K(f).resize(H.TARGET_WIDTH,H.TARGET_HEIGHT,{fit:"fill"}).composite([{input:Buffer.from(s),top:0,left:0}]).png({quality:100}).toBuffer();if(process.env.SHOW_DEBUG_GRID)try{let d=et.resolve(process.cwd(),"screenshots");await tt.ensureDir(d);let p=et.join(d,`${ot}.png`);await tt.writeFile(p,h),ot++}catch{}let y=h.toString("base64"),x=m?m.length:0,a=f,l=h;return a=null,l=null,{base64:y,mimeType:"image/png",width:H.TARGET_WIDTH,height:H.TARGET_HEIGHT,detectedCount:x}}catch(f){return console.error("Failed to capture gridded screenshot:",f),null}}function ut(e){if(e==null)return null;let n=null;if(typeof e=="number")n=e;else if(typeof e=="string"){let o=e.trim();if(/^\d+$/.test(o))n=parseInt(o,10);else{let i=o.match(/^([A-Z])([0-9]{1,2})$/i);if(i){let c=i[1].toUpperCase().charCodeAt(0)-65,r=parseInt(i[2],10)-1;n=c*H.COLS+r+1}}}if(n===null||isNaN(n))return null;if(_&&_.length>0){let o=_.find(i=>i.badgeId===n)||_.find(i=>i.cellNum===n);if(o){let i=U?q.COLS:H.COLS,c=o.col!==void 0?o.col:Math.floor((o.cellNum-1)%i),r=o.row!==void 0?o.row:Math.floor((o.cellNum-1)/i);return{x:o.cx,y:o.cy,colIdx:c>=0?c:0,rowIdx:r>=0?r:0,cellNum:n}}}let f=U?q.COLS:H.COLS,m=U?q.ROWS:H.ROWS,s=f*m;if(n<1||n>s)return null;let h=n-1,y=Math.floor(h/f),x=h%f,a=H.TARGET_WIDTH/f,l=H.TARGET_HEIGHT/m,d=Math.floor(x*a+a/2),p=Math.floor(y*l+l/2);return{x:d,y:p,colIdx:x,rowIdx:y,cellNum:n}}async function gt(e,n,f){let m=null;if(typeof e=="number"||typeof e=="string"?m=ut(e):e&&typeof e.x=="number"&&typeof e.y=="number"&&(m=e),!m)return null;let s=n,h=f,y=0,x=0,a=await st();try{let i=await P.listDisplays();if(i&&i.length>0){let c=i[a]||i[0];c.width&&c.height&&(s=c.width,h=c.height),c.left!==void 0&&(y=c.left),c.top!==void 0&&(x=c.top)}}catch{}if(!s||!h)try{let i=await P({}),c=await K(i).metadata();c&&c.width&&c.height?(s=c.width,h=c.height):(s=await j.width(),h=await j.height())}catch{(!s||!h)&&(s=await j.width(),h=await j.height())}let l=s/H.TARGET_WIDTH,d=h/H.TARGET_HEIGHT,p=Math.round(m.x*l)+y,o=Math.round(m.y*d)+x;return{x:p,y:o,screenW:s,screenH:h,offsetX:y,offsetY:x}}function wt(e){if(!e||typeof e.x!="number"||typeof e.y!="number")return null;if(_&&_.length>0){let x=_.find(d=>e.x>=d.startX&&e.x<=d.startX+d.cellW&&e.y>=d.startY&&e.y<=d.startY+d.cellH);if(x)return x.badgeId!==void 0?x.badgeId:x.cellNum;let a=null,l=1/0;for(let d of _){let p=e.x-d.cx,o=e.y-d.cy,i=p*p+o*o;i<l&&(l=i,a=d)}if(a&&l<=2025)return a.badgeId!==void 0?a.badgeId:a.cellNum}let n=U?q.COLS:H.COLS,f=U?q.ROWS:H.ROWS,m=H.TARGET_WIDTH/n,s=H.TARGET_HEIGHT/f,h=Math.max(0,Math.min(n-1,Math.floor(e.x/m)));return Math.max(0,Math.min(f-1,Math.floor(e.y/s)))*n+h+1}export{H as a,q as b,rt as c,lt as d,st as e,pt as f,ut as g,gt as h,wt as i};
5
+ `}return`<svg width="${e}" height="${n}" xmlns="http://www.w3.org/2000/svg">${x}</svg>`}var ot=1,J=e=>new Promise(n=>setTimeout(n,e));async function st(){try{let{loadSettings:e}=await import("./settings-UL5E3OYC.js"),n=await e();return Number(n.display||0)}catch{return 0}}async function at(){let e=await st();try{let n=await P.listDisplays();if(n&&n.length>0)return{format:"png",screen:(n[e]||n[0]).id}}catch{}return{format:"png"}}async function it(){let e=0,n=await at();for(;e<2;){let f=await P(n);await J(500);let m=await P(n);if(f.equals(m))return m;e++,e<2&&await J(3e3)}return await J(3e3),await P(n)}function ft(e=[],n=[]){if(!e||e.length===0)return n||[];if(!n||n.length===0)return e;let f=[...e],m=typeof e.getModelConfidence=="function"?e.getModelConfidence.bind(e):null;for(let s of n){if(m&&m(s.startX,s.startY,s.cellW,s.cellH)<.01)continue;let h=s.startX,y=s.startX+s.cellW,x=s.startY,a=s.startY+s.cellH;for(let M of e){let w=M.startX,C=M.startY,g=M.startX+M.cellW,t=M.startY+M.cellH;if(Math.max(0,Math.min(a,t)-Math.max(x,C))>s.cellH*.4&&w<y&&g>h){let I=(w+g)/2,S=(h+y)/2;I<=S?h=Math.max(h,g):y=Math.min(y,w)}}let l=y-h;if(l<18)continue;let d=h,p=x,o=y,i=a,c=Math.floor(h+l/2),r=s.cy,u=!1;for(let M of e){let w=M.startX,C=M.startY,g=M.startX+M.cellW,t=M.startY+M.cellH;if(c>=w&&c<=g&&r>=C&&r<=t){u=!0;break}let Y=Math.max(d,w),I=Math.max(p,C),S=Math.min(o,g),G=Math.min(i,t),X=Math.max(0,S-Y)*Math.max(0,G-I),T=(o-d)*(i-p);if(X/(T||1)>=.25){u=!0;break}}u||f.push({...s,startX:d,cellW:l,cx:c})}return f.sort((s,h)=>Math.abs(s.startY-h.startY)>18?s.startY-h.startY:s.startX-h.startX),f.forEach((s,h)=>{s.badgeId=h+1}),f}function ht(e,n,f,m){let s=e/f,h=n/m,y="";for(let a=0;a<=f;a++){let l=a*s;y+=`<line x1="${l}" y1="0" x2="${l}" y2="${n}" stroke="rgba(255, 255, 255, 0.28)" stroke-width="1.2"/>`}for(let a=0;a<=m;a++){let l=a*h;y+=`<line x1="0" y1="${l}" x2="${e}" y2="${l}" stroke="rgba(255, 255, 255, 0.28)" stroke-width="1.2"/>`}let x=1;for(let a=0;a<m;a++)for(let l=0;l<f;l++){let d=Math.floor(l*s+s/2),p=Math.floor(a*h+h/2)+5;y+=`<text x="${d}" y="${p}" font-family="'Segoe UI', Roboto, sans-serif" font-size="14" font-weight="700" fill="#FFFF00" stroke="#000000" stroke-width="2" paint-order="stroke fill" stroke-linejoin="round" opacity="0.95" text-anchor="middle">${x}</text>`,x++}return`<svg width="${e}" height="${n}" xmlns="http://www.w3.org/2000/svg">${y}</svg>`}async function pt(e={}){let n=typeof e=="boolean"?e:e?.canvasMode===!0||e?.canvas_mode===!0;try{let f=await it(),m=null,s="";if(n){U=!0;let d=q.COLS,p=q.ROWS,o=H.TARGET_WIDTH/d,i=H.TARGET_HEIGHT/p,c=[],r=1;for(let u=0;u<p;u++)for(let M=0;M<d;M++){let w=Math.floor(M*o),C=Math.floor(u*i);c.push({badgeId:r,cellNum:r,startX:w,startY:C,cellW:o,cellH:i,cx:Math.floor(w+o/2),cy:Math.floor(C+i/2)}),r++}_=c,m=c,s=ht(H.TARGET_WIDTH,H.TARGET_HEIGHT,d,p)}else{if(U=!1,rt){let d=(async()=>{try{let{detectUIBoxesONNX:p}=await import("./ui_detector_onnx-XRKXFWLG.js");return await p(f,H.TARGET_WIDTH,H.TARGET_HEIGHT)}catch{return null}})();if(lt)m=await d||[];else{let p=Z(f,!0),[o,i]=await Promise.all([d,p]);m=o&&o.length>0?ft(o,i):await Z(f,!1)}}else m=await Z(f,!1);_=m,s=ct(H.TARGET_WIDTH,H.TARGET_HEIGHT,H.COLS,H.ROWS,m)}let h=await K(f).resize(H.TARGET_WIDTH,H.TARGET_HEIGHT,{fit:"fill"}).composite([{input:Buffer.from(s),top:0,left:0}]).png({quality:100}).toBuffer();if(process.env.SHOW_DEBUG_GRID)try{let d=et.resolve(process.cwd(),"screenshots");await tt.ensureDir(d);let p=et.join(d,`${ot}.png`);await tt.writeFile(p,h),ot++}catch{}let y=h.toString("base64"),x=m?m.length:0,a=f,l=h;return a=null,l=null,{base64:y,mimeType:"image/png",width:H.TARGET_WIDTH,height:H.TARGET_HEIGHT,detectedCount:x}}catch(f){return console.error("Failed to capture gridded screenshot:",f),null}}function ut(e){if(e==null)return null;let n=null;if(typeof e=="number")n=e;else if(typeof e=="string"){let o=e.trim();if(/^\d+$/.test(o))n=parseInt(o,10);else{let i=o.match(/^([A-Z])([0-9]{1,2})$/i);if(i){let c=i[1].toUpperCase().charCodeAt(0)-65,r=parseInt(i[2],10)-1;n=c*H.COLS+r+1}}}if(n===null||isNaN(n))return null;if(_&&_.length>0){let o=_.find(i=>i.badgeId===n)||_.find(i=>i.cellNum===n);if(o){let i=U?q.COLS:H.COLS,c=o.col!==void 0?o.col:Math.floor((o.cellNum-1)%i),r=o.row!==void 0?o.row:Math.floor((o.cellNum-1)/i);return{x:o.cx,y:o.cy,colIdx:c>=0?c:0,rowIdx:r>=0?r:0,cellNum:n}}}let f=U?q.COLS:H.COLS,m=U?q.ROWS:H.ROWS,s=f*m;if(n<1||n>s)return null;let h=n-1,y=Math.floor(h/f),x=h%f,a=H.TARGET_WIDTH/f,l=H.TARGET_HEIGHT/m,d=Math.floor(x*a+a/2),p=Math.floor(y*l+l/2);return{x:d,y:p,colIdx:x,rowIdx:y,cellNum:n}}async function gt(e,n,f){let m=null;if(typeof e=="number"||typeof e=="string"?m=ut(e):e&&typeof e.x=="number"&&typeof e.y=="number"&&(m=e),!m)return null;let s=n,h=f,y=0,x=0,a=await st();try{let i=await P.listDisplays();if(i&&i.length>0){let c=i[a]||i[0];c.width&&c.height&&(s=c.width,h=c.height),c.left!==void 0&&(y=c.left),c.top!==void 0&&(x=c.top)}}catch{}if(!s||!h)try{let i=await P({}),c=await K(i).metadata();c&&c.width&&c.height?(s=c.width,h=c.height):(s=await j.width(),h=await j.height())}catch{(!s||!h)&&(s=await j.width(),h=await j.height())}let l=s/H.TARGET_WIDTH,d=h/H.TARGET_HEIGHT,p=Math.round(m.x*l)+y,o=Math.round(m.y*d)+x;return{x:p,y:o,screenW:s,screenH:h,offsetX:y,offsetY:x}}function wt(e){if(!e||typeof e.x!="number"||typeof e.y!="number")return null;if(_&&_.length>0){let x=_.find(d=>e.x>=d.startX&&e.x<=d.startX+d.cellW&&e.y>=d.startY&&e.y<=d.startY+d.cellH);if(x)return x.badgeId!==void 0?x.badgeId:x.cellNum;let a=null,l=1/0;for(let d of _){let p=e.x-d.cx,o=e.y-d.cy,i=p*p+o*o;i<l&&(l=i,a=d)}if(a&&l<=2025)return a.badgeId!==void 0?a.badgeId:a.cellNum}let n=U?q.COLS:H.COLS,f=U?q.ROWS:H.ROWS,m=H.TARGET_WIDTH/n,s=H.TARGET_HEIGHT/f,h=Math.max(0,Math.min(n-1,Math.floor(e.x/m)));return Math.max(0,Math.min(f-1,Math.floor(e.y/s)))*n+h+1}export{H as a,q as b,rt as c,lt as d,st as e,pt as f,ut as g,gt as h,wt as i};
@@ -1,2 +1,2 @@
1
- import{a as W}from"./chunk-ZPSNXBWW.js";import{g as B,i as S}from"./chunk-3SMC2C3F.js";import{a as P}from"./chunk-JWNCKRN6.js";import X from"screenshot-desktop";import O from"sharp";import j from"fs-extra";import G from"path";import"@nut-tree-fork/nut-js";async function U(t,o,e){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let s=G.resolve(process.cwd(),"screenshots",t);await j.ensureDir(s),await j.writeFile(G.join(s,o),e)}catch{}}function K(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q(t,o,e=1/0){if(t===o)return 0;if(t.length===0)return o.length;if(o.length===0)return t.length;if(Math.abs(t.length-o.length)>e)return e+1;let s=Array.from({length:o.length+1},(r,i)=>i);for(let r=1;r<=t.length;r++){let i=[r],a=r;for(let n=1;n<=o.length;n++){let c=t[r-1]===o[n-1]?0:1,l=Math.min(i[n-1]+1,s[n]+1,s[n-1]+c);i.push(l),l<a&&(a=l)}if(s=i,a>e)return e+1}return s[o.length]}function V(t){return t<=4?0:t<=8?1:2}async function H(t,o=3){let e=await O(t).metadata();return O(t).resize(Math.round(e.width*o),Math.round(e.height*o),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Y(t){if(!t)return{words:[],lines:[]};let o=[],e=new Map;for(let r of t.split(`
2
- `)){let i=r.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let n=i[2],c=i[3],l=i[4],w=parseInt(i[6]),x=parseInt(i[7]),R=parseInt(i[8]),M=parseInt(i[9]),f=parseFloat(i[10]),h=i.slice(11).join(" ").trim();if(!h||f<0)continue;let p={x0:w,y0:x,x1:w+R,y1:x+M},g={text:h,confidence:f,bbox:p};o.push(g);let u=`${n}_${c}_${l}`;e.has(u)||e.set(u,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let d=e.get(u);d.words.push(g),d.bbox.x0=Math.min(d.bbox.x0,p.x0),d.bbox.y0=Math.min(d.bbox.y0,p.y0),d.bbox.x1=Math.max(d.bbox.x1,p.x1),d.bbox.y1=Math.max(d.bbox.y1,p.y1)}let s=[];for(let r of e.values())r.words.length>0&&s.push({text:r.words.map(i=>i.text).join(" "),bbox:r.bbox,words:r.words});return{words:o,lines:s}}function Z(t){if(!(t.words&&t.words.length>0)){if(t.blocks&&t.blocks.length>0){t.words=[],t.lines=[];for(let o of t.blocks)for(let e of o.paragraphs||[])for(let s of e.lines||[]){s.bbox&&t.lines.push(s);for(let r of s.words||[])r.bbox&&t.words.push(r)}if(t.words.length>0)return}if(t.tsv){let o=Y(t.tsv);t.words=o.words,t.lines=o.lines}}}function L(t,o,e=0,s=0,r=1){Z(t);let i=n=>({x0:Math.round(n.x0/r)+e,y0:Math.round(n.y0/r)+s,x1:Math.round(n.x1/r)+e,y1:Math.round(n.y1/r)+s}),a=[];if(t.lines&&t.lines.length>0)for(let n of t.lines){let c=n.text?n.text.toLowerCase().trim():"";if(!c||!n.bbox||!(c===o||new RegExp(`\\b${K(o)}\\b`,"i").test(c)))continue;let w=n.words||(t.words?t.words.filter(f=>f.bbox&&f.bbox.x0>=n.bbox.x0-5&&f.bbox.x1<=n.bbox.x1+5&&f.bbox.y0>=n.bbox.y0-5&&f.bbox.y1<=n.bbox.y1+5):[]),x=o.split(/\s+/),R=x.map(f=>f.replace(/[^a-z0-9]/g,"")).join(" "),M=!1;if(w.length>0)for(let f=0;f<=w.length-x.length;f++){let h=w.slice(f,f+x.length),p=h.map(g=>(g.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(p===R||p.includes(R)){let g={x0:Math.min(...h.map(u=>u.bbox.x0)),y0:Math.min(...h.map(u=>u.bbox.y0)),x1:Math.max(...h.map(u=>u.bbox.x1)),y1:Math.max(...h.map(u=>u.bbox.y1))};a.push(i(g)),M=!0}}M||a.push(i(n.bbox))}if(a.length===0&&t.words&&t.words.length>0)for(let n of t.words){let c=n.text?n.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",l=o.replace(/[^a-z0-9]/g,"");c===l&&n.bbox&&a.push(i(n.bbox))}if(a.length===0&&t.words&&t.words.length>0){let n=V(o.length);for(let c of t.words){let l=c.text?c.text.toLowerCase().trim():"";l.length>=3&&Math.abs(l.length-o.length)<=n&&Q(l,o,n)<=n&&c.bbox&&a.push(i(c.bbox))}}return a}function N(t,o){let e=null,s=1/0;for(let r of t){let i=Math.round((r.x0+r.x1)/2),a=Math.round((r.y0+r.y1)/2),n=o.x>=r.x0&&o.x<=r.x1&&o.y>=r.y0&&o.y<=r.y1,c=Math.hypot(i-o.x,a-o.y),l=n?0:c;l<s&&(s=l,e={x:i,y:a,dist:c,containsPoint:n,bbox:r})}return e}var $=null;async function tt(){return $||($=(async()=>{let{createWorker:t}=await import("tesseract.js"),o=await import("fs-extra"),{CU_CACHE_DIR:e}=await import("./paths-4NQOSFLK.js");return o.ensureDirSync(e),t("eng",1,{cachePath:e,logger:()=>{}})})().catch(t=>{throw $=null,t})),$}var I=null,F=null;async function et(){let{getActiveDisplay:t}=await import("./screen_grid-Z5JHZZKA.js"),o=await t();if(I&&F===o)return I;F=o,I={format:"png"};try{let e=await X.listDisplays();e&&e.length>0&&(I={format:"png",screen:(e[o]||e[0]).id})}catch{}return I}var pt=async(t,o={})=>{let e=P(t,["gridId","grid","coordinate","target","id","type","clickType","button","intendedClickText","text","ocrCorrection","useOCR","words","lines"]),s=e.gridId||e.grid||e.coordinate||e.target||e.id,r=(e.type||e.clickType||"single").toLowerCase(),i=(e.button||"left").toLowerCase(),a=e.intendedClickText||e.text||"",n=e.ocrCorrection!==void 0?e.ocrCorrection===!0||e.ocrCorrection==="true":e.useOCR!==void 0?e.useOCR===!0||e.useOCR==="true":!1;if(!s&&!a)return'ERROR: Missing required "gridId" parameter for Click tool.';let c=s;if(n&&a)try{let x=s?B(s):null,R=await et(),M=await X(R),f=await O(M).metadata(),h=f.width||1920,p=f.height||1080,g=x?{x:Math.round(x.x*(h/1280)),y:Math.round(x.y*(p/720))}:{x:h/2,y:p/2},u=a.toLowerCase().trim(),d=await tt(),C=null,T="",q=x?320:500;if(x){let y=Math.min(Math.round(h/2),h),m=Math.min(Math.round(p/2),p),b=Math.max(0,Math.min(h-y,g.x-Math.floor(y/2))),k=Math.max(0,Math.min(p-m,g.y-Math.floor(m/2))),D=await O(M).extract({left:b,top:k,width:y,height:m}).toBuffer(),z=2,A=await H(D,z),J=u.replace(/[^a-z0-9]/g,"_");await U("cropped",`crop_${Date.now()}_${J}.png`,A),await d.setParameters({tessedit_pageseg_mode:"11"});let{data:v}=await d.recognize(A,{},{tsv:!0,blocks:!0});if(v&&v.text){let E=L(v,u,b,k,z);if(E.length>0){let _=N(E,g);_&&(_.containsPoint||_.dist<=q)&&(C=_,T="centered target crop OCR")}}}if(!C){let y=await H(M,2),m=u.replace(/[^a-z0-9]/g,"_");await U("fullscreen",`full_${Date.now()}_${m}.png`,y),await d.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await d.recognize(y,{},{tsv:!0,blocks:!0});if(b&&b.text){let k=L(b,u,0,0,2);if(k.length>0){let D=N(k,g);D&&(C=D,T="full-screen OCR")}}}if(C){let y={x:Math.round(C.x*(1280/h)),y:Math.round(C.y*(720/p))},m=await W("click",y,{button:i,clickType:r});if(typeof m=="string"&&m.startsWith("ERROR:"))return m;let b=S(y),k=`${r==="double"?"Double":"Single"} clicked ${i} button`;return s&&b&&String(s)!==String(b)?`${k}. Tried clicking grid ${s}, but OCR corrected to grid ${b} (${T} for "${a}"). If the click landed unintended, try with ocr correction off.`:`${k} on grid ${b||s} (${T} for "${a}").`}}catch{}let l=await W("click",c,{button:i,clickType:r});if(typeof l=="string"&&l.startsWith("ERROR:"))return l;let w=s||(typeof c=="object"?S(c):c);return`${r==="double"?"Double":"Single"} clicked ${i} button on grid ${w}.`};export{pt as click};
1
+ import{a as W}from"./chunk-KTD4WQBO.js";import{g as B,i as S}from"./chunk-QN4UHB5C.js";import{a as P}from"./chunk-JWNCKRN6.js";import X from"screenshot-desktop";import O from"sharp";import j from"fs-extra";import G from"path";import"@nut-tree-fork/nut-js";async function U(t,o,e){if(!(!process.env.SHOW_DEBUG_GRID&&!process.env.DEBUG_OCR))try{let s=G.resolve(process.cwd(),"screenshots",t);await j.ensureDir(s),await j.writeFile(G.join(s,o),e)}catch{}}function K(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q(t,o,e=1/0){if(t===o)return 0;if(t.length===0)return o.length;if(o.length===0)return t.length;if(Math.abs(t.length-o.length)>e)return e+1;let s=Array.from({length:o.length+1},(r,i)=>i);for(let r=1;r<=t.length;r++){let i=[r],a=r;for(let n=1;n<=o.length;n++){let c=t[r-1]===o[n-1]?0:1,l=Math.min(i[n-1]+1,s[n]+1,s[n-1]+c);i.push(l),l<a&&(a=l)}if(s=i,a>e)return e+1}return s[o.length]}function V(t){return t<=4?0:t<=8?1:2}async function H(t,o=3){let e=await O(t).metadata();return O(t).resize(Math.round(e.width*o),Math.round(e.height*o),{kernel:"lanczos3"}).greyscale().normalise().toBuffer()}function Y(t){if(!t)return{words:[],lines:[]};let o=[],e=new Map;for(let r of t.split(`
2
+ `)){let i=r.split(" ");if(i.length<12||parseInt(i[0])!==5)continue;let n=i[2],c=i[3],l=i[4],w=parseInt(i[6]),x=parseInt(i[7]),R=parseInt(i[8]),M=parseInt(i[9]),f=parseFloat(i[10]),h=i.slice(11).join(" ").trim();if(!h||f<0)continue;let p={x0:w,y0:x,x1:w+R,y1:x+M},g={text:h,confidence:f,bbox:p};o.push(g);let u=`${n}_${c}_${l}`;e.has(u)||e.set(u,{words:[],bbox:{x0:1/0,y0:1/0,x1:-1/0,y1:-1/0}});let d=e.get(u);d.words.push(g),d.bbox.x0=Math.min(d.bbox.x0,p.x0),d.bbox.y0=Math.min(d.bbox.y0,p.y0),d.bbox.x1=Math.max(d.bbox.x1,p.x1),d.bbox.y1=Math.max(d.bbox.y1,p.y1)}let s=[];for(let r of e.values())r.words.length>0&&s.push({text:r.words.map(i=>i.text).join(" "),bbox:r.bbox,words:r.words});return{words:o,lines:s}}function Z(t){if(!(t.words&&t.words.length>0)){if(t.blocks&&t.blocks.length>0){t.words=[],t.lines=[];for(let o of t.blocks)for(let e of o.paragraphs||[])for(let s of e.lines||[]){s.bbox&&t.lines.push(s);for(let r of s.words||[])r.bbox&&t.words.push(r)}if(t.words.length>0)return}if(t.tsv){let o=Y(t.tsv);t.words=o.words,t.lines=o.lines}}}function L(t,o,e=0,s=0,r=1){Z(t);let i=n=>({x0:Math.round(n.x0/r)+e,y0:Math.round(n.y0/r)+s,x1:Math.round(n.x1/r)+e,y1:Math.round(n.y1/r)+s}),a=[];if(t.lines&&t.lines.length>0)for(let n of t.lines){let c=n.text?n.text.toLowerCase().trim():"";if(!c||!n.bbox||!(c===o||new RegExp(`\\b${K(o)}\\b`,"i").test(c)))continue;let w=n.words||(t.words?t.words.filter(f=>f.bbox&&f.bbox.x0>=n.bbox.x0-5&&f.bbox.x1<=n.bbox.x1+5&&f.bbox.y0>=n.bbox.y0-5&&f.bbox.y1<=n.bbox.y1+5):[]),x=o.split(/\s+/),R=x.map(f=>f.replace(/[^a-z0-9]/g,"")).join(" "),M=!1;if(w.length>0)for(let f=0;f<=w.length-x.length;f++){let h=w.slice(f,f+x.length),p=h.map(g=>(g.text||"").toLowerCase().trim().replace(/[^a-z0-9]/g,"")).join(" ");if(p===R||p.includes(R)){let g={x0:Math.min(...h.map(u=>u.bbox.x0)),y0:Math.min(...h.map(u=>u.bbox.y0)),x1:Math.max(...h.map(u=>u.bbox.x1)),y1:Math.max(...h.map(u=>u.bbox.y1))};a.push(i(g)),M=!0}}M||a.push(i(n.bbox))}if(a.length===0&&t.words&&t.words.length>0)for(let n of t.words){let c=n.text?n.text.toLowerCase().trim().replace(/[^a-z0-9]/g,""):"",l=o.replace(/[^a-z0-9]/g,"");c===l&&n.bbox&&a.push(i(n.bbox))}if(a.length===0&&t.words&&t.words.length>0){let n=V(o.length);for(let c of t.words){let l=c.text?c.text.toLowerCase().trim():"";l.length>=3&&Math.abs(l.length-o.length)<=n&&Q(l,o,n)<=n&&c.bbox&&a.push(i(c.bbox))}}return a}function N(t,o){let e=null,s=1/0;for(let r of t){let i=Math.round((r.x0+r.x1)/2),a=Math.round((r.y0+r.y1)/2),n=o.x>=r.x0&&o.x<=r.x1&&o.y>=r.y0&&o.y<=r.y1,c=Math.hypot(i-o.x,a-o.y),l=n?0:c;l<s&&(s=l,e={x:i,y:a,dist:c,containsPoint:n,bbox:r})}return e}var $=null;async function tt(){return $||($=(async()=>{let{createWorker:t}=await import("tesseract.js"),o=await import("fs-extra"),{CU_CACHE_DIR:e}=await import("./paths-4NQOSFLK.js");return o.ensureDirSync(e),t("eng",1,{cachePath:e,logger:()=>{}})})().catch(t=>{throw $=null,t})),$}var I=null,F=null;async function et(){let{getActiveDisplay:t}=await import("./screen_grid-PHZTVWOJ.js"),o=await t();if(I&&F===o)return I;F=o,I={format:"png"};try{let e=await X.listDisplays();e&&e.length>0&&(I={format:"png",screen:(e[o]||e[0]).id})}catch{}return I}var pt=async(t,o={})=>{let e=P(t,["gridId","grid","coordinate","target","id","type","clickType","button","intendedClickText","text","ocrCorrection","useOCR","words","lines"]),s=e.gridId||e.grid||e.coordinate||e.target||e.id,r=(e.type||e.clickType||"single").toLowerCase(),i=(e.button||"left").toLowerCase(),a=e.intendedClickText||e.text||"",n=e.ocrCorrection!==void 0?e.ocrCorrection===!0||e.ocrCorrection==="true":e.useOCR!==void 0?e.useOCR===!0||e.useOCR==="true":!1;if(!s&&!a)return'ERROR: Missing required "gridId" parameter for Click tool.';let c=s;if(n&&a)try{let x=s?B(s):null,R=await et(),M=await X(R),f=await O(M).metadata(),h=f.width||1920,p=f.height||1080,g=x?{x:Math.round(x.x*(h/1280)),y:Math.round(x.y*(p/720))}:{x:h/2,y:p/2},u=a.toLowerCase().trim(),d=await tt(),C=null,T="",q=x?320:500;if(x){let y=Math.min(Math.round(h/2),h),m=Math.min(Math.round(p/2),p),b=Math.max(0,Math.min(h-y,g.x-Math.floor(y/2))),k=Math.max(0,Math.min(p-m,g.y-Math.floor(m/2))),D=await O(M).extract({left:b,top:k,width:y,height:m}).toBuffer(),z=2,A=await H(D,z),J=u.replace(/[^a-z0-9]/g,"_");await U("cropped",`crop_${Date.now()}_${J}.png`,A),await d.setParameters({tessedit_pageseg_mode:"11"});let{data:v}=await d.recognize(A,{},{tsv:!0,blocks:!0});if(v&&v.text){let E=L(v,u,b,k,z);if(E.length>0){let _=N(E,g);_&&(_.containsPoint||_.dist<=q)&&(C=_,T="centered target crop OCR")}}}if(!C){let y=await H(M,2),m=u.replace(/[^a-z0-9]/g,"_");await U("fullscreen",`full_${Date.now()}_${m}.png`,y),await d.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await d.recognize(y,{},{tsv:!0,blocks:!0});if(b&&b.text){let k=L(b,u,0,0,2);if(k.length>0){let D=N(k,g);D&&(C=D,T="full-screen OCR")}}}if(C){let y={x:Math.round(C.x*(1280/h)),y:Math.round(C.y*(720/p))},m=await W("click",y,{button:i,clickType:r});if(typeof m=="string"&&m.startsWith("ERROR:"))return m;let b=S(y),k=`${r==="double"?"Double":"Single"} clicked ${i} button`;return s&&b&&String(s)!==String(b)?`${k}. Tried clicking grid ${s}, but OCR corrected to grid ${b} (${T} for "${a}"). If the click landed unintended, try with ocr correction off.`:`${k} on grid ${b||s} (${T} for "${a}").`}}catch{}let l=await W("click",c,{button:i,clickType:r});if(typeof l=="string"&&l.startsWith("ERROR:"))return l;let w=s||(typeof c=="object"?S(c):c);return`${r==="double"?"Double":"Single"} clicked ${i} button on grid ${w}.`};export{pt as click};
@@ -0,0 +1,2 @@
1
+ import{a as C}from"./chunk-PTFCY2D5.js";import{a as k}from"./chunk-UM5SNZ6X.js";import"./chunk-NPXJIGAI.js";var H=async function*(E,y,M,x,w,$,b,N,O=1){let p=[];x&&p.push({role:"system",content:x});for(let o of M){let h=o.role==="user"?"user":"assistant",e=[];if(Array.isArray(o.parts)){for(let a of o.parts)if(a.text)e.push({type:"text",text:a.text});else if(a.inlineData&&b){let s=a.inlineData.mimeType,l=a.inlineData.data;s.startsWith("image/")&&e.push({type:"image_url",image_url:{url:`data:${s};base64,${l}`}})}}else{let a=o.text||"";a&&e.push({type:"text",text:a})}p.push({role:h,content:e.length===1&&e[0].type==="text"?e[0].text:e})}let _=k("CoArena",y,w),A=_!==null?_:{Fast:"low",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"xhigh"}[w],D={model:y,messages:p,stream:!0,stream_options:{include_usage:!0},temperature:O,tools:[],tool_choice:"none"};A&&(D.reasoning_effort=A);let F=process.env.COARENA_URL||"https://coarena.ai/api/v1/chat/completions",T={"Content-Type":"application/json","X-Title":"FluxFlow","User-Agent":"FluxFlow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},S=E||process.env.COARENA_API_KEY||"";T.Authorization=`Bearer ${S}`;let c=await C(F,{method:"POST",headers:T,body:JSON.stringify(D),signal:N});if(!c.ok){let o=await c.json().catch(()=>({}));throw new Error(`CoArena Error (${c.status}): ${o.error?.message||o.message||c.statusText}`)}let v=c.body.getReader(),P=new TextDecoder,g="",t=[],f=null,u=Date.now(),r=!1;for(;;){let{done:o,value:h}=await v.read();if(o)break;g+=P.decode(h,{stream:!0});let e=g.split(`
2
+ `);g=e.pop();for(let a of e){let s=a.trim();if(!s||s.startsWith(":"))continue;if(s==="data: [DONE]"){t.length>0&&(yield{candidates:[{content:{parts:[...t]}}],usageMetadata:f},t=[]);return}let l=!1;if(s.startsWith("data: ")){let m=s.slice(6);if(m==="[DONE]")l=!0;else try{let i=JSON.parse(m);i.usage&&(f={promptTokenCount:i.usage.prompt_tokens,candidatesTokenCount:i.usage.completion_tokens,totalTokenCount:i.usage.total_tokens});let n=i.choices?.[0]?.delta;if(n){let d=n.reasoning_content||n.reasoning||null;!d&&Array.isArray(n.reasoning_details)&&n.reasoning_details.length>0&&(d=n.reasoning_details.map(R=>R.text||"").filter(Boolean).join("")),d&&(t.push({text:d,thought:!0}),r=!0),n.content&&(t.push({text:n.content}),r=!0)}}catch{}}if((l||Date.now()-u>=150)&&r&&(yield{candidates:t.length>0?[{content:{parts:[...t]}}]:[],usageMetadata:f},t=[],u=Date.now(),r=!1),l)break}Date.now()-u>=150&&r&&(yield{candidates:t.length>0?[{content:{parts:[...t]}}]:[],usageMetadata:f},t=[],u=Date.now(),r=!1)}};export{H as getCoArenaStream};
@@ -1 +1 @@
1
- import{a as i,b as s}from"./chunk-ZPSNXBWW.js";import"./chunk-3SMC2C3F.js";import{a as c}from"./chunk-JWNCKRN6.js";var l=async(a,p={})=>{let t=c(a,["action","type","cmd","target","grid","gridCode","location","input","button","clickType","from","to","direction","amount","autoPressEnter","enter","text","keys"]),r=t.action||t.type||t.cmd,n=t.target||t.grid||t.gridCode||t.location||t.input;if(!r)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let e=r.toLowerCase();if(e.startsWith("mouse_")||["move","click","drag","scroll"].includes(e)){let o=e.replace("mouse_","");return await i(o,n,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(e.startsWith("key_")||e==="type"||e==="press"){let o=e;e==="press"&&(o="key_press");let u=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await s(o,n||t.text||t.keys,{...t,autoPressEnter:u})}return`ERROR: Unrecognized action "${r}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};export{l as computer_action};
1
+ import{a as i,b as s}from"./chunk-KTD4WQBO.js";import"./chunk-QN4UHB5C.js";import{a as c}from"./chunk-JWNCKRN6.js";var l=async(a,p={})=>{let t=c(a,["action","type","cmd","target","grid","gridCode","location","input","button","clickType","from","to","direction","amount","autoPressEnter","enter","text","keys"]),r=t.action||t.type||t.cmd,n=t.target||t.grid||t.gridCode||t.location||t.input;if(!r)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let e=r.toLowerCase();if(e.startsWith("mouse_")||["move","click","drag","scroll"].includes(e)){let o=e.replace("mouse_","");return await i(o,n,{button:t.button,clickType:t.clickType||t.type,from:t.from,to:t.to,direction:t.direction,amount:t.amount?parseInt(t.amount,10):void 0})}if(e.startsWith("key_")||e==="type"||e==="press"){let o=e;e==="press"&&(o="key_press");let u=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return await s(o,n||t.text||t.keys,{...t,autoPressEnter:u})}return`ERROR: Unrecognized action "${r}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};export{l as computer_action};
@@ -1,3 +1,3 @@
1
- import{a as m}from"./chunk-PTFCY2D5.js";import{a as R}from"./chunk-UM5SNZ6X.js";import{n as H}from"./chunk-IWIVGFAT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";var et=async function*(d,N,W,O,P,Q,B,_,F=1,J=""){let T=[];O&&T.push({role:"system",content:O});for(let t of W){let e=t.role==="user"?"user":"assistant",n=[];if(Array.isArray(t.parts)){for(let o of t.parts)if(o.text)n.push({type:"text",text:o.text});else if(o.inlineData&&B){let c=o.inlineData.mimeType,g=o.inlineData.data;c.startsWith("image/")&&n.push({type:"image_url",image_url:{url:`data:${c};base64,${g}`}})}}else{let o=t.text||"";o&&n.push({type:"text",text:o})}T.push({role:e,content:n.length===1&&n[0].type==="text"?n[0].text:n})}let S=R("c_openai",N,P),y=S!==null?S:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"xhigh"}[P],i={model:N,messages:T,stream:!0,stream_options:{include_usage:!0},temperature:F,tools:[],tool_choice:"none"};y&&y!=="none"&&(i.reasoning_effort=y,i.reasoning={effort:y});let D=(J||process.env.CUSTOM_OPENAI_URL||process.env.C_OPENAI_URL||"").trim();if(!D)throw new Error("Custom OpenAI Base URL is not configured. Please set Base URL in /settings -> Providers.");let f=D.replace(/\/+$/,"");f.endsWith("/chat/completions")||(f.endsWith("/v1")?f=`${f}/chat/completions`:f=`${f}/chat/completions`);let l={"Content-Type":"application/json",Accept:"text/event-stream, application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow"},I=d===H,C=I?"":d&&d!=="LOCAL"?d:process.env.CUSTOM_OPENAI_API_KEY||process.env.C_OPENAI_API_KEY||"";if(!I&&C&&C.trim()!==""){let t=C.trim();l.Authorization=t.startsWith("Bearer ")?t:`Bearer ${t}`,l["api-key"]=t}let s=await m(f,{method:"POST",headers:l,body:JSON.stringify(i),signal:_});if(!s.ok&&(s.status===400||s.status===422)&&(i.reasoning||i.reasoning_effort)){if(console.info(`
1
+ import{a as m}from"./chunk-PTFCY2D5.js";import{a as R}from"./chunk-UM5SNZ6X.js";import{n as H}from"./chunk-3PZTWZTT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";var et=async function*(d,N,W,O,P,Q,B,_,F=1,J=""){let T=[];O&&T.push({role:"system",content:O});for(let t of W){let e=t.role==="user"?"user":"assistant",n=[];if(Array.isArray(t.parts)){for(let o of t.parts)if(o.text)n.push({type:"text",text:o.text});else if(o.inlineData&&B){let c=o.inlineData.mimeType,g=o.inlineData.data;c.startsWith("image/")&&n.push({type:"image_url",image_url:{url:`data:${c};base64,${g}`}})}}else{let o=t.text||"";o&&n.push({type:"text",text:o})}T.push({role:e,content:n.length===1&&n[0].type==="text"?n[0].text:n})}let S=R("c_openai",N,P),y=S!==null?S:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"xhigh"}[P],i={model:N,messages:T,stream:!0,stream_options:{include_usage:!0},temperature:F,tools:[],tool_choice:"none"};y&&y!=="none"&&(i.reasoning_effort=y,i.reasoning={effort:y});let D=(J||process.env.CUSTOM_OPENAI_URL||process.env.C_OPENAI_URL||"").trim();if(!D)throw new Error("Custom OpenAI Base URL is not configured. Please set Base URL in /settings -> Providers.");let f=D.replace(/\/+$/,"");f.endsWith("/chat/completions")||(f.endsWith("/v1")?f=`${f}/chat/completions`:f=`${f}/chat/completions`);let l={"Content-Type":"application/json",Accept:"text/event-stream, application/json","X-Title":"FluxFlow","User-Agent":"FluxFlow"},I=d===H,C=I?"":d&&d!=="LOCAL"?d:process.env.CUSTOM_OPENAI_API_KEY||process.env.C_OPENAI_API_KEY||"";if(!I&&C&&C.trim()!==""){let t=C.trim();l.Authorization=t.startsWith("Bearer ")?t:`Bearer ${t}`,l["api-key"]=t}let s=await m(f,{method:"POST",headers:l,body:JSON.stringify(i),signal:_});if(!s.ok&&(s.status===400||s.status===422)&&(i.reasoning||i.reasoning_effort)){if(console.info(`
2
2
  `),i.reasoning&&i.reasoning_effort){let t={...i};delete t.reasoning_effort;let e=await m(f,{method:"POST",headers:l,body:JSON.stringify(t),signal:_}).catch(()=>null);e&&e.ok&&(s=e)}if(!s.ok&&i.reasoning_effort){let t={...i};delete t.reasoning;let e=await m(f,{method:"POST",headers:l,body:JSON.stringify(t),signal:_}).catch(()=>null);e&&e.ok&&(s=e)}if(!s.ok){let t={...i};delete t.reasoning,delete t.reasoning_effort;let e=await m(f,{method:"POST",headers:l,body:JSON.stringify(t),signal:_}).catch(()=>null);e&&e.ok&&(s=e)}}if(!s.ok){let t=await s.json().catch(()=>({})),e=t.error?.metadata?.raw||t.error?.message||(typeof t.error=="string"?t.error:"")||t.message||s.statusText||"Unknown error";throw new Error(`Custom OpenAI Error (${s.status}): ${e}`)}let K=s.body.getReader(),Y=new TextDecoder,w="",a=[],p=null,k=Date.now(),u=!1,x=[],L=0,b=5,M=!0,E=()=>{x.length>0&&(a.push(...x),x=[],u=!0),M=!1},q=(t,e)=>{if(!t&&!e)return null;if(t){if(typeof t.reasoning_content=="string"&&t.reasoning_content)return t.reasoning_content;if(typeof t.reasoning=="string"&&t.reasoning)return t.reasoning;if(typeof t.thinking=="string"&&t.thinking)return t.thinking;if(typeof t.thought=="string"&&t.thought)return t.thought;if(typeof t.reasoning_text=="string"&&t.reasoning_text)return t.reasoning_text;if(Array.isArray(t.reasoning_details)&&t.reasoning_details.length>0){let n=t.reasoning_details.map(o=>typeof o=="string"?o:o?.text||o?.content||"").filter(Boolean).join("");if(n)return n}}if(e){if(typeof e.reasoning_content=="string"&&e.reasoning_content)return e.reasoning_content;if(typeof e.reasoning=="string"&&e.reasoning)return e.reasoning}return null},z=(t,e)=>{if(t){if(typeof t.content=="string"&&t.content)return t.content;if(typeof t.text=="string"&&t.text)return t.text;if(Array.isArray(t.content))return t.content.map(n=>typeof n=="string"?n:n?.text||"").join("")}return e&&typeof e.text=="string"&&e.text?e.text:""},X=t=>{let e=t.usage||t.usageMetadata||t.choices?.[0]?.usage||null;if(!e)return null;let n=e.prompt_tokens||e.promptTokenCount||e.input_tokens||0,o=e.completion_tokens||e.candidatesTokenCount||e.output_tokens||0,c=e.total_tokens||e.totalTokenCount||n+o,g=e.prompt_tokens_details?.cached_tokens||e.prompt_tokens_details?.cache_read_input_tokens||e.cachedContentTokenCount||e.cache_read_input_tokens||0,r=e.completion_tokens_details?.reasoning_tokens||e.thoughtsTokenCount||e.reasoning_tokens||0;return{totalTokenCount:c,promptTokenCount:n,candidatesTokenCount:o,cachedContentTokenCount:g,thoughtsTokenCount:r}};for(;;){let{done:t,value:e}=await K.read();if(t){E(),u&&(a.length>0||p)&&(yield{candidates:a.length>0?[{content:{parts:a}}]:[],usageMetadata:p});break}w+=Y.decode(e,{stream:!0});let n=w.split(`
3
3
  `);w=n.pop();for(let o of n){let c=o.trim();if(!c||!c.startsWith("data: "))continue;let g=!1;if(c==="data: [DONE]"||c==="data: [DONE]\r")g=!0,E();else try{let r=JSON.parse(c.substring(6));if(r.error){let G=r.error.metadata?.raw||r.error.message||(typeof r.error=="string"?r.error:JSON.stringify(r.error));throw new Error(`Custom OpenAI Stream Error: ${G}`)}let h=r.choices?.[0],U=h?.delta;h?.finish_reason&&h.finish_reason!=="null"&&(g=!0);let v=X(r);v&&(p=v,u=!0);let $=q(U,h);$&&(a.push({text:$,thought:!0}),u=!0);let A=z(U,h);A&&(M?(x.push({text:A}),L++,L>=b&&E()):(a.push({text:A}),u=!0))}catch(r){if(r.message&&r.message.startsWith("Custom OpenAI Stream Error:"))throw r}if((g||Date.now()-k>=150)&&u&&(yield{candidates:a.length>0?[{content:{parts:[...a]}}]:[],usageMetadata:p},a=[],k=Date.now(),u=!1),g)break}Date.now()-k>=150&&u&&(yield{candidates:a.length>0?[{content:{parts:[...a]}}]:[],usageMetadata:p},a=[],k=Date.now(),u=!1)}};export{et as getCustomOpenAIStream};
@@ -1 +1 @@
1
- import{a as e}from"./chunk-ZPSNXBWW.js";import"./chunk-3SMC2C3F.js";import{a as d}from"./chunk-JWNCKRN6.js";var n=async(i,a={})=>{let r=d(i,["fromGridId","from","start","toGridId","to","end"]),o=r.fromGridId||r.from||r.start,t=r.toGridId||r.to||r.end;return!o||!t?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await e("drag",o,{from:o,to:t})};export{n as drag};
1
+ import{a as e}from"./chunk-KTD4WQBO.js";import"./chunk-QN4UHB5C.js";import{a as d}from"./chunk-JWNCKRN6.js";var n=async(i,a={})=>{let r=d(i,["fromGridId","from","start","toGridId","to","end"]),o=r.fromGridId||r.from||r.start,t=r.toGridId||r.to||r.end;return!o||!t?'ERROR: Drag requires both "fromGridId" and "toGridId" parameters.':await e("drag",o,{from:o,to:t})};export{n as drag};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i}from"./chunk-YI3O7C3D.js";import"./chunk-5KBOEKGE.js";import"./chunk-JWNCKRN6.js";export{d as activeChildProcess,h as adjustWindowsCommand,c as cleanTerminalOutput,i as exec_command,e as isActiveCommandPty,a as isPtyAvailable,b as stripAnsi,g as terminateActiveCommand,f as writeToActiveCommand};
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-BD6HA64O.js";import"./chunk-LTNOPF2E.js";import"./chunk-JWNCKRN6.js";export{d as activeChildProcess,h as adjustWindowsCommand,c as cleanTerminalOutput,i as exec_command,e as isActiveCommandPty,a as isPtyAvailable,b as stripAnsi,g as terminateActiveCommand,f as writeToActiveCommand};
@@ -1 +1 @@
1
- import{a as k}from"./chunk-2RTYI6K3.js";import{a as b}from"./chunk-JWNCKRN6.js";import{v as B,w as T,x as $}from"./chunk-5MJKHQVE.js";import{b as I}from"./chunk-KQNW7DK5.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";import C from"fs-extra";import x from"path";var F=(a,y={})=>{try{if(a.length<8||a[0]!==137||a[1]!==80||a[2]!==78||a[3]!==71)return a;let s=[],c=[];for(let r=0;r<256;r++){let e=r;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;c[r]=e}let l=r=>{let e=4294967295;for(let n=0;n<r.length;n++)e=c[(e^r[n])&255]^e>>>8;return(e^4294967295)>>>0},p=(r,e)=>{let n=Buffer.from(r,"ascii"),i=Buffer.from(e,"utf-8"),u=n.length+1+i.length,o=Buffer.alloc(8+u+4);o.writeUInt32BE(u,0),o.write("tEXt",4,"ascii"),n.copy(o,8),o[8+n.length]=0,i.copy(o,8+n.length+1);let w=l(o.subarray(4,8+u));return o.writeUInt32BE(w,8+u),o};for(let[r,e]of Object.entries(y))e!=null&&s.push(p(r,String(e)));if(s.length===0)return a;if(a.subarray(12,16).toString("ascii")==="IHDR"){let e=a.subarray(0,33),n=a.subarray(33);return Buffer.concat([e,...s,n])}return a}catch{return a}},N=async(a,y={})=>{let s=b(a,["prompt","text","path","outputPath","output","ratio"]),c=s.prompt||s.text,l=s.path||s.outputPath||s.output||"generated_image.png",p=s.ratio;if(!c)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"],e=c.toLowerCase();if(r.some(i=>e.includes(i)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let i=await I();if(!await B(i))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await T()).nextResetMin||60}m).`;let o=i.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},w=o.keyType==="Custom"&&o.apiKey?o.apiKey:FALLBACK_IMAGE_KEY,E={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[o.quality]||"zimage",g=1024,m=1024;if(p){let t=p.replace(/\s+/g,"");t==="16:9"?(g=1024,m=576):t==="9:16"?(g=576,m=1024):t==="4:3"?(g=1024,m=768):t==="3:4"?(g=768,m=1024):t==="1:1"&&(g=1024,m=1024)}let M=Math.floor(Math.random()*1e7),S=`https://gen.pollinations.ai/image/${encodeURIComponent(c)}?model=${E}&width=${g}&height=${m}&seed=${M}&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")}`,d=await fetch(S,{method:"GET",headers:{Authorization:`Bearer ${w}`}});if(!d.ok){let t=d.status,h="";try{h=await d.text()}catch{}return t===402||h.includes("Insufficient balance")||h.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${t}]: ${h||"Unknown API Error"}`}if((d.headers.get("content-type")||"").includes("application/json")){let t=await d.json();return t.status===402||t.error&&t.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${t.error?.message||JSON.stringify(t)}`}let O=await d.arrayBuffer(),f=Buffer.from(O),P={Title:c,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:c,Model:`Fluxflow:${E}`,Ratio:p||"1:1",Seed:String(M)};f=F(f,P);let R=x.resolve(process.cwd(),l);await C.ensureDir(x.dirname(R)),await k.recordFileChange(R),await C.writeFile(R,f),await $(i);let v=x.extname(l).toLowerCase(),L={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[v]||"image/png";return y.isMultiModal!==!1?{text:`Image successfully generated from prompt [${c}] and saved to [${l}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:f.toString("base64"),mimeType:L}}}:`Image successfully generated from prompt [${c}] and saved to [${l}].`}catch(i){return`ERROR: Failed during image generation: ${i instanceof Error?i.message:String(i)}`}};export{N as generate_image};
1
+ import{a as k}from"./chunk-2RTYI6K3.js";import{a as b}from"./chunk-JWNCKRN6.js";import{v as B,w as T,x as $}from"./chunk-KYIMFUZS.js";import{b as I}from"./chunk-MS7BITZ6.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";import C from"fs-extra";import x from"path";var F=(a,y={})=>{try{if(a.length<8||a[0]!==137||a[1]!==80||a[2]!==78||a[3]!==71)return a;let s=[],c=[];for(let r=0;r<256;r++){let e=r;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;c[r]=e}let l=r=>{let e=4294967295;for(let n=0;n<r.length;n++)e=c[(e^r[n])&255]^e>>>8;return(e^4294967295)>>>0},p=(r,e)=>{let n=Buffer.from(r,"ascii"),i=Buffer.from(e,"utf-8"),u=n.length+1+i.length,o=Buffer.alloc(8+u+4);o.writeUInt32BE(u,0),o.write("tEXt",4,"ascii"),n.copy(o,8),o[8+n.length]=0,i.copy(o,8+n.length+1);let w=l(o.subarray(4,8+u));return o.writeUInt32BE(w,8+u),o};for(let[r,e]of Object.entries(y))e!=null&&s.push(p(r,String(e)));if(s.length===0)return a;if(a.subarray(12,16).toString("ascii")==="IHDR"){let e=a.subarray(0,33),n=a.subarray(33);return Buffer.concat([e,...s,n])}return a}catch{return a}},N=async(a,y={})=>{let s=b(a,["prompt","text","path","outputPath","output","ratio"]),c=s.prompt||s.text,l=s.path||s.outputPath||s.output||"generated_image.png",p=s.ratio;if(!c)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"],e=c.toLowerCase();if(r.some(i=>e.includes(i)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let i=await I();if(!await B(i))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await T()).nextResetMin||60}m).`;let o=i.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},w=o.keyType==="Custom"&&o.apiKey?o.apiKey:FALLBACK_IMAGE_KEY,E={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[o.quality]||"zimage",g=1024,m=1024;if(p){let t=p.replace(/\s+/g,"");t==="16:9"?(g=1024,m=576):t==="9:16"?(g=576,m=1024):t==="4:3"?(g=1024,m=768):t==="3:4"?(g=768,m=1024):t==="1:1"&&(g=1024,m=1024)}let M=Math.floor(Math.random()*1e7),S=`https://gen.pollinations.ai/image/${encodeURIComponent(c)}?model=${E}&width=${g}&height=${m}&seed=${M}&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")}`,d=await fetch(S,{method:"GET",headers:{Authorization:`Bearer ${w}`}});if(!d.ok){let t=d.status,h="";try{h=await d.text()}catch{}return t===402||h.includes("Insufficient balance")||h.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${t}]: ${h||"Unknown API Error"}`}if((d.headers.get("content-type")||"").includes("application/json")){let t=await d.json();return t.status===402||t.error&&t.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${t.error?.message||JSON.stringify(t)}`}let O=await d.arrayBuffer(),f=Buffer.from(O),P={Title:c,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:c,Model:`Fluxflow:${E}`,Ratio:p||"1:1",Seed:String(M)};f=F(f,P);let R=x.resolve(process.cwd(),l);await C.ensureDir(x.dirname(R)),await k.recordFileChange(R),await C.writeFile(R,f),await $(i);let v=x.extname(l).toLowerCase(),L={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[v]||"image/png";return y.isMultiModal!==!1?{text:`Image successfully generated from prompt [${c}] and saved to [${l}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:f.toString("base64"),mimeType:L}}}:`Image successfully generated from prompt [${c}] and saved to [${l}].`}catch(i){return`ERROR: Failed during image generation: ${i instanceof Error?i.message:String(i)}`}};export{N as generate_image};
@@ -1,2 +1,2 @@
1
- import{a as A}from"./chunk-PTFCY2D5.js";import{a as b}from"./chunk-UM5SNZ6X.js";import"./chunk-NPXJIGAI.js";var B=async function*(C,v,E,w,x,j,N,O,S=1){let a=v,m=null;if(typeof a=="string"){let t={};if(a.includes("::")){let e=a.indexOf("::"),n=a.slice(0,e).trim();n&&(t.only=[n]),a=a.slice(e+2).trim()}let d=["flex","standard","priority"],o={fp16:"fp16",f16:"fp16",fp8:"fp8",f8:"fp8",int8:"int8",in8:"int8",int4:"int4",in4:"int4"},s=["throughput","latency","price","ttft"];if(a.includes(":")){let e=a.split(":");for(;e.length>1;){let n=e[e.length-1].toLowerCase().trim();if(d.includes(n))t.service_tier=n,t.allow_fallbacks=!1,e.pop();else if(o[n])t.quantizations=[o[n]],t.allow_fallbacks=!1,e.pop();else if(s.includes(n))t.sort=n,t.allow_fallbacks=!1,e.pop();else break}a=e.join(":").trim()}Object.keys(t).length>0&&(m=t)}let _=[];w&&_.push({role:"system",content:w});for(let t of E){let d=t.role==="user"?"user":"assistant",o=[];if(Array.isArray(t.parts)){for(let s of t.parts)if(s.text)o.push({type:"text",text:s.text});else if(s.inlineData&&N){let e=s.inlineData.mimeType,n=s.inlineData.data;e.startsWith("image/")&&o.push({type:"image_url",image_url:{url:`data:${e};base64,${n}`}})}}else{let s=t.text||"";s&&o.push({type:"text",text:s})}_.push({role:d,content:o.length===1&&o[0].type==="text"?o[0].text:o})}let T=b("Infron",a,x),D=T!==null?T:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[x],y={model:a,messages:_,stream:!0,stream_options:{include_usage:!0},temperature:S,tools:[],tool_choice:"none"};m&&(y.provider=m),D&&(y.reasoning={effort:D});let M=process.env.INFRON_URL||"https://llm.onerouter.pro/v1/chat/completions",I={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},F=C||process.env.INFRON_API_KEY||"";I.Authorization=`Bearer ${F}`;let f=await A(M,{method:"POST",headers:I,body:JSON.stringify(y),signal:O});if(!f.ok){let t=await f.json().catch(()=>({}));throw new Error(`Infron Error (${f.status}): ${t.error?.message||t.message||f.statusText}`)}let R=f.body.getReader(),L=new TextDecoder,k="",i=[],p=null,u=Date.now(),l=!1;for(;;){let{done:t,value:d}=await R.read();if(t){l&&(i.length>0||p)&&(yield{candidates:i.length>0?[{content:{parts:i}}]:[],usageMetadata:p});break}k+=L.decode(d,{stream:!0});let o=k.split(`
1
+ import{a as A}from"./chunk-PTFCY2D5.js";import{a as b}from"./chunk-UM5SNZ6X.js";import"./chunk-NPXJIGAI.js";var B=async function*(C,v,E,w,x,j,N,O,S=1){let a=v,m=null;if(typeof a=="string"){let t={};if(a.includes("::")){let e=a.indexOf("::"),n=a.slice(0,e).trim();n&&(t.only=[n]),a=a.slice(e+2).trim()}let d=["flex","standard","priority"],o={fp16:"fp16",f16:"fp16",fp8:"fp8",f8:"fp8",int8:"int8",in8:"int8",int4:"int4",in4:"int4"},s=["throughput","latency","price","ttft"];if(a.includes(":")){let e=a.split(":");for(;e.length>1;){let n=e[e.length-1].toLowerCase().trim();if(d.includes(n))t.service_tier=n,t.allow_fallbacks=!1,e.pop();else if(o[n])t.quantizations=[o[n]],t.allow_fallbacks=!1,e.pop();else if(s.includes(n))t.sort=n,t.allow_fallbacks=!1,e.pop();else break}a=e.join(":").trim()}Object.keys(t).length>0&&(m=t)}let _=[];w&&_.push({role:"system",content:w});for(let t of E){let d=t.role==="user"?"user":"assistant",o=[];if(Array.isArray(t.parts)){for(let s of t.parts)if(s.text)o.push({type:"text",text:s.text});else if(s.inlineData&&N){let e=s.inlineData.mimeType,n=s.inlineData.data;e.startsWith("image/")&&o.push({type:"image_url",image_url:{url:`data:${e};base64,${n}`}})}}else{let s=t.text||"";s&&o.push({type:"text",text:s})}_.push({role:d,content:o.length===1&&o[0].type==="text"?o[0].text:o})}let T=b("Infron",a,x),D=T!==null?T:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[x],y={model:a,messages:_,stream:!0,stream_options:{include_usage:!0},temperature:S,tools:[],tool_choice:"none"};m&&(y.provider=m),D&&(y.reasoning={effort:D});let M=process.env.INFRON_URL||"https://llm.onerouter.pro/v1/chat/completions",I={"Content-Type":"application/json","X-Title":"FluxFlow","User-Agent":"FluxFlow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},F=C||process.env.INFRON_API_KEY||"";I.Authorization=`Bearer ${F}`;let f=await A(M,{method:"POST",headers:I,body:JSON.stringify(y),signal:O});if(!f.ok){let t=await f.json().catch(()=>({}));throw new Error(`Infron Error (${f.status}): ${t.error?.message||t.message||f.statusText}`)}let R=f.body.getReader(),L=new TextDecoder,k="",i=[],p=null,u=Date.now(),l=!1;for(;;){let{done:t,value:d}=await R.read();if(t){l&&(i.length>0||p)&&(yield{candidates:i.length>0?[{content:{parts:i}}]:[],usageMetadata:p});break}k+=L.decode(d,{stream:!0});let o=k.split(`
2
2
  `);k=o.pop();for(let s of o){let e=s.trim();if(!e||!e.startsWith("data: "))continue;let n=!1;if(e==="data: [DONE]")n=!0;else try{let g=JSON.parse(e.substring(6)),c=g.choices?.[0]?.delta,r=g.usage;if(r&&(p={totalTokenCount:r.total_tokens||(r.prompt_tokens||0)+(r.completion_tokens||0),promptTokenCount:r.prompt_tokens||0,candidatesTokenCount:r.completion_tokens||0,cachedContentTokenCount:r.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:r.completion_tokens_details?.reasoning_tokens||r.reasoning_tokens||0},l=!0),c){let h=c.reasoning_content||c.reasoning||null;!h&&Array.isArray(c.reasoning_details)&&c.reasoning_details.length>0&&(h=c.reasoning_details.map(P=>P.text||"").filter(Boolean).join("")),h&&(i.push({text:h,thought:!0}),l=!0),c.content&&(i.push({text:c.content}),l=!0)}}catch{}if((n||Date.now()-u>=150)&&l&&(yield{candidates:i.length>0?[{content:{parts:[...i]}}]:[],usageMetadata:p},i=[],u=Date.now(),l=!1),n)break}Date.now()-u>=150&&l&&(yield{candidates:i.length>0?[{content:{parts:[...i]}}]:[],usageMetadata:p},i=[],u=Date.now(),l=!1)}};export{B as getInfronStream};
@@ -1,6 +1,6 @@
1
- import{a as b,c as p}from"./chunk-56EJGQU3.js";import{a as D}from"./chunk-JWNCKRN6.js";var q=async(_,s={})=>{let{runSubagent:y}=await import("./ai-6AZZQUJJ.js"),a=D(_,["task","instruction","prompt","model","title","tools","id"]),u=a.task||a.instruction||a.prompt,A=a.model||null,g=a.title||null,w=a.tools||null,m=a.id&&a.id!=="null"&&a.id!=="undefined"&&a.id!==""?String(a.id).trim():null;if(!u)return'ERROR: Missing "task" argument for invoke.';let d=null,U="";m&&(d=b.find(e=>e.id===m));let f=!!d,r=f?d.id:m||`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,I=f?d.history||[]:[],C=null;if(w)try{let e=w.trim();e.startsWith("[")&&e.endsWith("]")&&(e=e.substring(1,e.length-1)),C=e.split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=null,S=null,E=new Promise((e,n)=>{h=e,S=n}),t=d;t?(t.status="running",t.task=u,g&&(t.title=g),t.startedAt=Date.now(),t.lastChunkTime=Date.now(),t.completionPromise=E,t._resolveCompletion=h,t._rejectCompletion=S):(t={id:r,title:g||u.substring(0,30),task:u,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:e=>{e&&t.pendingSteerMessages.push(e)},completionPromise:E,_resolveCompletion:h,_rejectCompletion:S,progress:[],history:[]},b.push(t));let l={chunks:[],totalWords:0};s.onSubagentUpdate&&s.onSubagentUpdate();let i=[],M={...s,taskId:r,onHistoryUpdate:e=>{t.history=[...e]},onAskMain:async e=>{let n=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,o=null,k=new Promise(T=>{o=T}),c={id:n,question:e,answered:!1,answer:null,askedAt:Date.now(),_resolve:o};return t.questions.push(c),t.status="waiting",s.onSubagentUpdate&&s.onSubagentUpdate(),p(`[SYSTEM] Background subagent "${t.title}" is WAITING FOR YOUR INPUT: "${e}"
1
+ import{a as b,c as p}from"./chunk-56EJGQU3.js";import{a as D}from"./chunk-JWNCKRN6.js";var q=async(_,s={})=>{let{runSubagent:y}=await import("./ai-XPXVNDUQ.js"),a=D(_,["task","instruction","prompt","model","title","tools","id"]),u=a.task||a.instruction||a.prompt,A=a.model||null,g=a.title||null,w=a.tools||null,m=a.id&&a.id!=="null"&&a.id!=="undefined"&&a.id!==""?String(a.id).trim():null;if(!u)return'ERROR: Missing "task" argument for invoke.';let d=null,U="";m&&(d=b.find(e=>e.id===m));let f=!!d,r=f?d.id:m||`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,I=f?d.history||[]:[],C=null;if(w)try{let e=w.trim();e.startsWith("[")&&e.endsWith("]")&&(e=e.substring(1,e.length-1)),C=e.split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let h=null,S=null,E=new Promise((e,n)=>{h=e,S=n}),t=d;t?(t.status="running",t.task=u,g&&(t.title=g),t.startedAt=Date.now(),t.lastChunkTime=Date.now(),t.completionPromise=E,t._resolveCompletion=h,t._rejectCompletion=S):(t={id:r,title:g||u.substring(0,30),task:u,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:e=>{e&&t.pendingSteerMessages.push(e)},completionPromise:E,_resolveCompletion:h,_rejectCompletion:S,progress:[],history:[]},b.push(t));let l={chunks:[],totalWords:0};s.onSubagentUpdate&&s.onSubagentUpdate();let i=[],M={...s,taskId:r,onHistoryUpdate:e=>{t.history=[...e]},onAskMain:async e=>{let n=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,o=null,k=new Promise(T=>{o=T}),c={id:n,question:e,answered:!1,answer:null,askedAt:Date.now(),_resolve:o};return t.questions.push(c),t.status="waiting",s.onSubagentUpdate&&s.onSubagentUpdate(),p(`[SYSTEM] Background subagent "${t.title}" is WAITING FOR YOUR INPUT: "${e}"
2
2
  Respond using tool: [action:Answer(id="${r}", answer="...")]
3
3
  [/SYSTEM]`),await k},onVisualFeedback:e=>{t.lastChunkTime=Date.now();let n=e.replace(/\x1b\[[0-9;]*m/g,""),o=n.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);o?t.currentTool=o[1].trim():t.currentTool=n,s.onSubagentUpdate&&s.onSubagentUpdate()},onTokenChunk:(e,n)=>{let o=Date.now();if(t.lastChunkTime=o,t.currentTool="Thinking",typeof n=="number"&&n>0){l.totalWords+=n,l.chunks.push({time:o,words:n});let k=o-400;if(l.chunks=l.chunks.filter(c=>c.time>=k),l.chunks.length>0){let c=l.chunks.reduce((v,R)=>v+R.words,0),$=l.chunks[0].time,T=Math.max(.4,(o-$)/1e3);t.wps=Math.round(c/T)}}s.onSubagentUpdate&&s.onSubagentUpdate()}};return y(u,M,A,C,null,e=>{if(t.status==="cancelled")return;if(e.startsWith("[Subagent Turn")&&i.length>0&&(t.progress.push([...i]),i=[]),e.includes("[Executing Tool]")){let o=e.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);o&&(!t.currentTool||t.currentTool==="Thinking")&&(t.currentTool=o[1])}let n=e;if(n.startsWith("[Tool Result]")||n.startsWith("[Action Result]")){let o=n.split(`
4
4
  `);o.length>5&&(n=o.slice(0,4).join(`
5
5
  `)+`
6
- ... [Content/Diff Truncated from Logs] ...`)}i.push(n),s.onSubagentUpdate&&s.onSubagentUpdate()},!0,I).then(e=>{if(t.status==="cancelled"){t._resolveCompletion&&t._resolveCompletion(e);return}i.length>0&&(t.progress.push([...i]),i=[]),t.status="completed",t.finalAnswer=e,s.onSubagentUpdate&&s.onSubagentUpdate(),p(`[SYSTEM] Background subagent "${t.title}" (id: ${r}) has FINISHED. Call GetProgress(id="${r}") to see the final result. [/SYSTEM]`),t._resolveCompletion&&t._resolveCompletion(e)}).catch(async e=>{let{isTerminationSignaled:n}=await import("./ai-6AZZQUJJ.js");if(e.message==="Subagent task was cancelled."||t.status==="cancelled"||n()){t.status="cancelled",i.push("[SUBAGENT CANCELLED] Task was cancelled."),t.progress.push([...i]),s.onSubagentUpdate&&s.onSubagentUpdate(),t._resolveCompletion&&t._resolveCompletion(null);return}i.push(`[SUBAGENT FAILURE] Error: ${e.message}`),t.progress.push([...i]),t.status="failed",t.error=e.message,s.onSubagentUpdate&&s.onSubagentUpdate(),p(`[SYSTEM] Background subagent "${t.title}" (id: ${r}) FAILED with error: ${e.message}. [/SYSTEM]`),t._rejectCompletion&&t._rejectCompletion(e)}),f?`Background subagent ${r} resumed.`:U?`Background subagent started. Task ID: ${r}.${U}`:`Background subagent started. Task ID: ${r}`};export{q as invoke};
6
+ ... [Content/Diff Truncated from Logs] ...`)}i.push(n),s.onSubagentUpdate&&s.onSubagentUpdate()},!0,I).then(e=>{if(t.status==="cancelled"){t._resolveCompletion&&t._resolveCompletion(e);return}i.length>0&&(t.progress.push([...i]),i=[]),t.status="completed",t.finalAnswer=e,s.onSubagentUpdate&&s.onSubagentUpdate(),p(`[SYSTEM] Background subagent "${t.title}" (id: ${r}) has FINISHED. Call GetProgress(id="${r}") to see the final result. [/SYSTEM]`),t._resolveCompletion&&t._resolveCompletion(e)}).catch(async e=>{let{isTerminationSignaled:n}=await import("./ai-XPXVNDUQ.js");if(e.message==="Subagent task was cancelled."||t.status==="cancelled"||n()){t.status="cancelled",i.push("[SUBAGENT CANCELLED] Task was cancelled."),t.progress.push([...i]),s.onSubagentUpdate&&s.onSubagentUpdate(),t._resolveCompletion&&t._resolveCompletion(null);return}i.push(`[SUBAGENT FAILURE] Error: ${e.message}`),t.progress.push([...i]),t.status="failed",t.error=e.message,s.onSubagentUpdate&&s.onSubagentUpdate(),p(`[SYSTEM] Background subagent "${t.title}" (id: ${r}) FAILED with error: ${e.message}. [/SYSTEM]`),t._rejectCompletion&&t._rejectCompletion(e)}),f?`Background subagent ${r} resumed.`:U?`Background subagent started. Task ID: ${r}.${U}`:`Background subagent started. Task ID: ${r}`};export{q as invoke};
@@ -1,7 +1,7 @@
1
- import{a as m}from"./chunk-56EJGQU3.js";import{a as g}from"./chunk-JWNCKRN6.js";var A=async(p,a={})=>{let{runSubagent:f}=await import("./ai-6AZZQUJJ.js"),e=g(p,["task","instruction","prompt","model","tools","title","id"]),l=e.task||e.instruction||e.prompt,k=e.model||null,c=e.tools||null,u=e.id&&e.id!=="null"&&e.id!=="undefined"&&e.id!==""?String(e.id).trim():null;if(!l)return'ERROR: Missing "task" argument for invokeSync.';let n=null,d="";u&&(n=m.find(t=>t.id===u));let o=n?n.id:u||`subagent-sync-${Date.now()}-${Math.floor(Math.random()*1e3)}`,$=n?.history||[],b=null;if(c)try{let t=c.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.substring(1,t.length-1)),b=t.split(",").map(i=>i.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let r=e.title||(n?n.title:l.substring(0,30)),s=n;s?(s.status="running",s.task=l):(s={id:o,title:r,task:l,status:"running",startedAt:Date.now(),progress:[],history:[]},m.push(s));let y={...a,taskId:o,onHistoryUpdate:t=>{s.history=[...t]}};try{a.onVisualFeedback&&a.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${r}${n?" (Resumed)":""}`);let t=await f(l,y,k,b,null,null,!1,$);s.status="completed",s.finalAnswer=`Subagent task completed. (ID: ${o})
1
+ import{a as m}from"./chunk-56EJGQU3.js";import{a as g}from"./chunk-JWNCKRN6.js";var A=async(p,a={})=>{let{runSubagent:f}=await import("./ai-XPXVNDUQ.js"),e=g(p,["task","instruction","prompt","model","tools","title","id"]),l=e.task||e.instruction||e.prompt,k=e.model||null,c=e.tools||null,u=e.id&&e.id!=="null"&&e.id!=="undefined"&&e.id!==""?String(e.id).trim():null;if(!l)return'ERROR: Missing "task" argument for invokeSync.';let n=null,d="";u&&(n=m.find(t=>t.id===u));let o=n?n.id:u||`subagent-sync-${Date.now()}-${Math.floor(Math.random()*1e3)}`,$=n?.history||[],b=null;if(c)try{let t=c.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.substring(1,t.length-1)),b=t.split(",").map(i=>i.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let r=e.title||(n?n.title:l.substring(0,30)),s=n;s?(s.status="running",s.task=l):(s={id:o,title:r,task:l,status:"running",startedAt:Date.now(),progress:[],history:[]},m.push(s));let y={...a,taskId:o,onHistoryUpdate:t=>{s.history=[...t]}};try{a.onVisualFeedback&&a.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${r}${n?" (Resumed)":""}`);let t=await f(l,y,k,b,null,null,!1,$);s.status="completed",s.finalAnswer=`Subagent task completed. (ID: ${o})
2
2
  Final Answer:
3
3
  ${t}`,a.onVisualFeedback&&a.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${r} [COMPLETED]
4
4
  `);let i=`Subagent task completed. (ID: ${o})
5
5
  Final Answer:
6
- ${t}`;return d?`${i}${d}`:i}catch(t){s.status="failed",s.error=t.message;let{isTerminationSignaled:i}=await import("./ai-6AZZQUJJ.js"),h=t.message==="Subagent task was cancelled by user."||i();if(a.onVisualFeedback){let S=h?"[CANCELLED]":"[FAILED]";a.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${r} ${S}
6
+ ${t}`;return d?`${i}${d}`:i}catch(t){s.status="failed",s.error=t.message;let{isTerminationSignaled:i}=await import("./ai-XPXVNDUQ.js"),h=t.message==="Subagent task was cancelled by user."||i();if(a.onVisualFeedback){let S=h?"[CANCELLED]":"[FAILED]";a.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${r} ${S}
7
7
  `)}return`ERROR: Subagent execution failed: ${t.message}${d}`}};export{A as invokeSync};
@@ -1 +1 @@
1
- import{b as e}from"./chunk-ZPSNXBWW.js";import"./chunk-3SMC2C3F.js";import{a as i}from"./chunk-JWNCKRN6.js";var k=async(a,c={})=>{let t=i(a,["key","keys","input","shortcut"]),s=t.key||t.keys||t.input||t.shortcut;if(!s)return'ERROR: Missing required "key" parameter for KeyPress tool.';let r=String(s).trim().toLowerCase();if(r==="clearinput"||r==="clear_input"||r==="clear")return await e("clear_input");if(r==="back"||r==="browser_back"||r==="browserBack")return await e("browser_back");if(r.includes(";")||r.includes("+")){let o=r.split(/[;+]/).map(n=>n.trim()).filter(Boolean);return await e("key_combination",o)}return await e("key_press",r)};export{k as key_press};
1
+ import{b as e}from"./chunk-KTD4WQBO.js";import"./chunk-QN4UHB5C.js";import{a as i}from"./chunk-JWNCKRN6.js";var k=async(a,c={})=>{let t=i(a,["key","keys","input","shortcut"]),s=t.key||t.keys||t.input||t.shortcut;if(!s)return'ERROR: Missing required "key" parameter for KeyPress tool.';let r=String(s).trim().toLowerCase();if(r==="clearinput"||r==="clear_input"||r==="clear")return await e("clear_input");if(r==="back"||r==="browser_back"||r==="browserBack")return await e("browser_back");if(r.includes(";")||r.includes("+")){let o=r.split(/[;+]/).map(n=>n.trim()).filter(Boolean);return await e("key_combination",o)}return await e("key_press",r)};export{k as key_press};
@@ -1 +1 @@
1
- import{b as n}from"./chunk-ZPSNXBWW.js";import"./chunk-3SMC2C3F.js";import{a as r}from"./chunk-JWNCKRN6.js";var p=async(o,u={})=>{let t=r(o,["text","input","value","autoPressEnter"]),e=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return e==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await n("type",String(e),{autoPressEnter:s})};export{p as keyboard_typing};
1
+ import{b as n}from"./chunk-KTD4WQBO.js";import"./chunk-QN4UHB5C.js";import{a as r}from"./chunk-JWNCKRN6.js";var p=async(o,u={})=>{let t=r(o,["text","input","value","autoPressEnter"]),e=t.text||t.input||t.value||"",s=t.autoPressEnter===!0||t.autoPressEnter==="true"||t.enter===!0||t.enter==="true";return e==null?'ERROR: Missing required "text" parameter for KeyboardTyping tool.':await n("type",String(e),{autoPressEnter:s})};export{p as keyboard_typing};
@@ -1,3 +1,3 @@
1
- import{a as L}from"./chunk-UM5SNZ6X.js";import{n as A}from"./chunk-IWIVGFAT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";import{Ollama as b}from"ollama";var _=new Map;async function D(a,e,n){let o=`${e}::${n}`;if(_.has(o))return _.get(o);try{let u=(await a.show({model:n}))?.thinking||null;return _.set(o,u),u}catch{return _.set(o,null),null}}function E(a,e){let n=a?.values,o=Array.isArray(n)&&n.some(d=>typeof d=="boolean"),m=Array.isArray(n)&&n.some(d=>typeof d=="string");if(o)switch(e){case"Fast":return!1;case"Low":case"Medium":case"Standard":case"High":case"xHigh":return!0;default:return!0}if(m)switch(e){case"Fast":return n.includes("low")?"low":!1;case"Low":return"low";case"Medium":case"Standard":return"medium";case"High":case"xHigh":return"high";default:return"medium"}let u={Fast:!1,Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"};return u[e]!==void 0?u[e]:!0}var $=async function*(a,e,n,o,m,u,d,x,O=1,H="Cloud"){let s=[];o&&s.push({role:"system",content:o});for(let t of n){let r=t.role==="user"?"user":"assistant",c="",w=[];if(Array.isArray(t.parts)){c=t.parts.map(l=>l.text||"").filter(Boolean).join(`
1
+ import{a as L}from"./chunk-UM5SNZ6X.js";import{n as A}from"./chunk-3PZTWZTT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";import{Ollama as b}from"ollama";var _=new Map;async function D(a,e,n){let o=`${e}::${n}`;if(_.has(o))return _.get(o);try{let u=(await a.show({model:n}))?.thinking||null;return _.set(o,u),u}catch{return _.set(o,null),null}}function E(a,e){let n=a?.values,o=Array.isArray(n)&&n.some(d=>typeof d=="boolean"),m=Array.isArray(n)&&n.some(d=>typeof d=="string");if(o)switch(e){case"Fast":return!1;case"Low":case"Medium":case"Standard":case"High":case"xHigh":return!0;default:return!0}if(m)switch(e){case"Fast":return n.includes("low")?"low":!1;case"Low":return"low";case"Medium":case"Standard":return"medium";case"High":case"xHigh":return"high";default:return"medium"}let u={Fast:!1,Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"};return u[e]!==void 0?u[e]:!0}var $=async function*(a,e,n,o,m,u,d,x,O=1,H="Cloud"){let s=[];o&&s.push({role:"system",content:o});for(let t of n){let r=t.role==="user"?"user":"assistant",c="",w=[];if(Array.isArray(t.parts)){c=t.parts.map(l=>l.text||"").filter(Boolean).join(`
2
2
  `);for(let l of t.parts){let k=l.inlineData||l.inline_data;k&&k.data&&w.push(k.data)}}else c=t.text||"";if(c||w.length>0){let l={role:r,content:c};w.length>0&&(l.images=w),s.push(l)}}let C=a===A||H==="Local"||!a||a==="LOCAL",y=C?process.env.OLLAMA_HOST||"http://127.0.0.1:11434":process.env.OLLAMA_HOST||"https://ollama.com",M={host:y};!C&&a&&(M.headers={Authorization:"Bearer "+a});let T=new b(M),i=[],g=null,v=Date.now(),h=!1,f=L("Ollama",e,m),p;if(f!==null)p=f==="false"||f===!1?!1:f==="true"||f===!0?!0:f;else{let t=await D(T,y,e);p=E(t,m)}if(p&&e&&e.toLowerCase().includes("gemma4")){let t=s.findIndex(r=>r.role==="system");t!==-1?s[t].content.includes("<|think|>")||(s[t].content=`<|think|>
3
3
  ${s[t].content}`):s.unshift({role:"system",content:"<|think|>"})}let S={model:e,messages:s,stream:!0,think:p,keep_alive:"10m",tools:[],tool_choice:"none",options:{temperature:O}},N=await T.chat(S);for await(let t of N){if(x?.aborted)throw new DOMException("The user aborted a request.","AbortError");if(t.message?.thinking&&(i.push({text:t.message.thinking,thought:!0}),h=!0),t.message?.content&&(i.push({text:t.message.content}),h=!0),t.done){let r=t.prompt_eval_cached_count||0;if(!r&&t.prompt_eval_count){let c=t.prompt_eval_duration||0;c>0&&c<5e7&&(r=t.prompt_eval_count)}g={totalTokenCount:(t.prompt_eval_count||0)+(t.eval_count||0),promptTokenCount:t.prompt_eval_count||0,candidatesTokenCount:t.eval_count||0,cachedContentTokenCount:r,thoughtsTokenCount:0},h=!0}(t.done||Date.now()-v>=150&&h)&&(yield{candidates:i.length>0?[{content:{parts:[...i]}}]:[],usageMetadata:g},i=[],v=Date.now(),h=!1)}h&&(i.length>0||g)&&(yield{candidates:i.length>0?[{content:{parts:[...i]}}]:[],usageMetadata:g})};export{$ as getOllamaStream};
@@ -0,0 +1 @@
1
+ import{f as o}from"./chunk-QN4UHB5C.js";import{a as n}from"./chunk-JWNCKRN6.js";var m=async(r,c={})=>{let t=typeof r=="string"?n(r,["canvasMode","canvas_mode"]):r||{},a=t.canvasMode===!0||t.canvasMode==="true"||t.canvas_mode===!0||t.canvas_mode==="true";try{let e=await o({canvasMode:a});if(e&&e.base64)return{text:`Screen recaptured${a?" (static canvas grid mode). New action if needed: Drag(fromGridId=int, toGridId=int). Drag mouse from start grid number to target grid number":""}`,binaryPart:{inlineData:{mimeType:e.mimeType,data:e.base64}}}}catch{}return"Screen recaptured."};export{m as recapture_screen};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i}from"./chunk-3SMC2C3F.js";export{b as CANVAS_GRID_CONFIG,a as GRID_CONFIG,f as captureGriddedScreenshot,i as coordinates720pToGridId,e as getActiveDisplay,h as gridToNativeCoordinates,g as parseGridCodeTo720p,d as rawModelOnly,c as useModel};
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-QN4UHB5C.js";export{b as CANVAS_GRID_CONFIG,a as GRID_CONFIG,f as captureGriddedScreenshot,i as coordinates720pToGridId,e as getActiveDisplay,h as gridToNativeCoordinates,g as parseGridCodeTo720p,d as rawModelOnly,c as useModel};
@@ -1 +1 @@
1
- import{a as r}from"./chunk-ZPSNXBWW.js";import"./chunk-3SMC2C3F.js";import{a as t}from"./chunk-JWNCKRN6.js";var g=async(n,c={})=>{let o=t(n,["direction","amount","gridId","grid","coordinate","target","id"]),e=(o.direction||"down").toLowerCase(),i=o.amount?parseInt(o.amount,10):6,d=o.gridId||o.grid||o.coordinate||o.target||o.id||null;return await r("scroll",d,{direction:e,amount:i})};export{g as scroll};
1
+ import{a as r}from"./chunk-KTD4WQBO.js";import"./chunk-QN4UHB5C.js";import{a as t}from"./chunk-JWNCKRN6.js";var g=async(n,c={})=>{let o=t(n,["direction","amount","gridId","grid","coordinate","target","id"]),e=(o.direction||"down").toLowerCase(),i=o.amount?parseInt(o.amount,10):6,d=o.gridId||o.grid||o.coordinate||o.target||o.id||null;return await r("scroll",d,{direction:e,amount:i})};export{g as scroll};
@@ -1,4 +1,4 @@
1
- import{a as nt}from"./chunk-JWNCKRN6.js";import{b as rt}from"./chunk-KQNW7DK5.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import{w as Y,x as tt,y as et,z as st}from"./chunk-NPXJIGAI.js";import X from"fs/promises";import E from"path";import K from"fast-glob";import{Minimatch as it}from"minimatch";async function O(f,l,y=f,d=1){if(d>12)return[];let h=[],r;try{r=await X.readdir(f,{withFileTypes:!0})}catch{return[]}for(let t of r){let e=E.join(f,t.name),w=E.relative(y,e),F=w.split(E.sep).map(L=>L.toLowerCase()),N=t.name.toLowerCase();if(!l.some(L=>{let v=L.toLowerCase();return v.startsWith(".")&&N.endsWith(v)?!0:F.some(P=>P===v||P.startsWith(".pnpm"))}))if(t.isDirectory()){let L=await O(e,l,y,d+1);h=h.concat(L)}else t.isFile()&&h.push({fullPath:e,relativePath:w})}return h}function at(f,l,y=1/0){if(f===l)return 0;if(f.length===0)return l.length;if(l.length===0)return f.length;if(Math.abs(f.length-l.length)>y)return y+1;let d=Array.from({length:l.length+1},(h,r)=>r);for(let h=1;h<=f.length;h++){let r=[h],t=h;for(let e=1;e<=l.length;e++){let w=f[h-1]===l[e-1]?0:1,F=Math.min(r[e-1]+1,d[e]+1,d[e-1]+w);r.push(F),F<t&&(t=F)}if(d=r,t>y)return y+1}return d[l.length]}function ct(f,l){if(!f||!l)return!1;let y=f.toLowerCase(),d=l.toLowerCase();if(y.includes(d))return!0;let h=y.split(/[^a-z0-9]+/).filter(t=>t.length>0),r=d.split(/[^a-z0-9]+/).filter(t=>t.length>1||d.length===1&&t.length>0);return r.length===0?!1:r.every(t=>{let e=t.length<=2?0:t.length<=5?1:2;for(let w of h)if(w.includes(t)||t.length>=3&&w.length>=3&&Math.abs(w.length-t.length)<=e&&at(t,w,e)<=e)return!0;return!1})}var yt=async f=>{let{keyword:l,path:y,fuzzy:d,subString:h,regex:r}=nt(f,["keyword","path"]);if(l==null)return'ERROR: Missing "keyword" argument.';let t=String(l),e=y,w=!1;if(e){let{resolvedPath:s,isTildeResolved:u}=st(e);e=s,w=u;let n=e.trim().toLowerCase();if(n==="#docs"||n==="#doc"||n==="#documentation"||n.includes("#skill/global/fluxflow")||n.startsWith("#skill"))return"ERROR: Cannot search in reserved VFS '#skill' namespace. Use 'ReadFile' to read specific skills."}let F=s=>s===!0||s==="true"||s===1||s==="1"||s==="yes",N=r===!1||r==="false"||r===0||r==="0"||r==="no",T=r===!0||r==="true"||r===1||r==="1"||r==="yes",L=F(d)||F(h),v=null,P=null,H=s=>{let u=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=/^\w/.test(s)?"(?<![\\w])":"",k=/\w$/.test(s)?"(?![\\w])":"";return new RegExp(`${n}${u}${k}`,"i")};if(N)L||(P=H(t));else{try{let s=t;v=new RegExp(s,"i")}catch(s){if(T)return`ERROR: Invalid regex pattern "${t}": ${s.message}`}P=H(t)}let S=Array.from(new Set([...Y,...tt(process.cwd())])),V=150;try{let s=[],u=process.cwd(),n=null;if(e){let o=i=>i.startsWith("!")||!i.startsWith("-")?i:"!"+i.replace(/^-+/,""),g=e.split(";").map(i=>i.trim()).filter(Boolean).map(o).filter(i=>i!=="!"),c=g.some(i=>i.startsWith("!"));if(g.some(i=>K.isDynamicPattern(i)||/[*?{}[\]()|+]/.test(i))){n="glob";let i=e.replace(/\\/g,"/"),a=g.map(m=>m.replace(/\\/g,"/")),z=S.map(m=>m.startsWith(".")?`**/*${m}`:`**/${m}/**`);if(c&&!g.some(m=>!m.startsWith("!"))){let m=await O(u,S,u),R=$=>$.endsWith("/")?$+"**":$,p=a.filter($=>$.startsWith("!")).map($=>R($.slice(1))),M=a.filter($=>!$.startsWith("!")).map(R);s=m.filter($=>{let x=$.relativePath.replace(/\\/g,"/"),Z=M.length===0||M.some(C=>{try{return new it(C).match(x)}catch{return!1}}),j=p.some(C=>{try{return new it(C).match(x)}catch{return!1}});return Z&&!j})}else{let m=a.some(p=>/[\(\)\|]|\.\*/.test(p)),R=[];if(!m)try{R=await K(a,{cwd:u,ignore:z,dot:!0,onlyFiles:!0,absolute:!1})}catch{R=[]}if(R.length===0&&(m||K.isDynamicPattern(i))){let p=i.match(/^([^\*\?\(\)\|\[\]\s]+)\//),M=p&&!/[\*\?\(\)\|\[\]]/.test(p[1])?E.resolve(u,p[1]):u,$=await O(M,S,u);try{let x=i.replace(/^\.\//,"");x=x.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!x.startsWith("^")&&!x.startsWith(".*")&&(x=`.*${x}`);let Z=new RegExp(x.endsWith("$")?x:`${x}$`,"i");s=$.filter(j=>{let C=j.relativePath.replace(/\\/g,"/");return Z.test(C)})}catch{s=[]}}else s=R.map(p=>({fullPath:E.resolve(u,p),relativePath:p}))}}else{let i=[],a=!1,z=!1;for(let I of g){let m=I.replace(/[\/\\]+$/,""),R=E.resolve(u,m);try{let p=await X.stat(R);if(p.isDirectory()){z=!0;let M=await O(R,S,u);i.push(...M)}else if(p.isFile())a=!0,i.push({fullPath:R,relativePath:E.relative(u,R)});else return`ERROR: Path is neither a file nor a directory: ${I}`}catch{return`ERROR: Path not found: ${I}`}}s=i,a&&!z?n="file":n="dir"}}else s=await O(u,S);let k=s.map(async o=>{try{let g=await X.readFile(o.fullPath,"utf-8");if(g.includes("\0"))return[];let c=g.split(/\r?\n/),W=[];for(let a=0;a<c.length;a++)(L?c[a].toLowerCase().includes(t.toLowerCase())||ct(c[a],t):N?P&&P.test(c[a]):v&&v.test(c[a])||P&&P.test(c[a]))&&W.push({line:a+1,content:c[a].trim()});return W.length===0?null:{path:o.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),ot=await Promise.all(k),D=[],b=0;for(let o of ot){if(!o||!o.matches)continue;if(b>=V)break;let g=V-b,c=o.matches.slice(0,g);D.push({path:o.path,matches:c}),b+=c.length}typeof global.gc=="function"&&global.gc();let B=null;if(D.length===0){let o=n==="file"?` in '${e}'`:n==="dir"||n==="glob"?` in '${e}'`:". Try to specify files",g=n==="dir"?"[DIR]":n==="glob"?"[GLOB]":"";return`${g}${g?" ":""}Found 0 matches of '${t}'${o}${B?` ${B}`:""}`}let U=B?` ${B}`:"",q=`${D.length} file${D.length===1?"":"s"}`,_=`${b} match${b===1?"":"es"}`,G;n==="file"?G=`Found ${_} of '${t}' in '${e}'${U}:`:n==="dir"||n==="glob"?G=`Found ${_} of '${t}' in '${e}' across ${q}${U}:`:G=`Found ${_} of '${t}' across ${q}${U}:`;let J=n==="dir"?"[DIR]":n==="glob"?"[GLOB]":"",A=`${J}${J?" ":""}${G}
1
+ import{a as nt}from"./chunk-JWNCKRN6.js";import{b as rt}from"./chunk-MS7BITZ6.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import{w as Y,x as tt,y as et,z as st}from"./chunk-NPXJIGAI.js";import X from"fs/promises";import E from"path";import K from"fast-glob";import{Minimatch as it}from"minimatch";async function O(f,l,y=f,d=1){if(d>12)return[];let h=[],r;try{r=await X.readdir(f,{withFileTypes:!0})}catch{return[]}for(let t of r){let e=E.join(f,t.name),w=E.relative(y,e),F=w.split(E.sep).map(L=>L.toLowerCase()),N=t.name.toLowerCase();if(!l.some(L=>{let v=L.toLowerCase();return v.startsWith(".")&&N.endsWith(v)?!0:F.some(P=>P===v||P.startsWith(".pnpm"))}))if(t.isDirectory()){let L=await O(e,l,y,d+1);h=h.concat(L)}else t.isFile()&&h.push({fullPath:e,relativePath:w})}return h}function at(f,l,y=1/0){if(f===l)return 0;if(f.length===0)return l.length;if(l.length===0)return f.length;if(Math.abs(f.length-l.length)>y)return y+1;let d=Array.from({length:l.length+1},(h,r)=>r);for(let h=1;h<=f.length;h++){let r=[h],t=h;for(let e=1;e<=l.length;e++){let w=f[h-1]===l[e-1]?0:1,F=Math.min(r[e-1]+1,d[e]+1,d[e-1]+w);r.push(F),F<t&&(t=F)}if(d=r,t>y)return y+1}return d[l.length]}function ct(f,l){if(!f||!l)return!1;let y=f.toLowerCase(),d=l.toLowerCase();if(y.includes(d))return!0;let h=y.split(/[^a-z0-9]+/).filter(t=>t.length>0),r=d.split(/[^a-z0-9]+/).filter(t=>t.length>1||d.length===1&&t.length>0);return r.length===0?!1:r.every(t=>{let e=t.length<=2?0:t.length<=5?1:2;for(let w of h)if(w.includes(t)||t.length>=3&&w.length>=3&&Math.abs(w.length-t.length)<=e&&at(t,w,e)<=e)return!0;return!1})}var yt=async f=>{let{keyword:l,path:y,fuzzy:d,subString:h,regex:r}=nt(f,["keyword","path"]);if(l==null)return'ERROR: Missing "keyword" argument.';let t=String(l),e=y,w=!1;if(e){let{resolvedPath:s,isTildeResolved:u}=st(e);e=s,w=u;let n=e.trim().toLowerCase();if(n==="#docs"||n==="#doc"||n==="#documentation"||n.includes("#skill/global/fluxflow")||n.startsWith("#skill"))return"ERROR: Cannot search in reserved VFS '#skill' namespace. Use 'ReadFile' to read specific skills."}let F=s=>s===!0||s==="true"||s===1||s==="1"||s==="yes",N=r===!1||r==="false"||r===0||r==="0"||r==="no",T=r===!0||r==="true"||r===1||r==="1"||r==="yes",L=F(d)||F(h),v=null,P=null,H=s=>{let u=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=/^\w/.test(s)?"(?<![\\w])":"",k=/\w$/.test(s)?"(?![\\w])":"";return new RegExp(`${n}${u}${k}`,"i")};if(N)L||(P=H(t));else{try{let s=t;v=new RegExp(s,"i")}catch(s){if(T)return`ERROR: Invalid regex pattern "${t}": ${s.message}`}P=H(t)}let S=Array.from(new Set([...Y,...tt(process.cwd())])),V=150;try{let s=[],u=process.cwd(),n=null;if(e){let o=i=>i.startsWith("!")||!i.startsWith("-")?i:"!"+i.replace(/^-+/,""),g=e.split(";").map(i=>i.trim()).filter(Boolean).map(o).filter(i=>i!=="!"),c=g.some(i=>i.startsWith("!"));if(g.some(i=>K.isDynamicPattern(i)||/[*?{}[\]()|+]/.test(i))){n="glob";let i=e.replace(/\\/g,"/"),a=g.map(m=>m.replace(/\\/g,"/")),z=S.map(m=>m.startsWith(".")?`**/*${m}`:`**/${m}/**`);if(c&&!g.some(m=>!m.startsWith("!"))){let m=await O(u,S,u),R=$=>$.endsWith("/")?$+"**":$,p=a.filter($=>$.startsWith("!")).map($=>R($.slice(1))),M=a.filter($=>!$.startsWith("!")).map(R);s=m.filter($=>{let x=$.relativePath.replace(/\\/g,"/"),Z=M.length===0||M.some(C=>{try{return new it(C).match(x)}catch{return!1}}),j=p.some(C=>{try{return new it(C).match(x)}catch{return!1}});return Z&&!j})}else{let m=a.some(p=>/[\(\)\|]|\.\*/.test(p)),R=[];if(!m)try{R=await K(a,{cwd:u,ignore:z,dot:!0,onlyFiles:!0,absolute:!1})}catch{R=[]}if(R.length===0&&(m||K.isDynamicPattern(i))){let p=i.match(/^([^\*\?\(\)\|\[\]\s]+)\//),M=p&&!/[\*\?\(\)\|\[\]]/.test(p[1])?E.resolve(u,p[1]):u,$=await O(M,S,u);try{let x=i.replace(/^\.\//,"");x=x.replace(/\.\*\/(\\.|[^\/])/g,".*$1"),!x.startsWith("^")&&!x.startsWith(".*")&&(x=`.*${x}`);let Z=new RegExp(x.endsWith("$")?x:`${x}$`,"i");s=$.filter(j=>{let C=j.relativePath.replace(/\\/g,"/");return Z.test(C)})}catch{s=[]}}else s=R.map(p=>({fullPath:E.resolve(u,p),relativePath:p}))}}else{let i=[],a=!1,z=!1;for(let I of g){let m=I.replace(/[\/\\]+$/,""),R=E.resolve(u,m);try{let p=await X.stat(R);if(p.isDirectory()){z=!0;let M=await O(R,S,u);i.push(...M)}else if(p.isFile())a=!0,i.push({fullPath:R,relativePath:E.relative(u,R)});else return`ERROR: Path is neither a file nor a directory: ${I}`}catch{return`ERROR: Path not found: ${I}`}}s=i,a&&!z?n="file":n="dir"}}else s=await O(u,S);let k=s.map(async o=>{try{let g=await X.readFile(o.fullPath,"utf-8");if(g.includes("\0"))return[];let c=g.split(/\r?\n/),W=[];for(let a=0;a<c.length;a++)(L?c[a].toLowerCase().includes(t.toLowerCase())||ct(c[a],t):N?P&&P.test(c[a]):v&&v.test(c[a])||P&&P.test(c[a]))&&W.push({line:a+1,content:c[a].trim()});return W.length===0?null:{path:o.relativePath.replace(/\\/g,"/"),matches:W}}catch{return[]}}),ot=await Promise.all(k),D=[],b=0;for(let o of ot){if(!o||!o.matches)continue;if(b>=V)break;let g=V-b,c=o.matches.slice(0,g);D.push({path:o.path,matches:c}),b+=c.length}typeof global.gc=="function"&&global.gc();let B=null;if(D.length===0){let o=n==="file"?` in '${e}'`:n==="dir"||n==="glob"?` in '${e}'`:". Try to specify files",g=n==="dir"?"[DIR]":n==="glob"?"[GLOB]":"";return`${g}${g?" ":""}Found 0 matches of '${t}'${o}${B?` ${B}`:""}`}let U=B?` ${B}`:"",q=`${D.length} file${D.length===1?"":"s"}`,_=`${b} match${b===1?"":"es"}`,G;n==="file"?G=`Found ${_} of '${t}' in '${e}'${U}:`:n==="dir"||n==="glob"?G=`Found ${_} of '${t}' in '${e}' across ${q}${U}:`:G=`Found ${_} of '${t}' across ${q}${U}:`;let J=n==="dir"?"[DIR]":n==="glob"?"[GLOB]":"",A=`${J}${J?" ":""}${G}
2
2
 
3
3
  `,Q="";try{let o=await rt();o?.systemSettings?.alwaysAskFiles&&(Q=o.systemSettings.alwaysAskFiles)}catch{}for(let o of D)if(A+=`${o.path}:
4
4
  `,et(o.path,Q)){let c=o.matches.map(W=>`Line ${W.line}`).join(", ");A+=` ${c}. Line snapshot not available due to file restriction policy. ReadFile if needed
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m}from"./chunk-3HGLLXBK.js";import{n as a}from"./chunk-IWIVGFAT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{a as NULL_KEY_SENTINEL,b as getAPIKey,c as getProviderAPIKey,h as getSearchSecrets,f as getSecret,m as removeAPIKey,l as removeSecret,e as replaceActiveProviderKey,i as saveAPIKey,d as saveProviderAPIKey,k as saveSearchId,j as saveSearchKey,g as saveSecret};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m}from"./chunk-3WV6FIZV.js";import{n as a}from"./chunk-3PZTWZTT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{a as NULL_KEY_SENTINEL,b as getAPIKey,c as getProviderAPIKey,h as getSearchSecrets,f as getSecret,m as removeAPIKey,l as removeSecret,e as replaceActiveProviderKey,i as saveAPIKey,d as saveProviderAPIKey,k as saveSearchId,j as saveSearchKey,g as saveSecret};
@@ -1 +1 @@
1
- import{A,B,C,D,E,F,G,H,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-IWIVGFAT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{a as HIDDEN_FROM_SUMMARY,n as NULL_KEY_SENTINEL,b as PROVIDER_DEFS,A as addProviderKey,H as buildListLines,E as cleanProviderKeys,u as clearAllTempKeys,v as clearTempKey,j as countProviderKeys,G as formatBaseUrl,l as getActiveIndex,d as getCanonicalProviders,g as getProviderLabel,i as getProviderSlots,k as getProviderSummary,s as getTempKey,t as hasTempKey,f as isHiddenFromSummary,p as isNullMode,e as isUrlBearing,F as maskKey,h as migrateFromLegacy,c as normalizeProvider,C as removeProviderKey,B as replaceActiveProviderKey,x as resolveAPIKey,y as resolveBaseUrl,m as setActiveIndex,w as setNoticeHandler,q as setNullMode,r as setTempKey,o as supportsNullKey,D as useProviderKey,z as validateOpenAIBaseUrl};
1
+ import{A,B,C,D,E,F,G,H,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-3PZTWZTT.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{a as HIDDEN_FROM_SUMMARY,n as NULL_KEY_SENTINEL,b as PROVIDER_DEFS,A as addProviderKey,H as buildListLines,E as cleanProviderKeys,u as clearAllTempKeys,v as clearTempKey,j as countProviderKeys,G as formatBaseUrl,l as getActiveIndex,d as getCanonicalProviders,g as getProviderLabel,i as getProviderSlots,k as getProviderSummary,s as getTempKey,t as hasTempKey,f as isHiddenFromSummary,p as isNullMode,e as isUrlBearing,F as maskKey,h as migrateFromLegacy,c as normalizeProvider,C as removeProviderKey,B as replaceActiveProviderKey,x as resolveAPIKey,y as resolveBaseUrl,m as setActiveIndex,w as setNoticeHandler,q as setNullMode,r as setTempKey,o as supportsNullKey,D as useProviderKey,z as validateOpenAIBaseUrl};
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-KQNW7DK5.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{a as PROVIDER_BASE_URLS,b as loadSettings,c as saveSettings};
1
+ import{a,b,c}from"./chunk-MS7BITZ6.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{a as PROVIDER_BASE_URLS,b as loadSettings,c as saveSettings};
@@ -1,2 +1,2 @@
1
- import{a as R}from"./chunk-PTFCY2D5.js";import{a as C}from"./chunk-UM5SNZ6X.js";import"./chunk-NPXJIGAI.js";var J=async function*(A,k,N,y,x,$,M,v,B=1){let g=[];y&&g.push({role:"system",content:y});for(let s of N){let T=s.role==="user"?"user":"assistant",e=[];if(Array.isArray(s.parts)){for(let n of s.parts)if(n.text)e.push({type:"text",text:n.text});else if(n.inlineData&&M){let i=n.inlineData.mimeType,u=n.inlineData.data;i.startsWith("image/")&&e.push({type:"image_url",image_url:{url:`data:${i};base64,${u}`}})}}else{let n=s.text||"";n&&e.push({type:"text",text:n})}g.push({role:T,content:e.length===1&&e[0].type==="text"?e[0].text:e})}let w=C("TokenHarbor",k,x),H=w!==null?w:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[x],D={model:k,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:B,tools:[],tool_choice:"none"};H&&(D.reasoning_effort=H);let K=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",O={"Content-Type":"application/json","X-Title":"Flux-Flow","User-Agent":"Flux-Flow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},P=A||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";O.Authorization=`Bearer ${P}`;let l=await R(K,{method:"POST",headers:O,body:JSON.stringify(D),signal:v});if(!l.ok){let s=await l.json().catch(()=>({}));throw new Error(`Token Harbor Error (${l.status}): ${s.error?.message||s.message||l.statusText}`)}let F=l.body.getReader(),L=new TextDecoder,m="",t=[],c=null,f=Date.now(),o=!1,d=[],E=0,S=5,b=!0,_=()=>{d.length>0&&(t.push(...d),d=[],o=!0),b=!1};for(;;){let{done:s,value:T}=await F.read();if(s){_(),o&&(t.length>0||c)&&(yield{candidates:t.length>0?[{content:{parts:t}}]:[],usageMetadata:c});break}m+=L.decode(T,{stream:!0});let e=m.split(`
1
+ import{a as R}from"./chunk-PTFCY2D5.js";import{a as C}from"./chunk-UM5SNZ6X.js";import"./chunk-NPXJIGAI.js";var J=async function*(A,k,N,y,x,$,M,v,B=1){let g=[];y&&g.push({role:"system",content:y});for(let s of N){let T=s.role==="user"?"user":"assistant",e=[];if(Array.isArray(s.parts)){for(let n of s.parts)if(n.text)e.push({type:"text",text:n.text});else if(n.inlineData&&M){let i=n.inlineData.mimeType,u=n.inlineData.data;i.startsWith("image/")&&e.push({type:"image_url",image_url:{url:`data:${i};base64,${u}`}})}}else{let n=s.text||"";n&&e.push({type:"text",text:n})}g.push({role:T,content:e.length===1&&e[0].type==="text"?e[0].text:e})}let w=C("TokenHarbor",k,x),H=w!==null?w:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"}[x],D={model:k,messages:g,stream:!0,stream_options:{include_usage:!0},temperature:B,tools:[],tool_choice:"none"};H&&(D.reasoning_effort=H);let K=process.env.TOKENHARBOR_URL||process.env.TOKEN_HARBOR_URL||"https://tokenharbor.ai/v1/chat/completions",O={"Content-Type":"application/json","X-Title":"FluxFlow","User-Agent":"FluxFlow","HTTP-Referer":"https://fluxflow-cli.onrender.com/"},P=A||process.env.TOKENHARBOR_API_KEY||process.env.TOKEN_HARBOR_API_KEY||"";O.Authorization=`Bearer ${P}`;let l=await R(K,{method:"POST",headers:O,body:JSON.stringify(D),signal:v});if(!l.ok){let s=await l.json().catch(()=>({}));throw new Error(`Token Harbor Error (${l.status}): ${s.error?.message||s.message||l.statusText}`)}let F=l.body.getReader(),L=new TextDecoder,m="",t=[],c=null,f=Date.now(),o=!1,d=[],E=0,S=5,b=!0,_=()=>{d.length>0&&(t.push(...d),d=[],o=!0),b=!1};for(;;){let{done:s,value:T}=await F.read();if(s){_(),o&&(t.length>0||c)&&(yield{candidates:t.length>0?[{content:{parts:t}}]:[],usageMetadata:c});break}m+=L.decode(T,{stream:!0});let e=m.split(`
2
2
  `);m=e.pop();for(let n of e){let i=n.trim();if(!i||!i.startsWith("data: "))continue;let u=!1;if(i==="data: [DONE]")u=!0,_();else try{let p=JSON.parse(i.substring(6)),a=p.choices?.[0]?.delta,r=p.usage;if(r&&(c={totalTokenCount:r.total_tokens||(r.prompt_tokens||0)+(r.completion_tokens||0),promptTokenCount:r.prompt_tokens||0,candidatesTokenCount:r.completion_tokens||0,cachedContentTokenCount:r.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:r.completion_tokens_details?.reasoning_tokens||r.reasoning_tokens||0},o=!0),a){let h=a.reasoning_content||a.reasoning||null;!h&&Array.isArray(a.reasoning_details)&&a.reasoning_details.length>0&&(h=a.reasoning_details.map(U=>U.text||"").filter(Boolean).join("")),h&&(t.push({text:h,thought:!0}),o=!0),a.content&&(b?(d.push({text:a.content}),E++,E>=S&&_()):(t.push({text:a.content}),o=!0))}}catch{}if((u||Date.now()-f>=150)&&o&&(yield{candidates:t.length>0?[{content:{parts:[...t]}}]:[],usageMetadata:c},t=[],f=Date.now(),o=!1),u)break}Date.now()-f>=150&&o&&(yield{candidates:t.length>0?[{content:{parts:[...t]}}]:[],usageMetadata:c},t=[],f=Date.now(),o=!1)}};export{J as getTokenHarborStream};
@@ -1,4 +1,4 @@
1
- import{g as F,h as C,i as y,j as P}from"./chunk-JMMO76HS.js";import{a as E}from"./chunk-2RTYI6K3.js";import{a as M}from"./chunk-JWNCKRN6.js";import{o as w}from"./chunk-5MJKHQVE.js";import{b as $}from"./chunk-KQNW7DK5.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import{z as R}from"./chunk-NPXJIGAI.js";import p from"fs";import N from"path";var q=async(S,v={})=>{let n=M(S,["path","allowMultiple","searchContent*","replaceContent*","newContent*"]),e=n.path;if(!e)return'ERROR: Missing "path" argument for PatchFile.';let{resolvedPath:O,isTildeResolved:T}=R(e);e=O;let{patchPairs:i,allowMultiple:b,error:d}=F(n);if(d)return`ERROR: ${d}`;if(i.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let k=n.allowMultiple!==void 0?n.allowMultiple===!0||String(n.allowMultiple).toLowerCase()==="true":b,l=N.resolve(process.cwd(),e);try{if(!p.existsSync(l))return`ERROR: File [${e}] does not exist. Use WriteFile instead.`;let t=v.forcedContent||p.readFileSync(l,"utf8");t.startsWith("\uFEFF")&&(t=t.slice(1));let o=t.replace(/\r\n/g,`
1
+ import{g as F,h as C,i as y,j as P}from"./chunk-JMMO76HS.js";import{a as E}from"./chunk-2RTYI6K3.js";import{a as M}from"./chunk-JWNCKRN6.js";import{o as w}from"./chunk-KYIMFUZS.js";import{b as $}from"./chunk-MS7BITZ6.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import{z as R}from"./chunk-NPXJIGAI.js";import p from"fs";import N from"path";var q=async(S,v={})=>{let n=M(S,["path","allowMultiple","searchContent*","replaceContent*","newContent*"]),e=n.path;if(!e)return'ERROR: Missing "path" argument for PatchFile.';let{resolvedPath:O,isTildeResolved:T}=R(e);e=O;let{patchPairs:i,allowMultiple:b,error:d}=F(n);if(d)return`ERROR: ${d}`;if(i.length===0)return"ERROR: No valid replacement pairs found. Use searchContent1, newContent1, etc.";let k=n.allowMultiple!==void 0?n.allowMultiple===!0||String(n.allowMultiple).toLowerCase()==="true":b,l=N.resolve(process.cwd(),e);try{if(!p.existsSync(l))return`ERROR: File [${e}] does not exist. Use WriteFile instead.`;let t=v.forcedContent||p.readFileSync(l,"utf8");t.startsWith("\uFEFF")&&(t=t.slice(1));let o=t.replace(/\r\n/g,`
2
2
  `).replace(/\r/g,`
3
3
  `),{content:a,results:s}=C(o,i,{allowMultiple:k}),c=s.filter(r=>!r.success),u=s.filter(r=>r.success);if(u.length===0)return`ERROR: Patch Failed to apply to [${e}].
4
4
  ${c.map(r=>` \u2022 ${r.error}`).join(`
@@ -1 +1 @@
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,x,y}from"./chunk-5MJKHQVE.js";import"./chunk-KQNW7DK5.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{p as addToUsage,c as calculateTokenCost,v as checkImageQuota,s as checkQuota,r as checkQuotaDetailed,e as forceFlushUsage,y as getAllUsageData,q as getCustomPeriodUsage,j as getDailyUsage,t as getImageQuotaBuckets,u as getImageQuotaLimit,w as getImageQuotaStats,k as getMonthlyUsage,h as getTimedUsage,l as incrementUsage,i as initUsage,d as invalidateCachedBaseUrl,n as onCodeChange,g as purgeTimedUsage,o as recordCodeChange,x as recordImageGeneration,f as recordTimedUsage,m as runtimeSession,b as sendUsageFinalize,a as sendUsageHeartbeat};
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,x,y}from"./chunk-KYIMFUZS.js";import"./chunk-MS7BITZ6.js";import"./chunk-Y6O7SAPD.js";import"./chunk-ZGORMZE5.js";import"./chunk-NPXJIGAI.js";export{p as addToUsage,c as calculateTokenCost,v as checkImageQuota,s as checkQuota,r as checkQuotaDetailed,e as forceFlushUsage,y as getAllUsageData,q as getCustomPeriodUsage,j as getDailyUsage,t as getImageQuotaBuckets,u as getImageQuotaLimit,w as getImageQuotaStats,k as getMonthlyUsage,h as getTimedUsage,l as incrementUsage,i as initUsage,d as invalidateCachedBaseUrl,n as onCodeChange,g as purgeTimedUsage,o as recordCodeChange,x as recordImageGeneration,f as recordTimedUsage,m as runtimeSession,b as sendUsageFinalize,a as sendUsageHeartbeat};