fluxflow-cli 4.50.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +7 -16
- package/README.md +1 -4
- package/TOOLS.md +0 -9
- package/UI_FEATURES.md +1 -2
- package/dist/chunks/ai-WBRHU7IH.js +1 -0
- package/dist/chunks/app-YYK3S5Y5.js +325 -0
- package/dist/chunks/{auto_completion-5WD4TTIP.js → auto_completion-UG6IEWD2.js} +1 -1
- package/dist/chunks/{chat-BA72I6O3.js → chat-ISCVWNVN.js} +1 -1
- package/dist/chunks/chunk-24LJKH4G.js +847 -0
- package/dist/chunks/chunk-7SGZ66KT.js +44 -0
- package/dist/chunks/chunk-B4UKMX5E.js +1 -0
- package/dist/chunks/{chunk-Z5D4VQSG.js → chunk-EXT42EJZ.js} +1 -1
- package/dist/chunks/{chunk-6JMPGZPV.js → chunk-GBH7XI5A.js} +1 -1
- package/dist/chunks/{chunk-5KSNFTQN.js → chunk-J4J3F6BT.js} +1 -1
- package/dist/chunks/chunk-LQM3JK7N.js +1 -0
- package/dist/chunks/{chunk-ZURGYQ4L.js → chunk-QESQR5GB.js} +1 -1
- package/dist/chunks/chunk-V36DXF56.js +13 -0
- package/dist/chunks/{chunk-TRVRMCHV.js → chunk-ZNO55RNG.js} +1 -1
- package/dist/chunks/{click-F4M4FVLQ.js → click-AWHZCV2E.js} +2 -2
- package/dist/chunks/{computer_action-72ZORSKW.js → computer_action-MO2JR2XH.js} +1 -1
- package/dist/chunks/{custom_openai-BLC4CWOL.js → custom_openai-K554R7Q5.js} +1 -1
- package/dist/chunks/{drag-OT2BJZ4P.js → drag-D2GVPIQB.js} +1 -1
- package/dist/chunks/{generate_image-V4OMOT7Z.js → generate_image-45UQ6P2B.js} +1 -1
- package/dist/chunks/{invoke-L2V4QMJG.js → invoke-DVZUJJV3.js} +2 -2
- package/dist/chunks/{invokeSync-7NWIYBX5.js → invokeSync-NEZGW27B.js} +2 -2
- package/dist/chunks/{key_press-IVB7R7CK.js → key_press-AQNKL6UM.js} +1 -1
- package/dist/chunks/{keyboard_typing-A6VFLI7Q.js → keyboard_typing-QSBPTZJ6.js} +1 -1
- package/dist/chunks/{mistral-YTTOZB2J.js → mistral-ON6RQMK7.js} +1 -1
- package/dist/chunks/{model_config-JTMSQGKH.js → model_config-QRYAVWHF.js} +1 -1
- package/dist/chunks/{nvidia-ON4Q6Q26.js → nvidia-I6DPWP6U.js} +2 -2
- package/dist/chunks/{ollama-DIFOZ4PM.js → ollama-6WSZPCI5.js} +1 -1
- package/dist/chunks/{recapture_screen-TVTRNE7C.js → recapture_screen-PPXYK2YY.js} +1 -1
- package/dist/chunks/{screen_grid-AEHMTXP3.js → screen_grid-3RU324CV.js} +1 -1
- package/dist/chunks/{scroll-KFID5QKZ.js → scroll-TSU6MTGU.js} +1 -1
- package/dist/chunks/search_keyword-DZY4MWV7.js +8 -0
- package/dist/chunks/{secrets-JMSL57D2.js → secrets-TNMLVMST.js} +1 -1
- package/dist/chunks/{secrets_v2-U7JR7ZO6.js → secrets_v2-OBRWR3UT.js} +1 -1
- package/dist/chunks/{settings-3VSVCZDF.js → settings-PUFSRWT3.js} +1 -1
- package/dist/chunks/update_file-TGEB5UWK.js +13 -0
- package/dist/chunks/usage-EBE2OVES.js +1 -0
- package/dist/chunks/{usageServer-4X7T4FDJ.js → usageServer-RTK5N5KE.js} +1 -2
- package/dist/chunks/write_file-O6OF7Z2W.js +32 -0
- package/dist/cli.js +25 -22
- package/dist/model_config.json +2 -30
- package/dist/package.json +2 -2
- package/model_config.json +2 -30
- package/package.json +2 -2
- package/dist/chunks/ai-EWDCEXLL.js +0 -1
- package/dist/chunks/app-C7G3NWAQ.js +0 -333
- package/dist/chunks/chunk-HTOLY3HR.js +0 -1
- package/dist/chunks/chunk-OB2V6ZNC.js +0 -951
- package/dist/chunks/chunk-PACSPBDP.js +0 -1
- package/dist/chunks/chunk-T5CUPXCW.js +0 -13
- package/dist/chunks/chunk-TX3H7HDF.js +0 -44
- package/dist/chunks/search_keyword-666PL7YG.js +0 -8
- package/dist/chunks/update_file-RG5QSLR2.js +0 -13
- package/dist/chunks/usage-AJDMLXTH.js +0 -1
- package/dist/chunks/write_file-AQJXPIUV.js +0 -32
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import{c as X}from"./chunk-26BQ45XP.js";import K from"os";import{structuredPatch as Z}from"diff";var N=e=>typeof e!="string"?e:e.length>12?(e+"").replace("",""):e,j=(e,i)=>{if(!e)return"";let f=/\x1B\[[0-?]*[ -/]*[@-~]/g,d=e.split(`
|
|
2
|
+
`),c=[];if(i<=5)return e;let l=r=>r<32||r>=127&&r<160||r>=768&&r<=879||r>=7616&&r<=7679||r>=8400&&r<=8447||r>=65056&&r<=65071?0:r>=4352&&r<=4447||r>=9001&&r<=9002||r>=11904&&r<=12350||r>=12352&&r<=42191||r>=44032&&r<=55203||r>=63744&&r<=64255||r>=65040&&r<=65049||r>=65072&&r<=65135||r>=65280&&r<=65376||r>=65504&&r<=65510||r>=127744&&r<=128591||r>=128640&&r<=128767||r>=131072&&r<=262141?2:1,k=r=>{let o=r.replace(f,""),n=0;for(let s=0;s<o.length;s++){let p=o.codePointAt(s);p>65535&&s++,n+=l(p)}return n},A=(r,o)=>{let n=0,s=r.length,p=!1;for(let h=0;h<r.length;h++){if(r[h]==="\x1B"&&r[h+1]==="["&&(p=!0),p){(r[h]==="m"||r[h]>="@"&&r[h]<="~"&&r[h]!=="[")&&(p=!1);continue}let w=r.codePointAt(h);w>65535&&h++;let C=l(w);if(n+C>o){s=w>65535?h-1:h;break}if(n+=C,n>=o){s=h+1;break}}return{head:r.substring(0,s),tail:r.substring(s)}};return d.forEach(r=>{if(k(r)<=i){c.push(r);return}let n=r.split(/(\s+)/),s="",p=0,h=r.match(/^(\s*)/),w=h?h[1]:"";n.forEach(C=>{if(C.length===0)return;let I=C;for(;I.length>0;){let T=k(I);if(p+T<=i){s+=I,p+=T;break}s.trim().length>0&&(c.push(s.trimEnd()),s=w.substring(0,Math.min(w.length,8)),p=k(s));let t=Math.max(1,i-p);if(k(I)>t){let{head:a,tail:u}=A(I,t);c.push((s+a).trimEnd()),s=w.substring(0,Math.min(w.length,8)),p=k(s),I=u}else s+=I,p+=k(I),I=""}}),(s.trimEnd().length>0||s===w)&&c.push(s.trimEnd())}),N(c.join(`
|
|
3
|
+
`))},ce=e=>{if(!e)return 0;let i=0,f=e.match(/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g);f&&(i+=f.length*.55);let d=e.replace(/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g," "),c=d.match(/[<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}-]+/g);c&&(i+=c.length);let l=d.split(/[\s<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}-]+/g).filter(Boolean);return i+=l.length,Math.max(.1,i)},ae=e=>e?e.match(/[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]|\s+|[<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}-]+|[^\s<>/\._@#$%^&*+=`~|\\:;!?'"()\[\]{}\-\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]+/g)||[e]:[],fe=e=>{if(!e&&e!==0)return"0.0k";let i=typeof e=="string"?parseFloat(e):e;return i>=1e6?`${(i/1e6).toFixed(1)}m`:i>=1e3?`${(i/1e3).toFixed(1)}k`:i.toString()},ue=(e,i=40)=>{let f=X.replaceAll("\\\\","\\");if(e=e.replace(K.homedir(),"~").replace(f,"FluxFlow").replaceAll("\\","/"),!e||e.length<=i)return N(e);let d=Math.floor((i-3)/2);return N(e.substring(0,d)+"..."+e.substring(e.length-d).replaceAll("\\","/"))},he=e=>{let i=[],f=new Set,d=e.allowMultiple===!0||String(e.allowMultiple).toLowerCase()==="true";Object.keys(e).forEach(r=>{let o=r.match(/^(searchContent|search_content|replaceContent|replace_content|newContent|new_content|content_to_replace|content_to_add|searchBlock|search_block|newBlock|new_block)_?(\d+)?$/i);if(o){let n=o[2]?parseInt(o[2],10):1;f.add(n)}});let c=Array.from(f).sort((r,o)=>r-o),l=["searchContent","search_content","replaceContent","replace_content","content_to_replace","searchBlock","search_block"],k=["newContent","new_content","content_to_add","newBlock","new_block"],A=(r,o,n)=>{let s,p;for(let h of o){let w=r===1?[`${h}1`,h,`${h}_1`]:[`${h}${r}`,`${h}_${r}`];for(let C of w)if(e[C]!==void 0){s=e[C];break}if(s!==void 0)break}for(let h of n){let w=r===1?[`${h}1`,h,`${h}_1`]:[`${h}${r}`,`${h}_${r}`];for(let C of w)if(e[C]!==void 0){p=e[C];break}if(p!==void 0)break}return{r:s,n:p}};for(let r of c){let{r:o,n}=A(r,l,k);if(o!==void 0&&n!==void 0)i.push({replace:o,new:n});else if(o!==void 0||n!==void 0)return{error:`Mismatched replacement pair for index ${r}. Both replacement and new content must be provided.`,allowMultiple:d}}return{patchPairs:i,allowMultiple:d}},Y=e=>{if(!e)return null;let i="",f=0,d=e.length;for(;f<d;){let c=e[f];if(c==="\\"){for(;f<d&&e[f]==="\\";)f++;i+="\\\\*"}else if(c===`
|
|
4
|
+
`)i+="(?:\\r?\\n|\\\\*n|\\\\*r|\\s*)",f++;else if(c==="\r")i+="(?:\\r|\\\\*r)?",f++;else if(c===" ")i+="(?:\\t|\\\\*t|\\s*)",f++;else if(c==='"'||c==="'"||c==="`")i.endsWith("\\\\*")||(i+="\\\\*"),i+=c,f++;else if(/[.*+?^${}()|[\]]/.test(c))i+="\\"+c,f++;else if(/\s/.test(c)){for(;f<d&&/\s/.test(e[f])&&e[f]!==`
|
|
5
|
+
`&&e[f]!=="\r"&&e[f]!==" ";)f++;i+="\\s*"}else i+=c,f++}if(!i)return null;try{return new RegExp(i,"g")}catch{return null}},de=(e,i,f={})=>{let d=typeof f=="boolean"?f:!!(f&&f.allowMultiple),c=e.replace(/\r\n/g,`
|
|
6
|
+
`).replace(/\r/g,`
|
|
7
|
+
`),l=t=>t.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
|
|
8
|
+
`).replace(/\r/g,`
|
|
9
|
+
`),k=t=>t.match(/^\s*/)[0],A=t=>{let a=t.split(`
|
|
10
|
+
`).filter(g=>g.trim()!=="");if(a.length===0)return"";let u=k(a[0]);for(let g of a){let x=k(g);x.length<u.length&&(u=x)}return u},r=(t,a,u="")=>{if(!t||a===void 0)return t;let x=/^\t/m.test(a)?" ":" ",b=y=>y.split(`
|
|
11
|
+
`).find(M=>M.trim()!=="")??"",E=b(a).match(/^\s*/)[0].length,S=b(t).match(/^\s*/)[0].length,$=E-S,m=(u.match(/^\s*/)||[""])[0].length;return t.split(`
|
|
12
|
+
`).map((y,M)=>{if(y.trim()===""&&M!==0)return"";let L=y.match(/^\s*/)[0].length,_=Math.max(0,L+$);return M===0&&(_=Math.max(0,_-m)),x.repeat(_)+y.trimStart()}).join(`
|
|
13
|
+
`)},o=[];for(let t=0;t<i.length;t++){let a=i[t],u=(a.replace||"").trim(),g=l(a.new||"");if(u.startsWith("^LINE:")&&u.endsWith("$")){let $=u.slice(6,-1).trim(),m=$.includes("..")?$.split(".."):$.split("-"),F=parseInt(m[0]),y=m[1]!==void 0?parseInt(m[1]):F;if(!isNaN(F)&&!isNaN(y)){let M=c.split(`
|
|
14
|
+
`);if(F<1||F>M.length||y<F||y>M.length){o.push({index:t,success:!1,error:`Block ${t+1}: Line range ^LINE:${F}..${y}$ out of bounds (file has ${M.length} lines).`});continue}let _=M.slice(F-1,y).join(`
|
|
15
|
+
`),R=0;for(let B=0;B<F-1;B++)R+=M[B].length+1;o.push({index:t,success:!0,startPos:R,firstMatchContent:_,content_to_add:g});continue}}let x=l(a.replace||"");if(x===""&&g===""){o.push({index:t,success:!1,error:`Block ${t+1}: Empty replace and add content.`});continue}let b=x.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),E=null;if(x!==""&&c.includes(x))E=new RegExp(b,"g");else{let $=x.split(`
|
|
16
|
+
`).map(m=>m.trim()).filter(m=>m.length>0).map(m=>m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if($.length>0){let m=$.join("\\s*");try{E=new RegExp(m,"g")}catch{E=new RegExp(b,"g")}}else E=new RegExp(b,"g")}let S=[...c.matchAll(E)];if(S.length===0&&x!==""){let $=Y(x);$&&(S=[...c.matchAll($)])}if(S.length===0){o.push({index:t,success:!1,error:`Block ${t+1}: Could not find match.`});continue}if(S.length>1&&!d){o.push({index:t,success:!1,error:`Block ${t+1}: Found ${S.length} matches (must be unique or use allowMultiple: true if sure).`});continue}for(let $ of S)o.push({index:t,success:!0,startPos:$.index,firstMatchContent:$[0],content_to_add:g})}let n=o.filter(t=>t.success).sort((t,a)=>t.startPos-a.startPos);for(let t=0;t<n.length-1;t++){let a=n[t],u=n[t+1];a.startPos+a.firstMatchContent.length>u.startPos&&(a.success=!1,a.error=`Block ${a.index+1}: Overlaps with another block.`,u.success=!1,u.error=`Block ${u.index+1}: Overlaps with another block.`)}let s=new Map,p=c,h=0,w=0,C=o.filter(t=>t.success).sort((t,a)=>t.startPos-a.startPos);for(let t of C){let a=t.startPos,u=c.substring(0,a).split(`
|
|
17
|
+
`).length,g=a+h,x=u+w,b=p.lastIndexOf(`
|
|
18
|
+
`,g)+1,E=p.substring(b,g),S=r(t.content_to_add,t.firstMatchContent,E),$=p.split(`
|
|
19
|
+
`),m=[];for(let L=Math.max(0,x-4);L<x-1;L++)m.push({num:L+1,text:$[L]});let F=t.firstMatchContent.split(`
|
|
20
|
+
`),y=[],M=x+F.length-1;for(let L=M;L<Math.min($.length,M+3);L++)y.push({num:L+1,text:$[L]});s.set(t,{success:!0,index:t.index,oldContent:t.firstMatchContent,newContent:S,originalStartLine:u,finalStartLine:x,contextBefore:m,contextAfter:y}),p=p.substring(0,g)+S+p.substring(g+t.firstMatchContent.length),h+=S.length-t.firstMatchContent.length,w+=S.split(`
|
|
21
|
+
`).length-t.firstMatchContent.split(`
|
|
22
|
+
`).length}let I=[];for(let t=0;t<i.length;t++){let a=C.filter(u=>u.index===t);if(a.length>0)for(let u of a)s.has(u)&&I.push(s.get(u));else{let u=o.find(g=>g.index===t);I.push({success:!1,error:u?u.error:`Block ${t+1}: Unknown error.`})}}let T=I.filter(t=>!t.success&&t.error&&t.error.includes("Could not find match"));if(T.length===1)T[0].error+=" (Use Line Anchor or Run tool safely if search string fails)";else if(T.length>1){let t=T[T.length-1];t.error+=`
|
|
23
|
+
(Tip: Use Line Anchor or Run tool safely if search string fails)`}return{content:p,results:I}},pe=(e,i)=>{if(e===i)return{added:0,removed:0};let f=Z("","",e||"",i||"","","",{context:3});if(!f||!f.hunks||f.hunks.length===0)return{added:0,removed:0};let d=0,c=0;for(let l of f.hunks)for(let k of l.lines)k[0]==="+"?d++:k[0]==="-"&&c++;return{added:d,removed:c}},ge=(e,i,f,d=8,c=!1)=>{if(e===i)return"";let l=(e||"").split(/\r?\n/),k=(i||"").split(/\r?\n/),A=Math.max(l.length,k.length,1),r=Math.max(4,String(A).length),o=h=>String(h).padStart(r," "),n=`[DIFF_START]
|
|
24
|
+
`,s="\u2550".repeat(88),p=Z("","",e||"",i||"","","",{context:3});if(!p||!p.hunks||p.hunks.length===0)return"";if(p.hunks.forEach((h,w)=>{let C=0,I=0;for(let g of h.lines)g[0]==="+"?C++:g[0]==="-"&&I++;let T=[];C>0&&T.push(`+${C}`),I>0&&T.push(`-${I}`);let t=`@@ ${T.join(" ")} @@`;n+=`[UI_CONTEXT] ${t}
|
|
25
|
+
`;let a=h.oldStart,u=h.newStart;for(let g of h.lines){let x=g[0],b=g.slice(1);x===" "?(n+=`[UI_CONTEXT] ${o(u)} |${b}
|
|
26
|
+
`,a++,u++):x==="-"?(n+=`-${o(a)} |${b}
|
|
27
|
+
`,a++):x==="+"&&(n+=`+${o(u)} |${b}
|
|
28
|
+
`,u++)}}),c){let h=`[DIFF_START]
|
|
29
|
+
`,w=n.substring(h.length),C=`[UI_CONTEXT] ${s}
|
|
30
|
+
`,T=w.split(C).map(t=>t.split(`
|
|
31
|
+
`).filter(u=>u.trim()!=="").length>120?`[[VERIFIED]]
|
|
32
|
+
${t}
|
|
33
|
+
[[/VERIFIED]]`:t);n=h+T.join(C)}return n+="[DIFF_END]",N(n)},q=e=>{if(!e)return null;let i=e.replace("[UI_CONTEXT]","").replace(/\r/g,""),f=i.startsWith("-"),d=i.startsWith("+"),c=f||d?i.substring(1):i,l=c.indexOf("|"),k=l!==-1?N(c.substring(0,l).trim()):"",A=N(l!==-1?c.substring(l+1):c);return{isR:f,isA:d,num:k,content:A}},J=(e,i)=>{if(!e&&!i)return 1;if(!e||!i)return 0;let f=e.length,d=i.length,c=e,l=i;f<d&&(c=i,l=e);let k=c.length,A=l.length,r=new Int32Array(A+1),o=new Int32Array(A+1);for(let p=0;p<=A;p++)r[p]=p;for(let p=1;p<=k;p++){o[0]=p;let h=c[p-1];for(let w=1;w<=A;w++)h===l[w-1]?o[w]=r[w-1]:o[w]=Math.min(r[w],o[w-1],r[w-1])+1;r.set(o)}let n=r[A],s=Math.max(f,d);return s===0?1:1-n/s},G=e=>{let i=[],f=[];e.forEach((n,s)=>{n.parsed.isR?i.push({index:s,content:n.parsed.content}):n.parsed.isA&&f.push({index:s,content:n.parsed.content})});let d=i.length,c=f.length;if(d===0||c===0)return;let l=Array.from({length:d+1},()=>Array(c+1).fill(0)),k=Array.from({length:d+1},()=>Array(c+1).fill(""));for(let n=1;n<=d;n++)k[n][0]="up";for(let n=1;n<=c;n++)k[0][n]="left";let A=Array.from({length:d},()=>Array(c).fill(0));for(let n=0;n<d;n++)for(let s=0;s<c;s++)A[n][s]=J(i[n].content.trim(),f[s].content.trim());for(let n=1;n<=d;n++)for(let s=1;s<=c;s++){let p=A[n-1][s-1],h=p>=.2?p:-10,w=l[n-1][s-1]+h,C=l[n-1][s],I=l[n][s-1];w>=C&&w>=I?(l[n][s]=w,k[n][s]="diag"):C>=I?(l[n][s]=C,k[n][s]="up"):(l[n][s]=I,k[n][s]="left")}let r=d,o=c;for(;r>0||o>0;)if(k[r][o]==="diag"){if(A[r-1][o-1]>=.2){let s=i[r-1].index,p=f[o-1].index;e[s].pairContent=e[p].parsed.content,e[p].pairContent=e[s].parsed.content}r--,o--}else k[r][o]==="up"?r--:o--},v=new Map,D=new Map,V=200,U=5,H=(e,i)=>{i.set(e.key,e),e.type==="chunk"&&e.blocks&&e.blocks.forEach(f=>H(f,i))},xe=(e,i)=>{if(!e)return{completed:[],active:[]};let f=`${e.id}-${e.text?.length||0}-${i}-${e.isStreaming}-${e.workedDuration||0}`;if(!e.isStreaming&&v.has(f))return v.get(f);let d=N(re(e.text||"",e.role)),c=`${e.id}-${i}`,l=new Map;if(e.isStreaming){let t=D.get(c);t&&d.startsWith(t.text)&&(l=t.blocksMap)}let k=(t,a,u,g={})=>{let x=l.get(t);if(x&&x.text===u&&x.type===a&&!!x.isActiveBlock==!!g.isActiveBlock&&!!x.isStreaming==!!g.isStreaming&&x.pairContent===g.pairContent)return x;let b=N(u),E={...g};return typeof E.pairContent=="string"&&(E.pairContent=N(E.pairContent)),Array.isArray(E.wrappedLines)&&(E.wrappedLines=E.wrappedLines.map(N)),{key:t,isStreamingMsg:!!e.isStreaming,workedDuration:e.workedDuration,type:a,text:b,msg:a==="full-message"?e:void 0,...E}};if(d.includes("- Content Preview:")){let t="",a=d.match(/File\s+\[(.*?)\]/i);a&&(t=a[1].split(".").pop().toLowerCase());let E=((d.split("- Content Preview:")[1]||"").split("[SYSTEM] Check the content preview for verification [/SYSTEM]")[0]?.trim()||"").split(`
|
|
34
|
+
`).map(L=>L.replace(/\r$/,"")),S=String(E.length).length,$=[],m=null,F=[],y=()=>{if(!F.length)return;let L=F;F=[],$.push(L.length===1?L[0]:{key:`${L[0].key}-chunk`,type:"chunk",blocks:L})},M=i-(S+6);return E.forEach((L,_)=>{let R=_===E.length-1,B=j(L,M).split(`
|
|
35
|
+
`),W=k(`${e.id||Date.now()}-write-line-${_}`,"write-line",L,{gutterWidth:S,lineNum:_+1,isFirstLine:_===0,isLastLine:R,extension:t,wrappedLines:B});R&&e.isStreaming?(y(),m=W):(F.push(W),F.length>=U&&y())}),y(),{completed:$,active:m?[m]:[]}}let A=d.indexOf("[DIFF_START]");if(A!==-1&&!O(d,A)&&!d.includes("- Content Preview:")){let t=d.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),u=(t?t[1].trim():"").split(`
|
|
36
|
+
`).map(m=>m.replace(/\r$/,"")),g=u.map(m=>({line:m,parsed:q(m),pairContent:null})),x=[];for(let m=0;m<g.length;m++){let F=g[m];F.parsed&&(F.parsed.isR||F.parsed.isA)?x.push(F):x.length>0&&(G(x),x=[])}x.length>0&&G(x);let b=[],E=null,S=[],$=()=>{if(!S.length)return;let m=S;S=[],b.push(m.length===1?m[0]:{key:`${m[0].key}-chunk`,type:"chunk",blocks:m})};return u.forEach((m,F)=>{let y=F===u.length-1,M=g[F].parsed,L=null;M&&(L=j(M.content,i-17).split(`
|
|
37
|
+
`));let _=k(`${e.id||Date.now()}-diff-${F}`,"diff-line",m,{isFirstLine:F===0,isLastLine:y,pairContent:g[F].pairContent,wrappedLines:L});y&&e.isStreaming?($(),E=_):(S.push(_),S.length>=U&&$())}),$(),{completed:b,active:E?[E]:[]}}if(e.role==="system"||e.isLogo||e.isHelpRecord||e.isTerminalRecord||e.isHomeWarning||e.isImageStats||e.isAskRecord||e.isAboutRecord||e.isUpdateNotification||e.role==="user"){if(!d&&!e.isLogo&&!e.isHelpRecord&&!e.isTerminalRecord&&!e.isHomeWarning&&!e.isImageStats&&!e.isAskRecord&&!e.isAboutRecord&&!e.isUpdateNotification){let t={completed:[],active:[]};return v.set(f,t),t}return{completed:[k(`${e.id||Date.now()}-full`,"full-message",d)],active:[]}}if(!d&&!e.isStreaming){let t={completed:[],active:[]};return v.set(f,t),t}let o=[],n=null,s=[],p=null,h=()=>{if(!s.length)return;let t=s;s=[],p=null,o.push(t.length===1?t[0]:{key:`${e.id||"x"}-chunk-${t[0].key}`,type:"chunk",blocks:t})},w=(t,a=!1)=>{if(p!==null&&p!==t.type&&h(),s.push(t),p=t.type,s.length>=U){if(e.isStreaming&&a)return;h()}},C=Math.max(20,(i||80)-6),I=Math.max(20,(i||80)-8);if(e.role==="think"){o.push(k(`${e.id}-header`,"think-header","",{duration:e.duration}));let t=d.split(`
|
|
38
|
+
`),a=[];t.forEach(u=>{j(u,I).split(`
|
|
39
|
+
`).forEach(x=>a.push(x))}),a.forEach((u,g)=>{let x=g===a.length-1;w(k(`${e.id}-${g}`,"think-line",u,{}),x)}),e.isStreaming||(h(),o.push({key:`${e.id}-footer-padding`,type:"think-footer-padding",text:""}))}else{let t=d.split(`
|
|
40
|
+
`),a=!1,u=[],g=!1,x="",b=0,E=0,S=[];t.forEach($=>{let m=$.trim();m.startsWith("```")?(g=!g,S.push($)):g||m.startsWith("|")?S.push($):j($,C).split(`
|
|
41
|
+
`).forEach(y=>S.push(y))}),g=!1,S.forEach(($,m)=>{let F=m===S.length-1,y=$.trim().startsWith("|"),M=$.trim().startsWith("```");if(g)M?(g=!1,w(k(`${e.id}-code-close-${E}`,"code-fence-close","",{}),F)):(b++,w(k(`${e.id}-code-line-${m}`,"code-line",$,{lineNum:b,lang:x}),F));else if(M)g=!0,E=m,b=0,x=$.trim().replace(/^```/,"").trim(),w(k(`${e.id}-code-open-${m}`,"code-fence-open",x,{}),F);else if(y){if(a||(a=!0,u=[]),u.push($),u.length===2){let L=u[0],_=L.split("|");_[0]!==void 0&&_[0].trim()===""&&_.shift(),_.length>0&&_[_.length-1].trim()===""&&_.pop();let R=_.map(B=>B.trim());w(k(`${e.id}-table-hdr-${m}`,"table-header",L,{colHeaders:R,colCount:R.length}),F)}else if(u.length>2){let L=$.split("|");L[0]!==void 0&&L[0].trim()===""&&L.shift(),L.length>0&&L[L.length-1].trim()===""&&L.pop();let _=L.map(z=>z.trim()),R=u[0].split("|");R[0]!==void 0&&R[0].trim()===""&&R.shift(),R.length>0&&R[R.length-1].trim()===""&&R.pop();let B=R.map(z=>z.trim()),W=Math.max(1,B.length);w(k(`${e.id}-table-row-${m}`,"table-row",$,{cells:_,colHeaders:B,colCount:W,rowIndex:u.length-3}),F)}F&&!e.isStreaming&&(h(),w(k(`${e.id}-table-end-${m}`,"table-close","",{}),!0))}else a&&(w(k(`${e.id}-table-end-${m}`,"table-close","",{}),F),a=!1,u=[]),w(k(`${e.id}-${m}`,"agent-line",$,{}),F)}),!e.isStreaming&&e.workedDuration&&(h(),o.push(k(`${e.id}-worked-duration`,"worked-duration","")))}e.isStreaming&&s.length>0?n=s.length===1?s[0]:{key:`${e.id||"x"}-chunk-active-${s[0].key}`,type:"chunk",blocks:s}:h();let T={completed:o,active:n?[n]:[]};if(e.isStreaming){let t=new Map;if(o.forEach(a=>H(a,t)),n&&H(n,t),D.set(c,{text:d,blocksMap:t}),D.size>V){let a=D.keys().next().value;D.delete(a)}}else{if(v.set(f,T),v.size>V){let t=v.keys().next().value;v.delete(t)}D.delete(c)}return T},Q={},ee=/(\r?\n){2}(?=\[?(?:tool:(?:functions\.)?|tool\.functions|action:(?:functions\.)?|action:|action\.functions|\s*turn\s*:))/gi,O=(e,i)=>{let f=!1,d=!1,c=0;for(;c<i;){if(e.startsWith("```",c)){f=!f,c+=3;continue}if(f){c++;continue}if(e[c]===`
|
|
42
|
+
`){d=!1,c++;continue}e[c]==="`"&&(c===0||e[c-1]!=="\\")&&(d=!d),c++}if(f)return!0;if(d){let l=e.indexOf(`
|
|
43
|
+
`,i),k=l===-1?e.length:l;if(e.substring(i,k).includes("`"))return!0}return!1},te=/\[SYSTEM\][\s\S]*?\[\/SYSTEM\]|\[ANSWER\][\s\S]*?(?:\[\/ANSWER\]|$)|\[(?:TOOL|ACTION) RESULTS?\]:?\s*|\[\s*turn\s*:\s*(continue|finish)\s*\]|\[\[END\]\]|\[\s*turn\s*:?.*?$|\n\s*turn\s*:?.*?$|\[\s*(?:turn|ANSWER|TOOL|ACTION).*?$|\n\nResponded on .*|\n\n\[Prompted on: .*\]|@\[TerminalName:.*?, ProcessId:.*?\]/gm,ne=/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)|(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)|(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)|(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)|(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,se=/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,P=!1,re=(e,i="agent")=>{if(!e)return e;let f=i===!0||i==="think",d=i===!1||i==="agent",c=e.replace(/<\|channel>thought/gi,"<think_fluxflow>").replace(/<channel\|>/gi,"</think_fluxflow>");if(f)return c.replace(/^<think_fluxflow>/gi,"").replace(/<\/think_fluxflow>$/gi,"").replace(/^\r?\n+/,"").replace(/\r?\n+$/,"");let l=c;if(c.trimStart().startsWith("ERROR: [INTERNAL CRITICAL] "))return"";d&&(l=l.replace(/<\/?think_fluxflow>/gi,(o,n,s)=>O(s,n)?o:""),l=l.replace(ee,(o,n,s,p)=>!P&&O(p,s)?o:""),l&&(l.includes("[tool:")||l.includes("[action:"))&&(l=l.replace(/<(\w+)(?:[^>]*)>\s*([\s\S]*?\[(?:tool|action):[^\]]*\][\s\S]*?)\s*<\/\1>/gi,(o,n,s)=>s&&(s.includes("[tool:")||s.includes("[action:"))?s.trim():o),P&&(l=l.replace(/```(?:tool|action|yaml|function|json)?\s*\n?([\s\S]*?)\n?\```/gi,(o,n)=>n.includes("[tool:")||n.includes("[action:")?n.trim():o))));let k="tool:",A="action:";if(d&&(l.toLowerCase().includes(k)||l.toLowerCase().includes(A)))for(;;){let o=l.toLowerCase(),n=o.indexOf(k),s=o.indexOf(A),p=k,h=n;if((n===-1||s!==-1&&s<n)&&(p=A,h=s),h===-1)break;if(!P&&O(l,h)){let g=-1,x=0;for(;;){let b=o.indexOf(k,x),E=o.indexOf(A,x),S=-1,$=k;if(b===-1&&E===-1)break;if(b===-1||E!==-1&&E<b?(S=E,$=A):S=b,!O(l,S)){g=S,p=$;break}x=S+$.length}if(g===-1)break;h=g}let w=h,C=!1,I=h-1;for(;I>=0&&/\s/.test(l[I]);)I--;I>=0&&l[I]==="["&&(w=I,C=!0);let T=0,t=!1,a=null,u=h;for(;u<l.length;){let g=l[u];if(!a&&(g==="'"||g==='"'||g==="`")?a=g:a&&g===a&&l[u-1]!=="\\"&&(a=null),a||(g==="("?(T++,t=!0):g===")"&&T--),t&&T===0&&!a){let x=u;if(C){let b=u+1;for(;b<l.length&&/\s/.test(l[b]);)b++;b<l.length&&l[b]==="]"&&(x=b)}l=l.substring(0,w)+l.substring(x+1);break}if(u++,u===l.length){l=l.substring(0,w);break}}}d&&(l=l.replace(/\[\s*(?:tool|action):[a-zA-Z0-9_.]*\s*\([\s\S]*?\)\s*\]/gi,(o,n,s)=>!P&&O(s,n)?o:""),l=l.replace(/\[\s*(?:tool|action):[a-zA-Z0-9_.]*[\s\S]*$/gi,(o,n,s)=>!P&&O(s,n)?o:""),l=l.replace(/^(?:\s*=\s*["'][^"'\n]*["']|\s*[a-zA-Z0-9_]+\s*=\s*(?:["'][^"'\n]*["']|\d+|true|false))(?:\s*,\s*[a-zA-Z0-9_]+\s*=\s*(?:["'][^"'\n]*["']|\d+|true|false))*\s*\)?\]\s*/gm,(o,n,s)=>!P&&O(s,n)?o:""),l=l.replace(/(?:\r?\n|^)\s*=\s*["'][^"'\n]*["'][\s\S]*?\s*\)?\]\s*/g,(o,n,s)=>!P&&O(s,n)?o:`
|
|
44
|
+
`));let r=i==="tool_result"||i==="tool"||i==="action"||i==="action_result";return l=l.replace(te,(o,n,s,p)=>{if(/^\[(?:TOOL|ACTION) RESULTS?\]:?\s*/i.test(o)||/^\[\s*(?:TOOL|ACTION).*?$/i.test(o)){if(r||O(p,s))return o}else if(O(p,s))return o;return""}),l=l.replace(ne,o=>{let n=o.toLowerCase();return n.includes("leftrightarrow")?"\u2194":n.includes("rightarrow")?"\u2192":n.includes("leftarrow")?"\u2190":n.includes("uparrow")?"\u2191":n.includes("downarrow")?"\u2193":o}),l=l.replace(se,o=>Q[o.toLowerCase()]||o),l.trim()},ke=()=>{v.clear(),D.clear()};export{N as a,j as b,ce as c,ae as d,fe as e,ue as f,he as g,de as h,pe as i,ge as j,q as k,G as l,xe as m,O as n,re as o,ke as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{e as m,f as c}from"./chunk-P5HBJA23.js";import{b as s}from"./chunk-26BQ45XP.js";import n from"fs-extra";import p from"path";var o={mode:"Flux",display:0,thinkingLevel:"Medium",aiProvider:"",activeModel:"",activeKeyIndex:{},showFullThinking:!0,apiTier:"Free",quotas:{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0,providerTiers:{Google:"Free",DeepSeek:"Free",NVIDIA:"Free",OpenRouter:"Free",InferX:"Free",SenseNova:"Free",Poolside:"Free",ExpLabs:"Free",TokenHarbor:"Free",Infron:"Free",APInex:"Free",xKiro:"Free",c_openai:"Free"}},systemSettings:{customOpenAIBaseUrl:"",memory:!1,theme:"Dark",autoExec:!0,allowExternalAccess:!1,advanceRollback:!1,autoDeleteHistory:"7d",useExternalData:!1,externalDataPath:"",preserveThinking:!0,loadingPhrases:!1,progressiveRendering:!0,showTPMEstimate:!0,subAgents:!1,CustomSubAgent:!1,SubAgentModel:"Default",SubAgentProvider:"",commitMessageModel:"Default",commitMessageProvider:"",dynamicDirAwareness:!1,indentationTree:!0,ollamaEndpoint:"Cloud",compressToolResults:!1,autoTruncateResults:!0,agentFinishSound:!1,imageHistoryCU:"Standard",contextLength:"256k",keepReasoningContext:!1,autoExcludeMetadata:!1,disableTodo:!1,preferBash:!1,clipboardContext:!1,cacheCalculateMode:"Session",alwaysAskFiles:".env, .env.*, *.env",loopLimits:"Default",overwriteProtection:!0},profileData:{preset:"Default",name:null,nickname:null,instructions:null},imageSettings:{keyType:"Default",quality:"Low-High",apiKey:""},autoCompletion:{enabled:!1,model:"Default",provider:"",baseUrl:""}},I={Mistral:"https://api.mistral.ai/v1/chat/completions",DeepSeek:"https://api.deepseek.com/chat/completions",OpenRouter:"https://openrouter.ai/api/v1/chat/completions",NVIDIA:"https://integrate.api.nvidia.com/v1",Ollama:"https://ollama.com/v1",InferX:"https://model.inferx.net/endpoints/v1/chat/completions",SenseNova:"https://token.sensenova.ai/v1/chat/completions",Poolside:"https://inference.poolside.ai/v1/chat/completions",ExpLabs:"https://api.experientiallabs.ai/v1/chat/completions",TokenHarbor:"https://tokenharbor.ai/v1/chat/completions",Infron:"https://llm.onerouter.pro/v1/chat/completions",APInex:"https://api.apinex.bond/v1/chat/completions",xKiro:"https://api.xkiro.com/v1/chat/completions",AIHubMix:"https://aihubmix.com/v1/chat/completions",Google:"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"},g=async()=>{let t={...o};try{if(await n.exists(s)){let e=m(s);if(e.imageSettings&&e.imageSettings.apiKey)try{let a=e.imageSettings.apiKey,{saveSecret:i}=await import("./secrets-TNMLVMST.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-TNMLVMST.js"),a=await e("POLLINATIONS_API_KEY");a&&(t.imageSettings.apiKey=a)}catch{}if(t.showFullThinking===!1){t.showFullThinking=!0;try{c(s,t)}catch{}}return t},d=async t=>{let{FLUXFLOW_DIR:e}=await import("./paths-RQRI2XRY.js"),a=["logs","secret"];for(let i of a){let l=p.join(e,i),r=p.join(t,i);try{await n.exists(l)&&(await n.ensureDir(r),await n.copy(l,r,{overwrite:!0}))}catch(u){console.error(`Migration failed for ${i}:`,u)}}},D=async t=>{try{let e=await g();if(!e.systemSettings.useExternalData&&t.systemSettings?.useExternalData&&t.systemSettings?.externalDataPath&&await d(t.systemSettings.externalDataPath),t.imageSettings&&t.imageSettings.apiKey!==void 0){let{saveSecret:i,removeSecret:l}=await import("./secrets-TNMLVMST.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-EBE2OVES.js");i()}catch{}return!0}catch(e){return console.error("Failed to save settings:",e),!1}};export{I as a,g as b,D as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as O}from"./chunk-6EYQQ7GQ.js";import{c as u,d as p}from"./chunk-P5HBJA23.js";import{f as m,g as h,l as C,m as M,s as f}from"./chunk-26BQ45XP.js";import d from"fs-extra";import j from"path";import{nanoid as L}from"nanoid";var S=Promise.resolve(),T=t=>{let r=S.then(async()=>{try{return await t()}catch(e){throw console.error("Lock Operation Failed:",e),e}});return S=r.catch(()=>{}),r},B=(t,r="")=>{let e=n=>(n||"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();return t?.name&&!t.name.startsWith("Session")?e(t.name):t?.prompt?e(t.prompt):e(t?.name)||r},I=async()=>{await d.ensureDir(h);let t={};if(await d.pathExists(m))try{t=u(m,{})}catch{t={}}for(let r in t){let e=j.join(h,`${r}.json`);Object.defineProperty(t[r],"messages",{get:()=>{if(d.existsSync(e))try{return u(e,[])}catch{return[]}return[]},set:n=>{try{p(e,n)}catch{}},enumerable:!1,configurable:!0})}return t},G=async(t,r,e)=>T(async()=>{await d.ensureDir(h);let n=await I(),s=n[t],
|
|
1
|
+
import{a as O}from"./chunk-6EYQQ7GQ.js";import{c as u,d as p}from"./chunk-P5HBJA23.js";import{f as m,g as h,l as C,m as M,s as f}from"./chunk-26BQ45XP.js";import d from"fs-extra";import j from"path";import{nanoid as L}from"nanoid";var S=Promise.resolve(),T=t=>{let r=S.then(async()=>{try{return await t()}catch(e){throw console.error("Lock Operation Failed:",e),e}});return S=r.catch(()=>{}),r},B=(t,r="")=>{let e=n=>(n||"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();return t?.name&&!t.name.startsWith("Session")?e(t.name):t?.prompt?e(t.prompt):e(t?.name)||r},I=async()=>{await d.ensureDir(h);let t={};if(await d.pathExists(m))try{t=u(m,{})}catch{t={}}for(let r in t){let e=j.join(h,`${r}.json`);Object.defineProperty(t[r],"messages",{get:()=>{if(d.existsSync(e))try{return u(e,[])}catch{return[]}return[]},set:n=>{try{p(e,n)}catch{}},enumerable:!1,configurable:!0})}return t},G=async(t,r,e)=>T(async()=>{await d.ensureDir(h);let n=await I(),s=n[t],i=(e||[]).filter(a=>!a.isUpdateNotification&&(!a.isMeta||a.text&&a.text.includes("Request Cancelled"))),o=a=>{if(!a)return;let A=typeof a=="string"?a:a.text||a.content||"";if(!A||typeof A!="string")return;let g=A.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();if(!g)return;let N=g.split(/\s+/),E;return N.length>7?E=N.slice(0,7).join(" ")+"...":g.length>45?E=g.substring(0,45).trimEnd()+"...":E=g,E},c,x=i.filter(a=>a.role==="user"),l=x[0],w=x[x.length-1],y=o(w),D=o(l);s&&s.prompt?c=y:c=D||y;let H=r||(s?s.name:`Session ${t.slice(-6)}`),b=j.join(h,`${t}.json`);p(b,i),n[t]={name:H,prompt:c||void 0,updatedAt:Date.now()};let k={};for(let a in n)k[a]={name:n[a].name,prompt:n[a].prompt||void 0,updatedAt:n[a].updatedAt};p(m,k)}),J=async(t,r)=>T(async()=>{let e=await I();e[t]?(e[t].name=r,e[t].updatedAt=Date.now()):e[t]={name:r,updatedAt:Date.now()};let n={};for(let s in e)n[s]={name:e[s].name,prompt:e[s].prompt||void 0,updatedAt:e[s].updatedAt};p(m,n)}),F=async t=>T(async()=>{let r=await I();delete r[t];let e={};for(let o in r)e[o]={name:r[o].name,prompt:r[o].prompt||void 0,updatedAt:r[o].updatedAt};if(p(m,e),await d.pathExists(f))try{let o=u(f,[]);if(Array.isArray(o)){let c=o.filter(x=>Object.keys(x)[0]!==String(t));p(f,c)}}catch{}let n=u(C,{});n[t]&&(delete n[t],p(C,n));let s=u(M,{});s[t]&&(delete s[t],p(M,s)),await O.deleteChatBackups(t);let i=j.join(h,`${t}.json`);if(await d.pathExists(i))try{await d.remove(i)}catch{}return r}),Q=()=>`flow-${L(6)}`,W=async t=>{if(!t||t==="Never")return;let r=parseInt(t);if(isNaN(r))return;let e=await I(),n=Date.now(),s=r*24*60*60*1e3,i=0;for(let o in e){let c=e[o];c.updatedAt&&n-c.updatedAt>s&&(await F(o),i++)}return i};var Y=async(t,r,e)=>T(async()=>{let n=u(f,[]);Array.isArray(n)||(n=[]);let s=r||0,i=e||0,o={total:s,context:i},c=n.findIndex(l=>Object.keys(l)[0]===String(t));s===0&&i===0?c!==-1&&n.splice(c,1):c!==-1?n[c]={[String(t)]:o}:n.push({[String(t)]:o});let x=n.filter(l=>{if(!l||typeof l!="object")return!1;let w=Object.keys(l)[0];if(!w)return!1;let y=l[w];return y&&((y.total||0)>0||(y.context||0)>0)});p(f,x)}),q=async t=>{try{if(!await d.pathExists(f))return{total:0,context:0};let r=u(f,[]);if(!Array.isArray(r))return{total:0,context:0};let e=r.find(n=>Object.keys(n)[0]===String(t));return e?{total:0,context:0,...e[String(t)]}:{total:0,context:0}}catch{return{total:0,context:0}}};export{B as a,I as b,G as c,J as d,F as e,Q as f,W as g,Y as h,q as i};
|
|
@@ -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-
|
|
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-PUFSRWT3.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 +1 @@
|
|
|
1
|
-
import{c as v,d as T}from"./chunk-P5HBJA23.js";import{e as k}from"./chunk-26BQ45XP.js";import b from"fs-extra";import C from"path";var Y=C.join(k,"secrets_v2.json"),y=10,F=new Set(["9router","c_openai"]),z=new Set(["c_openai"]),U=[{canonical:"Google",secret:["GOOGLE_API_KEY","API_KEY"],aliases:["gemini"]},{canonical:"DeepSeek",secret:["DEEPSEEK_API_KEY"],aliases:["deepseek-ai","deepseekai"]},{canonical:"OpenRouter",secret:["OPENROUTER_API_KEY"],aliases:["open router","open_router"]},{canonical:"NVIDIA",secret:["NVIDIA_API_KEY"],aliases:["nvidia nim"]},{canonical:"Mistral",secret:["MISTRAL_API_KEY"],aliases:[]},{canonical:"Ollama",secret:["OLLAMA_API_KEY"],aliases:[]},{canonical:"InferX",secret:["INFERX_API_KEY"],aliases:["infer x","inferx"]},{canonical:"SenseNova",secret:["SENSENOVA_API_KEY"],aliases:["sensenova","sense nova"]},{canonical:"AIHubMix",secret:["AIHUBMIX_API_KEY"],aliases:["aihubmix","ai hub mix"]},{canonical:"Poolside",secret:["POOLSIDE_API_KEY"],aliases:[]},{canonical:"9router",secret:["9ROUTER_API_KEY"],aliases:["9router","9-router","nine router"]},{canonical:"ExpLabs",secret:["EXPLABS_API_KEY","EXPERIENTIALLABS_API_KEY"],aliases:["explabs","experientiallabs","experimentallabs","experiential labs"]},{canonical:"TokenHarbor",secret:["TOKENHARBOR_API_KEY","TOKEN_HARBOR_API_KEY"],aliases:["tokenharbor","token harbor","token_harbor","thk"]},{canonical:"Infron",secret:["INFRON_API_KEY"],aliases:["infron"]},{canonical:"APInex",secret:["APINEX_API_KEY"],aliases:["apinex","apx"]},{canonical:"xKiro",secret:["XKIRO_API_KEY"],aliases:["xkiro","kiro"]},{canonical:"c_openai",secret:["CUSTOM_OPENAI_API_KEY","C_OPENAI_API_KEY"],aliases:["custom","custom (openai)","custom openai"]}],L=new Map;for(let e of U){L.set(e.canonical.toLowerCase(),e.canonical);for(let t of e.aliases)L.set(t.toLowerCase(),e.canonical)}var f=e=>!e||typeof e!="string"?null:L.get(e.trim().toLowerCase())||null,J=()=>U.map(e=>e.canonical),h=e=>z.has(e),ie=e=>F.has(e);var ce=e=>{let t=f(e)||e;return t==="c_openai"?"custom":t},B=()=>new Array(y).fill(null),d=e=>e?typeof e=="string"?e.trim().length>0:typeof e=="object"?!!(e.key&&String(e.key).trim()):!1:!1,I=e=>e?typeof e=="string"?e:typeof e=="object"&&e.key?e.key:null:null,E=e=>{let t=B();if(Array.isArray(e))for(let s=0;s<y&&s<e.length;s++)t[s]=e[s]??null;else typeof e=="string"&&e.trim()&&(t[0]=e);return t},S=()=>{try{return v(Y,{})||{}}catch{return{}}},g=e=>{try{b.existsSync(k)||b.mkdirSync(k,{recursive:!0}),T(Y,e,!0)}catch{}},D=!1,le=async()=>{if(!D){D=!0;try{await b.pathExists(Y);let e=C.join(k,"secrets.json");if(!await b.pathExists(e))return;let t=v(e,{})||{},s=S(),n=!1;for(let o of U){let i=E(s[o.canonical]);if(i.some(d)){s[o.canonical]=i;continue}let r=null;for(let a of o.secret)if(t[a]){r=t[a];break}r&&(h(o.canonical)?i[0]={key:r,baseUrl:""}:i[0]=r,s[o.canonical]=i,n=!0)}n&&g(s)}catch{}}},A=e=>{let t=f(e)||e,s=S();return E(s[t])},q=e=>A(e).filter(d).length,ue=()=>U.filter(e=>!F.has(e.canonical)).map(e=>{let t=q(e.canonical);return{provider:e.canonical,count:t,hasKeys:t>0}}),H=async()=>{try{let{loadSettings:e}=await import("./settings-3VSVCZDF.js"),t=await e();return t&&t.activeKeyIndex||{}}catch{return{}}},Q=async e=>{try{let{loadSettings:t,saveSettings:s}=await import("./settings-3VSVCZDF.js"),n=await t();n.activeKeyIndex=e,await s(n)}catch{}},_=async e=>{let t=f(e)||e,n=(await H())[t];return Number.isInteger(n)?n:null},w=async(e,t)=>{let s=f(e)||e,n=await H();return n[s]=t,await Q(n),t},V=async()=>{try{let{loadSettings:e}=await import("./settings-3VSVCZDF.js"),t=await e();return t&&t.nullKeyProviders||{}}catch{return{}}},W=async e=>{try{let{loadSettings:t,saveSettings:s}=await import("./settings-3VSVCZDF.js"),n=await t();n.nullKeyProviders=e,await s(n)}catch{}},Z=new Set(["c_openai","Ollama"]),ee="__FLUX_NULL_KEY__",fe=e=>Z.has(f(e)||e),$=async e=>{let t=f(e)||e;return(await V())[t]===!0},P=async(e,t=!0)=>{let s=f(e)||e,n=await V();return t?n[s]=!0:delete n[s],await W(n),t===!0},x=new Map,de=(e,t,s=void 0)=>{let n=f(e)||e,o={key:t};s!==void 0&&(o.baseUrl=s),x.set(n,o)},pe=e=>{let t=f(e)||e;return x.get(t)||null},me=e=>x.has(f(e)||e),ye=()=>x.clear(),Ie=e=>x.delete(f(e)||e),O=null,xe=e=>{O=typeof e=="function"?e:null},te=e=>{try{O&&O(e)}catch{}},K=async()=>{try{let{loadSettings:e}=await import("./settings-3VSVCZDF.js"),t=await e();return t.systemSettings&&t.systemSettings.customOpenAIBaseUrl||""}catch{return""}},ge=async(e,t={})=>{let s=f(e)||e,n=t.silent===!0,o=x.get(s);if(o&&o.key)return o.key;if(await $(s))return ee;let i=A(s),r=await _(s);if(Number.isInteger(r)&&r>=0&&r<y&&d(i[r]))return I(i[r]);let a=i.findIndex(d);return a!==-1?(n||(await w(s,a),te(`No active key set for ${s}. Auto-selected slot ${a+1}.`)),I(i[a])):null},_e=async e=>{let t=f(e)||e;if(!h(t))return null;let s=x.get(t);if(s&&s.key)return s.baseUrl!==void 0?s.baseUrl:await K();if(await $(t))return await K();let n=A(t),o=await _(t);if(Number.isInteger(o)&&o>=0&&o<y){let r=n[o];if(r&&typeof r=="object"&&r.key)return r.baseUrl||""}let i=n.findIndex(d);if(i!==-1){let r=n[i];if(r&&typeof r=="object")return r.baseUrl||""}return await K()},R=async(e,t,s,n)=>{if(h(e)){let o=n!==void 0?n:s!==void 0?s:await K();return{key:t,baseUrl:o}}return t},X=e=>{let t=String(e||"").trim();if(!t)return{ok:!1,error:"URL is empty."};if(!/^https?:\/\/\S+$/i.test(t))return{ok:!1,error:"URL must start with http:// or https://"};let s=t.replace(/\/+$/,""),n=s.toLowerCase(),o=/(^|\/)v1$/.test(n),i=/(^|\/)v1\/chat\/completions$/.test(n);return!o&&!i?{ok:!1,error:"URL must end with /v1 or /v1/chat/completions"}:{ok:!0,url:s}},G=(e,t)=>{let s=String(t),n=[],o=[];return e.forEach((i,r)=>{let a=I(i);a&&(a===s?n.push(r):a.includes(s)&&o.push(r))}),n.length?n:o},he=async(e,t,s={})=>{let n=f(e)||e;if(!t||!String(t).trim())return{ok:!1,error:"Empty key."};let o=String(t).trim(),i;if(s.baseUrl!==void 0){if(!h(n))return{ok:!1,error:"--url is only supported for the custom provider."};let c=X(s.baseUrl);if(!c.ok)return{ok:!1,error:`Invalid URL: ${c.error}`};i=c.url}let r=S(),a=E(r[n]);if(a.some(c=>I(c)===o))return{ok:!1,error:`Key already exists in slot ${a.findIndex(l=>I(l)===o)+1}.`};if(Number.isInteger(s.index)){let c=s.index;if(c<0||c>=y)return{ok:!1,error:`Index must be between 1 and ${y}.`};let l=a[c]&&typeof a[c]=="object"?a[c].baseUrl:void 0;return a[c]=await R(n,o,l,i),r[n]=a,g(r),await P(n,!1),{ok:!0,index:c}}let u=a.findIndex(c=>!d(c));return u===-1?{ok:!1,error:"All slots full. Specify an index to overwrite.",full:!0}:(a[u]=await R(n,o,void 0,i),r[n]=a,g(r),await P(n,!1),{ok:!0,index:u})},we=async(e,t,s={})=>{let n=f(e)||e;if(!t||!String(t).trim())return{ok:!1,error:"Empty key."};let o=String(t).trim(),i;if(s.baseUrl!==void 0){if(!h(n))return{ok:!1,error:"Base URL is only supported for the custom provider."};let p=X(s.baseUrl);if(!p.ok)return{ok:!1,error:`Invalid URL: ${p.error}`};i=p.url}let r=S(),a=E(r[n]),u=await _(n),c=Number.isInteger(u)&&u>=0&&u<y&&d(a[u])?u:a.findIndex(d);c===-1&&(c=0);let l=a[c]&&typeof a[c]=="object"?a[c].baseUrl:void 0;return a[c]=await R(n,o,l,i),r[n]=a,g(r),await w(n,c),await P(n,!1),{ok:!0,index:c}},Ee=async(e,t,s={})=>{let n=f(e)||e,o=S(),i=E(o[n]);if(s.all||t==="--all"||t==="__all__")return o[n]=B(),g(o),await w(n,null),{ok:!0,all:!0,remaining:0,needsNewKey:!0};let r=-1;if(t==null){let l=await _(n);if(r=Number.isInteger(l)&&d(i[l])?l:i.findIndex(d),r===-1)return{ok:!1,error:"No keys to remove."}}else if(Number.isInteger(t)){if(r=t,r<0||r>=y)return{ok:!1,error:`Index must be between 1 and ${y}.`};if(!d(i[r]))return{ok:!1,error:`Slot ${r+1} is already empty.`}}else{let l=G(i,t);if(l.length===0)return{ok:!1,error:"No matching key found."};if(l.length>1)return{ok:!1,error:`Duplicate match (slots ${l.map(p=>p+1).join(", ")}). Be more specific.`};r=l[0]}let a=I(i[r]),u=await _(n)===r;i[r]=null,o[n]=i,g(o);let c=i.filter(d).length;if(u){let l=i.findIndex(d);await w(n,l===-1?null:l)}return{ok:!0,removed:a,removedIndex:r,remaining:c,needsNewKey:c===0}},Se=async(e,t)=>{let s=f(e)||e,n=A(s),o=-1;if(Number.isInteger(t)){if(o=t,o<0||o>=y)return{ok:!1,error:`Index must be between 1 and ${y}.`};if(!d(n[o]))return{ok:!1,error:`Slot ${o+1} is empty.`}}else{let r=G(n,t);if(r.length===0)return{ok:!1,error:"No matching key found."};if(r.length>1)return{ok:!1,error:`Duplicate match (slots ${r.map(a=>a+1).join(", ")}). Be more specific.`};o=r[0]}await w(s,o),await P(s,!1);let i=null;if(h(s)){let r=n[o],a=r&&typeof r=="object"&&r.baseUrl?r.baseUrl.trim():"";if(a)try{let{loadSettings:u,saveSettings:c}=await import("./settings-3VSVCZDF.js"),l=await u();if((l.systemSettings&&l.systemSettings.customOpenAIBaseUrl?l.systemSettings.customOpenAIBaseUrl.trim():"")!==a){let m={...l.systemSettings||{},customOpenAIBaseUrl:a,memory:!1};await c({...l,systemSettings:m}),i=a}}catch{}}return{ok:!0,index:o,key:I(n[o]),switchedBaseUrl:i}},ke=async(e=null)=>{let t=S(),s=e?[f(e)||e]:J(),n=0;for(let o of s){let i=E(t[o]),r=i.filter(d);if(r.length===0){t[o]=i;continue}let a=await _(o),u=Number.isInteger(a)&&d(i[a])?i[a]:null,c=B();r.forEach((p,m)=>{c[m]=p});let l=Number.isInteger(a)?a:null;if(u){let p=i.slice(0,y).map((m,N)=>({s:m,i:N})).filter(m=>d(m.s)).findIndex(m=>m.i===a);l=p===-1?null:p}t[o]=c,l!==a&&await w(o,l),n++}return g(t),{ok:!0,providers:s.length,touched:n}},j=e=>{if(!e)return"";let t=String(e),s=t.length;if(s<=3)return"...";let n=Math.floor(s/3),o=t.slice(0,n),i=t.slice(s-n);return o+"..."+i},ne=e=>{if(!e)return"";let t=String(e).replace(/\/+$/,"");return t.length<=28?t:"..."+t.replace(/^https?:\/\//i,"").slice(-24)},Ae=async(e,t={})=>{let s=t.unmask===!0,n=f(e)||e,o=A(n),i=await _(n),r=x.get(n),a=[];r&&r.key&&a.push(`Temporary: ${s?r.key:j(r.key)}`),await $(n)&&a.push("Mode: NO KEY (null) <- active");for(let u=0;u<y;u++){let c=o[u],l=I(c),p=l&&!s?j(l):l,m;if(!l)m="Empty";else if(h(n)){let M=c&&typeof c=="object"?ne(c.baseUrl):"";m=M?`${p} (Saved: ${M})`:p}else m=p;let N=u===i&&l?" \u2190 active":"";a.push(`${u+1}: ${m}${N}`)}return a};export{F as a,U as b,f as c,J as d,h as e,ie as f,ce as g,le as h,A as i,q as j,ue as k,_ as l,w as m,ee as n,fe as o,$ as p,P as q,de as r,pe as s,me as t,ye as u,Ie as v,xe as w,ge as x,_e as y,X as z,he as A,we as B,Ee as C,Se as D,ke as E,j as F,ne as G,Ae as H};
|
|
1
|
+
import{c as v,d as T}from"./chunk-P5HBJA23.js";import{e as k}from"./chunk-26BQ45XP.js";import b from"fs-extra";import C from"path";var Y=C.join(k,"secrets_v2.json"),y=10,F=new Set(["9router","c_openai"]),z=new Set(["c_openai"]),U=[{canonical:"Google",secret:["GOOGLE_API_KEY","API_KEY"],aliases:["gemini"]},{canonical:"DeepSeek",secret:["DEEPSEEK_API_KEY"],aliases:["deepseek-ai","deepseekai"]},{canonical:"OpenRouter",secret:["OPENROUTER_API_KEY"],aliases:["open router","open_router"]},{canonical:"NVIDIA",secret:["NVIDIA_API_KEY"],aliases:["nvidia nim"]},{canonical:"Mistral",secret:["MISTRAL_API_KEY"],aliases:[]},{canonical:"Ollama",secret:["OLLAMA_API_KEY"],aliases:[]},{canonical:"InferX",secret:["INFERX_API_KEY"],aliases:["infer x","inferx"]},{canonical:"SenseNova",secret:["SENSENOVA_API_KEY"],aliases:["sensenova","sense nova"]},{canonical:"AIHubMix",secret:["AIHUBMIX_API_KEY"],aliases:["aihubmix","ai hub mix"]},{canonical:"Poolside",secret:["POOLSIDE_API_KEY"],aliases:[]},{canonical:"9router",secret:["9ROUTER_API_KEY"],aliases:["9router","9-router","nine router"]},{canonical:"ExpLabs",secret:["EXPLABS_API_KEY","EXPERIENTIALLABS_API_KEY"],aliases:["explabs","experientiallabs","experimentallabs","experiential labs"]},{canonical:"TokenHarbor",secret:["TOKENHARBOR_API_KEY","TOKEN_HARBOR_API_KEY"],aliases:["tokenharbor","token harbor","token_harbor","thk"]},{canonical:"Infron",secret:["INFRON_API_KEY"],aliases:["infron"]},{canonical:"APInex",secret:["APINEX_API_KEY"],aliases:["apinex","apx"]},{canonical:"xKiro",secret:["XKIRO_API_KEY"],aliases:["xkiro","kiro"]},{canonical:"c_openai",secret:["CUSTOM_OPENAI_API_KEY","C_OPENAI_API_KEY"],aliases:["custom","custom (openai)","custom openai"]}],L=new Map;for(let e of U){L.set(e.canonical.toLowerCase(),e.canonical);for(let t of e.aliases)L.set(t.toLowerCase(),e.canonical)}var f=e=>!e||typeof e!="string"?null:L.get(e.trim().toLowerCase())||null,J=()=>U.map(e=>e.canonical),h=e=>z.has(e),ie=e=>F.has(e);var ce=e=>{let t=f(e)||e;return t==="c_openai"?"custom":t},B=()=>new Array(y).fill(null),d=e=>e?typeof e=="string"?e.trim().length>0:typeof e=="object"?!!(e.key&&String(e.key).trim()):!1:!1,I=e=>e?typeof e=="string"?e:typeof e=="object"&&e.key?e.key:null:null,E=e=>{let t=B();if(Array.isArray(e))for(let s=0;s<y&&s<e.length;s++)t[s]=e[s]??null;else typeof e=="string"&&e.trim()&&(t[0]=e);return t},S=()=>{try{return v(Y,{})||{}}catch{return{}}},g=e=>{try{b.existsSync(k)||b.mkdirSync(k,{recursive:!0}),T(Y,e,!0)}catch{}},D=!1,le=async()=>{if(!D){D=!0;try{await b.pathExists(Y);let e=C.join(k,"secrets.json");if(!await b.pathExists(e))return;let t=v(e,{})||{},s=S(),n=!1;for(let o of U){let i=E(s[o.canonical]);if(i.some(d)){s[o.canonical]=i;continue}let r=null;for(let a of o.secret)if(t[a]){r=t[a];break}r&&(h(o.canonical)?i[0]={key:r,baseUrl:""}:i[0]=r,s[o.canonical]=i,n=!0)}n&&g(s)}catch{}}},A=e=>{let t=f(e)||e,s=S();return E(s[t])},q=e=>A(e).filter(d).length,ue=()=>U.filter(e=>!F.has(e.canonical)).map(e=>{let t=q(e.canonical);return{provider:e.canonical,count:t,hasKeys:t>0}}),H=async()=>{try{let{loadSettings:e}=await import("./settings-PUFSRWT3.js"),t=await e();return t&&t.activeKeyIndex||{}}catch{return{}}},Q=async e=>{try{let{loadSettings:t,saveSettings:s}=await import("./settings-PUFSRWT3.js"),n=await t();n.activeKeyIndex=e,await s(n)}catch{}},_=async e=>{let t=f(e)||e,n=(await H())[t];return Number.isInteger(n)?n:null},w=async(e,t)=>{let s=f(e)||e,n=await H();return n[s]=t,await Q(n),t},V=async()=>{try{let{loadSettings:e}=await import("./settings-PUFSRWT3.js"),t=await e();return t&&t.nullKeyProviders||{}}catch{return{}}},W=async e=>{try{let{loadSettings:t,saveSettings:s}=await import("./settings-PUFSRWT3.js"),n=await t();n.nullKeyProviders=e,await s(n)}catch{}},Z=new Set(["c_openai","Ollama"]),ee="__FLUX_NULL_KEY__",fe=e=>Z.has(f(e)||e),$=async e=>{let t=f(e)||e;return(await V())[t]===!0},P=async(e,t=!0)=>{let s=f(e)||e,n=await V();return t?n[s]=!0:delete n[s],await W(n),t===!0},x=new Map,de=(e,t,s=void 0)=>{let n=f(e)||e,o={key:t};s!==void 0&&(o.baseUrl=s),x.set(n,o)},pe=e=>{let t=f(e)||e;return x.get(t)||null},me=e=>x.has(f(e)||e),ye=()=>x.clear(),Ie=e=>x.delete(f(e)||e),O=null,xe=e=>{O=typeof e=="function"?e:null},te=e=>{try{O&&O(e)}catch{}},K=async()=>{try{let{loadSettings:e}=await import("./settings-PUFSRWT3.js"),t=await e();return t.systemSettings&&t.systemSettings.customOpenAIBaseUrl||""}catch{return""}},ge=async(e,t={})=>{let s=f(e)||e,n=t.silent===!0,o=x.get(s);if(o&&o.key)return o.key;if(await $(s))return ee;let i=A(s),r=await _(s);if(Number.isInteger(r)&&r>=0&&r<y&&d(i[r]))return I(i[r]);let a=i.findIndex(d);return a!==-1?(n||(await w(s,a),te(`No active key set for ${s}. Auto-selected slot ${a+1}.`)),I(i[a])):null},_e=async e=>{let t=f(e)||e;if(!h(t))return null;let s=x.get(t);if(s&&s.key)return s.baseUrl!==void 0?s.baseUrl:await K();if(await $(t))return await K();let n=A(t),o=await _(t);if(Number.isInteger(o)&&o>=0&&o<y){let r=n[o];if(r&&typeof r=="object"&&r.key)return r.baseUrl||""}let i=n.findIndex(d);if(i!==-1){let r=n[i];if(r&&typeof r=="object")return r.baseUrl||""}return await K()},R=async(e,t,s,n)=>{if(h(e)){let o=n!==void 0?n:s!==void 0?s:await K();return{key:t,baseUrl:o}}return t},X=e=>{let t=String(e||"").trim();if(!t)return{ok:!1,error:"URL is empty."};if(!/^https?:\/\/\S+$/i.test(t))return{ok:!1,error:"URL must start with http:// or https://"};let s=t.replace(/\/+$/,""),n=s.toLowerCase(),o=/(^|\/)v1$/.test(n),i=/(^|\/)v1\/chat\/completions$/.test(n);return!o&&!i?{ok:!1,error:"URL must end with /v1 or /v1/chat/completions"}:{ok:!0,url:s}},G=(e,t)=>{let s=String(t),n=[],o=[];return e.forEach((i,r)=>{let a=I(i);a&&(a===s?n.push(r):a.includes(s)&&o.push(r))}),n.length?n:o},he=async(e,t,s={})=>{let n=f(e)||e;if(!t||!String(t).trim())return{ok:!1,error:"Empty key."};let o=String(t).trim(),i;if(s.baseUrl!==void 0){if(!h(n))return{ok:!1,error:"--url is only supported for the custom provider."};let c=X(s.baseUrl);if(!c.ok)return{ok:!1,error:`Invalid URL: ${c.error}`};i=c.url}let r=S(),a=E(r[n]);if(a.some(c=>I(c)===o))return{ok:!1,error:`Key already exists in slot ${a.findIndex(l=>I(l)===o)+1}.`};if(Number.isInteger(s.index)){let c=s.index;if(c<0||c>=y)return{ok:!1,error:`Index must be between 1 and ${y}.`};let l=a[c]&&typeof a[c]=="object"?a[c].baseUrl:void 0;return a[c]=await R(n,o,l,i),r[n]=a,g(r),await P(n,!1),{ok:!0,index:c}}let u=a.findIndex(c=>!d(c));return u===-1?{ok:!1,error:"All slots full. Specify an index to overwrite.",full:!0}:(a[u]=await R(n,o,void 0,i),r[n]=a,g(r),await P(n,!1),{ok:!0,index:u})},we=async(e,t,s={})=>{let n=f(e)||e;if(!t||!String(t).trim())return{ok:!1,error:"Empty key."};let o=String(t).trim(),i;if(s.baseUrl!==void 0){if(!h(n))return{ok:!1,error:"Base URL is only supported for the custom provider."};let p=X(s.baseUrl);if(!p.ok)return{ok:!1,error:`Invalid URL: ${p.error}`};i=p.url}let r=S(),a=E(r[n]),u=await _(n),c=Number.isInteger(u)&&u>=0&&u<y&&d(a[u])?u:a.findIndex(d);c===-1&&(c=0);let l=a[c]&&typeof a[c]=="object"?a[c].baseUrl:void 0;return a[c]=await R(n,o,l,i),r[n]=a,g(r),await w(n,c),await P(n,!1),{ok:!0,index:c}},Ee=async(e,t,s={})=>{let n=f(e)||e,o=S(),i=E(o[n]);if(s.all||t==="--all"||t==="__all__")return o[n]=B(),g(o),await w(n,null),{ok:!0,all:!0,remaining:0,needsNewKey:!0};let r=-1;if(t==null){let l=await _(n);if(r=Number.isInteger(l)&&d(i[l])?l:i.findIndex(d),r===-1)return{ok:!1,error:"No keys to remove."}}else if(Number.isInteger(t)){if(r=t,r<0||r>=y)return{ok:!1,error:`Index must be between 1 and ${y}.`};if(!d(i[r]))return{ok:!1,error:`Slot ${r+1} is already empty.`}}else{let l=G(i,t);if(l.length===0)return{ok:!1,error:"No matching key found."};if(l.length>1)return{ok:!1,error:`Duplicate match (slots ${l.map(p=>p+1).join(", ")}). Be more specific.`};r=l[0]}let a=I(i[r]),u=await _(n)===r;i[r]=null,o[n]=i,g(o);let c=i.filter(d).length;if(u){let l=i.findIndex(d);await w(n,l===-1?null:l)}return{ok:!0,removed:a,removedIndex:r,remaining:c,needsNewKey:c===0}},Se=async(e,t)=>{let s=f(e)||e,n=A(s),o=-1;if(Number.isInteger(t)){if(o=t,o<0||o>=y)return{ok:!1,error:`Index must be between 1 and ${y}.`};if(!d(n[o]))return{ok:!1,error:`Slot ${o+1} is empty.`}}else{let r=G(n,t);if(r.length===0)return{ok:!1,error:"No matching key found."};if(r.length>1)return{ok:!1,error:`Duplicate match (slots ${r.map(a=>a+1).join(", ")}). Be more specific.`};o=r[0]}await w(s,o),await P(s,!1);let i=null;if(h(s)){let r=n[o],a=r&&typeof r=="object"&&r.baseUrl?r.baseUrl.trim():"";if(a)try{let{loadSettings:u,saveSettings:c}=await import("./settings-PUFSRWT3.js"),l=await u();if((l.systemSettings&&l.systemSettings.customOpenAIBaseUrl?l.systemSettings.customOpenAIBaseUrl.trim():"")!==a){let m={...l.systemSettings||{},customOpenAIBaseUrl:a,memory:!1};await c({...l,systemSettings:m}),i=a}}catch{}}return{ok:!0,index:o,key:I(n[o]),switchedBaseUrl:i}},ke=async(e=null)=>{let t=S(),s=e?[f(e)||e]:J(),n=0;for(let o of s){let i=E(t[o]),r=i.filter(d);if(r.length===0){t[o]=i;continue}let a=await _(o),u=Number.isInteger(a)&&d(i[a])?i[a]:null,c=B();r.forEach((p,m)=>{c[m]=p});let l=Number.isInteger(a)?a:null;if(u){let p=i.slice(0,y).map((m,N)=>({s:m,i:N})).filter(m=>d(m.s)).findIndex(m=>m.i===a);l=p===-1?null:p}t[o]=c,l!==a&&await w(o,l),n++}return g(t),{ok:!0,providers:s.length,touched:n}},j=e=>{if(!e)return"";let t=String(e),s=t.length;if(s<=3)return"...";let n=Math.floor(s/3),o=t.slice(0,n),i=t.slice(s-n);return o+"..."+i},ne=e=>{if(!e)return"";let t=String(e).replace(/\/+$/,"");return t.length<=28?t:"..."+t.replace(/^https?:\/\//i,"").slice(-24)},Ae=async(e,t={})=>{let s=t.unmask===!0,n=f(e)||e,o=A(n),i=await _(n),r=x.get(n),a=[];r&&r.key&&a.push(`Temporary: ${s?r.key:j(r.key)}`),await $(n)&&a.push("Mode: NO KEY (null) <- active");for(let u=0;u<y;u++){let c=o[u],l=I(c),p=l&&!s?j(l):l,m;if(!l)m="Empty";else if(h(n)){let M=c&&typeof c=="object"?ne(c.baseUrl):"";m=M?`${p} (Saved: ${M})`:p}else m=p;let N=u===i&&l?" \u2190 active":"";a.push(`${u+1}: ${m}${N}`)}return a};export{F as a,U as b,f as c,J as d,h as e,ie as f,ce as g,le as h,A as i,q as j,ue as k,_ as l,w as m,ee as n,fe as o,$ as p,P as q,de as r,pe as s,me as t,ye as u,Ie as v,xe as w,ge as x,_e as y,X as z,he as A,we as B,Ee as C,Se as D,ke as E,j as F,ne as G,Ae as H};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as p}from"./chunk-26BQ45XP.js";import a from"fs";import g from"path";import{fileURLToPath as O}from"url";var y={version:0,release:20261106,fallbacks:{},providers:{}};var P=O(import.meta.url),b=g.dirname(P),v="",S=[g.join(b,"../../model_config.json"),g.join(b,"../model_config.json")];for(let e of S)try{if(a.existsSync(e)){v=e;break}}catch{}var x=g.join(p,"model_config.json"),d=null,M=()=>{if(v)try{let e=a.readFileSync(v,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object")return t}catch{}return y&&typeof y=="object"?JSON.parse(JSON.stringify(y)):{version:0,release:20260913,fallbacks:{},providers:{}}};if(a.existsSync(x))try{let e=a.readFileSync(x,"utf-8"),t=JSON.parse(e);if(t&&typeof t=="object"){let o=M();t.fallbacks={...o.fallbacks||{},...t.fallbacks||{}},t.providers||(t.providers={}),t.release||(t.release=o.release||20260913),d=t}}catch{}d||(d=M());var h=new Set,_=new Set,u=()=>{let e=new Set,t=new Set;if(d.providers)for(let o of Object.keys(d.providers)){let s=d.providers[o];if(s&&s.models){let i=["Free","Paid"];for(let l of i){let r=s.models[l];if(Array.isArray(r)){for(let n of r)if(n&&n.cmd){let c=n.cmd.trim().toLowerCase();n.multimodal===!0&&e.add(c),n.hasReasoning===!0&&t.add(c)}}}}}if(Array.isArray(d.multimodal_models))for(let o of d.multimodal_models)o&&typeof o=="string"&&e.add(o.trim().toLowerCase());h=e,_=t};u();var $=()=>d,m=()=>{try{return a.existsSync(p)||a.mkdirSync(p,{recursive:!0}),a.writeFileSync(x,JSON.stringify(d,null,2),"utf-8"),!0}catch{return!1}},U=(e,t,o=!1,s=null,i=null)=>{if(!e||!t)return{success:!1,reason:"Invalid provider or model ID"};let l=t.trim();if(!l)return{success:!1,reason:"Model ID cannot be empty"};d.providers||(d.providers={}),d.providers[e]||(d.providers[e]={default_free:"",default_paid:"",models:{Free:[],Paid:[]}});let r=d.providers[e];r.models||(r.models={Free:[],Paid:[]}),Array.isArray(r.models.Free)||(r.models.Free=[]);let n=i?String(i).trim().replace(/\/+$/,""):null,c=r.models.Free.find(f=>(typeof f=="string"?f:f?.cmd)===l);if(c)if(typeof c=="string"){let f=r.models.Free.indexOf(c),F={cmd:l,multimodal:!!o,desc:l};s&&Object.keys(s).length>0&&(F.info=s),n&&(F.baseUrl=n),r.models.Free[f]=F}else c.multimodal=!!o,s&&Object.keys(s).length>0&&(c.info={...c.info||{},...s}),n&&(c.baseUrl=n);else{let f={cmd:l,multimodal:!!o,desc:l};s&&Object.keys(s).length>0&&(f.info=s),n&&(f.baseUrl=n),r.models.Free.push(f)}return u(),m(),{success:!0}},R=(e,t,o={})=>{if(!e||!t)return{success:!1,reason:"Invalid provider or model ID"};let s=t.trim();if(!s)return{success:!1,reason:"Model ID cannot be empty"};d.providers||(d.providers={}),d.providers[e]||(d.providers[e]={default_free:"",default_paid:"",models:{Free:[],Paid:[]}});let i=d.providers[e];i.models||(i.models={Free:[],Paid:[]}),Array.isArray(i.models.Free)||(i.models.Free=[]);let l=s.toLowerCase(),r=i.models.Free.find(n=>{let c=typeof n=="string"?n:n?.cmd;return c&&c.trim().toLowerCase()===l});if(o===null)r&&typeof r=="object"&&delete r.info;else if(!r)i.models.Free.push({cmd:s,multimodal:!1,desc:s,info:o});else if(typeof r=="string"){let n=i.models.Free.indexOf(r);i.models.Free[n]={cmd:r,multimodal:!1,desc:r,info:o}}else r.info={...r.info||{},...o};return m(),{success:!0}},T=(e,t,o=!0)=>{if(!e||!t)return{success:!1,reason:"Invalid provider or model ID"};let s=t.trim();if(!s)return{success:!1,reason:"Model ID cannot be empty"};let i=d.providers?.[e];if(!i||!i.models||!Array.isArray(i.models.Free))return{success:!1,reason:`Provider ${e} has no models configured`};let l=i.models.Free.find(r=>(typeof r=="string"?r:r?.cmd)===s);if(!l)return{success:!1,reason:`Model "${s}" not found in ${e} model list`};if(typeof l=="string"){let r=i.models.Free.indexOf(l);i.models.Free[r]={cmd:s,multimodal:!!o,desc:s}}else l.multimodal=!!o;return u(),m(),{success:!0}},J=(e,t,o=!1,s=null)=>{if(!e||!t)return{success:!1,reason:"Invalid provider or model ID"};let i=t.trim();if(!i)return{success:!1,reason:"Model ID cannot be empty"};d.providers||(d.providers={}),d.providers[e]||(d.providers[e]={default_free:"",default_paid:"",models:{Free:[],Paid:[]}});let l=d.providers[e];l.models||(l.models={Free:[],Paid:[]}),Array.isArray(l.models.Free)||(l.models.Free=[]);let r=l.models.Free.find(n=>(typeof n=="string"?n:n?.cmd)===i);if(r)if(typeof r=="string"){let n=l.models.Free.indexOf(r),c={cmd:i,multimodal:!!o,desc:i};s&&Object.keys(s).length>0&&(c.info=s),l.models.Free[n]=c}else o&&(r.multimodal=!0),s&&Object.keys(s).length>0&&(r.info={...r.info||{},...s});else{let n={cmd:i,multimodal:!!o,desc:i};s&&Object.keys(s).length>0&&(n.info=s),l.models.Free.push(n)}return l.default_free=i,u(),m(),{success:!0}},W=(e,t)=>{if(!e||!t)return{success:!1,reason:"Invalid provider or model ID"};let o=t.trim();if(!o)return{success:!1,reason:"Model ID cannot be empty"};let s=d.providers?.[e];if(!s||!s.models||!Array.isArray(s.models.Free))return{success:!1,reason:`Provider ${e} has no models configured`};let i=s.models.Free.findIndex(l=>(typeof l=="string"?l:l?.cmd)===o);return i===-1?{success:!1,reason:`Model "${o}" not found in ${e} model list`}:(s.models.Free.splice(i,1),s.default_free===o&&(s.default_free=""),s.default_paid===o&&(s.default_paid=""),u(),m(),{success:!0})},E=(e,t,o)=>{if(!e||!t||!o)return{success:!1,reason:"Invalid provider or model IDs"};let s=t.trim(),i=o.trim();if(!s||!i)return{success:!1,reason:"Model IDs cannot be empty"};let l=d.providers?.[e];if(!l||!l.models||!Array.isArray(l.models.Free))return{success:!1,reason:`Provider ${e} has no models configured`};let r=l.models.Free.find(n=>(typeof n=="string"?n:n?.cmd)===s);if(!r)return{success:!1,reason:`Model "${s}" not found in ${e} model list`};if(typeof r=="string"){let n=l.models.Free.indexOf(r);l.models.Free[n]={cmd:i,multimodal:!1,desc:i}}else r.cmd=i,(r.desc===s||!r.desc)&&(r.desc=i);return u(),m(),{success:!0}},I=!1,k=e=>{I=!!e},G=k,K=e=>{if(!e)return!1;let t=e.trim().toLowerCase();return!!(I||h.has(t)||t.startsWith("gemini-")||t.startsWith("gemma-"))},V=e=>{if(!e)return!1;let t=e.trim().toLowerCase();return _.has(t)},X=(e,t,o=null)=>{let s=d.providers[e];if(!s)return[];let i=s.models[t==="Free"?"Free":"Paid"]||[];if(e==="c_openai"&&o){let l=String(o).trim().replace(/\/+$/,"");return i.filter(r=>typeof r=="object"&&r?.baseUrl?r.baseUrl.replace(/\/+$/,"")===l:!0)}return i},q=(e,t)=>{let o=d.providers[e];return o?t==="Free"?o.default_free:o.default_paid:""},z=(e,t)=>{if(!e||!t||!d.providers)return null;let o=d.providers[e];if(!o||!o.models)return null;let s=t.trim().toLowerCase(),i=["Free","Paid"];for(let l of i){let r=o.models[l];if(Array.isArray(r)){for(let n of r)if(typeof n=="object"&&n?.cmd&&n.cmd.trim().toLowerCase()===s&&n.info)return{IN:Number(n.info.IN)||0,OUT:Number(n.info.OUT)||0,CR:Number(n.info.CR)||0,CW:Number(n.info.CW)||0}}}return null},B=e=>d?.fallbacks?.[e];export{y as a,$ as b,m as c,U as d,R as e,T as f,J as g,W as h,E as i,k as j,G as k,K as l,V as m,X as n,q as o,z as p,B as q};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as r,c as P,h as K,i as o,n as c,x as u}from"./chunk-
|
|
1
|
+
import{B as r,c as P,h as K,i as o,n as c,x as u}from"./chunk-J4J3F6BT.js";import{c as E,d as A}from"./chunk-P5HBJA23.js";import{e as l}from"./chunk-26BQ45XP.js";import i from"fs-extra";import f from"path";K();var s=f.join(l,"secrets.json"),w=async()=>{try{let t=E(s,{});if(t.API_KEY)return t.API_KEY}catch{}return null},y=async(t,n={})=>{try{let{isNullMode:e}=await import("./secrets_v2-OBRWR3UT.js");if(await e(t))return c}catch{}try{let e=await u(t,n);if(e)return e}catch{}try{let e=E(s,{});if(t==="Google")return e.GOOGLE_API_KEY||e.API_KEY||null;if(t==="DeepSeek")return e.DEEPSEEK_API_KEY||null;if(t==="OpenRouter")return e.OPENROUTER_API_KEY||null;if(t==="Mistral")return e.MISTRAL_API_KEY||null;if(t==="NVIDIA")return e.NVIDIA_API_KEY||null;if(t==="Ollama")return e.OLLAMA_API_KEY||"LOCAL";if(t==="InferX")return e.INFERX_API_KEY||null;if(t==="SenseNova"||t==="Sensenova")return e.SENSENOVA_API_KEY||null;if(t==="Poolside"||t==="poolside")return e.POOLSIDE_API_KEY||null;if(t==="9router"||t==="9Router")return e["9ROUTER_API_KEY"]||"LOCAL";if(t==="ExpLabs"||t==="ExperientialLabs"||t==="ExperimentalLabs"||t==="explabs")return e.EXPLABS_API_KEY||e.EXPERIENTIALLABS_API_KEY||null;if(t==="TokenHarbor"||t==="Token Harbor"||t==="tokenharbor"||t==="token_harbor"||t==="thk")return e.TOKENHARBOR_API_KEY||e.TOKEN_HARBOR_API_KEY||null;if(t==="Infron"||t==="infron")return e.INFRON_API_KEY||null;if(t==="APInex"||t==="apinex"||t==="apx")return e.APINEX_API_KEY||null;if(t==="xKiro"||t==="xkiro"||t==="kiro")return e.XKIRO_API_KEY||null;if(t==="c_openai"||t==="Custom (OpenAI)")return e.CUSTOM_OPENAI_API_KEY||e.C_OPENAI_API_KEY||null}catch{}return null},h=async(t,n)=>{try{let{addProviderKey:e}=await import("./secrets_v2-OBRWR3UT.js"),_=P(t)||t;o(_).some(I=>I&&(typeof I=="string"?I.trim():I.key))?await e(_,n):await e(_,n,{index:0});return}catch{}t==="Google"?(await a("GOOGLE_API_KEY",n),await a("API_KEY",n)):t==="DeepSeek"?await a("DEEPSEEK_API_KEY",n):t==="OpenRouter"?await a("OPENROUTER_API_KEY",n):t==="Mistral"?await a("MISTRAL_API_KEY",n):t==="NVIDIA"?await a("NVIDIA_API_KEY",n):t==="Ollama"?await a("OLLAMA_API_KEY",n):t==="InferX"?await a("INFERX_API_KEY",n):t==="SenseNova"||t==="Sensenova"?await a("SENSENOVA_API_KEY",n):t==="Poolside"||t==="poolside"?await a("POOLSIDE_API_KEY",n):t==="9router"||t==="9Router"?await a("9ROUTER_API_KEY",n):t==="ExpLabs"||t==="ExperientialLabs"||t==="ExperimentalLabs"||t==="explabs"?await a("EXPLABS_API_KEY",n):t==="TokenHarbor"||t==="Token Harbor"||t==="tokenharbor"||t==="token_harbor"||t==="thk"?await a("TOKENHARBOR_API_KEY",n):t==="Infron"||t==="infron"?await a("INFRON_API_KEY",n):t==="APInex"||t==="apinex"||t==="apx"?await a("APINEX_API_KEY",n):t==="xKiro"||t==="xkiro"||t==="kiro"?await a("XKIRO_API_KEY",n):(t==="c_openai"||t==="Custom (OpenAI)")&&await a("CUSTOM_OPENAI_API_KEY",n)},T=async(t,n,e={})=>{try{return await r(t,n,e)}catch(_){return{ok:!1,error:_&&_.message||"Failed to replace key."}}},b=async t=>{try{return E(s,{})[t]||null}catch{return null}},a=async(t,n)=>{await i.ensureDir(l);let e=E(s,{});e[t]=n,A(s,e,!0)},D=async()=>{try{let t=E(s,{});return{key:t.GOOGLE_API_KEY||t.API_KEY,cx:t.SEARCH_ID}}catch{}return{key:null,cx:null}},g=async t=>a("API_KEY",t),C=async t=>a("GOOGLE_API_KEY",t),X=async t=>a("SEARCH_ID",t),Y=async t=>{try{let n=E(s,{});delete n[t],A(s,n,!0)}catch{}},G=async()=>Y("API_KEY");export{w as a,y as b,h as c,T as d,b as e,a as f,D as g,g as h,C as i,X as j,Y as k,G as l};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{b as z}from"./chunk-B4UKMX5E.js";import{p as ht}from"./chunk-LQM3JK7N.js";import{a as ft,b as W}from"./chunk-P5HBJA23.js";import{d as J,h as Z,i as M,j as b}from"./chunk-26BQ45XP.js";import S from"fs-extra";import U from"path";import 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
|
+
-------------------------------------
|
|
3
|
+
|
|
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(`
|
|
5
|
+
`).filter(Boolean),c=t?t.trim().toLowerCase():"",r=e?e.trim().toLowerCase():"";for(let m=n.length-1;m>=0;m--)try{let l=JSON.parse(n[m]),a=l.provider&&l.provider.trim().toLowerCase()===r,u=l.model&&l.model.trim().toLowerCase()===c;if(a&&u&&l.cached!==void 0){let d=Number(l.cached)||0;return H.set(o,d),d}}catch{}}}catch{}return H.set(o,0),0},qt=(e,t,{input:o=0,cached:i=0,output:s=0})=>{let n=ht(e,t);if(!n)return{cost:0,uncachedInput:Math.max(0,o-i),estimatedCacheWrite:0,pricing:null};let c=Math.max(0,o-i),r=`${e}:${t}`,m=Pt(e,t);H.set(r,i);let l=i>m?i-m:0,a=c/1e6*n.IN,u=s/1e6*n.OUT,d=i/1e6*n.CR,g=l/1e6*n.CW,C=a+u+d+g;return{cost:Number(C.toFixed(6)),uncachedInput:c,estimatedCacheWrite:l,breakdown:{inputCost:Number(a.toFixed(6)),outputCost:Number(u.toFixed(6)),cacheReadCost:Number(d.toFixed(6)),cacheWriteCost:Number(g.toFixed(6))},pricing:n}},Q=null,ie=()=>{Q=null},at=async e=>{if(e!=="c_openai")return e;if(Q)return Q;try{let o=(await z())?.systemSettings?.customOpenAIBaseUrl||"";if(o=o.trim().replace(/\/+$/,""),o){let i=o.indexOf("/v1");return i!==-1&&(o=o.substring(0,i+3)),Q=o,o}}catch{}return"c_openai"},X=async(e,t)=>{let o=t?.stack||t?.message||String(t);console.error(`[Usage Error] [${e}]:`,t);try{await S.ensureDir(U.dirname(yt));let s=`[${new Date().toISOString()}] [${e}] ${o}
|
|
6
|
+
-------------------------------------
|
|
7
|
+
|
|
8
|
+
`;await S.appendFile(yt,s,"utf8")}catch{}},p=null,v={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,cost:0,imageCalls:[]},Y=(e,t)=>{if(!e)return{};let o=Object.keys(e),i=new Date(new Date(t).getTime()-720*60*60*1e3),s={};for(let n of o)new Date(n)>=i&&(s[n]=e[n]);return s},j=async()=>{let e=new Date().toISOString().split("T")[0];try{!await S.exists(M)&&await S.exists(Z)&&(await S.ensureDir(U.dirname(M)),await S.move(Z,M))}catch{}let t=null;try{if(await S.exists(M)){let i=(await S.readFile(M,"utf8")).trim();i.startsWith("{")||i.startsWith("[")?t=JSON.parse(i):t=JSON.parse(W(i))}}catch(i){await X("loadUsageFromFile",i)}let o=t;if(o){let i=o.stats||{...v},s={...v,...i};Array.isArray(s.imageCalls)||(s.imageCalls=[]);let n=o.history||{},c=Y(n,e);if(o.date===e)return{...o,stats:s,history:c};{let r=o.date,m=s,l={...c};return r&&(l[r]=m),{date:e,stats:{...v},history:Y(l,e)}}}return{date:e,stats:{...v},history:{}}},_t=async()=>{},ot=500,wt=0,kt=()=>{let t=new Date().toISOString().split("T")[0];return U.join(b,`${t}.jsonl`)},ne=async e=>{try{await S.ensureDir(b);let t=await at(e.provider),o=Number(e.prompt)||0,i=Number(e.cached)||0,s=Number(e.output)||0,n=qt(e.provider,e.model,{input:o,cached:i,output:s}),c={time:new Date().toISOString(),provider:t||"unknown",model:e.model||"unknown",input:o,cached:i,output:s,reasoning:Number(e.reasoning)||0,ttft:Number(e.ttft)||0,cost:n.cost,estimatedCacheWrite:n.estimatedCacheWrite};n.breakdown&&(c.costBreakdown=n.breakdown),await S.appendFile(kt(),JSON.stringify(c)+`
|
|
9
|
+
`,"utf8"),n.cost>0&&await nt("cost",n.cost,e.provider,e.model),++wt>=10&&(wt=0,await Ct())}catch{}},Ct=async()=>{try{if(!await S.exists(b))return;let e=(await S.readdir(b)).filter(s=>s.endsWith(".jsonl")).sort(),t=[];for(let s of e)try{let n=await S.readFile(U.join(b,s),"utf8");for(let c of n.split(`
|
|
10
|
+
`))c.trim()&&t.push({file:s,line:c})}catch{}if(t.length<=ot)return;let o=t.slice(-ot),i=new Map;for(let s of o)i.has(s.file)||i.set(s.file,[]),i.get(s.file).push(s.line);for(let s of e){let n=i.get(s);!n||n.length===0?await S.remove(U.join(b,s)):await S.writeFile(U.join(b,s),n.join(`
|
|
11
|
+
`)+`
|
|
12
|
+
`,"utf8")}}catch{}},ae=async(e=30)=>{let t=[];try{if(!await S.exists(b))return t;let i=(await S.readdir(b)).filter(s=>s.endsWith(".jsonl")).sort().slice(-Math.max(1,e));for(let s of i)try{let n=await S.readFile(U.join(b,s),"utf8");for(let c of n.split(`
|
|
13
|
+
`))if(c.trim())try{t.push(JSON.parse(c))}catch(r){await X(`getTimedUsage:parseLine (${s})`,r)}}catch(n){await X(`getTimedUsage:readFile (${s})`,n)}}catch(o){await X("getTimedUsage",o)}return t.slice(-ot)},re=async()=>{p=await j(),await Ct()},F=async()=>{let e=new Date().toISOString().split("T")[0];if(!p)p=await j();else if(p.date!==e){let t=p.date,o=p.stats,i=p.history||{};o&&(i[t]=o),p={date:e,stats:{...v},history:Y(i,e)},await _t()}return p&&p.stats&&!Array.isArray(p.stats.imageCalls)&&(p.stats.imageCalls=[]),p.stats},Tt=async()=>{let e=new Date().toISOString().split("T")[0];p||(p=await j()),p.date!==e&&await F();let t=p.history||{},o=Y(t,e);p.history=o;let i=p.stats||{...v},s={...v};s.imageCalls=[],s.models={},s.providerRequests={};let n=(c,r)=>{for(let m in c)if(m==="imageCalls")c.imageCalls=[...c.imageCalls||[],...r.imageCalls||[]];else if(m==="providerRequests"){let l=r.providerRequests||{};for(let a in l)c.providerRequests[a]=(c.providerRequests[a]||0)+(l[a]||0)}else if(m==="models"){let l=r.models||{};for(let a in l){c.models[a]||(c.models[a]={});for(let u in l[a]){c.models[a][u]||(c.models[a][u]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0,cost:0});let d=c.models[a][u],g=l[a][u];d.tokens+=g.tokens||0,d.cachedTokens+=g.cachedTokens||0,d.candidateTokens+=g.candidateTokens||0,d.cost=Number(((d.cost||0)+(g.cost||0)).toFixed(6)),d.ttftSum=(d.ttftSum||0)+(g.ttftSum||0),d.ttftCalls=(d.ttftCalls||0)+(g.ttftCalls||0)}}}else m==="cost"?c.cost=Number(((c.cost||0)+(r.cost||0)).toFixed(6)):typeof c[m]=="number"&&(c[m]+=r[m]||0)};n(s,i);for(let c in o)n(s,o[c]);return s},ce=async(e,t)=>{t=await at(t),e==="toolSuccess"?R.toolSuccess++:e==="toolFailure"?R.toolFailure++:e==="toolDenied"&&R.toolDenied++;let o=await F();o[e]!==void 0&&o[e]++,t&&e==="agent"&&(o.providerRequests||(o.providerRequests={}),o.providerRequests[t]=(o.providerRequests[t]||0)+1),await st({key:e,amount:1,provider:t})},R={linesAdded:0,linesRemoved:0,toolSuccess:0,toolFailure:0,toolDenied:0,cost:0},it=new Set,le=e=>(it.add(e),()=>it.delete(e)),de=async({added:e=0,removed:t=0,file:o=""}={})=>{let i=Math.max(0,Math.floor(Number(e)||0)),s=Math.max(0,Math.floor(Number(t)||0));if(i>0&&await nt("linesAdded",i),s>0&&await nt("linesRemoved",s),i>0||s>0)for(let n of it)try{n({added:i,removed:s,file:o})}catch{}},nt=async(e,t,o,i)=>{o=await at(o),e==="linesAdded"?R.linesAdded+=t:e==="linesRemoved"?R.linesRemoved+=t:e==="cost"&&(R.cost=Number(((R.cost||0)+Number(t)).toFixed(6)));let s=await F();if(s[e]!==void 0&&(e==="cost"?s.cost=Number(((s.cost||0)+Number(t)).toFixed(6)):s[e]+=Math.floor(t)),o&&i&&(e==="tokens"||e==="cachedTokens"||e==="candidateTokens"||e==="ttft"||e==="cost")){s.models||(s.models={}),s.models[o]||(s.models[o]={}),s.models[o][i]||(s.models[o][i]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0,cost:0});let n=s.models[o][i];e==="tokens"&&(n.tokens+=Math.floor(t)),e==="cachedTokens"&&(n.cachedTokens+=Math.floor(t)),e==="candidateTokens"&&(n.candidateTokens+=Math.floor(t)),e==="cost"&&(n.cost=Number(((n.cost||0)+Number(t)).toFixed(6))),e==="ttft"&&(n.ttftSum=(n.ttftSum||0)+Math.floor(t),n.ttftCalls=(n.ttftCalls||0)+1)}await st({key:e,amount:t,provider:o,model:i})},St=async(e=1)=>{let t=new Date,o=t.toISOString().split("T")[0];p||(p=await j()),p.date!==o&&await F();let i=t.getFullYear(),s=t.getMonth();t.getDate()<e&&(s-=1,s<0&&(s=11,i-=1));let r=new Date(i,s,e).toISOString().split("T")[0],m=p.history||{},l=p.stats||{...v},a={...v};a.imageCalls=[],a.models={},a.providerRequests={};let u=(d,g)=>{for(let C in d)if(C==="imageCalls")d.imageCalls=[...d.imageCalls||[],...g.imageCalls||[]];else if(C==="providerRequests"){let h=g.providerRequests||{};for(let f in h)d.providerRequests[f]=(d.providerRequests[f]||0)+(h[f]||0)}else if(C==="models"){let h=g.models||{};for(let f in h){d.models[f]||(d.models[f]={});for(let w in h[f]){d.models[f][w]||(d.models[f][w]={tokens:0,cachedTokens:0,candidateTokens:0,ttftSum:0,ttftCalls:0});let T=d.models[f][w],y=h[f][w];T.tokens+=y.tokens||0,T.cachedTokens+=y.cachedTokens||0,T.candidateTokens+=y.candidateTokens||0,T.ttftSum=(T.ttftSum||0)+(y.ttftSum||0),T.ttftCalls=(T.ttftCalls||0)+(y.ttftCalls||0)}}}else typeof d[C]=="number"&&(d[C]+=g[C]||0)};u(a,l);for(let d in m)d>=r&&d<o&&u(a,m[d]);return a},Bt=async(e,t={})=>{let o=await z().catch(()=>({})),i=t.apiTier||o.apiTier||"Free",s=t.quotas||t.systemSettings?.quotas||o.quotas||{},n=s.providerBudgets||{},c=!!n.__useProvider,r=t.aiProvider||o.aiProvider||"Google",m=c&&!!n[r],l=()=>{if(m){let a=n[r];return{agentLimit:typeof a.agentLimit=="number"&&a.agentLimit>0?a.agentLimit:99999999,tokenLimit:typeof a.tokenLimit=="number"&&a.tokenLimit>0?a.tokenLimit:99999999999999,monthlyTokenLimit:typeof a.monthlyTokenLimit=="number"&&a.monthlyTokenLimit>0?a.monthlyTokenLimit:99999999999999,dailyCostLimit:typeof a.dailyCostLimit=="number"&&a.dailyCostLimit>0?a.dailyCostLimit:99999999999999,monthlyCostLimit:typeof a.monthlyCostLimit=="number"&&a.monthlyCostLimit>0?a.monthlyCostLimit:99999999999999}}return{agentLimit:s.agentLimit||99999999,tokenLimit:s.tokenLimit||99999999999999,monthlyTokenLimit:s.monthlyTokenLimit||99999999999999,dailyCostLimit:typeof s.dailyCostLimit=="number"&&s.dailyCostLimit>0?s.dailyCostLimit:99999999999999,monthlyCostLimit:typeof s.monthlyCostLimit=="number"&&s.monthlyCostLimit>0?s.monthlyCostLimit:99999999999999}};if(e==="agent"){let{agentLimit:a,tokenLimit:u,monthlyTokenLimit:d,dailyCostLimit:g,monthlyCostLimit:C}=l(),h=await F(),f;s.resetMode==="Custom"?f=await St(s.resetDay||1):f=await Tt();let w=0,T=0,y=0,O=0,L=0;if(m){w=h.providerRequests?.[r]||0;let D=h.models?.[r]||{};for(let x in D)T+=D[x]?.tokens||0,O+=D[x]?.cost||0;let k=f.models?.[r]||{};for(let x in k)y+=k[x]?.tokens||0,L+=k[x]?.cost||0}else w=h.agent||0,T=h.tokens||0,y=f.tokens||0,O=h.cost||0,L=f.cost||0;return i==="Free"&&h.agent+h.background>=999999?{allowed:!1,reason:"Free Tier Daily Usage Limit Exceeded"}:w>=a?{allowed:!1,reason:m?`Daily Request Limit Reached for ${r}`:"Daily Agent Request Limit Reached"}:T>=u?{allowed:!1,reason:m?`Daily Token Budget Exhausted for ${r}`:"Daily Token Budget Exhausted"}:y>=d?{allowed:!1,reason:m?`Monthly Token Budget Exhausted for ${r}`:"Monthly Token Budget Exhausted"}:O>=g?{allowed:!1,reason:m?`Daily Cost Budget Exhausted for ${r} ($${O.toFixed(4)} >= $${g.toFixed(4)})`:`Daily Cost Budget Exhausted ($${O.toFixed(4)} >= $${g.toFixed(4)})`}:L>=C?{allowed:!1,reason:m?`Monthly Cost Budget Exhausted for ${r} ($${L.toFixed(4)} >= $${C.toFixed(4)})`:`Monthly Cost Budget Exhausted ($${L.toFixed(4)} >= $${C.toFixed(4)})`}:{allowed:!0}}if(e==="background"){let a=await F();if(i==="Free"&&a.agent+a.background>=999999)return{allowed:!1,reason:"Free Tier Background Limit Exceeded"};let u=a.background<(s.backgroundLimit||999999);return{allowed:u,reason:u?void 0:"Background Request Limit Exceeded"}}if(e==="search"){let u=(await F()).search<(s.searchLimit||100);return{allowed:u,reason:u?void 0:"Search Quota Exceeded"}}return{allowed:!0}},me=async(e,t={})=>(await Bt(e,t)).allowed,rt=e=>{if(!e||e.length===0)return[];let o=[...e].sort((s,n)=>s.timestamp-n.timestamp),i=[];for(let s of o){if(i.length>0){let n=i[i.length-1];if(s.timestamp>=n.start&&s.timestamp<n.end){n.calls.push(s),n.spent+=s.cost;continue}}i.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return i},Lt=(e,t)=>{if(!e||e.length===0)return .025;let i=rt(e);if(i.length===0)return .025;let s=[];for(let u of i){let d=.025;if(s.length>0){let C=s[s.length-1],h=!1;if(s.length>=2){let f=s[s.length-2];C.ratio>=.8&&f.ratio>=.8&&(h=!0)}if(h)d=.015;else{let f=C.limit,w=C.ratio;w>=.8?d=f===.015?.015:f:w<.4?d=Math.min(.025,f+.005):w>=.4&&w<.6?d=Math.min(.025,f+.004):d=Math.min(.025,f+.002)}}let g=d>0?u.spent/d:0;s.push({limit:d,spent:u.spent,ratio:g})}let n=i[i.length-1];if(t<n.end)return s[s.length-1].limit;let c=s[s.length-1].limit,r=c,m=s[s.length-1].ratio,l=n.end,a=0;for(let u=s.length-1;u>=0&&s[u].ratio>=.8;u--)a++;for(;l<=t;){let u=.025;a>=2?u=.015:m>=.8?u=r===.015?.015:r:m<.4?u=Math.min(.025,r+.005):m>=.4&&m<.6?u=Math.min(.025,r+.004):u=Math.min(.025,r+.002),r=u,m=0,a=0,l+=36e5,c=u}return c},ue=async e=>{let t=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(t.keyType!=="Default")return!0;let i={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[t.quality]||.002,s=await F();s.imageCalls||(s.imageCalls=[]);let n=Date.now(),c=rt(s.imageCalls),r=0;if(c.length>0){let l=c[c.length-1];n>=l.start&&n<l.end&&(r=l.spent)}let m=Lt(s.imageCalls,n);return r+i<=m},fe=async()=>{let e=await F();e.imageCalls||(e.imageCalls=[]);let t=Date.now(),o=rt(e.imageCalls),i=[],s=0,n=0;if(o.length>0){let l=o[o.length-1];t>=l.start&&t<l.end&&(i=l.calls,s=l.spent,n=Math.max(0,Math.ceil((l.end-t)/(60*1e3))))}let c=Lt(e.imageCalls,t),r=Math.max(0,c-s),m=s;return{totalSpent:s,remaining:r,activeCallsCount:i.length,nextResetMin:n,reclaimCost:m,limit:c}},he=async e=>{let t=e.imageSettings||{keyType:"Default",quality:"Low-High"},i={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[t.quality]||.002,s=await F();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:i}),queueFlush()},ge=async()=>{let e=new Date().toISOString().split("T")[0];p||(p=await j()),p.date!==e&&await F();let t=p.stats||{...v},o=p.history||{},i=new Set(Object.keys(o));i.add(e);let n=Array.from(i).sort().map(L=>{let D=L===e?t:o[L]||{},k={...v,...D},x=k.tokens||0,P=k.cachedTokens||0,q=k.candidateTokens||0,G=Math.max(0,x-q),_=Math.max(0,G-P),A=k.agent||0,I=k.background||0,E=k.search||0,Dt=A+I+E,V=k.toolSuccess||0,ct=k.toolFailure||0,lt=k.toolDenied||0,K=V+ct+lt,xt=K>0?(V/K*100).toFixed(1):"100.0",dt=k.linesAdded||0,mt=k.linesRemoved||0,ut=Array.isArray(k.imageCalls)?k.imageCalls:[],Mt=ut.reduce((bt,vt)=>bt+(vt.cost||0),0);return{date:L,tokens:x,cachedTokens:P,candidateTokens:q,promptTokens:G,uncachedPromptTokens:_,agent:A,background:I,search:E,totalRequests:Dt,toolSuccess:V,toolFailure:ct,toolDenied:lt,totalTools:K,toolSuccessRate:parseFloat(xt),linesAdded:dt,linesRemoved:mt,netLines:dt-mt,duration:k.duration||0,cost:k.cost||0,imageCallsCount:ut.length,imageCost:Mt,models:k.models||{},providerRequests:k.providerRequests||{}}}),c=await z().catch(()=>({})),r=c.quotas||{},m=c.apiTier||"Free",l=await Tt().catch(()=>({tokens:0,agent:0})),a=null;r.resetMode==="Custom"&&(a=await St(r.resetDay||1).catch(()=>({tokens:0})));let u=r.tokenLimit||0,d=r.monthlyTokenLimit||0,g=r.agentLimit||0,C=r.resetMode||"Daily",h=r.resetDay||1,f=r.providerBudgets||{},w=!!f.__useProvider,T=["Google","Anthropic","OpenAI","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside"];Object.keys(f).forEach(L=>{L!=="__useProvider"&&!T.includes(L)&&T.push(L)});let y=[];for(let L of T){let D=f[L];if(D&&(D.agentLimit||D.tokenLimit||D.monthlyTokenLimit)){let k=0,x=t.models?.[L]||{};for(let E in x)k+=x[E]?.tokens||0;let P=0,q=(r.resetMode==="Custom"?a?.models:l?.models)?.[L]||{};for(let E in q)P+=q[E]?.tokens||0;let G=t.providerRequests?.[L]||0,_=D.tokenLimit||0,A=D.monthlyTokenLimit||0,I=D.agentLimit||0;y.push({provider:L,dailyTokens:k,dailyTokenLimit:_,isDailyUnlimited:_>=9999999999999||_===0,monthlyTokens:P,monthlyTokenLimit:A,isMonthlyUnlimited:A>=9999999999999||A===0,dailyRequests:G,dailyAgentLimit:I,isRequestsUnlimited:I>=9999999||I===0})}}let O={apiTier:m,resetMode:C,resetDay:h,quotas:r,usingProviderBudgets:w&&y.length>0||y.length>0,providerBudgetsList:y,daily:{tokensUsed:t.tokens||0,tokenLimit:u,cost:t.cost||0,costLimit:r.dailyCostLimit||0,agentRequests:t.agent||0,agentLimit:g,isUnlimitedTokens:u>=9999999999999||u===0,isUnlimitedCost:!r.dailyCostLimit||r.dailyCostLimit>=9999999999999||r.dailyCostLimit===0,isUnlimitedRequests:g>=9999999||g===0},monthly:{tokensUsed:(r.resetMode==="Custom"?a?.tokens:l?.tokens)||0,tokenLimit:d,cost:(r.resetMode==="Custom"?a?.cost:l?.cost)||0,costLimit:r.monthlyCostLimit||0,isUnlimitedTokens:d>=9999999999999||d===0,isUnlimitedCost:!r.monthlyCostLimit||r.monthlyCostLimit>=9999999999999||r.monthlyCostLimit===0},providerBudgets:f};return{currentDate:e,todayStats:t,history:o,timeline:n,budget:O,runtimeSession:{...R}}};export{Nt as a,$t as b,qt as c,ie as d,_t as e,ne as f,Ct as g,ae as h,re as i,F as j,Tt as k,ce as l,R as m,le as n,de as o,nt as p,St as q,Bt as r,me as s,rt as t,Lt as u,ue as v,fe as w,he as x,ge as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as f}from"./chunk-
|
|
1
|
+
import{h as f}from"./chunk-GBH7XI5A.js";import{mouse as c,keyboard as i,Button as u,Key as e,Point as l,clipboard as g}from"@nut-tree-fork/nut-js";c.config.autoDelayMs=50;i.config.autoDelayMs=50;async function w(){try{await i.releaseKey(e.LeftControl,e.RightControl,e.LeftAlt,e.RightAlt,e.LeftShift,e.RightShift,e.LeftSuper,e.RightSuper)}catch{}}async function h(n,t,s={}){let r=await f(t);if(!r&&(n==="move"||n==="click"||n==="drag"))return`ERROR: Invalid target location specified: ${JSON.stringify(t)}`;try{switch(n.toLowerCase()){case"move":return await c.setPosition(new l(r.x,r.y)),`Moved mouse to grid target ${typeof t=="string"?t:`(${r.x}, ${r.y})`}`;case"click":{await c.setPosition(new l(r.x,r.y));let a=s.button==="right"?u.RIGHT:s.button==="middle"?u.MIDDLE:u.LEFT;return s.clickType==="double"?await c.doubleClick(a):await c.click(a),`${s.clickType||"Single"} clicked ${s.button||"left"} button at ${typeof t=="string"?t:`(${r.x}, ${r.y})`}`}case"drag":{let a=await f(s.from||t),o=await f(s.to);return!a||!o?'ERROR: Drag requires valid "from" and "to" target coordinates/grid codes.':(await c.setPosition(new l(a.x,a.y)),await c.pressButton(u.LEFT),await c.setPosition(new l(o.x,o.y)),await c.releaseButton(u.LEFT),`Dragged mouse from (${a.x}, ${a.y}) to (${o.x}, ${o.y})`)}case"scroll":{let a=r||await f({x:640,y:360});a&&(await c.setPosition(new l(a.x,a.y)),await new Promise(d=>setTimeout(d,60)));let o=parseInt(s.amount,10);(isNaN(o)||o<=0)&&(o=5);let y=o>50?Math.min(20,Math.max(1,Math.round(o/100))):Math.min(20,o),R=s.direction==="up";for(let d=0;d<y;d++)R?await c.scrollUp(120):await c.scrollDown(120),await new Promise(L=>setTimeout(L,20));return`Scrolled ${s.direction||"down"} (${y} notches${r?` at target (${r.x}, ${r.y})`:" at screen center"})`}default:return`ERROR: Unsupported mouse action "${n}"`}}catch(a){return`ERROR: Mouse action failed: ${a.message}`}}var m={enter:e.Enter,return:e.Return,escape:e.Escape,esc:e.Escape,backspace:e.Backspace,tab:e.Tab,space:e.Space,up:e.Up,down:e.Down,left:e.Left,right:e.Right,ctrl:e.LeftControl,control:e.LeftControl,alt:e.LeftAlt,shift:e.LeftShift,cmd:e.LeftCmd,win:e.LeftWin,meta:e.LeftWin,super:e.LeftSuper,a:e.A,b:e.B,c:e.C,d:e.D,e:e.E,f:e.F,g:e.G,h:e.H,i:e.I,j:e.J,k:e.K,l:e.L,m:e.M,n:e.N,o:e.O,p:e.P,q:e.Q,r:e.R,s:e.S,t:e.T,u:e.U,v:e.V,w:e.W,x:e.X,y:e.Y,z:e.Z,0:e.Num0,1:e.Num1,2:e.Num2,3:e.Num3,4:e.Num4,5:e.Num5,6:e.Num6,7:e.Num7,8:e.Num8,9:e.Num9,f1:e.F1,f2:e.F2,f3:e.F3,f4:e.F4,f5:e.F5,f6:e.F6,f7:e.F7,f8:e.F8,f9:e.F9,f10:e.F10,f11:e.F11,f12:e.F12},p=n=>{if(!n)return;let t=String(n).toLowerCase().trim();if(m[t]!==void 0)return m[t];if(e[n]!==void 0)return e[n];if(e[t.toUpperCase()]!==void 0)return e[t.toUpperCase()]};async function E(n,t,s={}){try{switch(n.toLowerCase()){case"type":{if(typeof t!="string")return"ERROR: Type action requires a valid string input";await w(),await g.setContent(t);let a=process.platform==="darwin"?e.LeftSuper:e.LeftControl;return await i.pressKey(a,e.V),await i.releaseKey(a,e.V),await w(),s.autoPressEnter?(await new Promise(o=>setTimeout(o,50)),await i.type(e.Enter),`Typed text input ("${t.length>20?t.substring(0,20)+"...":t}") and pressed Enter`):`Typed text input ("${t.length>20?t.substring(0,20)+"...":t}")`}case"key_press":{let r=p(t);return r===void 0?`ERROR: Unknown key name "${t}"`:(await i.type(r),`Pressed key ${t}`)}case"key_combination":{if(!Array.isArray(t))return'ERROR: key_combination requires an array of keys (e.g. ["ctrl", "c"])';let r=t.map(a=>p(a)).filter(a=>a!==void 0);return r.length===0?"ERROR: Invalid key combination":(await i.pressKey(...r),await i.releaseKey(...r),`Executed key combination [${t.join(" + ")}]`)}case"clear_input":return await i.pressKey(e.LeftControl,e.A),await i.releaseKey(e.LeftControl,e.A),await i.type(e.Backspace),"Cleared active text input (Select All + Backspace)";case"browser_back":{let r=process.platform==="darwin";return r?(await i.pressKey(e.LeftSuper,e.Left),await i.releaseKey(e.LeftSuper,e.Left)):(await i.pressKey(e.LeftAlt,e.Left),await i.releaseKey(e.LeftAlt,e.Left)),await w(),`Browser back navigation (${r?"Cmd+Left":"Alt+Left"})`}default:return`ERROR: Unsupported keyboard action "${n}"`}}catch(r){return`ERROR: Keyboard action failed: ${r.message}`}}export{h as a,E as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as W}from"./chunk-
|
|
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 C=null;async function tt(){return C||(C=(async()=>{let{createWorker:t}=await import("tesseract.js"),o=await import("fs-extra"),{CU_CACHE_DIR:e}=await import("./paths-RQRI2XRY.js");return o.ensureDirSync(e),t("eng",1,{cachePath:e,logger:()=>{}})})().catch(t=>{throw C=null,t})),C}var I=null,F=null;async function et(){let{getActiveDisplay:t}=await import("./screen_grid-
|
|
1
|
+
import{a as W}from"./chunk-ZNO55RNG.js";import{g as B,i as S}from"./chunk-GBH7XI5A.js";import{a as P}from"./chunk-Y5JU726N.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 C=null;async function tt(){return C||(C=(async()=>{let{createWorker:t}=await import("tesseract.js"),o=await import("fs-extra"),{CU_CACHE_DIR:e}=await import("./paths-RQRI2XRY.js");return o.ensureDirSync(e),t("eng",1,{cachePath:e,logger:()=>{}})})().catch(t=>{throw C=null,t})),C}var I=null,F=null;async function et(){let{getActiveDisplay:t}=await import("./screen_grid-3RU324CV.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),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(),D=null,T="",q=x?320:500;if(x){let m=Math.min(Math.round(h/2),h),y=Math.min(Math.round(p/2),p),b=Math.max(0,Math.min(h-m,g.x-Math.floor(m/2))),k=Math.max(0,Math.min(p-y,g.y-Math.floor(y/2))),_=await O(M).extract({left:b,top:k,width:m,height:y}).toBuffer(),z=2,A=await H(_,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)&&(D=$,T="centered target crop OCR")}}}if(!D){let m=await H(M,2),y=u.replace(/[^a-z0-9]/g,"_");await U("fullscreen",`full_${Date.now()}_${y}.png`,m),await d.setParameters({tessedit_pageseg_mode:"3"});let{data:b}=await d.recognize(m,{},{tsv:!0,blocks:!0});if(b&&b.text){let k=L(b,u,0,0,2);if(k.length>0){let _=N(k,g);_&&(D=_,T="full-screen OCR")}}}if(D){let m={x:Math.round(D.x*(1280/h)),y:Math.round(D.y*(720/p))},y=await W("click",m,{button:i,clickType:r});if(typeof y=="string"&&y.startsWith("ERROR:"))return y;let b=S(m),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 +1 @@
|
|
|
1
|
-
import{a as i,b as s}from"./chunk-
|
|
1
|
+
import{a as i,b as s}from"./chunk-ZNO55RNG.js";import"./chunk-GBH7XI5A.js";import{a as c}from"./chunk-Y5JU726N.js";var d=async(a,p={})=>{let e=c(a),r=e.action||e.type||e.cmd,n=e.target||e.grid||e.gridCode||e.location||e.input;if(!r)return'ERROR: Missing required "action" argument for computer_action (e.g. move, click, drag, scroll, type, key_press, key_combination).';let t=r.toLowerCase();if(t.startsWith("mouse_")||["move","click","drag","scroll"].includes(t)){let o=t.replace("mouse_","");return await i(o,n,{button:e.button,clickType:e.clickType||e.type,from:e.from,to:e.to,direction:e.direction,amount:e.amount?parseInt(e.amount,10):void 0})}if(t.startsWith("key_")||t==="type"||t==="press"){let o=t;t==="press"&&(o="key_press");let u=e.autoPressEnter===!0||e.autoPressEnter==="true"||e.enter===!0||e.enter==="true";return await s(o,n||e.text||e.keys,{...e,autoPressEnter:u})}return`ERROR: Unrecognized action "${r}". Supported actions: move, click, drag, scroll, type, key_press, key_combination.`};export{d as computer_action};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as m}from"./chunk-PTFCY2D5.js";import{a as L}from"./chunk-HFTI3R3Q.js";import{n as U}from"./chunk-
|
|
1
|
+
import{a as m}from"./chunk-PTFCY2D5.js";import{a as L}from"./chunk-HFTI3R3Q.js";import{n as U}from"./chunk-J4J3F6BT.js";import"./chunk-P5HBJA23.js";import"./chunk-26BQ45XP.js";var Q=async function*(_,C,v,E,A,b,$,d,W=1,B=""){let x=[];E&&x.push({role:"system",content:E});for(let t of v){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&&$){let c=o.inlineData.mimeType,u=o.inlineData.data;c.startsWith("image/")&&n.push({type:"image_url",image_url:{url:`data:${c};base64,${u}`}})}}else{let o=t.text||"";o&&n.push({type:"text",text:o})}x.push({role:e,content:n.length===1&&n[0].type==="text"?n[0].text:n})}let P=L("c_openai",C,A),y=P!==null?P:{Fast:"none",Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"xhigh"}[A],a={model:C,messages:x,stream:!0,stream_options:{include_usage:!0},temperature:W,tools:[],tool_choice:"none"};y&&y!=="none"&&(a.reasoning_effort=y,a.reasoning={effort:y});let N=(B||process.env.CUSTOM_OPENAI_URL||process.env.C_OPENAI_URL||"").trim();if(!N)throw new Error("Custom OpenAI Base URL is not configured. Please set Base URL in /settings -> Providers.");let f=N.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"},S=_===U,T=S?"":_&&_!=="LOCAL"?_:process.env.CUSTOM_OPENAI_API_KEY||process.env.C_OPENAI_API_KEY||"";if(!S&&T&&T.trim()!==""){let t=T.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(a),signal:d});if(!s.ok&&(s.status===400||s.status===422)&&(a.reasoning||a.reasoning_effort)){if(console.info(`
|
|
2
2
|
`),a.reasoning&&a.reasoning_effort){let t={...a};delete t.reasoning_effort;let e=await m(f,{method:"POST",headers:l,body:JSON.stringify(t),signal:d}).catch(()=>null);e&&e.ok&&(s=e)}if(!s.ok&&a.reasoning_effort){let t={...a};delete t.reasoning;let e=await m(f,{method:"POST",headers:l,body:JSON.stringify(t),signal:d}).catch(()=>null);e&&e.ok&&(s=e)}if(!s.ok){let t={...a};delete t.reasoning,delete t.reasoning_effort;let e=await m(f,{method:"POST",headers:l,body:JSON.stringify(t),signal:d}).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 F=s.body.getReader(),J=new TextDecoder,w="",i=[],p=null,k=Date.now(),g=!1,R=(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},K=(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:""},Y=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,u=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:u,thoughtsTokenCount:r}};for(;;){let{done:t,value:e}=await F.read();if(t){g&&(i.length>0||p)&&(yield{candidates:i.length>0?[{content:{parts:i}}]:[],usageMetadata:p});break}w+=J.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 u=!1;if(c==="data: [DONE]"||c==="data: [DONE]\r")u=!0;else try{let r=JSON.parse(c.substring(6));if(r.error){let H=r.error.metadata?.raw||r.error.message||(typeof r.error=="string"?r.error:JSON.stringify(r.error));throw new Error(`Custom OpenAI Stream Error: ${H}`)}let h=r.choices?.[0],O=h?.delta;h?.finish_reason&&h.finish_reason!=="null"&&(u=!0);let D=Y(r);D&&(p=D,g=!0);let I=R(O,h);I&&(i.push({text:I,thought:!0}),g=!0);let M=K(O,h);M&&(i.push({text:M}),g=!0)}catch(r){if(r.message&&r.message.startsWith("Custom OpenAI Stream Error:"))throw r}if((u||Date.now()-k>=150)&&g&&(yield{candidates:i.length>0?[{content:{parts:[...i]}}]:[],usageMetadata:p},i=[],k=Date.now(),g=!1),u)break}Date.now()-k>=150&&g&&(yield{candidates:i.length>0?[{content:{parts:[...i]}}]:[],usageMetadata:p},i=[],k=Date.now(),g=!1)}};export{Q as getCustomOpenAIStream};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-
|
|
1
|
+
import{a as e}from"./chunk-ZNO55RNG.js";import"./chunk-GBH7XI5A.js";import{a as d}from"./chunk-Y5JU726N.js";var m=async(a,i={})=>{let r=d(a),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{m as drag};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as k}from"./chunk-6EYQQ7GQ.js";import{a as b}from"./chunk-Y5JU726N.js";import{
|
|
1
|
+
import{a as k}from"./chunk-6EYQQ7GQ.js";import{a as b}from"./chunk-Y5JU726N.js";import{v as B,w as T,x as $}from"./chunk-V36DXF56.js";import{b as I}from"./chunk-B4UKMX5E.js";import"./chunk-LQM3JK7N.js";import"./chunk-P5HBJA23.js";import"./chunk-26BQ45XP.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},f=(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(f(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),c=s.prompt||s.text,l=s.path||s.outputPath||s.output||"generated_image.png",f=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(f){let t=f.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(),p=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:f||"1:1",Seed:String(M)};p=F(p,P);let R=x.resolve(process.cwd(),l);await C.ensureDir(x.dirname(R)),await k.recordFileChange(R),await C.writeFile(R,p),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:p.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,6 +1,6 @@
|
|
|
1
|
-
import{a as k,c as d}from"./chunk-56EJGQU3.js";import{a as b}from"./chunk-Y5JU726N.js";var I=async(w,s={})=>{let{runSubagent:U}=await import("./ai-
|
|
1
|
+
import{a as k,c as d}from"./chunk-56EJGQU3.js";import{a as b}from"./chunk-Y5JU726N.js";var I=async(w,s={})=>{let{runSubagent:U}=await import("./ai-WBRHU7IH.js"),l=b(w),c=l.task||l.instruction||l.prompt,E=l.model||null,C=l.title||null,m=l.tools||null;if(!c)return'ERROR: Missing "task" argument for invoke.';let f=null;if(m)try{let t=m.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.substring(1,t.length-1)),f=t.split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let i=`subagent-${Date.now()}-${Math.floor(Math.random()*1e3)}`,h=null,S=null,$=new Promise((t,n)=>{h=t,S=n}),e={id:i,title:C||c.substring(0,30),task:c,status:"running",startedAt:Date.now(),lastChunkTime:Date.now(),wps:0,questions:[],pendingSteerMessages:[],steer:t=>{t&&e.pendingSteerMessages.push(t)},completionPromise:$,_resolveCompletion:h,_rejectCompletion:S,progress:[]},r={chunks:[],totalWords:0};k.push(e),s.onSubagentUpdate&&s.onSubagentUpdate();let a=[],A={...s,taskId:i,onAskMain:async t=>{let n=`q-${Date.now()}-${Math.floor(Math.random()*1e3)}`,o=null,p=new Promise(g=>{o=g}),u={id:n,question:t,answered:!1,answer:null,askedAt:Date.now(),_resolve:o};return e.questions.push(u),e.status="waiting",s.onSubagentUpdate&&s.onSubagentUpdate(),d(`[SYSTEM] Background subagent "${e.title}" is WAITING FOR YOUR INPUT: "${t}"
|
|
2
2
|
Respond using tool: [action:Answer(id="${i}", answer="...")]
|
|
3
3
|
[/SYSTEM]`),await p},onVisualFeedback:t=>{e.lastChunkTime=Date.now();let n=t.replace(/\x1b\[[0-9;]*m/g,""),o=n.match(/[✔✘✗✖🔍📖→➕↻•]\s*([A-Za-z0-9\s-]+)/);o?e.currentTool=o[1].trim():e.currentTool=n,s.onSubagentUpdate&&s.onSubagentUpdate()},onTokenChunk:(t,n)=>{let o=Date.now();if(e.lastChunkTime=o,e.currentTool="Thinking",typeof n=="number"&&n>0){r.totalWords+=n,r.chunks.push({time:o,words:n});let p=o-400;if(r.chunks=r.chunks.filter(u=>u.time>=p),r.chunks.length>0){let u=r.chunks.reduce((M,_)=>M+_.words,0),T=r.chunks[0].time,g=Math.max(.4,(o-T)/1e3);e.wps=Math.round(u/g)}}s.onSubagentUpdate&&s.onSubagentUpdate()}};return U(c,A,E,f,null,t=>{if(e.status==="cancelled")return;if(t.startsWith("[Subagent Turn")&&a.length>0&&(e.progress.push([...a]),a=[]),t.includes("[Executing Tool]")){let o=t.match(/\[Executing Tool\]\s*([a-zA-Z0-9_]+)/);o&&(!e.currentTool||e.currentTool==="Thinking")&&(e.currentTool=o[1])}let n=t;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] ...`)}a.push(n),s.onSubagentUpdate&&s.onSubagentUpdate()},!0).then(t=>{if(e.status==="cancelled"){e._resolveCompletion&&e._resolveCompletion(t);return}a.length>0&&(e.progress.push([...a]),a=[]),e.status="completed",e.finalAnswer=t,s.onSubagentUpdate&&s.onSubagentUpdate(),d(`[SYSTEM] Background subagent "${e.title}" (id: ${i}) has FINISHED. Call GetProgress(id="${i}") to see the final result. [/SYSTEM]`),e._resolveCompletion&&e._resolveCompletion(t)}).catch(async t=>{let{isTerminationSignaled:n}=await import("./ai-
|
|
6
|
+
... [Content/Diff Truncated from Logs] ...`)}a.push(n),s.onSubagentUpdate&&s.onSubagentUpdate()},!0).then(t=>{if(e.status==="cancelled"){e._resolveCompletion&&e._resolveCompletion(t);return}a.length>0&&(e.progress.push([...a]),a=[]),e.status="completed",e.finalAnswer=t,s.onSubagentUpdate&&s.onSubagentUpdate(),d(`[SYSTEM] Background subagent "${e.title}" (id: ${i}) has FINISHED. Call GetProgress(id="${i}") to see the final result. [/SYSTEM]`),e._resolveCompletion&&e._resolveCompletion(t)}).catch(async t=>{let{isTerminationSignaled:n}=await import("./ai-WBRHU7IH.js");if(t.message==="Subagent task was cancelled."||e.status==="cancelled"||n()){e.status="cancelled",a.push("[SUBAGENT CANCELLED] Task was cancelled."),e.progress.push([...a]),s.onSubagentUpdate&&s.onSubagentUpdate(),e._resolveCompletion&&e._resolveCompletion(null);return}a.push(`[SUBAGENT FAILURE] Error: ${t.message}`),e.progress.push([...a]),e.status="failed",e.error=t.message,s.onSubagentUpdate&&s.onSubagentUpdate(),d(`[SYSTEM] Background subagent "${e.title}" (id: ${i}) FAILED with error: ${t.message}. [/SYSTEM]`),e._rejectCompletion&&e._rejectCompletion(t)}),`Background subagent started. Task ID: ${i}`};export{I as invoke};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as o}from"./chunk-Y5JU726N.js";var k=async(b,t={})=>{let{runSubagent:u}=await import("./ai-
|
|
2
|
-
`),e}catch(e){let{isTerminationSignaled:i}=await import("./ai-
|
|
1
|
+
import{a as o}from"./chunk-Y5JU726N.js";var k=async(b,t={})=>{let{runSubagent:u}=await import("./ai-WBRHU7IH.js"),s=o(b),a=s.task||s.instruction||s.prompt,m=s.model||null,l=s.tools||null;if(!a)return'ERROR: Missing "task" argument for invokeSync.';let r=null;if(l)try{let e=l.trim();e.startsWith("[")&&e.endsWith("]")&&(e=e.substring(1,e.length-1)),r=e.split(",").map(i=>i.trim().replace(/^["']|["']$/g,"")).filter(Boolean)}catch{}let n=s.title||a.substring(0,30);try{t.onVisualFeedback&&t.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${n}`);let e=await u(a,t,m,r,null);return t.onVisualFeedback&&t.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${n} [COMPLETED]
|
|
2
|
+
`),e}catch(e){let{isTerminationSignaled:i}=await import("./ai-WBRHU7IH.js"),c=e.message==="Subagent task was cancelled by user."||i();if(t.onVisualFeedback){let d=c?"[CANCELLED]":"[FAILED]";t.onVisualFeedback(`\x1B[95mSubAgent\x1B[0m: \x1B[32mGeneralist\x1B[0m \u2192 ${n} ${d}
|
|
3
3
|
`)}return`ERROR: Subagent execution failed: ${e.message}`}};export{k as invokeSync};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e}from"./chunk-
|
|
1
|
+
import{b as e}from"./chunk-ZNO55RNG.js";import"./chunk-GBH7XI5A.js";import{a as i}from"./chunk-Y5JU726N.js";var k=async(s,c={})=>{let t=i(s),a=t.key||t.keys||t.input||t.shortcut;if(!a)return'ERROR: Missing required "key" parameter for KeyPress tool.';let r=String(a).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-
|
|
1
|
+
import{b as n}from"./chunk-ZNO55RNG.js";import"./chunk-GBH7XI5A.js";import{a as r}from"./chunk-Y5JU726N.js";var p=async(o,u={})=>{let t=r(o),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,2 +1,2 @@
|
|
|
1
|
-
import{a as O,b as j,c as f}from"./chunk-PTFCY2D5.js";import{a as N}from"./chunk-HFTI3R3Q.js";import"./chunk-
|
|
1
|
+
import{a as O,b as j,c as f}from"./chunk-PTFCY2D5.js";import{a as N}from"./chunk-HFTI3R3Q.js";import"./chunk-LQM3JK7N.js";import"./chunk-26BQ45XP.js";var X=async function*(M,T,B,b,m,K,E,J,P=1,W=null){let w=[];b&&w.push({role:"system",content:b});for(let t of B){let g=t.role==="user"?"user":"assistant",e=[];if(Array.isArray(t.parts)){for(let i of t.parts)if(i.text)e.push({type:"text",text:i.text});else if(i.inlineData&&E){let p=i.inlineData.mimeType,d=i.inlineData.data;p.startsWith("image/")&&e.push({type:"image_url",image_url:`data:${p};base64,${d}`})}}else{let i=t.text||"";i&&e.push({type:"text",text:i})}e.length>0&&w.push({role:g,content:e.length===1&&e[0].type==="text"?e[0].text:e})}let S={Fast:"none",Low:"none",Medium:"high",Standard:"high",High:"high",xHigh:"high"},F=`${M.slice(-5)}${W||""}${m}${T}`,H=await j(F),C={model:T,messages:w,stream:!0,temperature:P,prompt_cache_key:H,tools:[],tool_choice:"none"},h=N("Mistral",T,m);h!==null&&h!=="none"?h&&h!=="none"&&h!=="disabled"&&h!==!1&&(C.reasoning_effort=h):m&&S[m]!=="none"&&(C.reasoning_effort=S[m]||"high");let y=await O("https://api.mistral.ai/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${M}`,"Content-Type":"application/json"},body:JSON.stringify(C),signal:J});if(!y.ok){let t=await y.text().catch(()=>""),g=y.statusText;try{let e=JSON.parse(t);g=e.error?.message||e.message||JSON.stringify(e.detail||e)}catch{t&&(g=t)}throw new Error(`Mistral Error (${y.status}): ${JSON.stringify(g)}`)}let R=y.body.getReader(),q=new TextDecoder,D="",n=[],x=null,k=Date.now(),r=!1,o=t=>t?typeof t=="string"?f(t):Array.isArray(t)?t.map(o).filter(Boolean).join(""):typeof t=="object"&&t!==null?typeof t.text=="string"?f(t.text):typeof t.content=="string"?f(t.content):typeof t.thinking=="string"?f(t.thinking):typeof t.reasoning_content=="string"?f(t.reasoning_content):typeof t.reasoning=="string"?f(t.reasoning):typeof t.value=="string"?f(t.value):t.text?o(t.text):t.content?o(t.content):t.thinking?o(t.thinking):t.reasoning_content?o(t.reasoning_content):t.reasoning?o(t.reasoning):t.value?o(t.value):"":f(String(t)):"";for(;;){let{done:t,value:g}=await R.read();if(t){r&&(n.length>0||x)&&(yield{candidates:n.length>0?[{content:{parts:n}}]:[],usageMetadata:x});break}D+=q.decode(g,{stream:!0});let e=D.split(`
|
|
2
2
|
`);D=e.pop();for(let i of e){let p=i.trim();if(!p||!p.startsWith("data: "))continue;let d=!1;if(p==="data: [DONE]")d=!0;else try{let _=JSON.parse(p.substring(6)),c=_.choices?.[0]?.delta,u=_.usage;if(_.choices?.[0]?.finish_reason&&(d=!0),u&&(x={totalTokenCount:u.total_tokens||(u.prompt_tokens||0)+(u.completion_tokens||0),promptTokenCount:u.prompt_tokens||0,candidatesTokenCount:u.completion_tokens||0,cachedContentTokenCount:u.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:u.completion_tokens_details?.reasoning_tokens||0},r=!0),c){let z=c.thinking||c.reasoning_content||c.reasoning,$=o(z);$&&(n.push({text:$,thought:!0}),r=!0);let a=c.content||(!c.thinking&&!c.reasoning_content&&!c.reasoning?c.text:null);if(a)if(Array.isArray(a))for(let s of a)if(typeof s=="object"&&s!==null){let l=s.type==="thinking"||s.type==="reasoning"||!!s.thought,A=o(s);A&&(n.push({text:A,...l?{thought:!0}:{}}),r=!0)}else{let l=o(s);l&&(n.push({text:l}),r=!0)}else if(typeof a=="object"&&a!==null){let s=a.type==="thinking"||a.type==="reasoning"||!!a.thought,l=o(a);l&&(n.push({text:l,...s?{thought:!0}:{}}),r=!0)}else{let s=o(a);s&&(n.push({text:s}),r=!0)}}}catch{}if((d||Date.now()-k>=150)&&r&&(yield{candidates:n.length>0?[{content:{parts:[...n]}}]:[],usageMetadata:x},n=[],k=Date.now(),r=!1),d)break}Date.now()-k>=150&&r&&(yield{candidates:n.length>0?[{content:{parts:[...n]}}]:[],usageMetadata:x},n=[],k=Date.now(),r=!1)}};export{X as getMistralStream};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q}from"./chunk-LQM3JK7N.js";import"./chunk-26BQ45XP.js";export{a as DEFAULT_MODEL_CONFIG,o as getDefaultModel,q as getFallbackValue,b as getModelConfig,p as getModelPricing,n as getModels,m as hasModelReasoning,l as isModelMultimodal,h as removeModelFromProvider,i as renameModelInProvider,c as saveModelConfigToDisk,d as saveModelToProvider,j as setCustomMultimodal,g as setDefaultModelForProvider,f as setModelMultimodalInProvider,k as setOllamaMultimodal,e as updateModelInfoInProvider};
|