mistwatch 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +119 -2
- package/dist/cli.js +192 -0
- package/dist/web/apple-touch-icon.png +0 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/favicon.svg +1 -0
- package/dist/web/icon-192.png +0 -0
- package/dist/web/icon-512.png +0 -0
- package/dist/web/index.html +1460 -0
- package/dist/web/logo-dark.svg +1 -0
- package/dist/web/logo.svg +1 -0
- package/dist/web/mark.svg +1 -0
- package/dist/web/site.webmanifest +1 -0
- package/package.json +66 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var Hl=Object.defineProperty;var E=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ae=(e,t)=>{for(var n in t)Hl(e,n,{get:t[n],enumerable:!0})};function Fl(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function ql(e,t,n){let r=e.split(/\r?\n/),s="",o=(Math.log10(t+1)|0)+1;for(let i=t-1;i<=t+1;i++){let a=r[i-1];a&&(s+=i.toString().padEnd(o," "),s+=": ",s+=a,s+=`
|
|
3
|
+
`,i===t&&(s+=" ".repeat(o+n+2),s+=`^
|
|
4
|
+
`))}return s}var A,Xe=E(()=>{A=class e extends Error{line;column;codeblock;constructor(t,n){let[r,s]=Fl(n.toml,n.ptr),o=ql(n.toml,r,s);super(`Invalid TOML document: ${t}
|
|
5
|
+
|
|
6
|
+
${o}`,n),this.line=r,this.column=s,this.codeblock=o}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}}});function xn(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,s=n===39,o=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);o&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let i="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),o&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)A.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!o||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(o&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!u){let l=e.s.slice(a,e.p);i=i?i+l:l}return e.p+=o?3:1,i}else if(!u)!s&&n===92&&(i+=e.s.slice(a,a=e.p),u=1);else if(u===1)if(n===120||n===117||n===85){let l=e.p++-1,f=0,d=n===120?2:n===117?4:8;for(let p=0;p<d;p++,e.p++){let c=e.s.charCodeAt(e.p),m=c>=48&&c<=57?c-48:c>=65&&c<=70?c-65+10:c>=97&&c<=102?c-97+10:-1;m<0&&A.x("invalid non-hex character in unicode escape",e),f=f<<4|m}(f<0||f>1114111||f>=55296&&f<=57343)&&A.x("invalid unicode escape",e,l),i+=String.fromCodePoint(f),a=e.p--,u=0}else o&&(n===32||n===9)?u=2:(n===98?i+="\b":n===116?i+=" ":n===110?i+=`
|
|
7
|
+
`:n===102?i+="\f":n===114?i+="\r":n===101?i+="\x1B":n===34?i+='"':n===92?i+="\\":A.x("unrecognised escape sequence",e),a=e.p+1,u=0);else n!==32&&n!==9&&(u===2&&A.x("invalid escape: only line-ending whitespace may be escaped",e,a),u=!s&&n===92?1:0,a=e.p);A.x("unfinished string",e,t)}var Dr=E(()=>{Xe();});var Wl,Ht,Mr=E(()=>{Wl=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,Ht=class e extends Date{#e=!1;#t=!1;#n=null;constructor(t,n,r){let s=!0,o=!0,i="Z",a;if(typeof t=="string")if(n)e:{if(n<3){if(+t.slice(11,13)>23){t="";break e}n===2?(i=null,t+="Z"):(a=t.charCodeAt(t.length-1))!==90&&a!==122&&(i=t.slice(t.length-6)),r&&(t=t.slice(0,10)+"T"+t.slice(11))}else n===4&&(t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`);s=n!==4,o=n!==3}else{let u=t.match(Wl);u?(u[1]||(s=!1,t=`0000-01-01T${t}`),o=!!u[2],o&&t[10]===" "&&(t=t.replace(" ","T")),u[2]&&+u[2]>23?t="":(i=u[3]||null,!i&&o&&(t+="Z"))):t=""}super(t),isNaN(this.getTime())||(this.#e=s,this.#t=o,this.#n=i)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#n===null)return t.slice(0,-1);if(this.#n==="Z"||this.#n==="z")return t;let n=+this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return n=this.#n[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}}});function Z(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Ur(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function qt(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||A.x("document contains excessively nested structures. aborting.",e);let s=r===91?Do(e):No(e);return e.d++,s}return r===34||r===39?xn(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&A.x("invalid value",e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&A.x("invalid value",e,n),e.p++,!1):r===43||r===45?Rn(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?Kl(e,r,t):e.s.charCodeAt(e.p+2)===58?zl(e,r,t):Rn(e,e.p,r,0,t)}function Rn(e,t,n,r,s){let o=n,i=0,a=!1;if(o===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&A.x("invalid value",e,t),e.p++,(r||1)/0;if(o===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&A.x("invalid value",e,t),e.p++,NaN;if(o===48){if(++e.p>=e.s.length||Ur(o=e.s.charCodeAt(e.p),s))return e.bi===!0?0n:0;if(!r){if(o===120)return jr(e,t,16,s);if(o===98)return jr(e,t,2,s);if(o===111)return jr(e,t,8,s)}o===46?i=2:o===101||o===69?i=4:A.x("illegal leading zero",e,t)}else Z(o)||A.x("invalid value",e,t);for(;++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!Ur(o,s));)i||(i=1),o===95?(i&1||A.x("illegal underscore",e),i+=11,a=!0):i===1&&o===46?i=2:(i===1||i===3)&&(o===101||o===69)?i=4:i===4&&(o===43||o===45)?i=6:Z(o)?i>9?i-=11:i&1||i++:A.x("illegal character in numeric literal",e);if(!i){let l=(n-48)*(r||1);return e.bi===!0?BigInt(l):l}i&1||A.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);return a&&(u=u.replaceAll("_","")),i>1?parseFloat(u):Lo(e,u,10,t)}function jr(e,t,n,r){let s,o=1;for(;++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!Ur(s,r));)s===95?(o&1&&A.x("illegal underscore",e),o=3):Z(s,n)?o&1&&o--:A.x("illegal character in numeric literal",e);o&1&&A.x("unfinished numeric value",e);let i=e.s.slice(t+2,e.p);return o&&(i=i.replaceAll("_","")),Lo(e,i,n,t)}function Lo(e,t,n,r){if(e.bi!==!0)e:{let s=parseInt(t,n);if(!Number.isSafeInteger(s)){if(e.bi)break e;A.x("integer value cannot be represented losslessly",e,r)}return s}return BigInt(n===10?t:(n===2?"0b":n===8?"0o":"0x")+t)}function Kl(e,t,n){let r=e.p++,s;if(!Z(t)||!Z(e.s.charCodeAt(e.p++))||!Z(e.s.charCodeAt(e.p++))||!Z(e.s.charCodeAt(e.p++)))return Rn(e,e.p=r,t,0,n);if(e.p+=5,Z(e.s.charCodeAt(e.p++))||A.x("invalid date-time: date part is malformed",e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(s=!0,!Z(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let i=e.s.slice(r,e.p);return Ft(e,i,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58&&A.x("invalid date-time: time part is malformed",e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Z(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let i=e.s.slice(r,++e.p);return Ft(e,i,1,s,r,"[+00:00]")}if(t===43||t===45){let i=e.s.slice(r,e.p+=6);return Ft(e,i,1,s,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let o=e.s.slice(r,e.p);return Ft(e,o,2,s,r)}function zl(e,t,n){let r=e.p;if(!Z(t)||!Z(e.s.charCodeAt(++e.p)))return Rn(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;Z(e.s.charCodeAt(++e.p)););let s=e.s.slice(r,e.p);return Ft(e,s,4,!1,r)}function Ft(e,t,n,r,s,o){if(e.ld){let i=new Ht(t,n,r);return i.isValid()||A.x("invalid date",e,s),i}try{switch(o&&(t+=o),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(i){A.x(i instanceof Error?i.message:""+i,e,s)}}var Br=E(()=>{Dr();Hr();Xe();Mr();});function Gl(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&A.x("control characters are not allowed in comments",e)}}function ce(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;Gl(e)}}var Fr=E(()=>{Xe();});function Tn(e,t=61){let n,r=0,s=[],o,i=e.s.charCodeAt(n=e.p);do{if(i===t)return r||A.x("unexpected end of key",e),r===1&&s.push(e.s.slice(o,e.p)),e.p++,s;i===46?(r||A.x("illegal empty bare key",e),r===1&&s.push(e.s.slice(o,e.p)),r=0):!r&&(i===34||i===39)?(i===e.s.charCodeAt(e.p+1)&&i===e.s.charCodeAt(e.p+2)&&A.x("illegal quoted key: multiline strings are not allowed",e),s.push(xn(e)),r=2,e.p--):i===32||i===9?r===1&&(s.push(e.s.slice(o,e.p)),r=2):r===2||i<48&&i!==45||i>57&&i<65||i>90&&i<97&&i!==95||i>122?A.x("illegal character in key",e):r||(r=1,o=e.p)}while(i=e.s.charCodeAt(++e.p));A.x("incomplete key-value: cannot find end of key",e,n)}function No(e){let t=e.p++,n=Object.create(null),r=new Set,s;for(;e.p<e.s.length;){if(ce(e),(s=e.s.charCodeAt(e.p))===125)return e.p++,n;let o,i=n,a=!1,u=e.p,l=Tn(e);for(let d=0;d<l.length;d++){d&&(i=a?i[o]:i[o]=Object.create(null)),o=l[d],(a=Object.hasOwn(i,o))&&(typeof i[o]!="object"||r.has(i[o]))&&A.x("trying to redefine an already defined value",e,u);let p=o==="__proto__";if(e.uk&&(p||o==="constructor")){i=e.uk!==1&&A.x("document contains an unsafe property",e,u);break}!a&&p&&Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0})}a&&A.x("trying to redefine an already defined value",e,u),ce(e,!0,!0);let f=qt(e,125);if(i&&typeof(i[o]=f)=="object"&&r.add(f),ce(e),(s=e.s.charCodeAt(e.p++))===125)return n;s!==44&&A.x("expected comma or end of structure",e,e.p-1)}A.x("unfinished table",e,t)}function Do(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(ce(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(qt(e,93)),ce(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&A.x("expected comma or end of structure",e,e.p-1)}A.x("unfinished array",e,t)}var Hr=E(()=>{Dr();Br();Fr();Xe();});function Mo(e,t,n,r,s){let o=n,i=r,a,u=!1,l;for(let f=0;f<t.length;f++){if(f){if(o=u?o[a]:o[a]=Object.create(null),i=(l=i[a]).c,s===0&&(l.t===1||l.t===2))return null;if(l.t===2){let d=o.length-1;o=o[d],i=i[d].c}}if(a=t[f],(u=Object.hasOwn(o,a))&&i[a]?.t===0&&i[a]?.d)return null;if(!u){let d=a==="__proto__";if(e.uk&&(d||a==="constructor"))return!1;d&&(Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0})),i[a]={t:f<t.length-1&&s===2?3:s,d:!1,i:0,c:Object.create(null)}}}if(l=i[a],l.t!==s&&!(s===1&&l.t===3)||(s===2&&(l.d||(l.d=!0,o[a]=[]),o[a].push(o=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,s===1)o=u?o[a]:o[a]=Object.create(null);else if(s===0&&u)return null;return[a,o,l.c]}function jo(e,t,n){(t===null||e.uk===2)&&A.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function Me(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),s=Object.create(null),o,i=!1,a=r,u=s;for(e.charCodeAt(0)===65279&&n.p++,ce(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let l=e.charCodeAt(++n.p)===91;o=n.p+=+l,i=!1;let f=Tn(n,93);l&&(e.charCodeAt(n.p)!==93&&A.x("expected end of table array declaration",n),n.p++);let d=Mo(n,f,r,s,l?2:1);d?(u=d[2],a=d[1]):(jo(n,d,o),i=!0)}else{o=n.p;let l=Tn(n),f=Mo(n,l,a,u,0);!f&&!i&&jo(n,f,o),ce(n,!0,!0);let d=qt(n,void 0);f&&!i&&(f[1][f[0]]=d)}ce(n,!0),n.p<e.length&&(o=e.charCodeAt(n.p))!==10&&(o!==13||e.charCodeAt(n.p+1)!==10)&&A.x("each key-value declaration must be followed by an end-of-line",n),ce(n)}return r}var Uo=E(()=>{Hr();Br();Fr();Xe();});var oh,Bo=E(()=>{oh=!!"".isWellFormed});var qr=E(()=>{Uo();Bo();Mr();Xe();});import{createRequire as Vl}from"node:module";var Wt,pt,Xl,Wr,Jl,Yl,Zl,Kr,zr,dt,Gr=E(()=>{"use strict";pt=()=>{if(Wt===void 0)try{Wt=Vl(import.meta.url)("@napi-rs/keyring")}catch{Wt=null}if(!Wt)throw new Error("the OS keyring is not available on this system");return Wt},Xl={read:(e,t)=>pt().findCredentials(e,t)[0]??null,write:(e,t,n,r)=>pt().Entry.withTarget(t,e,n).setPassword(r),remove:(e,t)=>{pt().Entry.withTarget(t,e,"").deletePassword()}},Wr=(e,t)=>`${e}@${t}`,Jl=e=>({get:(t,n)=>{let r=e.read(t,t);return r&&(!n||r.account===n)?r.password:e.read(t,Wr(n,t))?.password??null},set:(t,n,r)=>{let s=e.read(t,t);s&&e.write(t,Wr(s.account,t),s.account,s.password),e.write(t,t,n,r)},drop:(t,n)=>{for(let r of[t,Wr(n,t)]){let s=e.read(t,r);s&&s.account===n&&e.remove(t,r)}}}),Yl=e=>({get:(t,n)=>{let r=e.read(t,n);return r&&r.account===n?r.password:null},set:(t,n,r)=>e.write(t,n,r),drop:(t,n)=>{let r=e.read(t,n);r&&r.account===n&&e.remove(t,n)}}),Zl={read:(e,t)=>{let n=new(pt()).Entry(e,t).getPassword();return n===null?null:{account:t,password:n}},write:(e,t,n)=>new(pt()).Entry(e,t).setPassword(n),remove:(e,t)=>{new(pt()).Entry(e,t).deletePassword()}},Kr=process.platform==="win32"?Jl(Xl):Yl(Zl),zr=()=>!!process.env.MISTWATCH_NO_KEYRING,dt={get:(e,t)=>zr()?null:Kr.get(e,t),set:(e,t,n)=>{if(zr())throw new Error("the OS keyring is disabled (MISTWATCH_NO_KEYRING)");Kr.set(e,t,n)},drop:(e,t)=>{zr()||Kr.drop(e,t)}}});var mt={};Ae(mt,{CONFIG_TEMPLATE:()=>Qr,DEFAULT_USD_TO_EUR:()=>Yr,anyKey:()=>lc,clientBaseUrl:()=>je,configPath:()=>zt,defaultConfig:()=>Wo,defaultLimits:()=>qo,homeDir:()=>Zr,keyFor:()=>ve,loadConfig:()=>es,resolveSecret:()=>Gt});import{existsSync as Ql,readFileSync as ec}from"node:fs";import{isIPv6 as Fo}from"node:net";import{homedir as tc}from"node:os";import{join as Jr}from"node:path";var Yr,je,Zr,zt,Qr,qo,nc,Wo,Ko,Je,Vr,Xr,rc,sc,Se,fe,oc,B,Kt,xe,Ho,ic,ac,uc,es,Gt,ve,lc,W=E(()=>{"use strict";qr();Gr();Yr=.9117,je=(e,t="")=>{let n=e.host==="0.0.0.0"||e.host==="::"||e.host===""?"127.0.0.1":e.host;return`http://${Fo(n)?`[${n}]`:n}:${e.port}${t}`},Zr=()=>process.env.MISTWATCH_HOME||Jr(tc(),".mistwatch"),zt=()=>process.env.MISTWATCH_CONFIG||Jr(Zr(),"config.toml"),Qr=`# mistwatch config (server, limits, pricing). Accounts, keys and logins are managed in the web UI.
|
|
8
|
+
[server]
|
|
9
|
+
host = "127.0.0.1"
|
|
10
|
+
port = 8787
|
|
11
|
+
# Extra host names allowed to reach the UI and API, for example a tunnel: allowed_hosts = ["mw.example.com"]
|
|
12
|
+
|
|
13
|
+
[upstream]
|
|
14
|
+
base_url = "https://api.mistral.ai"
|
|
15
|
+
|
|
16
|
+
[pricing]
|
|
17
|
+
usd_to_eur = ${Yr} # docs prices are USD, budgets are EUR
|
|
18
|
+
|
|
19
|
+
[limits]
|
|
20
|
+
reserve_pct = 3.0 # untouchable slice of every pool's monthly budget
|
|
21
|
+
burst_5h = 2.0 # x fair pace allowed within any 5h window
|
|
22
|
+
burst_day = 1.5
|
|
23
|
+
burst_week = 1.25
|
|
24
|
+
sync_interval_s = 300
|
|
25
|
+
strategy = "most_headroom" # or "priority"
|
|
26
|
+
fallback_to_other_pool = true
|
|
27
|
+
vibe_user_agent_regex = "Mistral-Vibe"
|
|
28
|
+
|
|
29
|
+
[router]
|
|
30
|
+
llm_classifier = true # ask a tiny model to rate prompt difficulty for \`auto\`
|
|
31
|
+
classifier_model = "ministral-3b-latest"
|
|
32
|
+
`,qo=()=>({reserve_pct:3,burst_5h:2,burst_day:1.5,burst_week:1.25,sync_interval_s:300,strategy:"most_headroom",fallback_to_other_pool:!0,vibe_user_agent_regex:"Mistral-Vibe"}),nc=()=>({llm_classifier:!0,classifier_model:"ministral-3b-latest",classifier_timeout_s:2}),Wo=()=>({host:"127.0.0.1",port:8787,allowed_hosts:[],upstream:"https://api.mistral.ai",usd_to_eur:Yr,db_path:Jr(Zr(),"mistwatch.db"),limits:qo(),router:nc(),accounts:[],clients:[],price_overrides:{}}),Ko=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Je=e=>Array.isArray(e)?"array":e===null?"null":typeof e,Vr=e=>typeof e=="boolean"?e:typeof e=="number"||typeof e=="bigint"?e!==0:typeof e=="string"||Array.isArray(e)?e.length>0:Ko(e)?Object.keys(e).length>0:!1,Xr=e=>{if(typeof e=="boolean")return e?1:0;if(typeof e=="number")return Math.trunc(e);if(typeof e=="bigint")return Number(e);if(typeof e=="string"&&/^[+-]?\d+$/.test(e.trim()))return Number.parseInt(e.trim(),10);throw new TypeError(`int() argument must be a string or a number, not ${Je(e)}`)},rc=e=>{if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError(`cannot convert ${e} to int`);return Xr(e)},sc=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$|^[+-]?infinity$/i,Se=e=>{if(typeof e=="boolean")return e?1:0;if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);if(typeof e=="string"){let t=e.trim(),n=Number(t);if(sc.test(t)&&!Number.isNaN(n))return n}throw new TypeError(`float() argument must be a string or a number, not ${Je(e)}`)},fe=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint")return String(e);if(typeof e=="boolean")return e?"True":"False";throw new TypeError(`str() argument must be a primitive, not ${Je(e)}`)},oc=e=>{if(!Array.isArray(e))throw new TypeError(`allowed_hosts must be a list of host names, not ${Je(e)}`);return e.map(t=>fe(t).trim().toLowerCase().replace(/\.$/,"")).filter(t=>t!=="").map(t=>{let n=t.replace(/^\[|\]$/g,"");if(Fo(n))return n;if(/[:/[\]\s]/.test(t))throw new TypeError(`allowed_hosts entries are bare host names without port, scheme or path, not ${JSON.stringify(t)}`);return t})},B=(e,t,n,r)=>t in e?r(e[t]):n,Kt=(e,t)=>{if(!Ko(e))throw new TypeError(`${t} must be a table, not ${Je(e)}`);return e},xe=(e,t)=>e===void 0?{}:Kt(e,t),Ho=(e,t)=>{if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError(`${t} must be an array, not ${Je(e)}`);return e},ic=e=>Object.fromEntries(Object.entries(xe(e,"account.keys")).map(([t,n])=>[t,fe(n)])),ac=e=>Object.fromEntries(Object.entries(xe(e,"account.manual")).map(([t,n])=>[t,Object.fromEntries(Object.entries(Kt(n,"account.manual entry")).map(([r,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return[r,s];if(typeof s=="bigint")return[r,Number(s)];throw new TypeError(`account.manual.${t}.${r} must be a primitive, not ${Je(s)}`)}))])),uc=e=>Object.fromEntries(Object.entries(xe(e,"pricing.models")).map(([t,n])=>{let r=Kt(n,`price override for ${t}`);return[t,{input:Se(r.input),output:Se(r.output),cached:r.cached===void 0?void 0:Se(r.cached)}]})),es=e=>{let t=e??zt();if(!Ql(t))throw new Error(`${t} not found - run \`mistwatch init\` first`);let n;try{n=Me(ec(t,"utf8"))}catch(l){let f=l instanceof A?` at line ${l.line}, column ${l.column}`:"";throw new Error(`${t}: invalid TOML${f}`)}let r=Wo(),s=xe(n.server,"server");r.host=process.env.MISTWATCH_HOST||B(s,"host",r.host,fe),r.port=B(s,"port",r.port,Xr),r.allowed_hosts=B(s,"allowed_hosts",r.allowed_hosts,oc),r.upstream=B(xe(n.upstream,"upstream"),"base_url",r.upstream,fe).replace(/\/+$/,"");let o=xe(n.pricing,"pricing");r.usd_to_eur=B(o,"usd_to_eur",r.usd_to_eur,Se),r.price_overrides=uc(o.models);let i=xe(n.storage,"storage");"db_path"in i&&(r.db_path=fe(i.db_path));let a=xe(n.limits,"limits");r.limits={reserve_pct:B(a,"reserve_pct",r.limits.reserve_pct,Se),burst_5h:B(a,"burst_5h",r.limits.burst_5h,Se),burst_day:B(a,"burst_day",r.limits.burst_day,Se),burst_week:B(a,"burst_week",r.limits.burst_week,Se),sync_interval_s:B(a,"sync_interval_s",r.limits.sync_interval_s,rc),strategy:B(a,"strategy",r.limits.strategy,fe),fallback_to_other_pool:B(a,"fallback_to_other_pool",r.limits.fallback_to_other_pool,Vr),vibe_user_agent_regex:B(a,"vibe_user_agent_regex",r.limits.vibe_user_agent_regex,fe)};let u=xe(n.router,"router");r.router={llm_classifier:B(u,"llm_classifier",r.router.llm_classifier,Vr),classifier_model:B(u,"classifier_model",r.router.classifier_model,fe),classifier_timeout_s:B(u,"classifier_timeout_s",r.router.classifier_timeout_s,Se)};for(let l of Ho(n.accounts,"accounts")){let f=Kt(l,"account entry");r.accounts.push({name:fe(f.name),keys:ic(f.keys),priority:f.priority===void 0?100:Xr(f.priority),enabled:f.enabled===void 0?!0:Vr(f.enabled),manual:ac(f.manual)})}for(let l of Ho(n.clients,"clients")){let f=Kt(l,"client entry");r.clients.push({name:fe(f.name),token:fe(f.token)})}return r},Gt=(e,t=dt)=>{if(e.startsWith("env:")){let n=process.env[e.slice(4)];if(!n)throw new Error(`environment variable ${e.slice(4)} is not set`);return n}if(e.startsWith("keyring:")){let n=e.slice(8),r=n.indexOf("/"),s=r<0?n:n.slice(0,r),o=r<0?"":n.slice(r+1),i=t.get(s,o);if(!i)throw new Error(`no keyring entry ${s}/${o}`);return i}return e},ve=(e,t)=>{let n=e.keys[t];return n?Gt(n):null},lc=e=>{for(let t of Object.values(e.keys))return Gt(t);throw new Error(`account ${e.name} has no keys configured`)}});var Zo={};Ae(Zo,{AUTO_MODELS:()=>Cn,LADDER:()=>ke,LLM_WEIGHT:()=>ts,SCORE_TO_LEVEL:()=>Go,TOP:()=>Vt,VALID_EFFORT:()=>Vo,apply:()=>ss,cpLen:()=>Q,decide:()=>rs,decisionHeader:()=>$n,messageText:()=>ht,scoreRequest:()=>In,trimUnicode:()=>Yo,truthy:()=>Ee,worthAsking:()=>ns});var ke,Vt,ts,Go,Vo,Cn,C,cc,fc,pc,dc,mc,Pn,Ee,ht,Xo,Jo,hc,Q,yc,Yo,gc,zo,In,ns,On,rs,ss,$n,Ye=E(()=>{"use strict";ke=[{model:"mistral-small-2603",effort:"none",vision:!0,ctx:262144,label:"small/none"},{model:"zai-glm-5-3-flash",effort:"low",vision:!0,ctx:1048576,label:"glm-flash/low"},{model:"mistral-large-4-0",effort:"medium",vision:!0,ctx:1048576,label:"large-4/medium"},{model:"mistral-large-4-0",effort:"high",vision:!0,ctx:1048576,label:"large-4/high"},{model:"deepseek-v4-1-flash-1017",effort:"high",vision:!0,ctx:1048576,label:"deepseek/high"},{model:"zai-glm-5-3",effort:"high",vision:!1,ctx:1048576,label:"glm-5.3/high"},{model:"zai-glm-5-3",effort:"max",vision:!1,ctx:1048576,label:"glm-5.3/max"}],Vt=ke.length-1,ts=.8,Go=[[1,0],[3,1],[4,2],[5,3],[6,4],[8,5],[10,6]],Vo={"mistral-small-2603":new Set(["none","high"]),"mistral-large-4-0":new Set(["low","medium","high"]),"deepseek-v4-1-flash-1017":new Set(["none","low","high","max","xhigh"]),"zai-glm-5-3":new Set(["low","high","max"]),"zai-glm-5-3-flash":new Set(["low","high","max"])},Cn=new Map([["auto",[0,Vt]],["auto-fast",[0,2]],["auto-max",[4,Vt]]]),C="\\p{L}\\p{N}_",cc=new RegExp(`(?<![${C}])(debug[${C}]*|bug|refactor[${C}]*|architect[${C}]*|design|optimi[sz][${C}]*|prove|proof|algorithm[${C}]*|race condition|deadlock|security|vulnerab[${C}]*|migrat[${C}]*|implement[${C}]*|rewrite|analy[sz][${C}]*|investigat[${C}]*|root cause|concurren[${C}]*|performance|benchmark[${C}]*|navrhni|architektur[${C}]*|refaktor[${C}]*|oprav[${C}]*|optimaliz[${C}]*|analyz[${C}]*|implementuj|zjisti|p\u0159epi\u0161|migrac[${C}]*|bezpe\u010Dnost[${C}]*|chyb[${C}]*)(?![${C}])`,"giu"),fc=new RegExp(`step[- ]by[- ]step|think (hard|carefully)|carefully|rigorous|krok za krokem|d\u016Fkladn[${C}]+|po\u0159\xE1dn\u011B`,"iu"),pc=new RegExp(`^\\s*(hi|hello|hey|thanks?|ok|ahoj|\u010Dau|d\xEDky|d\xEDk)(?![${C}])|(?<![${C}])(translate|p\u0159elo\u017E[${C}]*|summari[sz]e|shr\u0148[${C}]*|typo|rename|format|co je|what is|what's|kolik je)(?![${C}])`,"iu"),dc=/Traceback \(most recent|^\s+at .+\(.+:\d+\)|\bException\b|\bpanic:|error\[E\d+\]|Segmentation fault/m,mc=new RegExp("(?:^\\s*|\\s)(\\p{Nd}{1,2}[.)]|[-*\u2022])\\s+\\S","gmu"),Pn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ee=e=>Array.isArray(e)?e.length>0:Pn(e)?Object.keys(e).length>0:!!e,ht=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>Pn(t)&&t.type==="text").map(t=>typeof t.text=="string"?t.text:"").join(" "):"",Xo=e=>(Array.isArray(e.messages)?e.messages:[]).filter(Pn),Jo=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.role==="user")return ht(n.content)}return""},hc=e=>e.some(t=>Array.isArray(t.content)&&t.content.some(n=>Pn(n)&&(n.type==="image_url"||n.type==="image"))),Q=e=>{let t=0;for(let n of e)t++;return t},yc=/^[\t-\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\t-\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,Yo=e=>e.replace(yc,""),gc=(e,t)=>{let n=Array.from(e,o=>o.codePointAt(0)??0),r=Array.from(t,o=>o.codePointAt(0)??0),s=Math.min(n.length,r.length);for(let o=0;o<s;o++){let i=(n[o]??0)-(r[o]??0);if(i!==0)return i}return n.length-r.length},zo=e=>`[${e.map(t=>`'${t}'`).join(", ")}]`,In=e=>{let t=Xo(e),n=Jo(t),r=0;for(let d of t)r+=Q(ht(d.content));let s=Math.floor(r/4),o=0,i=[],a=(d,p)=>{o+=d,i.push(`${d>=0?"+":""}${d} ${p}`)},u=Q(n);u>400&&a(1,"long prompt"),u>1500&&a(1,"very long prompt"),u>6e3&&a(1,"huge prompt"),(n.includes("```")||t.slice(-3).map(d=>ht(d.content)).join(" ").includes("```"))&&a(1,"code"),dc.test(n)&&a(1,"stack trace");let l=new Set;for(let d of n.matchAll(cc)){let p=d[0];p!==void 0&&l.add(p.toLowerCase())}let f=[...l].sort(gc);return l.size>=4?a(3,`many hard keywords ${zo(f.slice(0,4))}`):l.size>=3?a(2,`hard keywords ${zo(f.slice(0,4))}`):l.size>=1&&a(1,`hard keyword ${f[0]??""}`),fc.test(n)&&a(1,"asks for careful reasoning"),[...n.matchAll(mc)].length>=3&&a(1,"multi-part"),Ee(e.tools)&&a(2,"tools available"),t.some(d=>d.role==="tool")&&a(1,"agent loop"),t.length>10&&a(1,"long conversation"),s>3e4&&a(1,"large context"),s>1e5&&a(1,"huge context"),u<200&&pc.test(n)&&a(-1,"easy pattern"),u<40&&l.size===0&&a(-1,"tiny prompt"),[Math.max(0,Math.min(10,o)),i,s,hc(t)]},ns=(e,t)=>{let n=Jo(Xo(e));return Q(Yo(n))>=30&&t<8},On=e=>{let t=ke[(e%ke.length+ke.length)%ke.length];if(!t)throw new RangeError("ladder index out of range");return t},rs=(e,t="auto",n=1,r)=>{let[s,o]=Cn.get(t)??[0,Vt],[i,a,u,l]=In(e);if(r!=null){let v=Math.round((1-ts)*i+ts*r);a.push(`tiny-LLM says ${r}, heuristic ${i} -> ${v}`),i=v}let f=Go.find(([v])=>i<=v),d=f?f[1]:Vt;d=Math.max(s,Math.min(o,d)),Ee(e.tools)&&d<2&&i>=4&&(d=2,a.push("tools+hard -> large-4"));let p=n<.1?2:n<.25?1:0;p&&(d=Math.max(Math.min(s,1),d-p),a.push(`budget pressure ${Math.round(n*100)}% -> -${p}`));let c=On(d);if(l&&!c.vision){for(;!On(d).vision;)d--;c=On(d),a.push("image -> vision model")}u>2e5&&c.ctx<4e5&&(d=Math.max(d,1),c=On(d),a.push("long context -> 1M model"));let m=c.effort,y=e.reasoning_effort,b=Vo[c.model];return typeof y=="string"&&y&&b?.has(y)&&(m=y,a.push(`client effort ${y} kept`)),{model:c.model,effort:m,level:d,score:i,reason:a.join("; ")||"default",llm_score:r??null}},ss=(e,t)=>{let n={...e};return n.model=t.model,t.effort?n.reasoning_effort=t.effort:delete n.reasoning_effort,n},$n=e=>`${e.model};effort=${e.effort??"None"};level=${e.level};score=${e.score}${e.llm_score!==null?`;llm=${e.llm_score}`:""}`});var bc,wc,vc,kc,Ec,_c,Qo,Ac,Sc,is,xc,as,ei,Rc,os,ti,Tc,Ln,ni,Nn,ri,Oc,Dn,Mn=E(()=>{"use strict";W();Ye();bc=12*3600,wc=[[/^mistral-large-4(-0)?$|^mistral-large-latest$/,"Mistral Large 4"],[/^mistral-small-4$|^mistral-small-2603$|^mistral-small-latest$|^mistral-vibe-cli-fast$/,"Mistral Small 4"],[/^mistral-medium(-latest|-3-5|-3\.5)?$|^mistral-vibe-cli(-latest|-with-tools)?$/,"Mistral Medium 3.5"],[/^(zai-)?glm-5-3$|^zai-glm-(5|latest)$/,"GLM 5.3"],[/^(zai-)?glm-5-3-flash$/,"GLM 5.3 Flash"],[/^(zai-)?glm-5-2$/,"GLM 5.2"],[/^deepseek-v4-1-flash(-1017)?$/,"DeepSeek V4.1 Flash"],[/^ministral-3b(-latest|-2512)?$/,"Ministral 3 3B"],[/^ministral-8b(-latest|-2512)?$/,"Ministral 3 8B"],[/^ministral-14b(-latest|-2512)?$/,"Ministral 3 14B"],[/^codestral(-latest|-2508)?$|^mistral-code(-fim)?-latest$/,"Codestral"]],vc=new Map([["glm","GLM"],["ocr","OCR"],["tts","TTS"],["gpt","GPT"],["deepseek","DeepSeek"],["llm","LLM"]]),kc=new Set(["zai"]),Ec=/^v?\d{1,2}$/,_c=/^\d+(\.\d+)?[bkm]$/,Qo=/^\d{1,2}$/,Ac=/^\d{4}$/,Sc=/^v\d+(\.\d+)*$/,is=e=>{let t=e.toLowerCase();for(let[n,r]of wc)if(n.test(t))return r;return null},xc=e=>{let t=vc.get(e);return t||(_c.test(e)||Sc.test(e)?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},as=e=>{let t=os(e).toLowerCase().split(/[-_ ]+/).filter(o=>o);for(;t.length&&kc.has(t[0]??"");)t.shift();let n="";t.length&&t[t.length-1]==="latest"?(t.pop(),n=" (latest)"):t.length>1&&Ac.test(t[t.length-1]??"")&&(n=` (${t.pop()??""})`);let r=[],s=0;for(;s<t.length;){let o=t[s];if(o===void 0)break;let i=t[s+1];if(Ec.test(o)&&i!==void 0&&Qo.test(i)){let a=[o];for(s++;s<t.length;){let u=t[s];if(u===void 0||!Qo.test(u))break;a.push(u),s++}for(;a.length>1&&a[a.length-1]==="0";)a.pop();r.push(a.map(u=>u.startsWith("v")?u.toUpperCase():u).join("."));continue}r.push(xc(o)),s++}return r.join(" ")+n||e},ei=`
|
|
33
|
+
\v\f\r- \x85\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000`,Rc=new RegExp(`^[${ei}]+|[${ei}]+$`,"g"),os=e=>e.replace(Rc,""),ti=(e,t)=>{let n=Array.from(e,o=>o.codePointAt(0)??0),r=Array.from(t,o=>o.codePointAt(0)??0),s=Math.min(n.length,r.length);for(let o=0;o<s;o++){let i=(n[o]??0)-(r[o]??0);if(i!==0)return i}return n.length-r.length},Tc=e=>e.includes(" ")||[...e].some(t=>t!==t.toLowerCase()),Ln=e=>{if(typeof e!="string")throw new TypeError("db: expected string");return e},ni=e=>{if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);throw new TypeError("db: expected number")},Nn=e=>typeof e=="string"?e:null,ri=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Oc=e=>{try{let t=JSON.parse(typeof e=="string"&&e?e:"[]");return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},Dn=e=>{let t=new Map,n=new Map,r=()=>{let a=new Map;for(let l of e.stmt("SELECT model_id, display FROM model_names").all())a.set(Ln(l.model_id),Ln(l.display));t=a;let u=new Map;for(let l of e.stmt("SELECT model_id, name, aliases, description FROM model_catalog").all())u.set(Ln(l.model_id),{name:Nn(l.name),aliases:Oc(l.aliases),description:Nn(l.description)});n=u};r();let s=a=>n.get(a)?.name||a,o=a=>{let u=os(a??"");if(!u)return["(unknown)","auto"];let l=s(u);for(let f of[u,l]){let d=t.get(f);if(d!==void 0)return[d,"custom"]}for(let f of[u,l]){let d=is(f);if(d)return[d,"built-in"]}return l!==u&&Tc(l)?[l,"mistral"]:[as(l),"auto"]},i=async(a,u,l,f=Date.now()/1e3)=>{let d=await a(`${u}/v1/models`,{redirect:"manual",headers:{Authorization:`Bearer ${l}`,"User-Agent":"mistwatch/0.1"},signal:AbortSignal.timeout(2e4)});if(!d.ok)throw new Error(`upstream returned ${d.status}`);let p=await d.json(),c=[],m=ri(p)&&Array.isArray(p.data)?p.data:[];for(let y of m)!ri(y)||typeof y.id!="string"||!y.id||c.push([y.id,Nn(y.name),JSON.stringify(Array.isArray(y.aliases)?y.aliases:[]),Nn(y.description)]);return c.length?(e.tx(()=>{e.stmt("DELETE FROM model_catalog").run();let y=e.stmt("INSERT INTO model_catalog(model_id, name, aliases, description) VALUES(?,?,?,?)");for(let b of c)y.run(b[0],b[1],b[2],b[3])}),e.setMeta("catalog_ts",String(f)),r(),c.length):0};return{reload:r,groupKey:s,setOverride:(a,u)=>{let l=os(u);if(!l||Array.from(l).length>80||[...l].some(f=>f.charCodeAt(0)<32))throw new Error("Name must be 1-80 printable characters.");e.stmt("INSERT INTO model_names(model_id, display) VALUES(?,?) ON CONFLICT(model_id) DO UPDATE SET display=excluded.display").run(s(a),l),r()},clearOverride:a=>{e.stmt("DELETE FROM model_names WHERE model_id IN (?,?)").run(a,s(a)),r()},resolve:o,display:a=>o(a)[0],refresh:i,maybeRefresh:async(a,u,l,f=Date.now()/1e3)=>{let d=Number.parseFloat(e.getMeta("catalog_ts")??"0")||0;if(f-d<bc)return null;for(let p of l)for(let c of Object.keys(p.keys))try{return await i(a,u,ve(p,c)??"",f)}catch{}return null},listing:(a=!1)=>{let u=new Map;for(let p of e.stmt("SELECT model, COUNT(*) n, MAX(ts) m FROM ledger WHERE model IS NOT NULL GROUP BY model").all())u.set(Ln(p.model),[ni(p.n),ni(p.m)]);let l=new Set(u.keys());for(let p of ke)l.add(p.model);if(a)for(let p of n.keys())l.add(p);let f=new Map;for(let p of[...l].sort(ti)){let c=s(p),m=f.get(c);m||(m={ids:[],calls:0,last:0},f.set(c,m)),m.ids.push(p);let[y,b]=u.get(p)??[0,0];m.calls+=y,m.last=Math.max(m.last,b)}for(let p of t.keys())f.has(p)||f.set(p,{ids:[p],calls:0,last:0});let d=[];for(let[p,c]of f){let m=c.ids[0],[y,b]=o(m??null),v=m!==void 0?n.get(m):void 0;d.push({key:p,ids:c.ids,display:y,source:b,calls:c.calls,last:c.last||null,description:v?.description??null})}return d.sort((p,c)=>c.calls-p.calls||ti(p.display.toLowerCase(),c.display.toLowerCase()))}}}});import{isAbsolute as Cc,join as si}from"node:path";var pe,oi,Pc,yt,ii,Xt,Jt,us,ls,jn,Un,ai,ui,li,Yt=E(()=>{"use strict";Mn();Ye();pe="MISTWATCH_TOKEN",oi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pc=/[\u0080-\uffff]/g,yt=e=>JSON.stringify(e,null,2).replace(Pc,t=>`\\u${(t.codePointAt(0)??0).toString(16).padStart(4,"0")}`),ii=()=>{let e=[["auto","Auto (budget-aware router)",262144,!0],["auto-fast","Auto, cheaper models only",262144,!0],["auto-max","Auto, aims for quality",1048576,!0]],t=new Set;for(let n of ke)t.has(n.model)||(t.add(n.model),e.push([n.model,is(n.model)??as(n.model),n.ctx,n.vision]));return e},Xt=(e,t=pe)=>({providers:{mistwatch:{baseUrl:`${e}/v1`,api:"openai-completions",apiKey:t,models:ii().map(([n,r,s,o])=>({id:n,name:r,reasoning:n!=="mistral-small-2603",input:o?["text","image"]:["text"],contextWindow:s,maxTokens:32768}))}}}),Jt=(e,t=pe)=>({$schema:"https://opencode.ai/config.json",provider:{mistwatch:{npm:"@ai-sdk/openai-compatible",name:"mistwatch",options:{baseURL:`${e}/v1`,apiKey:`{env:${t}}`},models:Object.fromEntries(ii().map(([n,r,s])=>[n,{name:r,limit:{context:s,output:32768}}]))}}}),us=(e,t=pe)=>`[[providers]]
|
|
34
|
+
name = "mistwatch"
|
|
35
|
+
api_base = "${e}/v1"
|
|
36
|
+
api_key_env_var = "${t}"
|
|
37
|
+
backend = "mistral"
|
|
38
|
+
|
|
39
|
+
# Then set provider = "mistwatch" on the models you use.
|
|
40
|
+
`,ls=(e,t)=>{for(let[n,r]of Object.entries(t)){if(n==="__proto__"||n==="constructor"||n==="prototype")continue;let s=e[n];e[n]=oi(r)&&oi(s)?ls(s,r):r}return e},jn=(e,t,n=process.env)=>{let r=n.XDG_CONFIG_HOME,s=t!=="win32"&&r&&Cc(r)?r:si(e,".config");return si(s,"opencode","opencode.json")},Un={opencode:{label:"OpenCode",path:"~/.config/opencode/opencode.json",language:"json"},pi:{label:"Pi",path:"~/.pi/agent/models.json",language:"json"},vibe:{label:"Vibe CLI",path:"~/.vibe/config.toml",language:"toml"},env:{label:"Other tools",path:"environment",language:"sh"}},ai=["opencode","pi","vibe","env"],ui=(e,t,n=pe)=>{let{label:r,path:s,language:o}=Un[e],i,a;return e==="opencode"?(i=`${yt(Jt(t,n))}
|
|
41
|
+
`,a="Merge this into the file, or run: mistwatch agent-config opencode --write"):e==="pi"?(i=`${yt(Xt(t,n))}
|
|
42
|
+
`,a="Merge this into the file, or run: mistwatch agent-config pi --write"):e==="vibe"?(i=us(t,n),a="Add this to the file."):(i=`export OPENAI_BASE_URL="${t}/v1"
|
|
43
|
+
export OPENAI_API_KEY="$${n}"
|
|
44
|
+
`,a='Any tool that speaks the OpenAI chat completions API. Use the model name "auto".'),{tool:e,label:r,path:s,language:o,content:i,filename:s.includes("/")?s.split("/").pop()??s:"mistwatch.env",note:`${a} Set ${n} to a key from the API keys page.`}},li=e=>`# Mistwatch
|
|
45
|
+
|
|
46
|
+
> A local gateway in front of Mistral AI. It speaks the OpenAI/Mistral chat completions API, tracks the Vibe Code and Studio (API) budgets, spreads spending over time and can pick the model for you (\`auto\`). Unofficial: not affiliated with Mistral AI.
|
|
47
|
+
|
|
48
|
+
## Connect
|
|
49
|
+
|
|
50
|
+
- Base URL: \`${e}/v1\`
|
|
51
|
+
- Auth: \`Authorization: Bearer mw-...\` (or \`x-api-key\`). Create keys in the web UI under "API keys". Without any key the gateway is open to the local machine.
|
|
52
|
+
- Format: Mistral/OpenAI chat completions, including streaming and tool calls. \`POST /v1/chat/completions\`, \`/v1/fim/completions\`, \`/v1/embeddings\`, \`/v1/ocr\`, \`/v1/moderations\` and \`/v1/conversations\` are counted against the budget. Every other path is forwarded without accounting.
|
|
53
|
+
- Not offered: Anthropic Messages (\`/v1/messages\`) and OpenAI Responses (\`/v1/responses\`). Mistral does not serve them, so Claude Code and current Codex CLI need a translating proxy (for example LiteLLM) in front, or their own provider.
|
|
54
|
+
|
|
55
|
+
## Models
|
|
56
|
+
|
|
57
|
+
- \`auto\` picks a model and reasoning effort from how hard the request is and how much budget is left.
|
|
58
|
+
- \`auto-fast\` stays with cheaper models, \`auto-max\` aims higher.
|
|
59
|
+
- Any Mistral model id is forwarded unchanged. \`GET /v1/models\` lists the upstream models.
|
|
60
|
+
|
|
61
|
+
## What a client should handle
|
|
62
|
+
|
|
63
|
+
- \`401\` with \`error.type = "mistwatch_auth"\`: the key is wrong or revoked.
|
|
64
|
+
- \`429\` with \`error.type = "mistwatch_budget_exhausted"\`: no account has room right now. Wait for the \`Retry-After\` header (seconds) instead of retrying at once. The body lists each pool and when it frees up.
|
|
65
|
+
- Requests whose \`User-Agent\` contains \`Mistral-Vibe\` are charged to the Vibe Code budget, all others to the Studio API budget. If one is used up, the other is tried.
|
|
66
|
+
- Response headers on accounted calls: \`x-mw-account\`, \`x-mw-pool\`, \`x-mw-room-eur\` (what can still be spent now) and, for \`auto\`, \`x-mw-routed\` (the model and effort chosen).
|
|
67
|
+
|
|
68
|
+
## Set up a tool
|
|
69
|
+
|
|
70
|
+
- Run one command: \`npx mistwatch setup --yes --harness vibe\` (or \`opencode\`, \`pi\`, or a list such as \`vibe,opencode\`). It creates the config, links the Vibe CLI login, creates a client token (shown once) and writes the tool's provider config. Any file it changes is copied to \`<file>.<timestamp>.bak\` first and merged, never replaced. Safe to run again. Needs Node 24+. If the default port 8787 is taken, add \`--port N\`: it writes the port into config.toml and into the tool configs (\`serve --port N\` alone changes neither).
|
|
71
|
+
- Give the token to tools through the environment variable \`${pe}\`. Never ask the user to paste keys into chat and never print the token again.
|
|
72
|
+
- Verify with \`mistwatch status\` and, while the proxy runs, \`curl -H "Authorization: Bearer $${pe}" ${e}/v1/models\`.
|
|
73
|
+
- If the Vibe login is missing, the user runs \`vibe --setup\` and then \`mistwatch import-vibe\`.
|
|
74
|
+
- Ask the user before starting \`mistwatch serve\`: it keeps running.
|
|
75
|
+
- By hand: \`mistwatch agent-config opencode --write\`, \`mistwatch agent-config pi --write\`, \`mistwatch vibe-config\`. Any other OpenAI-compatible tool: base URL \`${e}/v1\`, key from the API keys page, model \`auto\`.
|
|
76
|
+
- The same snippets can be copied or downloaded from the web UI: ${e}/#/keys
|
|
77
|
+
- Full agent instructions: AGENTS.md in the repository.
|
|
78
|
+
|
|
79
|
+
## Building an integration
|
|
80
|
+
|
|
81
|
+
- Read the key from an environment variable (\`${pe}\`); never write it into a file you commit.
|
|
82
|
+
- Default to the model \`auto\` and let the gateway choose.
|
|
83
|
+
- On \`429\`, show the user the wait time from \`Retry-After\`. Do not switch models to get around it.
|
|
84
|
+
- Use one key per tool so its usage shows up separately under "Spend by key".
|
|
85
|
+
`});import{mkdirSync as Ic}from"node:fs";import{dirname as $c}from"node:path";import{DatabaseSync as Lc}from"node:sqlite";var Nc,ee,H,bt,gt,Dc,Mc,ci,Ze,cs,Bn,Hn=E(()=>{"use strict";Nc=`
|
|
86
|
+
CREATE TABLE IF NOT EXISTS ledger(
|
|
87
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
88
|
+
ts REAL NOT NULL, account TEXT NOT NULL, pool TEXT NOT NULL, client TEXT,
|
|
89
|
+
model TEXT, endpoint TEXT, prompt_tokens INTEGER, completion_tokens INTEGER,
|
|
90
|
+
cached_tokens INTEGER, cost_eur REAL NOT NULL, source TEXT NOT NULL, -- proxy | sync
|
|
91
|
+
estimated INTEGER DEFAULT 0, status INTEGER, latency_ms INTEGER
|
|
92
|
+
);
|
|
93
|
+
CREATE INDEX IF NOT EXISTS ix_ledger ON ledger(account, pool, ts);
|
|
94
|
+
CREATE INDEX IF NOT EXISTS ix_ledger_ts ON ledger(ts);
|
|
95
|
+
CREATE TABLE IF NOT EXISTS snapshots(
|
|
96
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
97
|
+
ts REAL NOT NULL, account TEXT NOT NULL, pool TEXT NOT NULL,
|
|
98
|
+
used_eur REAL NOT NULL, initial_eur REAL NOT NULL, reset_at REAL NOT NULL, currency TEXT
|
|
99
|
+
);
|
|
100
|
+
CREATE INDEX IF NOT EXISTS ix_snap ON snapshots(account, pool, ts);
|
|
101
|
+
CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT);
|
|
102
|
+
CREATE TABLE IF NOT EXISTS model_names(model_id TEXT PRIMARY KEY, display TEXT NOT NULL); -- your own overrides
|
|
103
|
+
CREATE TABLE IF NOT EXISTS model_catalog( -- cached /v1/models: display name + aliases per model id
|
|
104
|
+
model_id TEXT PRIMARY KEY, name TEXT, aliases TEXT, description TEXT
|
|
105
|
+
);
|
|
106
|
+
CREATE TABLE IF NOT EXISTS users(
|
|
107
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
|
108
|
+
pw_hash TEXT NOT NULL, created REAL NOT NULL
|
|
109
|
+
);
|
|
110
|
+
CREATE TABLE IF NOT EXISTS sessions(
|
|
111
|
+
token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
112
|
+
created REAL NOT NULL, last_seen REAL NOT NULL, expires REAL NOT NULL
|
|
113
|
+
);
|
|
114
|
+
CREATE TABLE IF NOT EXISTS api_keys( -- keys local tools use against the proxy; only the hash is kept
|
|
115
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, prefix TEXT NOT NULL,
|
|
116
|
+
key_hash TEXT NOT NULL UNIQUE, created REAL NOT NULL, last_used REAL
|
|
117
|
+
);
|
|
118
|
+
CREATE TABLE IF NOT EXISTS accounts(
|
|
119
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, priority INTEGER NOT NULL DEFAULT 100,
|
|
120
|
+
enabled INTEGER NOT NULL DEFAULT 1, keys TEXT NOT NULL DEFAULT '{}', -- {pool: secret reference}
|
|
121
|
+
manual TEXT NOT NULL DEFAULT '{}', created REAL NOT NULL
|
|
122
|
+
);
|
|
123
|
+
`,ee=e=>{if(typeof e!="string")throw new TypeError(`db: expected string, got ${typeof e}`);return e},H=e=>{if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);throw new TypeError(`db: expected number, got ${typeof e}`)},bt=e=>e==null?null:ee(e),gt=e=>e==null?null:H(e),Dc=e=>({ts:H(e.ts),account:ee(e.account),pool:ee(e.pool),used_eur:H(e.used_eur),initial_eur:H(e.initial_eur),reset_at:H(e.reset_at),currency:bt(e.currency)}),Mc=e=>({id:H(e.id),ts:H(e.ts),account:ee(e.account),pool:ee(e.pool),client:bt(e.client),model:bt(e.model),endpoint:bt(e.endpoint),prompt_tokens:gt(e.prompt_tokens),completion_tokens:gt(e.completion_tokens),cached_tokens:gt(e.cached_tokens),cost_eur:H(e.cost_eur),source:ee(e.source),estimated:gt(e.estimated),status:gt(e.status),latency_ms:gt(e.latency_ms)}),ci=e=>typeof e=="string"?["account=?",[e]]:[`account IN (${e.map(()=>"?").join(",")})`,[...e]],Ze=(e,t)=>Buffer.compare(Buffer.from(e),Buffer.from(t)),cs=(e,t)=>{let n=[],r=new Set,s=t;for(;!r.has(s);){r.add(s),n.push(s);let o=e.get(s);if(o===void 0)return s;s=o}return n.slice(n.indexOf(s)).reduce((o,i)=>Ze(i,o)<0?i:o)},Bn=e=>{e!==":memory:"&&Ic($c(e),{recursive:!0});let t=new Lc(e);t.exec("PRAGMA journal_mode=WAL"),t.exec("PRAGMA busy_timeout=5000"),t.exec("PRAGMA foreign_keys=ON"),t.exec(Nc);let n=new Map,r=a=>{let u=n.get(a);if(u!==void 0)return u;let l=t.prepare(a);return n.set(a,l),l},s=(a,u)=>r(a).get(...u),o=!1,i={conn:t,links:new Map,linksInfo:new Map,stmt:r,getMeta:a=>{let u=s("SELECT v FROM meta WHERE k=?",[a]);return u?ee(u.v):null},setMeta:(a,u)=>{r("INSERT INTO meta(k, v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(a,u)},canonical:a=>cs(i.links,a),members:a=>{let u=i.canonical(a),l=[...i.links.keys()].filter(f=>f!==u&&i.canonical(f)===u).sort(Ze);return[u,...l]},addLedger:a=>{r("INSERT INTO ledger(ts,account,pool,client,model,endpoint,prompt_tokens,completion_tokens,cached_tokens,cost_eur,source,estimated,status,latency_ms) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(a.ts,a.account,a.pool,a.client??null,a.model??null,a.endpoint??null,a.prompt_tokens??null,a.completion_tokens??null,a.cached_tokens??null,a.cost_eur,a.source,a.estimated??null,a.status??null,a.latency_ms??null)},addSnapshot:a=>{r("INSERT INTO snapshots(ts,account,pool,used_eur,initial_eur,reset_at,currency) VALUES(?,?,?,?,?,?,?)").run(a.ts,a.account,a.pool,a.used_eur,a.initial_eur,a.reset_at,a.currency)},latestSnapshot:(a,u)=>{let l=s("SELECT * FROM snapshots WHERE account=? AND pool=? ORDER BY ts DESC LIMIT 1",[a,u]);return l?Dc(l):null},costBetween:(a,u,l,f={})=>{let[d,p]=ci(a),c=`SELECT COALESCE(SUM(cost_eur),0) AS s FROM ledger WHERE ${d} AND pool=? AND ts${f.inclusive?">=":">"}?`,m=[...p,u,l];f.upto!=null&&(c+=" AND ts<=?",m.push(f.upto)),f.source&&(c+=" AND source=?",m.push(f.source));let y=s(c,m);return H(y?.s??0)},rowsSince:(a,u,l)=>{let[f,d]=ci(a);return r(`SELECT ts, cost_eur FROM ledger WHERE ${f} AND pool=? AND ts>=? ORDER BY ts`).all(...d,u,l).map(p=>[H(p.ts),H(p.cost_eur)])},sumCost:(a,u)=>{let l=s("SELECT COALESCE(SUM(cost_eur),0) s FROM ledger WHERE ts>=? AND ts<?",[a,u]);return H(l?.s??0)},usageRows:(a,u)=>r("SELECT ts, cost_eur, model, client, account, pool, source FROM ledger WHERE ts>=? AND ts<? ORDER BY ts").all(a,u).map(l=>({ts:H(l.ts),cost_eur:H(l.cost_eur),model:bt(l.model),client:bt(l.client),account:ee(l.account),pool:ee(l.pool),source:ee(l.source)})),recent:(a=50)=>r("SELECT * FROM ledger ORDER BY ts DESC LIMIT ?").all(a).map(Mc),byClientSince:a=>r("SELECT COALESCE(client,'-') client, account, pool, COUNT(*) n, SUM(cost_eur) cost_eur FROM ledger WHERE ts>=? AND source='proxy' GROUP BY 1,2,3 ORDER BY cost_eur DESC").all(a).map(u=>({client:ee(u.client),account:ee(u.account),pool:ee(u.pool),n:H(u.n),cost_eur:H(u.cost_eur)})),tx:a=>{if(o)return a();t.exec("BEGIN IMMEDIATE"),o=!0;try{let u=a();return t.exec("COMMIT"),u}catch(u){throw t.exec("ROLLBACK"),u}finally{o=!1}},close:()=>{t.close()}};return i}});var M,T,de,Fn,Zt,vt,Qe,wt,x,kt=E(()=>{"use strict";M=(e,t,n,r={})=>({code:e,status:t,message:n,retryAfter:r.retryAfter,extra:r.extra}),T=e=>{let t=Object.assign(new Error(e.message),e);return t.name=e.code,t},de=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.code=="string"&&typeof t.status=="number"&&typeof t.message=="string"},Fn=(e,t)=>de(e)?e:t??x.internal(),Zt=e=>({error:{type:e.code,message:e.message,...e.extra??{}}}),vt=e=>({detail:e.message}),Qe=e=>e.retryAfter===void 0?{}:{"Retry-After":String(Math.max(Math.ceil(e.retryAfter),1))},wt=e=>Math.max(Math.ceil(e),1),x={auth:()=>M("mistwatch_auth",401,"Missing or invalid Mistwatch key. Create one under API keys in the web UI and send it as Authorization: Bearer mw-..."),budget:(e,t)=>{let n=wt(e);return M("mistwatch_budget_exhausted",429,"No account has budget room right now. Wait for the Retry-After delay and try again.",{retryAfter:n,extra:{pools:t,retry_after:n}})},upstream:()=>M("mistwatch_upstream",502,"Could not get a usable answer from Mistral on any account (network error or rejected key). Check the connection and the account keys in the web UI, then try again."),upstreamTimeout:()=>M("mistwatch_upstream_timeout",504,"Mistral did not answer in time. Try again.",{retryAfter:1}),tooLarge:()=>M("mistwatch_body_too_large",413,"The request body is too large."),queueFull:(e=1)=>M("mistwatch_queue_full",503,"Mistwatch is busy with too many requests. Retry in a moment.",{retryAfter:wt(e)}),queueTimeout:(e=1)=>M("mistwatch_queue_timeout",503,"The request waited or ran too long. Retry in a moment.",{retryAfter:wt(e)}),rateLimited:e=>M("mistwatch_rate_limited",429,"Too many requests. Slow down and retry after the Retry-After delay.",{retryAfter:wt(e)}),locked:e=>M("mistwatch_login_locked",429,`Too many attempts, try again in ${wt(e)} s.`,{retryAfter:wt(e)}),badRequest:e=>M("mistwatch_bad_request",400,e),unauthorized:e=>M("mistwatch_unauthorized",401,e),forbiddenHost:e=>M("mistwatch_forbidden",403,`This address is not allowed. Open Mistwatch at http://127.0.0.1:${e}/ or add this host to allowed_hosts under [server] in config.toml.`),forbidden:e=>M("mistwatch_forbidden",403,e),shuttingDown:()=>M("mistwatch_shutting_down",503,"Mistwatch is shutting down. Retry in a moment.",{retryAfter:1}),internal:()=>M("mistwatch_internal",500,"Something went wrong inside Mistwatch. Check the server log.")}});var qn,fi,Wn=E(()=>{"use strict";kt();qn=e=>{let t=Math.max(1,Math.floor(e.concurrency)),n=Math.max(0,Math.floor(e.maxPending)),r=[],s=0,o=(f,d)=>{f.done=!0,f.cleanup();let p=r.indexOf(f);p>=0&&r.splice(p,1),f.fail(d)},i=(f,d,p)=>{f.done||(f.done=!0,f.cleanup(),d?f.ok(p):f.fail(p))},a=()=>{s--,u()},u=()=>{for(;s<t;){let f=r.shift();if(f===void 0)return;if(f.ctrl.signal.aborted){o(f,f.ctrl.signal.reason);continue}if(f.deadline!==void 0&&Date.now()>=f.deadline){o(f,T(x.queueTimeout()));continue}f.running=!0,s++;let d=f.ctrl.signal,p=new Promise((m,y)=>{f.onAbort=()=>y(d.reason),d.addEventListener("abort",f.onAbort,{once:!0})}),c=Promise.resolve().then(()=>f.fn(d));Promise.race([c,p]).then(m=>i(f,!0,m),m=>i(f,!1,m)),c.then(a,a)}};return{run:(f,d={})=>d.signal?.aborted?Promise.reject(d.signal.reason):r.length>=n?Promise.reject(T(x.queueFull())):new Promise((p,c)=>{let m=d.signal,y=()=>b.ctrl.abort(m?.reason),b={fn:f,ok:g=>p(g),fail:c,ctrl:new AbortController,timer:void 0,deadline:void 0,running:!1,done:!1,onAbort:void 0,cleanup:()=>{b.timer!==void 0&&clearTimeout(b.timer),m!==void 0&&m.removeEventListener("abort",y),b.ctrl.signal.removeEventListener("abort",v),b.onAbort!==void 0&&b.ctrl.signal.removeEventListener("abort",b.onAbort)}},v=()=>{b.done||b.running||o(b,b.ctrl.signal.reason)};b.ctrl.signal.addEventListener("abort",v,{once:!0});let h=d.timeoutMs??e.timeoutMs;h!==void 0&&(b.deadline=Date.now()+h,b.timer=setTimeout(()=>b.ctrl.abort(T(x.queueTimeout())),h)),m!==void 0&&m.addEventListener("abort",y,{once:!0}),r.push(b),u()}),get pending(){return r.length},get active(){return s}}},fi=()=>{let e=new Map,t=(n,r)=>{if(!Number.isFinite(r)||r<0)throw new TypeError("reservation amount must be >= 0");e.set(n,(e.get(n)??0)+r);let s=!1,o=()=>{if(s)return;s=!0;let i=(e.get(n)??0)-r;i<=1e-9?e.delete(n):e.set(n,i)};return{amount:r,release:o,settle:o,get done(){return s}}};return{reserve:t,tryReserve:(n,r,s)=>(e.get(n)??0)+r>s?null:t(n,r),outstanding:n=>{if(n!==void 0)return e.get(n)??0;let r=0;for(let s of e.values())r+=s;return r}}}});var mi={};Ae(mi,{DAY:()=>Et,MIN_DAYS_LEFT:()=>di,WINDOWS:()=>Qt,createBudgetEngine:()=>tn,poolBlockedBy:()=>en,poolGrossRoom:()=>Kn,poolPressure:()=>fs,poolRetryAt:()=>_t,poolRoom:()=>ie,poolStatusDict:()=>ps,roundTo:()=>K});var Et,Qt,di,ie,Kn,fs,en,_t,pi,K,ps,tn,et=E(()=>{"use strict";Wn();Et=86400,Qt={"5h":5/24,day:1,week:7},di=1/24,ie=e=>Math.min(e.month_room,...Object.values(e.windows).map(t=>t.room))-e.inflight,Kn=e=>Math.min(e.month_room,...Object.values(e.windows).map(t=>t.room)),fs=e=>{let t=Object.values(e.windows).filter(r=>r.cap>0).map(r=>Math.max(r.room,0)/r.cap),n=e.initial-e.reserve;return n>0&&t.push(Math.max(e.month_room,0)/n),t.length?Math.min(...t):1},en=e=>{if(ie(e)>0)return null;if(e.month_room-e.inflight<=0)return"month";let t=null;for(let n of Object.values(e.windows))(!t||n.room<t.room)&&(t=n);return t?t.name:"month"},_t=e=>{let t=en(e);return t===null?null:t==="month"?e.month_retry_at:e.windows[t]?.retry_at??null},pi=new DataView(new ArrayBuffer(8)),K=(e,t)=>{if(!Number.isFinite(e)||e===0)return e;pi.setFloat64(0,Math.abs(e));let n=pi.getBigUint64(0),r=Number(n>>52n&0x7ffn),s=n&0xfffffffffffffn,o=r===0?s:s|1n<<52n,i=(r===0?1:r)-1075,a=o*10n**BigInt(t),u;if(i>=0)u=a<<BigInt(i);else{let l=1n<<BigInt(-i);u=a/l;let f=a%l*2n;(f>l||f===l&&u%2n===1n)&&(u+=1n)}return+`${e<0?"-":""}${u}e-${t}`},ps=e=>({account:e.account,pool:e.pool,group:e.group,members:e.members,initial_eur:K(e.initial,4),used_eur:K(e.used,4),remaining_eur:K(e.remaining,4),reserve_eur:K(e.reserve,4),reset_at:e.reset_at,days_left:K(e.days_left,3),snapshot_age_s:K(e.snapshot_age_s,1),daily_fair_share_eur:K(Math.max(e.remaining-e.reserve,0)/e.days_left,4),room_eur:K(ie(e),4),blocked_by:en(e),retry_at:_t(e),month:{cap:K(e.initial-e.reserve,4),spent:K(e.used,4),room:K(e.month_room,4)},windows:Object.fromEntries(Object.entries(e.windows).map(([t,n])=>[t,{cap:K(n.cap,4),spent:K(n.spent,4),room:K(n.room,4),retry_at:n.retry_at}]))}),tn=(e,t)=>{let n=fi(),r=Math.max(...Object.values(Qt)),s=(f,d)=>`${f}\0${d}`,o=(f,d)=>{let p=0;for(let c of f)p+=n.outstanding(s(c,d));return p},i=f=>{let d=f==="5h"?t.burst_5h:f==="day"?t.burst_day:f==="week"?t.burst_week:void 0;if(d===void 0)throw new RangeError(`unknown window ${f}`);return d},a=(f,d,p,c)=>{if(c>=1)return null;let m=p*c/(1-c),y=0;for(let[,v]of f)y+=v;for(let[v,h]of f)if(y-=h,y<m)return v+d*Et+1;let b=f[f.length-1];return b?b[0]+d*Et+1:null};return{db:e,burst:i,status:(f,d,p)=>{let c=p??Date.now()/1e3,m=e.canonical(f),y=e.latestSnapshot(m,d);if(y===null&&m!==f&&(m=f,y=e.latestSnapshot(f,d)),y===null)return null;let b=e.members(m),v=y.initial_eur,h=c>=y.reset_at,g,w;h?(g=e.costBetween(b,d,y.reset_at,{inclusive:!0}),w=30):(g=y.used_eur+e.costBetween(b,d,y.ts),w=Math.max((y.reset_at-c)/Et,di));let _=v-g,O=v*t.reserve_pct/100,L=_-O,N={account:f,pool:d,initial:v,used:g,remaining:_,reserve:O,reset_at:y.reset_at,days_left:w,snapshot_age_s:c-y.ts,windows:{},month_room:L,month_retry_at:L<=0?y.reset_at:null,inflight:o(b.includes(f)?b:[...b,f],d),group:m,members:b},V=e.rowsSince(b,d,c-r*Et);for(let[se,D]of Object.entries(Qt)){let he=V.filter(([ft])=>ft>=c-D*Et),Ke=0;for(let[,ft]of he)Ke+=ft;let _n=Math.min(Math.max(_,0)+Ke,v),ze=D/(w+D)*i(se),ye=_n*ze,Ge=ye-Ke;N.windows[se]={name:se,length_days:D,cap:ye,spent:Ke,room:Ge,retry_at:Ge<=0&&he.length?a(he,D,Math.max(_,0),ze):null}}return N},tryReserve:(f,d,p,c)=>{let m=e.members(e.canonical(f)).filter(y=>y!==f);return n.tryReserve(s(f,d),p,c-o(m,d))}}}});var Ue,zn=E(()=>{"use strict";Ue=["vibe","api"]});var jc,ds,hi,Gn,Uc,gi,Bc,nn,Be,yi,ms,rn=E(()=>{"use strict";et();Hn();zn();jc=90,ds=1e-6,hi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>{let t=e.getMeta("links");if(e.links=new Map,e.linksInfo=new Map,!!t)try{let n=JSON.parse(t);if(!hi(n))throw new TypeError("bad links");let r=new Map,s=new Map;for(let[o,i]of Object.entries(n)){if(!hi(i)||typeof i.canonical!="string"||typeof i.confidence!="string")throw new TypeError("bad links");r.set(o,i.canonical),s.set(o,i.confidence)}e.links=r,e.linksInfo=s}catch{e.links=new Map,e.linksInfo=new Map}},Uc=(e,t)=>{let n=Object.keys(e);if(!n.length||n.length!==Object.keys(t).length)return!1;for(let r of n){let s=e[r],o=t[r];if(!s||!o||Math.abs(s.initial_eur-o.initial_eur)>ds||Math.abs(s.reset_at-o.reset_at)>1||Math.abs(s.used_eur-o.used_eur)>ds)return!1}return!0},gi=(e,t)=>{let n=new Map;for(let c of t){let m={};for(let y of Ue){let b=e.latestSnapshot(c.name,y);b&&(m[y]=b)}Object.keys(m).length&&n.set(c.name,m)}if(!n.size)return e.links;let r=-1/0;for(let c of n.values())for(let m of Object.values(c))r=Math.max(r,m.ts);let s=new Map,o=new Set;for(let[c,m]of n){let y=1/0;for(let b of Object.values(m))y=Math.min(y,b.ts);y>=r-jc?s.set(c,m):o.add(c)}let i=[...s.keys()].sort(Ze),a=new Map(i.map(c=>[c,c])),u=c=>{let m=c;for(;;){let y=a.get(m)??m;if(y===m)return m;a.set(m,a.get(y)??y),m=y}};for(let c=0;c<i.length;c++){let m=i[c];if(m===void 0)continue;let y=s.get(m);for(let b of i.slice(c+1)){let v=s.get(b);y&&v&&Uc(y,v)&&a.set(u(b),u(m))}}let l=new Map;for(let c of i){let m=u(c),y=l.get(m);y?y.push(c):l.set(m,[c])}let f=new Map(t.map(c=>[c.name,c.priority])),d=new Map,p=new Map;for(let[c,m]of e.links)(o.has(c)||o.has(m))&&(d.set(c,m),p.set(c,e.linksInfo.get(c)??"likely"));for(let c of l.values()){if(c.length<2)continue;let m=c[0]??"";for(let g of c){let w=f.get(g)??999,_=f.get(m)??999;(w<_||w===_&&Ze(g,m)<0)&&(m=g)}let y=d.get(m),b=p.get(m)??"likely";d.delete(m),p.delete(m),y!==void 0&&y!==m&&!c.includes(y)&&(d.set(y,m),p.set(y,b));let v=s.get(m),h=v?Object.values(v).some(g=>g.used_eur>ds):!1;for(let g of c)g!==m&&(d.set(g,m),p.set(g,h?"sure":"likely"))}for(let[c,m]of[...d.keys()].map(y=>[y,cs(d,y)]))m===c?(d.delete(c),p.delete(c)):d.set(c,m);return e.links=d,e.linksInfo=p,e.setMeta("links",JSON.stringify(Object.fromEntries([...d].map(([c,m])=>[c,{canonical:m,confidence:p.get(c)??"likely"}])))),d},Bc=e=>{let t=new Map;for(let n of e.links.keys()){let r=e.canonical(n),s=t.get(r);s||(s={canonical:r,members:[r],confidence:"sure"},t.set(r,s)),s.members.push(n),e.linksInfo.get(n)!=="sure"&&(s.confidence="likely")}return[...t.values()].map(n=>({...n,members:[...n.members].sort(Ze)}))},nn=e=>Math.max(e,0),Be=(e,t)=>e.reduce((n,r)=>n+t(r),0),yi=e=>{let t={};for(let o of Object.keys(Qt)){let i=0,a=0,u=0;for(let l of e){let f=l.windows[o];f&&(i+=f.cap,a+=f.spent,u+=nn(f.room))}t[o]={cap:i,spent:a,room:u}}let n=e.filter(o=>ie(o)<=0),r=e.length>0&&n.length===e.length,s=n.map(o=>_t(o)).filter(o=>o!==null);return{budgets:e.length,accounts:[...new Set(e.flatMap(o=>o.members))].sort(Ze),initial_eur:Be(e,o=>o.initial),used_eur:Be(e,o=>o.used),remaining_eur:Be(e,o=>nn(o.remaining)),month:{cap:Be(e,o=>o.initial-o.reserve),spent:Be(e,o=>o.used),room:Be(e,o=>nn(o.month_room))},room_eur:Be(e,o=>nn(ie(o))),fair_daily_eur:Be(e,o=>nn(o.remaining-o.reserve)/o.days_left),windows:t,blocked:r,retry_at:r&&s.length?Math.min(...s):null,reset_at:e.length?Math.min(...e.map(o=>o.reset_at)):null}},ms=(e,t,n)=>{let r=n??Date.now()/1e3,s=new Set,o={vibe:[],api:[]};for(let u of t)if(u.enabled)for(let l of Ue){let f=e.status(u.name,l,r);if(!f)continue;let d=`${f.group}${l}`;s.has(d)||(s.add(d),o[l]?.push(f))}let i={};for(let[u,l]of Object.entries(o))l.length&&(i[u]=yi(l));let a=Object.values(o).flat();return{pools:i,all:s.size?yi(a):null,shared:Bc(e.db),accounts:t.filter(u=>u.enabled).length}}});import{createHash as Fh,randomBytes as Hc,scrypt as Fc,timingSafeEqual as qc}from"node:crypto";var ys,Ei,_i,Wc,Kc,zc,At,Ai,Gc,Vc,Xc,Si,xi,Ri,Vn,Xn,bi,wi,vi,Ti,Oi,Jc,Ci,Jn,hs,ki,gs,Yc,Pi,Zc,Ii,sn=E(()=>{"use strict";kt();Wn();ys=new Set(["localhost","127.0.0.1","::1"]),Ei=(e,t)=>ys.has(e)||(t.extraHosts?.includes(e)??!1),_i=(e,t)=>t.extraHosts?.includes(e)??!1,Wc=e=>{let t=e.trim().toLowerCase();if(t===""||/\s/.test(t))return null;if(t.startsWith("[")){let o=t.indexOf("]");if(o<0)return null;let i=t.slice(o+1),a=t.slice(1,o);if(i==="")return{name:a,port:null};if(!i.startsWith(":"))return null;let u=Number(i.slice(1));return Number.isInteger(u)&&u>=0&&u<=65535?{name:a,port:u}:null}let n=t.lastIndexOf(":");if(n<0)return{name:t,port:null};let r=t.slice(0,n),s=Number(t.slice(n+1));return r===""||!Number.isInteger(s)||s<0||s>65535?null:{name:r,port:s}},Kc=(e,t)=>{if(e==null)return!1;let n=Wc(e);if(n===null)return!1;let r=n.name.endsWith(".")?n.name.slice(0,-1):n.name;return Ei(r,t)?!ys.has(r)||_i(r,t)||n.port===null||n.port===t.port:!1},zc=(e,t)=>{if(e==null||e==="")return!0;if(e==="null")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username!==""||n.password!=="")return!1;let r=n.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return Ei(r,t)?!ys.has(r)||_i(r,t)?!0:(n.port===""?n.protocol==="https:"?443:80:Number(n.port))===t.port:!1},At=(e,t)=>Kc(e.host,t)&&zc(e.origin,t),Ai=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","trailers","transfer-encoding","upgrade","host","content-length","content-encoding"]),Gc=new Set(["authorization","x-api-key","cookie","accept-encoding"]),Vc=new Set([...Ai,...Gc]),Xc=new Set([...Ai,"set-cookie"]),Si=e=>{let t=new Set;for(let[n,r]of e)if(n.toLowerCase()==="connection")for(let s of r.split(","))t.add(s.trim().toLowerCase());return t},xi=(e,t=[])=>{let n=[];for(let[s,o]of e)n.push([s,o]);let r=new Set(Vc);for(let s of Si(n))r.add(s);for(let s of t)r.add(s.toLowerCase());return n.filter(([s])=>{let o=s.toLowerCase();return!r.has(o)&&o!=="x-mw"&&!o.startsWith("x-mw-")})},Ri=(e,t=[])=>{let n=[];for(let[s,o]of e)n.push([s,o]);let r=new Set(Xc);for(let s of Si(n))r.add(s);for(let s of t)r.add(s.toLowerCase());return n.filter(([s])=>!r.has(s.toLowerCase()))},Vn=(e,t)=>{if(e==null)return!0;let n=Number(e);return!Number.isFinite(n)||n<=t},Xn=async(e,t)=>{if(e===null)return new Uint8Array(0);let n=e.getReader(),r=[],s=0;try{for(;;){let{done:a,value:u}=await n.read();if(a)break;if(s+=u.byteLength,s>t)throw await n.cancel().catch(()=>{}),T(x.tooLarge());r.push(u)}}finally{n.releaseLock()}let o=new Uint8Array(s),i=0;for(let a of r)o.set(a,i),i+=a.byteLength;return o},bi=15,wi=8,vi=1,Ti=256*1024*1024,Oi=4096,Jc=qn({concurrency:2,maxPending:64}),Ci=(e,t,n,r,s)=>Jc.run(()=>new Promise((o,i)=>{Fc(e,t,32,{N:n,r,p:s,maxmem:Ti},(a,u)=>a===null?o(u):i(a))})),Jn=async e=>{if(Buffer.byteLength(e,"utf8")>Oi)throw T(x.badRequest("Password is too long."));let t=Hc(16),n=await Ci(e,t,2**bi,wi,vi);return`scrypt$${bi}$${wi}$${vi}$${t.toString("base64")}$${n.toString("base64")}`},hs=/^[0-9]+$/,ki=/^[A-Za-z0-9+/]*={0,2}$/,gs=async(e,t)=>{let n=t.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let[r="",s="",o="",i="",a=""]=n.slice(1);if(!hs.test(r)||!hs.test(s)||!hs.test(o)||!ki.test(i)||!ki.test(a))return!1;let u=Number(r),l=Number(s),f=Number(o),d=Buffer.from(i,"base64"),p=Buffer.from(a,"base64");if(p.length!==32||d.length===0||d.length>64||u<1||u>24||l<1||l>64||f<1||f>32||128*l*2**u>Ti||Buffer.byteLength(e,"utf8")>Oi)return!1;try{let c=await Ci(e,d,2**u,l,f);return qc(c,p)}catch(c){if(de(c))throw c;return!1}},Yc=[[/Bearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]"],[/mw-[A-Za-z0-9_-]{12,}/g,"mw-[redacted]"]],Pi=(e,t=[])=>{let n=e;for(let[r,s]of Yc)n=n.replace(r,s);for(let r of t)r.length>=8&&(n=n.split(r).join("[redacted]"));return n},Zc=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Ii=e=>Zc.test(e)});var _s={};Ae(_s,{ACCOUNT_RE:()=>Mi,KEYRING_SERVICE:()=>St,MIN_PASSWORD:()=>vs,NAME_RE:()=>Di,SESSION_IDLE_S:()=>ws,SESSION_TTL:()=>er,StoreError:()=>I,VIBE_REF:()=>Re,checkPasswordPolicy:()=>on,createStore:()=>an,dropSecret:()=>Zn,hashPassword:()=>Qn,mask:()=>tr,refKind:()=>Ui,saveSecret:()=>ks,verifyPassword:()=>Yn,vibeCliKeyPresent:()=>xt});import{createHash as Qc,randomBytes as bs,scryptSync as ef,timingSafeEqual as tf}from"node:crypto";var Di,Mi,er,ws,nf,St,Re,vs,I,$i,Li,Ni,ji,Qn,Yn,rf,sf,of,af,tt,on,Ui,tr,ks,Zn,xt,z,F,uf,Es,lf,cf,ff,an,nt=E(()=>{"use strict";W();Gr();sn();zn();Di=/^[A-Za-z0-9._-]{1,40}$/,Mi=/^[A-Za-z0-9._+@-]{1,80}$/,er=30*86400,ws=7*86400,nf=60,St="mistwatch",Re="keyring:ai.mistral.vibe/MISTRAL_API_KEY",vs=10,I=class extends Error{constructor(t){super(t),this.name="StoreError"}},$i=15,Li=8,Ni=1,ji=(e,t,n,r,s)=>ef(e,t,32,{N:2**n,r,p:s,maxmem:256*1024*1024}),Qn=e=>{let t=bs(16),n=ji(e,t,$i,Li,Ni);return`scrypt$${$i}$${Li}$${Ni}$${t.toString("base64")}$${n.toString("base64")}`},Yn=(e,t)=>{try{let n=t.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let[r,s,o,i,a]=[n[1]??"",n[2]??"",n[3]??"",n[4]??"",n[5]??""];if(!/^[+-]?\d+$/.test(r)||!/^[+-]?\d+$/.test(s)||!/^[+-]?\d+$/.test(o))return!1;let u=ji(e,Buffer.from(i,"base64"),Number(r),Number(s),Number(o)),l=Buffer.from(a,"base64");return u.length===l.length&&tf(u,l)}catch{return!1}},rf=null,sf=()=>rf??=Qn("dummy-password-for-timing"),of=null,af=()=>of??=Jn("dummy-password-for-timing"),tt=e=>Qc("sha256").update(e,"utf8").digest("hex"),on=e=>{let t=Array.from(e).length;if(t<vs)throw new I(`Password must be at least ${vs} characters.`);if(t>256)throw new I("Password is too long.")},Ui=e=>e===Re?"vibe-cli":e.startsWith("keyring:")?"keyring":e.startsWith("env:")?"env":"inline",tr=e=>e.length>12?`${e.slice(0,5)}\u2026${e.slice(-4)}`:`\u2026${e.slice(-3)}`,ks=(e,t,n,r=dt)=>{if(process.env.MISTWATCH_NO_KEYRING)return n;try{let s=`${e}/${t}`;if(r.set(St,s,n),r.get(St,s)===n)return`keyring:${St}/${s}`}catch{}return n},Zn=(e,t=dt)=>{if(e.startsWith(`keyring:${St}/`))try{let n=e.slice(8);t.drop(St,n.slice(n.indexOf("/")+1))}catch{}},xt=(e=dt)=>{try{return!!e.get("ai.mistral.vibe","MISTRAL_API_KEY")}catch{return!1}},z=e=>{if(typeof e!="string")throw new TypeError("db: expected string");return e},F=e=>{if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);throw new TypeError("db: expected number")},uf=e=>e==null?null:F(e),Es=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lf=e=>{let t=e.codePointAt(0);return t!==void 0&&(/\s/u.test(e)||t>=28&&t<=31||t===133)},cf=e=>{let t=JSON.parse(z(e));if(!Es(t))throw new TypeError("accounts.keys is not an object");return Object.fromEntries(Object.entries(t).map(([n,r])=>{if(typeof r!="string")throw new TypeError("accounts.keys values must be strings");return[n,r]}))},ff=e=>{let t=JSON.parse(z(e));if(!Es(t))throw new TypeError("accounts.manual is not an object");return Object.fromEntries(Object.entries(t).map(([n,r])=>{if(!Es(r))throw new TypeError("accounts.manual values must be objects");return[n,Object.fromEntries(Object.entries(r).map(([s,o])=>{if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw new TypeError("accounts.manual values must be primitives");return[s,o]}))]}))},an=e=>{let t=new Map,n=(p,c=[])=>e.stmt(p).get(...c),r=(p,...c)=>e.stmt(p).run(...c),s=()=>F(n("SELECT COUNT(*) c FROM users")?.c??0),o=(p,c,m)=>{r("INSERT INTO api_keys(name, prefix, key_hash, created) VALUES(?,?,?,?)",p,c.slice(0,7),tt(c),m)},i=p=>(p===void 0?e.stmt("SELECT id, name, prefix, created, last_used FROM api_keys ORDER BY id").all():e.stmt("SELECT id, name, prefix, created, last_used FROM api_keys WHERE name=?").all(p)).map(c=>({id:F(c.id),name:z(c.name),prefix:z(c.prefix),created:F(c.created),last_used:uf(c.last_used)})),a=p=>({name:z(p.name),keys:cf(p.keys),priority:F(p.priority),enabled:F(p.enabled)!==0,manual:ff(p.manual)}),u=p=>{let c=n("SELECT * FROM accounts WHERE name=?",[p]);return c?a(c):null},l=(p,c=100,m=Date.now()/1e3)=>{let y=p.trim();if(!Mi.test(y))throw new I("Account name (may be an e-mail): 1-80 characters, letters, digits and . _ + @ -");if(u(y))throw new I("An account with this name already exists.");r("INSERT INTO accounts(name, priority, created) VALUES(?,?,?)",y,c,m)},f=(p,c,m)=>{e.tx(()=>{c!=null&&r("UPDATE accounts SET enabled=? WHERE name=?",c?1:0,p),m!=null&&r("UPDATE accounts SET priority=? WHERE name=?",Math.trunc(m),p)})},d=(p,c,m={})=>{if(!Ue.some(h=>h===c))throw new I("Unknown pool.");let y=u(p);if(!y)throw new I("Account does not exist.");let b;if(m.value!=null){let h=Array.from(m.value.trim());if(h.length<8||h.some(lf))throw new I("Key looks invalid.");b=ks(p,c,h.join(""))}else if(m.ref)b=m.ref;else throw new I("Key is missing.");let v=y.keys[c];y.keys[c]=b,r("UPDATE accounts SET keys=? WHERE name=?",JSON.stringify(y.keys),p),v&&v!==b&&Zn(v)};return{countUsers:s,listUsers:()=>e.stmt("SELECT id, username, created FROM users ORDER BY id").all().map(p=>({id:F(p.id),username:z(p.username),created:F(p.created)})),createUser:(p,c,m=Date.now()/1e3)=>{let y=p.trim();if(!/^[A-Za-z0-9._@-]{2,40}$/.test(y))throw new I("Username: 2-40 characters, letters, digits and . _ - @");if(on(c),n("SELECT 1 FROM users WHERE username=?",[y]))throw new I("A user with this name already exists.");return Number(r("INSERT INTO users(username, pw_hash, created) VALUES(?,?,?)",y,Qn(c),m).lastInsertRowid)},verifyLogin:(p,c)=>{let m=n("SELECT id, username, pw_hash FROM users WHERE username=?",[p.trim()]);return m?Yn(c,z(m.pw_hash))?{id:F(m.id),username:z(m.username)}:null:(Yn(c,sf()),null)},createUserAsync:async(p,c,m=Date.now()/1e3)=>{let y=p.trim();if(!/^[A-Za-z0-9._@-]{2,40}$/.test(y))throw new I("Username: 2-40 characters, letters, digits and . _ - @");if(on(c),n("SELECT 1 FROM users WHERE username=?",[y]))throw new I("A user with this name already exists.");return Number(r("INSERT INTO users(username, pw_hash, created) VALUES(?,?,?)",y,await Jn(c),m).lastInsertRowid)},verifyLoginAsync:async(p,c)=>{let m=n("SELECT id, username, pw_hash FROM users WHERE username=?",[p.trim()]),y=m?z(m.pw_hash):await af();return await gs(c,y)&&m?{id:F(m.id),username:z(m.username)}:null},setPasswordAsync:async(p,c)=>{on(c),r("UPDATE users SET pw_hash=? WHERE id=?",await Jn(c),p)},checkUserPasswordAsync:async(p,c)=>{let m=n("SELECT pw_hash FROM users WHERE id=?",[p]);return m!==void 0&&await gs(c,z(m.pw_hash))},setPassword:(p,c)=>{on(c),r("UPDATE users SET pw_hash=? WHERE id=?",Qn(c),p)},checkUserPassword:(p,c)=>{let m=n("SELECT pw_hash FROM users WHERE id=?",[p]);return m!==void 0&&Yn(c,z(m.pw_hash))},deleteUser:p=>{if(s()<=1)throw new I("The last user cannot be deleted.");e.tx(()=>{r("DELETE FROM sessions WHERE user_id=?",p),r("DELETE FROM users WHERE id=?",p)})},findUser:p=>{let c=n("SELECT id, username FROM users WHERE username=?",[p]);return c?{id:F(c.id),username:z(c.username)}:null},createSession:(p,c=Date.now()/1e3)=>{let m=bs(32).toString("base64url");return e.tx(()=>{r("DELETE FROM sessions WHERE expires<? OR last_seen<?",c,c-ws),r("INSERT INTO sessions(token_hash, user_id, created, last_seen, expires) VALUES(?,?,?,?,?)",tt(m),p,c,c,c+er)}),m},getSession:(p,c=Date.now()/1e3)=>{if(!p)return null;let m=n("SELECT u.id id, u.username username, s.expires expires, s.last_seen last_seen FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=?",[tt(p)]);return!m||F(m.expires)<c||c-F(m.last_seen)>ws?null:(c-F(m.last_seen)>nf&&r("UPDATE sessions SET last_seen=? WHERE token_hash=?",c,tt(p)),{id:F(m.id),username:z(m.username)})},deleteSession:p=>{p&&r("DELETE FROM sessions WHERE token_hash=?",tt(p))},deleteOtherSessions:(p,c)=>{r("DELETE FROM sessions WHERE user_id=? AND token_hash<>?",p,tt(c||""))},hasApiKeys:()=>n("SELECT 1 FROM api_keys LIMIT 1")!==void 0,createApiKey:(p,c=Date.now()/1e3)=>{let m=p.trim();if(!Di.test(m))throw new I("Key name: 1-40 characters, letters, digits and . _ -");if(n("SELECT 1 FROM api_keys WHERE name=?",[m]))throw new I("A key with this name already exists.");let y=`mw-${bs(32).toString("base64url")}`;o(m,y,c);let b=i(m)[0];if(!b)throw new Error("api key insert failed");return[b,y]},listApiKeys:i,deleteApiKey:p=>Number(r("DELETE FROM api_keys WHERE id=?",p).changes)>0,verifyApiKey:(p,c=Date.now()/1e3)=>{if(!p)return null;let m=n("SELECT id, name FROM api_keys WHERE key_hash=?",[tt(p)]);if(!m)return null;let y=F(m.id);return c-(t.get(y)??0)>60&&(t.set(y,c),r("UPDATE api_keys SET last_used=? WHERE id=?",c,y)),{id:y,name:z(m.name)}},listAccounts:()=>e.stmt("SELECT * FROM accounts ORDER BY priority, id").all().map(a),getAccount:u,createAccount:l,updateAccount:f,deleteAccount:p=>{let c=u(p);if(r("DELETE FROM accounts WHERE name=?",p),c)for(let m of Object.values(c.keys))Zn(m)},setKey:d,removeKey:(p,c)=>{let m=u(p);if(!m||!Object.hasOwn(m.keys,c))return;let y=m.keys[c];delete m.keys[c],r("UPDATE accounts SET keys=? WHERE name=?",JSON.stringify(m.keys),p),y!==void 0&&Zn(y)},keyInfo:p=>{let c={};for(let m of Ue){let y=p.keys[m];if(!y){c[m]=null;continue}let b={source:Ui(y),hint:null,ok:!0};try{b.hint=tr(Gt(y))}catch(v){b.ok=!1,b.error=v instanceof Error?v.message:String(v)}c[m]=b}return c},migrateConfig:p=>{n("SELECT 1 FROM meta WHERE k='config_migrated'")||e.tx(()=>{for(let c of p.accounts)if(!u(c.name)){l(c.name,c.priority);for(let[m,y]of Object.entries(c.keys)){let b=/^(env|keyring):/.test(y)?y:ks(c.name,m,y);d(c.name,m,{ref:b})}f(c.name,c.enabled),Object.keys(c.manual).length&&r("UPDATE accounts SET manual=? WHERE name=?",JSON.stringify(c.manual),c.name)}for(let c of p.clients)n("SELECT 1 FROM api_keys WHERE name=?",[c.name])||o(c.name,c.token,Date.now()/1e3);r("INSERT INTO meta(k, v) VALUES('config_migrated','1')")})}}}});var Rs={};Ae(Rs,{freeVibeName:()=>Ss,linkVibeLogin:()=>xs,openApp:()=>As});var As,Ss,xs,nr=E(()=>{"use strict";W();Hn();rn();nt();As=()=>{let e=es(),t=Bn(e.db_path),n=an(t);return Gn(t),n.migrateConfig(e),e.accounts.splice(0,e.accounts.length,...n.listAccounts()),{cfg:e,db:t,store:n}},Ss=(e,t="vibe-login")=>{let n=t;for(let r=2;e.getAccount(n);r++)n=`${t}-${r}`;return n},xs=(e,t)=>{let n=e.getAccount(t);if(n?.keys.vibe!==void 0&&n.keys.vibe!==Re)throw new I(`Account '${t}' already has its own Vibe key; pick another name with --name.`);n||e.createAccount(t),e.setKey(t,"vibe",{ref:Re})}});var Bi,Hi=E(()=>{Bi="x-hono-already-sent"});var Fi,qi=E(()=>{Fi=e=>((...t)=>{if(typeof t[0]=="function"){let[n,r]=t;return async function(o,i){let a=await e(o,await n(o),r);if(a)return a;await i()}}else{let[n,r,s]=t;return(async()=>{let o=await e(n,r,s);if(!o)throw new Error("Failed to upgrade WebSocket");return o})()}})});import{STATUS_CODES as pf,ServerResponse as df,createServer as mf}from"node:http";import{Http2ServerRequest as Ce,constants as hf}from"node:http2";import{Readable as Wi}from"node:stream";async function jf(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function ca(e,t,n){let r=u=>{e.cancel(u).catch(()=>{})},s=t.stream;if(t.destroyed||s?.closed||s?.destroyed)return r(),e.closed;return t.on("close",r),t.on("error",r),(n??e.read()).then(a,o),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function o(u){u&&t.destroy(u)}function i(){e.read().then(a,o)}function a({done:u,value:l}){try{u?t.end():t.write(l)?e.read().then(a,o):t.once("drain",i)}catch(f){o(f)}}}function Zi(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");if(t.destroyed){e.cancel().catch(()=>{});return}return ca(e.getReader(),t)}var ae,yf,gf,rr,Ki,zi,Ds,ta,Ms,na,bf,wf,vf,or,ra,kf,Gi,Tt,oa,Ef,_f,Ts,Cs,ia,js,Vi,ir,Xi,Af,Fe,Te,Ot,cn,aa,ua,un,Ps,Is,He,sr,Pe,Ji,ln,ar,pn,Sf,xf,Rf,Tf,Of,Cf,Pf,Us,If,Yi,$f,me,Lf,rt,$s,Rt,Oe,fn,_e,Nf,Df,Mf,Ls,ur,Qi,Uf,Bf,fa,Hf,Ff,qf,pa,lr,Ns,da,Os,ma,ha,Wf,Kf,zf,Gf,Vf,ya,ga,Xf,ba,ea,Jf,Yf,uy,Zf,wa,va=E(()=>{Hi();qi();ae=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},yf=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),gf=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,rr=e=>e===9||e===10||e===13||e===32,Ki=e=>{if(!rr(e.charCodeAt(0))&&!rr(e.charCodeAt(e.length-1)))return e;let t=0,n=e.length;for(;t<n&&rr(e.charCodeAt(t));)t++;for(;n>t&&rr(e.charCodeAt(n-1));)n--;return e.slice(t,n)},zi=/[\0\r\n]/,Ds=globalThis.Headers,ta=(e,t=Ds)=>{let n=new t;for(let r=0;r<e.length;r+=2){let s=e[r];s.startsWith(":")||n.append(s,e[r+1])}return n},Ms=class{#e;#t;#n;#o;constructor(e){this.#e=e,e instanceof Ce&&(this.#t=e.rawHeaders.slice())}get#s(){return this.#t??=this.#e.rawHeaders.slice()}get#r(){return this.#n||(this.#n=ta(this.#s),this.#t=void 0),this.#n}#u(e){if(typeof e=="string"){if(!gf.test(e))throw new TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#i(e){let t=this.#e instanceof Ce?void 0:this.#e.headers;if(!t||yf.has(e)||e==="set-cookie"||e==="__proto__")return;if(!Object.hasOwn(t,e))return null;let n=t[e];if(typeof n=="string"){let r=Ki(n);return zi.test(r)?void 0:r}}#a(e,t){let n=t==="cookie"?"; ":", ",r=null;for(let s=0;s<e.length;s+=2){let o=e[s];if(o.length===t.length&&o.toLowerCase()===t){let i=Ki(e[s+1]);if(zi.test(i)){this.#o=!0;return}r=r===null?i:r+n+i}}return r}append(e,t){this.#r.append(e,t)}delete(e){this.#r.delete(e)}get(e){let t=this.#u(e);if(t&&!this.#n&&!this.#o){let n=this.#i(t);if(n!==void 0)return n;let r=this.#a(this.#s,t);if(r!==void 0)return r}return this.#r.get(e)}has(e){let t=this.#u(e);if(t&&!this.#n&&!this.#o){let n=this.#i(t);if(n!==void 0)return n!==null;let r=this.#a(this.#s,t);if(r!==void 0)return r!==null}return this.#r.has(e)}set(e,t){this.#r.set(e,t)}getSetCookie(){return this.#r.getSetCookie()}keys(){return this.#r.keys()}values(){return this.#r.values()}entries(){return this.#r.entries()}forEach(e,t){this.#r.forEach((n,r)=>{e.call(t,n,r,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ms.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Headers (lightweight) ${n(Object.fromEntries(this),{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Ms.prototype,Ds.prototype);na=e=>globalThis.Headers===Ds?new Ms(e):ta(e.rawHeaders,globalThis.Headers),bf=/^\/[!#$&-;=?-\[\]_a-z~]*$/,wf=/\/\.\.?(?:[/?#]|$)/,vf=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,or=e=>{let t=e.indexOf("\\");if(t!==-1){let n=e.indexOf("?");if(n===-1||t<n)throw new ae("Backslash in request path")}},ra=(e,t,n)=>{let r=`${e}://${t}${n}`;if(vf.test(t)){if(n.length===0)return r+"/";if(n.charCodeAt(0)!==47)throw new ae("Invalid URL");return!bf.test(n)||wf.test(n)?(or(n),new URL(r).href):r}else{or(n);let s=new URL(r);if(s.hostname.length!==t.length&&s.hostname!==(t.includes(":")?t.replace(/:\d+$/,""):t).toLowerCase())throw new ae("Invalid host header");return s.href}},kf=e=>e instanceof ae?e:new ae(e.message,{cause:e}),Gi=global.Request,Tt=class sa extends Gi{static[Symbol.hasInstance](t){return this===sa?t instanceof Gi||Function.prototype[Symbol.hasInstance].call(this,t):Function.prototype[Symbol.hasInstance].call(this,t)}constructor(t,n){if(typeof t=="object"&&Fe in t){let r=n!==void 0&&"body"in n&&n.body!=null;if(t[Pe]&&!r)throw new TypeError("Cannot construct a Request with a Request object that has already been used.");t=t[Fe]()}typeof n?.body?.getReader<"u"&&(n.duplex??="half"),super(t,n)}},oa=Symbol("wrapBodyStream"),Ef=new Set(["latin1","binary","hex","base64","base64url"]),_f=e=>e===null||Ef.has(e),Ts=Symbol("bodyBufferedBeforeDisconnect"),Cs=Symbol("bodyBufferedLengthBeforeDisconnect"),ia=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),js=e=>!(e instanceof Ce)&&!!e.complete&&!!e.readableAborted&&typeof e.read=="function"&&_f(e.readableEncoding),Vi=e=>{if(e.readableDidRead||!js(e))return;let t=e;t[Cs]??=e.readableLength},ir=(e,t)=>{if(e.readableDidRead&&!t||!js(e))return;let n=e;if(n[Ts]!==void 0)return n[Ts];let r,s=e.errored;if(s&&s.code!=="ECONNRESET")r=s;else if(n[Cs]!==void 0&&e.readableLength!==n[Cs])r=ar();else{let o=t??[],i;for(;(i=e.read())!==null;)o.push(ia(i,e.readableEncoding));let a=o.length===1?o[0]:Buffer.concat(o);r=a;let u=e.headers["content-length"];if(typeof u=="string"&&/^\d+$/.test(u)){let l=Number(u);Number.isSafeInteger(l)&&a.length!==l&&(r=ar())}}return n[Ts]=r,r},Xi=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},Af=(e,t,n,r,s)=>{let o={method:e,headers:n,signal:s.signal};if(e==="TRACE"){o.method="GET";let i=new Tt(t,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(r.rawBody),i.close()}});else if(r[oa]){let i;o.body=new ReadableStream({async pull(a){try{if(!i){let f=ir(r);if(f!==void 0){Xi(a,f);return}}i||=Wi.toWeb(r).getReader();let{done:u,value:l}=await i.read();u?a.close():a.enqueue(l)}catch(u){a.error(u)}}})}else{let i=ir(r);i!==void 0?o.body=new ReadableStream({start(a){Xi(a,i)}}):o.body=Wi.toWeb(r)}return new Tt(t,o)},Fe=Symbol("getRequestCache"),Te=Symbol("requestCache"),Ot=Symbol("incomingKey"),cn=Symbol("urlKey"),aa=Symbol("methodKey"),ua=Symbol("headersKey"),un=Symbol("abortControllerKey"),Ps=Symbol("getAbortController"),Is=Symbol("abortRequest"),He=Symbol("bodyBuffer"),sr=Symbol("bodyReadPromise"),Pe=Symbol("bodyConsumedDirectly"),Ji=Symbol("bodyLockReader"),ln=Symbol("abortReason"),ar=()=>new TypeError("Body is unusable"),pn=()=>Promise.reject(ar()),Sf=new TextDecoder,xf=e=>{if(e[Pe])return pn();e[Pe]=!0},Rf=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),Tf=e=>(e[ua]||=na(e[Ot])).get("content-type")||"",Of=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Cf=e=>{if(typeof e!="string"||e.length===0)return"GET";switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":case"QUERY":return e}let t=e.toUpperCase();switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"POST":case"PUT":return t;default:return e}},Pf=e=>{if(!Of.test(e))return new TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t==="CONNECT"||t==="TRACK"||t==="TRACE"&&e!=="TRACE")return new TypeError(`'${e}' HTTP method is unsupported.`)},Us=(e,t,n)=>{if(e[Pe])return pn();let r=e.method;if(r==="GET"||r==="HEAD")return e[Fe]()[t]();let s=Pf(r);if(s)return Promise.reject(s);if(e[Te]&&r!=="TRACE")return e[Te][t]();let o=xf(e);if(o)return o;let i=If(e);if(i){let a=Promise.resolve(n(i,e));return e[He]=void 0,a}return $f(e).then(a=>{let u=n(a,e);return e[He]=void 0,u})},If=e=>{let t=e[Ot];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},Yi=(e,t)=>{if(t.errored)return t.errored;let n=e[ln];return n!==void 0?n instanceof Error?n:new Error(String(n)):new Error("Client connection prematurely closed.")},$f=e=>{if(e[He])return Promise.resolve(e[He]);if(e[sr])return e[sr];let t=e[Ot];if(t.readableDidRead)return pn();let n=ir(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[He]=n,Promise.resolve(n));let r=new Promise((s,o)=>{let i=[],a=!1,u=y=>{a||(a=!0,m(),y())},l=y=>{let b=t.errored??y;return!js(t)||b&&b.code!=="ECONNRESET"?!1:(u(()=>{let v=ir(t,i);v instanceof Error?o(v):v===void 0?o(y??Yi(e,t)):(e[He]=v,s(v))}),!0)},f=y=>{i.push(ia(y,t.readableEncoding))},d=()=>{u(()=>{let y=i.length===1?i[0]:Buffer.concat(i);e[He]=y,s(y)})},p=y=>{l(y)||u(()=>{o(y)})},c=()=>{if(t.readableEnded){d();return}l()||u(()=>{o(Yi(e,t))})},m=()=>{t.off("data",f),t.off("end",d),t.off("error",p),t.off("close",c),e[sr]=void 0};t.on("data",f),t.on("end",d),t.on("error",p),t.on("close",c),queueMicrotask(()=>{a||(t.readableEnded?d():t.errored?p(t.errored):t.destroyed&&c())})});return e[sr]=r,r},me={get method(){return this[aa]},get url(){return this[cn]},get headers(){return this[ua]||=na(this[Ot])},[Is](e){this[ln]===void 0&&(this[ln]=e);let t=this[un];t&&!t.signal.aborted&&t.abort(e)},[Ps](){return this[un]||=new AbortController,this[ln]!==void 0&&!this[un].signal.aborted&&this[un].abort(this[ln]),this[un]},[Fe](){let e=this[Ps]();if(this[Te])return this[Te];let t=this.method;if(this[Pe]&&!(t==="GET"||t==="HEAD")){this[He]=void 0;let n={method:t==="TRACE"?"GET":t,headers:this.headers,signal:e.signal};t!=="TRACE"&&(n.body=new ReadableStream({start(s){s.close()}}),n.duplex="half");let r=new Tt(this[cn],n);return t==="TRACE"&&Object.defineProperty(r,"method",{get(){return"TRACE"}}),this[Te]=r}return this[Te]=Af(this.method,this[cn],this.headers,this[Ot],e)},get body(){if(!this[Pe])return this[Fe]().body;let e=this[Fe]();return!this[Ji]&&e.body&&(this[Ji]=e.body.getReader()),e.body},get bodyUsed(){return this[Pe]?!0:this[Te]?this[Te].bodyUsed:!1}};Object.defineProperty(me,"signal",{get(){return this[Ps]().signal}});["cache","credentials","destination","duplex","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(me,e,{get(){return this[Fe]()[e]}})});["clone","formData"].forEach(e=>{Object.defineProperty(me,e,{value:function(){if(this[Pe]){if(e==="clone")throw ar();return pn()}return this[Fe]()[e]()}})});Object.defineProperty(me,"text",{value:function(){return Us(this,"text",e=>Sf.decode(e))}});Object.defineProperty(me,"arrayBuffer",{value:function(){return Us(this,"arrayBuffer",e=>Rf(e))}});Object.defineProperty(me,"blob",{value:function(){return Us(this,"blob",(e,t)=>{let n=Tf(t),r=n?{headers:{"content-type":n}}:void 0;return new Response(e,r).blob()})}});Object.defineProperty(me,"bytes",{value:function(){return this.arrayBuffer().then(e=>new Uint8Array(e))}});Object.defineProperty(me,"json",{value:function(){return this[Pe]?pn():this.text().then(JSON.parse)}});Object.defineProperty(me,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Te]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(me,Tt.prototype);Lf=(e,t)=>{let n=Object.create(me);n[Ot]=e,n[aa]=Cf(e.method);let r=e.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(e instanceof Ce)throw new ae("Absolute URL for :path is not allowed in HTTP/2");try{or(r),n[cn]=new URL(r).href}catch(i){throw new ae("Invalid absolute URL",{cause:i})}return n}let s=(e instanceof Ce?e.authority:e.headers.host)||t;if(!s)throw new ae("Missing host header");let o;if(e instanceof Ce){if(o=e.scheme,!(o==="http"||o==="https"))throw new ae("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";try{n[cn]=ra(o,s,r)}catch(i){throw i instanceof ae?i:new ae("Invalid URL",{cause:i})}return n},rt="text/plain; charset=UTF-8",$s=Symbol("responseCache"),Rt=Symbol("getResponseCache"),Oe=Symbol("cache"),fn=global.Response,_e=class la{#e;#t;static[Symbol.hasInstance](t){return this===la?t instanceof fn||Function.prototype[Symbol.hasInstance].call(this,t):Function.prototype[Symbol.hasInstance].call(this,t)}[Rt](){let t=this[Oe],n=t&&t[2]instanceof Headers?t[2]:void 0;return delete this[Oe],this[$s]||=new fn(this.#e,n?{status:this.#t?.status,statusText:this.#t?.statusText,headers:n}:this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof fn){let s=n[$s];if(s){this.#t=s,this[Rt]();return}this.#t=#t in n?n.#t:n,r=new Headers(n.headers)}else this.#t=n;(t==null||typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[Oe]=[n?.status||200,t??null,r||n?.headers])}get headers(){let t=this[Oe];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||(t[1]===null?void 0:{"content-type":rt}))),t[2]):this[Rt]().headers}get status(){return this[Oe]?.[0]??this[Rt]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(_e.prototype,e,{get(){return this[Rt]()[e]}})});["arrayBuffer","blob","bytes","clone","formData","json","text"].forEach(e=>{Object.defineProperty(_e.prototype,e,{value:function(){return this[Rt]()[e]()}})});Object.defineProperty(_e.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[$s]},{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(_e,fn);Object.setPrototypeOf(_e.prototype,fn.prototype);Nf=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,Df=e=>e instanceof URL?e.href:Nf.test(e)?e:new URL(e).href,Mf=new Set([301,302,303,307,308]);Object.defineProperty(_e,"redirect",{value:function(t,n=302){if(!Mf.has(n))throw new RangeError("Invalid status code");return new _e(null,{status:n,headers:{location:Df(t)}})},writable:!0,configurable:!0});Object.defineProperty(_e,"json",{value:function(t,n){let r=JSON.stringify(t);if(r===void 0)throw new TypeError("The data is not JSON serializable");let s=n?.headers,o;return s?(o=new Headers(s),o.has("content-type")||o.set("content-type","application/json")):o={"content-type":"application/json"},new _e(r,{status:n?.status??200,statusText:n?.statusText,headers:o})},writable:!0,configurable:!0});Ls=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has("set-cookie")){let r=[];for(let[s,o]of e)s==="set-cookie"?r.push(o):n[s]=o;r.length>0&&(n["set-cookie"]=r)}else for(let[r,s]of e)n[r]=s;return t&&(n["content-type"]??=t),n},ur=Symbol("outgoingEnded"),Qi=Symbol("incomingDraining"),Uf=500,Bf=64*1024*1024,fa=e=>{let t=e;if(e.destroyed||t[Qi])return;if(t[Qi]=!0,e instanceof Ce){try{e.stream?.close?.(hf.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(o),e.off("data",i),e.off("end",r),e.off("error",r)},s=()=>{r();let a=e.socket;a&&!a.destroyed&&(typeof a.destroySoon=="function"?a.destroySoon():typeof a.destroy=="function"&&a.destroy())},o=setTimeout(s,Uf);o.unref?.();let i=a=>{n+=a.length,n>Bf&&s()};e.on("data",i),e.on("end",r),e.on("error",r),e.resume()},Hf=(e,t,n,r)=>()=>{t.errored?(Vi(t),e[Is](t.errored.toString())):(!n.writableFinished||t instanceof Ce&&t.aborted)&&(Vi(t),e[Is]("Client connection prematurely closed.")),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{fa(t)})})},Ff=e=>{if(!(Oe in e))return!1;let t=e[Oe][1];return t===null||typeof t=="string"||t instanceof Uint8Array},qf=()=>new Response(null,{status:400}),pa=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),lr=(e,t)=>{let n=e instanceof Error?e:new Error("unknown error",{cause:e});n.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||(t instanceof df&&(t._contentLength=null),t.writeHead(500,{"Content-Type":"text/plain"})),t.end(`Error: ${n.message}`),t.destroy(n))},Ns=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},da=(e,t,n)=>{let r=e;return r._contentLength===null&&r._hasBody&&r.useChunkedEncodingByDefault&&!r._removedContLen&&t>=200&&t!==204&&t!==304&&!e.hasHeader("content-length")&&!e.hasHeader("transfer-encoding")&&!e.hasHeader("trailer")?(r._contentLength=n,!0):!1},Os=(e,t,n)=>{da(e,t,n)?e.writeHead(t,{"Content-Type":rt}):e.writeHead(t,{"Content-Type":rt,"Content-Length":n})},ma=async(e,t)=>{let[n,r,s]=e[Oe];if(!s){r===null?(t.writeHead(n),t.end()):typeof r=="string"?(Os(t,n,Buffer.byteLength(r)),t.end(r)):r instanceof Uint8Array?(Os(t,n,r.byteLength),t.end(r)):r instanceof Blob?(Os(t,n,r.size),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":rt}),Ns(t),await Zi(r,t)?.catch(u=>lr(u,t))),t[ur]?.();return}let o=!1,i=!1,a=!0;if(s instanceof Headers)o=s.has("content-length"),s=Ls(s,r===null?void 0:rt);else if(Array.isArray(s)){let u=new Headers(s);o=u.has("content-length"),s=Ls(u,r===null?void 0:rt)}else{i=!0;for(let u in s){if(u.length===14&&u.toLowerCase()==="content-length"){o=!0;break}(u.length===17&&u.toLowerCase()==="transfer-encoding"||u.length===7&&u.toLowerCase()==="trailer")&&(a=!1)}}if(!o){let u;typeof r=="string"?u=Buffer.byteLength(r):r instanceof Uint8Array?u=r.byteLength:r instanceof Blob&&(u=r.size),u!==void 0&&(!i||!a||!da(t,n,u))&&(i&&(s={...s}),s["Content-Length"]=u)}t.writeHead(n,s),r==null?t.end():typeof r=="string"||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(Ns(t),await Zi(r,t)?.catch(u=>lr(u,t))),t[ur]?.()},ha=e=>typeof e.then=="function",Wf=async(e,t,n={})=>{if(ha(e))if(n.errorHandler)try{e=await e}catch(s){let o=await n.errorHandler(s);if(!o)return;e=o}else e=await e.catch(pa);if(Oe in e)return ma(e,t);let r=Ls(e.headers,e.body===null?void 0:rt);if(e.body){let s=e.body.getReader(),o=[],i=!1,a;if(r["transfer-encoding"]!=="chunked"){let u=2;for(let l=0;l<u;l++){a||=s.read();let f=await jf(a);if(!f){if(l===1){await new Promise(d=>setTimeout(d)),u=3;continue}break}if(a=void 0,f.value&&o.push(f.value),f.done){i=!0;break}}i&&!("content-length"in r)&&(r["content-length"]=o.reduce((l,f)=>l+f.length,0))}t.writeHead(e.status,r),o.forEach(u=>{t.write(u)}),i?t.end():(o.length===0&&Ns(t),await ca(s,t,a))}else r[Bi]||(t.writeHead(e.status,r),t.end());t[ur]?.()},Kf=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Tt&&(Object.defineProperty(global,"Request",{value:Tt}),Object.defineProperty(global,"Response",{value:_e})),async(r,s)=>{let o,i,a=!1,u=!1,l=()=>{!i||u||(u=!0,s.on("close",Hf(i,r,s,a)))};try{if(i=Lf(r,t.hostname),a=n&&!(r.method==="GET"||r.method==="HEAD"),a&&(r[oa]=!0,r instanceof Ce&&(s[ur]=()=>{r.readableEnded||setTimeout(()=>{r.readableEnded||setTimeout(()=>{r.destroy(),s.destroy()})})})),o=e(i,{incoming:r,outgoing:s}),!ha(o)&&Ff(o))return a&&!r.readableEnded&&s.once("finish",()=>{r.readableEnded||fa(r)}),ma(o,s);l()}catch(f){if(o)return lr(f,s);if(t.errorHandler){if(l(),o=await t.errorHandler(i?f:kf(f)),!o)return}else i?o=pa(f):o=qf()}try{return await Wf(o,s,t)}catch(f){return lr(f,s)}}},zf=globalThis.CloseEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get wasClean(){return this.#e.wasClean??!1}get code(){return this.#e.code??0}get reason(){return this.#e.reason??""}},Gf=globalThis.ErrorEvent??class extends Event{#e;constructor(e,t={}){super(e,t),this.#e=t}get message(){return this.#e.message??""}get filename(){return this.#e.filename??""}get lineno(){return this.#e.lineno??0}get colno(){return this.#e.colno??0}get error(){return this.#e.error??null}},Vf=()=>Symbol("connection"),ya=Symbol("CONNECTION_SYMBOL_KEY"),ga=Symbol("WAIT_FOR_WEBSOCKET_SYMBOL"),Xf=new Set(["connection","content-length","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-accept","sec-websocket-extensions","sec-websocket-protocol"]),ba=(e,t)=>{t&&t.forEach((n,r)=>{Xf.has(r.toLowerCase())||e.push(`${r}: ${n}`)})},ea=(e,t,n)=>{if(e.destroyed)return;let r=["Connection: close","Content-Length: 0"];ba(r,n),e.end(`HTTP/1.1 ${t.toString()} ${pf[t]??""}\r
|
|
124
|
+
${r.join(`\r
|
|
125
|
+
`)}\r
|
|
126
|
+
\r
|
|
127
|
+
`)},Jf=e=>{let t=e.socket.encrypted?"https":"http",n=e.url??"/",r;n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))?(or(n),r=new URL(n).href):r=ra(t,e.headers.host??"localhost",n);let s=new Headers;for(let o in e.headers){let i=e.headers[o];i&&s.append(o,Array.isArray(i)?i[0]:i)}return new Request(r,{headers:s})},Yf=e=>{let{server:t,fetchCallback:n,wss:r}=e,s=new Map;r.on("connection",(a,u)=>{let l=s.get(u);l&&(l.resolve(a),s.delete(u))});let o=a=>{let u=s.get(a);u&&(s.delete(a),u.reject(new Error("WebSocket handshake aborted")))},i=(a,u)=>new Promise((l,f)=>{s.set(a,{resolve:l,reject:f,connectionSymbol:u})});t.on("upgrade",async(a,u,l)=>{if(a.headers.upgrade?.toLowerCase()!=="websocket")return;let f=()=>{},d=()=>o(a);u.on("error",f),u.once("close",d);let p={incoming:a,outgoing:void 0,wss:r,[ga]:i},c=400,m;try{let v=await n(Jf(a),p);v instanceof Response&&(c=v.status,m=v.headers)}catch(v){t.listenerCount("upgrade")===1&&ea(u,v instanceof ae?400:500);return}if(u.destroyed){o(a);return}let y=s.get(a);if(!y||y.connectionSymbol!==p[ya]){o(a),t.listenerCount("upgrade")===1&&ea(u,c,m);return}let b=v=>{ba(v,m)};r.on("headers",b);try{r.handleUpgrade(a,u,l,v=>{u.off("close",d),u.off("error",f),r.emit("connection",v,a)})}finally{r.off("headers",b)}}),t.on("close",()=>{r.close()})},uy=Fi(async(e,t,n)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let r=e.env,s=r[ga];if(!s||!r.incoming)return new Response(null,{status:500});let o=Vf();return r[ya]=o,(async()=>{let i;try{i=await s(r.incoming,o)}catch{return}let a=[],u=(d,p)=>{a.push([d,p])};i.on("message",u);let l={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),l)}catch(d){(n?.onError??console.error)(d)}let f=(d,p)=>{let c=Array.isArray(d)?d:[d];for(let m of c)try{t?.onMessage?.(new MessageEvent("message",{data:p?m instanceof ArrayBuffer?m:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength):typeof m=="string"?m:Buffer.from(m).toString("utf-8")}),l)}catch(y){(n?.onError??console.error)(y)}};i.off("message",u);for(let d of a)f(...d);i.on("message",(d,p)=>{f(d,p)}),i.on("close",(d,p)=>{try{t?.onClose?.(new zf("close",{code:d,reason:p.toString()}),l)}catch(c){(n?.onError??console.error)(c)}}),i.on("error",d=>{try{t?.onError?.(new Gf("error",{error:d}),l)}catch(p){(n?.onError??console.error)(p)}})})(),new Response}),Zf=e=>{let t=e.fetch,n=Kf(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),r=(e.createServer||mf)(e.serverOptions||{},n);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");Yf({server:r,fetchCallback:t,wss:e.websocket.server})}return r},wa=(e,t)=>{let n=Zf(e);return n.listen(e?.port??3e3,e.hostname,()=>{let r=n.address();t&&t(r)}),n}});var dn,Bs=E(()=>{dn=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}}});var Ct,cr=E(()=>{Ct=Symbol()});var ka=E(()=>{});var Ea,_a=E(()=>{ka();Ea=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData()});async function ep(e,t){if(!fr(e)&&e.bodyCache.formData)return Aa(await e.bodyCache.formData,t);let n=fr(e)?e.headers:e.raw.headers,r=await e.arrayBuffer(),s=Ea(r,n.get("Content-Type")||"");fr(e)||(e.bodyCache.formData=s);let o=await s;return o?Aa(o,t):{}}function Aa(e,t){let n=Object.create(null),r={count:0};return e.forEach((s,o)=>{t.all||o.endsWith("[]")?tp(n,o,s):n[o]=s}),t.dot&&Object.entries(n).forEach(([s,o])=>{s.includes(".")&&(np(n,s,o,r),delete n[s])}),n}var Qf,fr,xa,tp,np,Sa,Ra=E(()=>{_a();Qf=1e4,fr=e=>"headers"in e,xa=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,s=(fr(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return s==="multipart/form-data"||s==="application/x-www-form-urlencoded"?ep(e,{all:n,dot:r}):{}};tp=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n},np=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let s=e,o=t.split(".",34);o.length>33&&Sa(),o.forEach((i,a)=>{a===o.length-1?s[i]=n:((!s[i]||typeof s[i]!="object"||Array.isArray(s[i])||s[i]instanceof File)&&(r.count++>=Qf&&Sa(),s[i]=Object.create(null)),s=s[i])})},Sa=()=>{throw new Error("Nesting limit exceeded")}});var qs,mn,rp,sp,pr,hn,dr,Hs,Ws,Ta,st,mr,Pt,Fs,Oa,Ca,Pa,op,Ie=E(()=>{qs=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},mn=e=>{let{groups:t,path:n}=rp(e),r=qs(n);return sp(r,t)},rp=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},sp=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},pr={},hn=(e,t)=>{if(e==="*")return"*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return pr[r]||(n[2]?pr[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:pr[r]=[e,n[1],!0]),pr[r]}return null},dr=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},Hs=e=>decodeURI(e.includes("%25")?e.replace(/%25/g,"%2525"):e),Ws=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let o=t.indexOf("?",r),i=t.indexOf("#",r),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),u=t.slice(n,a),l=dr(u,Hs);if(/%(?![0-9A-Fa-f]{2})/.test(u)){let f=new URL("http://localhost");if(f.pathname=l.replace(/[\\\t\n\r]/g,encodeURIComponent),dr(f.pathname,Hs)!==l)return dr(u.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"),Hs)}return l}else if(s===63||s===35)break}return t.slice(n,r)},Ta=e=>{let t=Ws(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},st=(e,t,...n)=>(n.length&&(t=st(t,...n)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),mr=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),n=[],r="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(s.charCodeAt(s.length-1)===63){n.length===0&&r===""?n.push("/"):n.push(r);let o=s.slice(0,-1);r+="/"+o,n.push(r)}else r+="/"+s}),n.filter((s,o,i)=>i.indexOf(s)===o)},Pt=e=>e.indexOf("%")!==-1?dr(e,op):e,Fs=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Pt(e)),Oa=(e,t,n)=>{let r=e.indexOf("#",8);r!==-1&&(e=e.slice(0,r));let s;if(!n&&t&&!/[%+&=]/.test(t)){let a=e.indexOf("?",8),u=a;if(u===-1)return;for(e.startsWith(t,u+1)||(u=e.indexOf(`&${t}`,u+1));u!==-1;){let l=e.charCodeAt(u+t.length+1);if(l===61||l===38||isNaN(l)){if(u>a&&/(?:^|&)[^=&]*[%+]/.test(e.slice(a+1,u)))break;if(l===61){let f=u+t.length+2,d=e.indexOf("&",f);return Fs(e.slice(f,d===-1?void 0:d))}return""}u=e.indexOf(`&${t}`,u+1)}if(s=/[%+]/.test(e),!s)return}let o=Object.create(null);s??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),u=e.indexOf("=",i);u>a&&a!==-1&&(u=-1);let l=e.slice(i+1,u===-1?a===-1?void 0:a:u);if(s&&(l=Fs(l)),i=a,l==="")continue;let f;u===-1?f="":(f=e.slice(u+1,a===-1?void 0:a),s&&(f=Fs(f))),n?(o[l]&&Array.isArray(o[l])||(o[l]=[]),o[l].push(f)):o[l]??=f}return t?o[t]:o},Ca=Oa,Pa=(e,t)=>Oa(e,t,!0),op=decodeURIComponent});var Ia,$a=E(()=>{Bs();cr();Ra();Ie();Ia=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#o()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#s(t);return n&&Pt(n)}#o(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let r=this.#s(this.#t[0][this.routeIndex][1][n]);r!==void 0&&(e[n]=Pt(r))}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Ca(this.url,e)}queries(e){return Pa(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return xa(this,e)}#r=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let s in t)return t[s].then(o=>{s==="json"&&(o=JSON.stringify(o));let i=s==="formData"?void 0:n.headers.get("content-type");return new Response(o,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=n[e]()};json(){return this.#r("text").then(e=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}bytes(){return this.#r("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#r("blob")}formData(){return this.#r("formData")}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ct](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}}});var La,ip,Ks,Na=E(()=>{La={Stringify:1,BeforeStream:2,Stream:3},ip=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Ks=async(e,t,n,r,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let i=Promise.all(o.map(a=>a({phase:t,buffer:s,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(u=>Ks(u,t,!1,r,s))).then(()=>s[0]));return n?ip(await i,o):i}});var ap,zs,yn,Gs,Vs=E(()=>{$a();Na();ap="text/plain; charset=UTF-8",zs=(e,t)=>({"Content-Type":e,...t}),yn=(e,t)=>new Response(e,t),Gs=class{#e;#t;env={};#n;finalized=!1;error;#o;#s;#r;#u;#i;#a;#c;#f;#p;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#a=t.notFoundHandler,this.#p=t.path,this.#f=t.matchResult)}get req(){return this.#t??=new Ia(this.#e,this.#p,this.#f),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#r||=yn(null,{headers:this.#c??=new Headers})}set res(e){if(this.#r&&e){e=yn(e.body,e);for(let[t,n]of this.#r.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s)}else e.headers.set(t,n)}this.#r=e,this.finalized=!0}render=(...e)=>(this.#i??=t=>this.html(t),this.#i(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#i=e};header=(e,t,n)=>{this.finalized&&!this.#r.bodyUsed&&(this.#r=yn(this.#r.body,this.#r));let r=this.#r?this.#r.headers:this.#c??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#l(e,t,n){let r=this.#r?new Headers(this.#r.headers):this.#c;if(typeof t=="object"&&t.headers){r??=new Headers;for(let[o,i]of new Headers(t.headers))o==="set-cookie"?r.append(o,i):r.set(o,i)}if(n){if(!r){let o=0;for(let i in n)if(++o>1||typeof n[i]!="string"){r=new Headers;break}}if(r)for(let o in n){let i=n[o];if(typeof i=="string")r.set(o,i);else{r.delete(o);for(let a of i)r.append(o,a)}}}let s=typeof t=="number"?t:t?.status??this.#o;return yn(e,{status:s,headers:r??n})}newResponse=(...e)=>this.#l(...e);body=(e,t,n)=>this.#l(e,t,n);text=(e,t,n)=>!this.#c&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#l(e,t,zs(ap,n));json=(e,t,n)=>this.#l(JSON.stringify(e),t,zs("application/json",n));html=(e,t,n)=>{let r=s=>this.#l(s,t,zs("text/html; charset=UTF-8",n));return typeof e=="object"?Ks(e,La.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#a??=()=>yn(),this.#a(this))}});var Xs,Da=E(()=>{Xs=(e,t,n)=>(r,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let u,l=!1,f;if(e[a]?(f=e[a][0][0],r.req.routeIndex=a):f=a===e.length&&s||void 0,f)try{u=await f(r,()=>i(a+1))}catch(d){if(d instanceof Error&&t)r.error=d,u=await t(d,r),l=!0;else throw d}else r.finalized===!1&&n&&(u=await n(r));return u&&(r.finalized===!1||l)&&(r.res=u),r}}});var up,Ma,ja=E(()=>{cr();Ie();up=e=>e.req[Ct][0].map(([[,t]])=>t),Ma=(e,t)=>up(e).at(t??e.req.routeIndex)?.path??""});var Ua,hr,yr,It=E(()=>{Ua=["get","post","put","delete","options","patch","query"],hr="Can not add a route since the matcher is already built.",yr=class extends Error{}});var Ba,Ha=E(()=>{Ba="__COMPOSED_HANDLER"});var Fa,lp,qa,Wa=E(()=>{Bs();cr();Ie();Fa=e=>{let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.length-t},lp=(e,t,n)=>{if(!/[:*]/.test(t))return t.length;let r=e.req.path,s=e.req[Ct],o=new Set,i=0;for(let a of mn(t)){if(a[0]===":"&&a.endsWith("}?"))throw new Error(`mount(): Optional regular expression parameters are not supported in "${n}".`);let u=hn(a);if(u&&u!=="*"){let l=u[1];if(o.has(l))throw new Error(`mount(): Duplicate path parameter "${l}" in "${n}".`);o.add(l)}if(u&&u!=="*"&&u[2]!==!0){let l=s.length===2?s[1][s[0][e.req.routeIndex][1][u[1]]]:s[0][e.req.routeIndex][1][u[1]];i+=l.length+1}else if(u||a.endsWith("*")){let l=r.indexOf("/",i+1);i=l===-1?r.length:l}else i+=a.length+1}return i},qa=(e,t,n)=>{if(/[^/]\*$/.test(n))throw new Error(`mount(): Wildcard must follow "/" in "${n}".`);let r=lp(e,t,n),s=e.req.path.slice(r)||"/";if(r>e.req.path.length||s[0]!=="/"||/\/(?:\.|%2e){1,2}(?:\/|$)/i.test(s))throw new dn(400,{message:"Invalid mounted path"});let o=e.req.raw.url;if(/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(o))throw new dn(400,{message:"Invalid mounted path"});let i=o.search(/[?#]/),a=Fa(i===-1?o:o.slice(0,i));if(a>1&&Fa(e.req.path)===a-1)throw new dn(400,{message:"Invalid mounted path"});let u=new URL(o);return u.pathname=s.replace(/[\\\t\n\r]/g,encodeURIComponent),s.includes("%"),new Request(u,e.req.raw)}});var cp,Ka,za,Va=E(()=>{Da();Ie();Vs();ja();It();Ha();Wa();cp=e=>e.text("404 Not Found",404),Ka=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},za=class Ga{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Ua,"all"].forEach(s=>{this[s]=(o,...i)=>{let a=s.toUpperCase();return typeof o=="string"?this.#e=o:this.#o(a,this.#e,o),i.forEach(u=>{this.#o(a,this.#e,u)}),this}}),this.on=(s,o,...i)=>{for(let a of[o].flat()){this.#e=a;for(let u of[s].flat()){let l=u.toUpperCase();for(let f of i)this.#o(l,this.#e,f)}}return this},this.use=(s,...o)=>(typeof s=="string"?this.#e=s:(this.#e="*",o.unshift(s)),o.forEach(i=>{this.#o("ALL",this.#e,i)}),this);let{strict:n,...r}=t;Object.assign(this,r),this.getPath=n??!0?t.getPath??Ws:Ta}#t(){let t=new Ga({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=cp;errorHandler=Ka;route(t,n){let r=this.basePath(t);return n.routes.map(s=>{let o;n.errorHandler===Ka?o=s.handler:(o=async(i,a)=>(await Xs([],n.errorHandler)(i,()=>s.handler(i,a))).res,o[Ba]=s.handler),r.#o(s.method,s.path,o,s.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=st(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,r){let s,o;r&&(typeof r=="function"?o=r:(o=r.optionHandler,r.replaceRequest===!1?s=l=>l:s=r.replaceRequest));let i=o?l=>{let f=o(l);return Array.isArray(f)?f:[f]}:l=>{let f;try{f=l.executionCtx}catch{}return[l.env,f]},a=l=>{let f=Ma(l);return qa(l,f.replace(/\/?\*$/,""),f)},u=async(l,f)=>{let d=await n(s?s(l.req.raw):a(l),...i(l));if(d)return d;await f()};return this.#o("ALL",st(t,"*"),u),this}#o(t,n,r,s){n=st(this._basePath,n);let o={basePath:s!==void 0?st(this._basePath,s):this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,o]),this.routes.push(o)}#s(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return(async()=>new Response(null,await this.#r(t,n,r,"GET")))();let o=this.getPath(t,{env:r}),i=this.router.match(s,o),a=new Gs(t,{path:o,matchResult:i,env:r,executionCtx:n,notFoundHandler:this.#n});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#n(a)})}catch(f){return this.#s(f,a)}return l instanceof Promise?l.then(f=>f||(a.finalized?a.res:this.#n(a))).catch(f=>this.#s(f,a)):l??this.#n(a)}let u=Xs(i[0],this.errorHandler,this.#n);return(async()=>{try{let l=await u(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#s(l,a)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${st("/",t)}`,n),r,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}}});var te,gn=E(()=>{te=()=>Object.create(null)});function Xa(e,t){let n=this.buildAllMatchers(),r=((s,o)=>{let i=n[s]||n.ALL,a=i[2][o];if(a)return a;let u=o.match(i[0]);if(!u)return[[],Js];let l=u.indexOf("",1);return[i[1][l],u]});return this.match=r,r(e,t)}var Js,Ja=E(()=>{It();Js=[]});function mp(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e==="[^]*"||e==="(?:|/[^]*)"?t==="[^]*"?-1:1:t==="[^]*"||t==="(?:|/[^]*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var fp,pp,dp,qe,Ya,Za,Zs=E(()=>{gn();fp="[^/]+",pp="[^]*",dp="(?:|/[^]*)",qe=Symbol(),Ya=new Set(".\\+*[^]$()");Za=class Ys{#e;#t;#n=te();insert(t,n,r,s,o){let i=this;for(let a=0,u=t.length;a<u;a++){let l=t[a],f=l.length===1?l==="*"?a===u-1?["","",pp]:["","",fp]:null:l==="/*"?["","",dp]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(f){let p=f[1],c=f[2]||"[^/]+";if(p&&f[2]&&(new RegExp(c).test("")||(c=c.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(c))||c.length===1&&Ya.has(c)))throw qe;if(o.push(c),d=i.#n[c],!d){if(c!=="[^]*"&&c!=="(?:|/[^]*)"){for(let m in i.#n)if((c.length>1||m.length>1)&&m!=="[^]*"&&m!=="(?:|/[^]*)")throw qe}d=i.#n[c]=new Ys}p!==""&&(d.#t??=s.varIndex++,r.push([p,d.#t]))}else if(o.push(l),d=i.#n[l],!d){for(let p in i.#n)if(p.length>1&&p!=="[^]*"&&p!=="(?:|/[^]*)")throw qe;d=i.#n[l]=new Ys}i=d}if(i.#e!==void 0)throw qe;i.#e=n}buildRegExpStr(){let t=Object.keys(this.#n).sort(mp).map(n=>{let r=this.#n[n],s=r.buildRegExpStr();return s===""?"":(typeof r.#t=="number"?`(${n})@${r.#t}`:Ya.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#e=="number"&&this.#e!==-1&&t.unshift(`#${this.#e}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}}});var Qs,Qa=E(()=>{gn();Zs();Qs=class{#e={varIndex:0};#t=new Za;#n=0;paths=te();insert(e,t){let n=[];if(t){this.#t.insert(e.split(""),-1,[],this.#e,n),this.paths[e]=[-1,[],n];return}let r=[],s=[],o=e;for(let a=0;;){let u=!1;if(o=o.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,l=>{let f=`@\\${a}`;return s[a]=[f,l],a++,u=!0,f}),!u)break}let i=o.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let a=s.length-1;a>=0;a--){let[u]=s[a];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(u)!==-1){i[l]=i[l].replace(u,s[a][1]);break}}this.#t.insert(i,this.#n,r,this.#e,n),this.paths[e]=[this.#n++,r,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>o!==void 0?(n[++t]=Number(o),"$()"):(i!==void 0&&(r[Number(i)]=++t),"")),[new RegExp(`^${e}`),n,r]}}});function hp(e){let t=e[e.length-1];return t==="[^]*"||t==="(?:|/[^]*)"}function yp(e,t){let n=e.length-1;for(let r=0;r<n;r++)if(e[r]!==t[r])return!1;return e[n]==="[^]*"||t.length===n||t[n]==="/"}var eu,tu=E(()=>{Ie();It();gn();Ja();Zs();Qa();eu=class{name="RegExpRouter";#e;#t;constructor(){this.#e={ALL:[]},this.#t={ALL:new Qs}}#n(e,t){try{this.#t[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===qe?new yr(t):n}}add(e,t,n){let r=this.#e;if(!r)throw new Error(hr);let s=this.#t;if(!r[e]){s[e]=new Qs,r[e]=[...r.ALL];for(let a in s.ALL.paths)this.#n(e,a)}t==="/*"&&(t="*");let o=e==="ALL"?Object.keys(r):[e],i=mr(t)||[t];for(let a of i)for(let u of o)s[u].paths[a]||this.#n(u,a),r[u].push([n,a])}match=Xa;buildAllMatchers(){let e=te();for(let t of Object.keys(this.#e))e[t]=this.#o(t);return this.#e=this.#t=void 0,e}#o(e){let t=this.#e[e],n=this.#t[e],r=te(),s=[],[o,i,a]=n.buildRegExp(),u=te(),l=t.map(([d,p],c)=>((u[p]??=[]).push(c),[d,n.paths[p][1].reduceRight((m,[y,b])=>(m[y]=a[b],m),te())])),f=Object.keys(u).filter(d=>hp(n.paths[d][2]));for(let d in n.paths){let[p,,c]=n.paths[d],m=[...u[d]];for(let b of f)b!==d&&yp(n.paths[b][2],c)&&m.push(...u[b]);let y=m.sort((b,v)=>b-v).map(b=>l[b]);if(p===-1){let b=Math.max(-1,...y.flatMap(([,v])=>Object.values(v)));r[d]=[y,b===-1?Js:d.match(o).slice(0,b+1)]}else s[p]=y}return[o,i.map(d=>s[d]),r]}}});var nu,ru=E(()=>{It();nu=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw new Error(hr);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,r=this.#t,s=n.length,o=0,i;for(;o<s;o++){let a=n[o];try{for(let u=0,l=r.length;u<l;u++)a.add(...r[u]);i=a.match(e,t)}catch(u){if(u instanceof yr)continue;throw u}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(o===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}}});var eo,gp,su,iu=E(()=>{Ie();It();gn();eo=te(),gp=0,su=class ou{#e=[];#t=te();#n=[];#o;#s=eo;insert(t,n,r){let s=this,o=mn(n),i=new Set,a=0;for(let u of o){let l=o[++a],f=hn(u,l)||(l===void 0&&u&&u.indexOf("*")===u.length-1?u:null),d=Array.isArray(f),p=d?f[0]:f||u,c=s.#t[p]||=new ou;f&&!c.#o&&(c.#o=f,s.#n.push(c)),s=c,d&&i.add(f[1])}s.#e.push({[t]:{handler:r,possibleKeys:[...i],score:++gp}})}#r(t,n,r,s,o){for(let i=0,a=n.#e.length;i<a;i++){let u=n.#e[i],l=u[r]||u.ALL;if(l){l.params=te(),t.push(l);for(let f=0,d=l.possibleKeys.length;f<d;f++){let p=l.possibleKeys[f];l.params[p]=o?.[p]&&!f?o[p]:s[p]??o?.[p]}}}}search(t,n){let r=[];this.#s=eo;let s=[this],o=qs(n),i=[],a=o.length,u=null;for(let l=0;l<a;l++){let f=o[l],d=l===a-1,p=[];for(let m=0,y=s.length;m<y;m++){let b=s[m],v=b.#t[f];v&&(v.#s=b.#s,d?(v.#t["*"]&&this.#r(r,v.#t["*"],t,b.#s),this.#r(r,v,t,b.#s)):p.push(v));for(let h of b.#n){let g=h.#o,w=b.#s===eo?{}:{...b.#s};if(typeof g=="string"){(g==="*"||f.startsWith(g.slice(0,-1)))&&(this.#r(r,h,t,b.#s),g==="*"&&(h.#s=w,p.push(h)));continue}let[,_,O]=g;if(!(!f&&O===!0)){if(O!==!0){if(!u){u=[];let V=n[0]==="/"?1:0;for(let se=0;se<a;se++)u[se]=V,V+=o[se].length+1}let L=n.slice(u[l]),N=O.exec(L);if(N){Object.hasOwn(w,_)||(w[_]=N[0]),this.#r(r,h,t,b.#s,w),N[0].length===L.length&&h.#t["*"]&&this.#r(r,h.#t["*"],t,b.#s,w);for(let V in h.#t){h.#s=w;let se=N[0].match(/\//g)?.length??0;(i[se]||=[]).push(h);break}continue}}(O===!0||O.test(f))&&(Object.hasOwn(w,_)||(w[_]=f),d?(this.#r(r,h,t,w,b.#s),h.#t["*"]&&this.#r(r,h.#t["*"],t,w,b.#s)):(h.#s=w,p.push(h)))}}}let c=i.shift();s=c?p.concat(c):p}return r[1]&&r.sort((l,f)=>l.score-f.score),[r.map(({handler:l,params:f})=>[l,f])]}}});var to,no=E(()=>{Ie();iu();to=class{name="TrieRouter";#e=new su;add(e,t,n){for(let r of mr(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}}});var au=E(()=>{no()});var bn,uu=E(()=>{Va();tu();ru();no();au();bn=class extends za{constructor(e={}){super(e),this.router=e.router??new nu({routers:[new eu,new to]})}}});var ro=E(()=>{Vs();uu()});var pu={};Ae(pu,{CACHE_MAX:()=>fu,SYSTEM:()=>gr,parseDigits:()=>cu,promptView:()=>br,rate:()=>so});import{createHash as bp}from"node:crypto";var gr,wp,vp,kp,cu,fu,ot,$t,lu,br,so,oo=E(()=>{"use strict";Ye();gr=`Rate how hard the user's last request is for an AI assistant on a 0-10 integer scale. 0-1 greeting or trivial; 2-3 simple question, short edit, translation; 4-5 moderate coding or analysis; 6-7 multi-step debugging, design, long reasoning; 8-10 research-grade, hard math or proofs, large system design. Reply with JSON only: {"difficulty": <int>}`,wp=new RegExp("\\p{Nd}","u"),vp=new RegExp('"difficulty"\\s*:\\s*(\\p{Nd}+)',"u"),kp=e=>{if(e>=120782&&e<=120831)return(e-120782)%10;let t=0;for(;wp.test(String.fromCodePoint(e-t-1));)t++;return t%10},cu=e=>{let t=0;for(let n of e)t=Math.min(t*10+kp(n.codePointAt(0)??0),1e6);return t},fu=1024,ot=new Map,$t=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lu=e=>{if(e==null)return 0;if(typeof e=="number")return Math.trunc(e);if(typeof e=="boolean")return e?1:0;if(typeof e=="string"&&/^[+-]?\d+$/.test(e.trim()))return Number.parseInt(e.trim(),10);throw new TypeError("int() failed")},br=e=>{let t=(Array.isArray(e.messages)?e.messages:[]).filter($t),n="";for(let s=t.length-1;s>=0;s--){let o=t[s];if(o&&o.role==="user"){n=ht(o.content);break}}if(Q(n)>1800){let s=Array.from(n);n=`${s.slice(0,1200).join("")}
|
|
128
|
+
[...]
|
|
129
|
+
${s.slice(-600).join("")}`}let r=[];return Ee(e.tools)&&r.push("the assistant has tools available"),t.some(s=>s.role==="tool")&&r.push("this is mid-way through an agentic tool loop"),t.length>10&&r.push(`long conversation (${t.length} messages)`),n+(r.length?`
|
|
130
|
+
|
|
131
|
+
[context: ${r.join("; ")}]`:"")},so=async(e,t,n,r,s,o,i)=>{let a=br(r),u=bp("sha1").update(a,"utf8").digest("hex"),l=ot.get(u);if(l!==void 0)return ot.delete(u),ot.set(u,l),[l,0,0];let f={model:s,temperature:0,max_tokens:24,response_format:{type:"json_object"},messages:[{role:"system",content:gr},{role:"user",content:a}]},d,p=0,c=0;try{let m=await e(`${t}/v1/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"User-Agent":"mistwatch/0.1 router","Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.any([AbortSignal.timeout(o*1e3),...i?[i]:[]]),redirect:"manual"});if(!m.ok)throw new Error(`upstream ${m.status}`);let y=await m.json(),v=($t(y)&&Array.isArray(y.choices)?y.choices:[])[0],h=$t(v)&&$t(v.message)&&typeof v.message.content=="string"?v.message.content:"",g=vp.exec(h);if(!g||g[1]===void 0)return null;d=Math.max(0,Math.min(10,cu(g[1])));let w=$t(y)&&$t(y.usage)?y.usage:{};p=lu(w.prompt_tokens),c=lu(w.completion_tokens)}catch{return null}if(ot.set(u,d),ot.size>fu){let m=ot.keys().next().value;m!==void 0&&ot.delete(m)}return[d,p,c]}});var it,du,io=E(()=>{"use strict";it=e=>{let t=Math.max(e.limit,0),n=Math.max(e.windowS,.001),r=Math.max(e.maxKeys??4096,1),s=e.now??(()=>Date.now()/1e3),o=t/n,i=new Map,a=()=>{let l=i.keys().next();l.done||i.delete(l.value)};return{check:(l,f=1)=>{let d=s(),p=i.get(l);return p===void 0?(i.size>=r&&a(),p={tokens:t,at:d}):(i.delete(l),p.tokens=Math.min(t,p.tokens+(d-p.at)*o),p.at=d),i.set(l,p),p.tokens>=f?(p.tokens-=f,{allowed:!0,retryAfter:0}):{allowed:!1,retryAfter:(f-p.tokens)/o}},reset:l=>{l===void 0?i.clear():i.delete(l)},get size(){return i.size}}},du=(e={})=>{let t=Math.max(e.maxFails??5,1),n=e.lockS??60,r=e.windowS??600,s=Math.max(e.maxKeys??8192,1),o=e.now??(()=>Date.now()/1e3),i=new Map,a=(p,c)=>`${c}|${p.toLowerCase()}`,u=p=>{let c=i.get(p);if(c===void 0){if(i.size>=s){let m=i.keys().next();m.done||i.delete(m.value)}c={fails:[],until:0}}else i.delete(p);return i.set(p,c),c};return{check:(p,c)=>{let m=i.get(a(p,c)),y=o();return m!==void 0&&m.until>y?Math.ceil(m.until-y):0},fail:(p,c)=>{let m=o(),y=u(a(p,c));return y.until>m?Math.ceil(y.until-m):(y.fails=y.fails.filter(b=>m-b<r),y.fails.push(m),y.fails.length>=t?(y.until=m+n,y.fails=[],Math.ceil(n)):0)},success:(p,c)=>{i.delete(a(p,c))},get size(){return i.size}}}});var Ep,_p,Ap,Sp,mu,hu=E(()=>{"use strict";Ep={"mistral-large-4-0":{input:.7,output:2.1,cached:.07},"mistral-small-4":{input:.15,output:.6,cached:.015},"mistral-medium-3-5":{input:1.5,output:7.5,cached:null},"zai-glm-5-3":{input:1.4,output:4.4,cached:.14},"zai-glm-5-3-flash":{input:.15,output:.5,cached:.03},"deepseek-v4-1-flash-1017":{input:.3,output:1.2,cached:.007},"ministral-3-14b":{input:.2,output:.2,cached:.02},"ministral-3-8b":{input:.15,output:.15,cached:.015},"ministral-3-3b":{input:.1,output:.1,cached:.01},codestral:{input:.3,output:.9,cached:.03},"codestral-embed":{input:.15,output:0,cached:.015},"mistral-embed":{input:.1,output:0,cached:.01}},_p={"mistral-large-4-0-3":"mistral-large-4-0","mistral-large-4":"mistral-large-4-0","mistral-large-latest":"mistral-large-4-0","mistral-small-2603":"mistral-small-4","mistral-small-latest":"mistral-small-4","mistral-medium-latest":"mistral-medium-3-5","mistral-medium":"mistral-medium-3-5","mistral-medium-3.5":"mistral-medium-3-5","mistral-vibe-cli-latest":"mistral-medium-3-5","mistral-vibe-cli-fast":"mistral-small-4","ministral-3b-latest":"ministral-3-3b","ministral-3b-2512":"ministral-3-3b","ministral-8b-latest":"ministral-3-8b","ministral-8b-2512":"ministral-3-8b","ministral-14b-latest":"ministral-3-14b","ministral-14b-2512":"ministral-3-14b","glm-5-3":"zai-glm-5-3","zai-glm-5":"zai-glm-5-3","zai-glm-latest":"zai-glm-5-3","codestral-latest":"codestral","codestral-2508":"codestral"},Ap={input:.7,output:2.1,cached:.07},Sp={ocr:4},mu=(e,t)=>{let n=new Map(Object.entries(Ep)),r=new Map(Object.entries(_p)),s=new Set;for(let[u,l]of Object.entries(t??{}))n.set(u,{input:l.input,output:l.output,cached:l.cached??null}),s.add(u);let o=[...n.keys()].sort((u,l)=>l.length-u.length),i=u=>{let l=(u??"").toLowerCase(),f=s.has(l)?l:r.get(l)??l,d=n.get(f);if(d)return[d,!0];for(let p of o)if(f.startsWith(p)){let c=n.get(p);if(c)return[c,!0]}return[Ap,!1]};return{fx:e,prices:n,lookup:i,costEur:(u,l,f,d=0)=>{let[p,c]=i(u),m=Math.min(Math.max(d,0),l),y=p.cached??p.input;return[((l-m)*p.input+m*y+f*p.output)/1e6*e,c]},pagesCostEur:u=>u/1e3*Sp.ocr*e}}});var vu={};Ae(vu,{USER_AGENT:()=>at,checkKey:()=>wr,nextReset:()=>uo,parseIso:()=>gu,prevReset:()=>bu,startSyncLoop:()=>co,syncAll:()=>ut});var at,yu,lo,Lt,xp,Rp,Tp,gu,ao,uo,bu,wu,Op,wr,Cp,Pp,ut,co,wn=E(()=>{"use strict";W();rn();at="mistwatch/0.1",yu={vibe_budget:"vibe",api_budget:"api"},lo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lt=e=>{if(typeof e=="boolean")return e?1:0;if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);if(typeof e=="string"&&e.trim()!==""&&!Number.isNaN(Number(e.trim())))return Number(e.trim());throw new TypeError(`float() argument must be a number or numeric string, not ${typeof e}`)},xp=e=>e instanceof Error?e.name:"Error",Rp=e=>Object.assign(new Error(`HTTP ${e}`),{status:e}),Tp=e=>e instanceof Error&&"status"in e&&typeof e.status=="number",gu=e=>{let t=Date.parse(e);if(Number.isNaN(t))throw new TypeError(`invalid iso timestamp: ${e}`);return t/1e3},ao=(e,t)=>new Date(Date.UTC(e,t+1,0)).getUTCDate(),uo=(e,t)=>{let n=new Date(t*1e3),r=n.getUTCFullYear(),s=n.getUTCMonth(),o=Date.UTC(r,s,Math.min(e,ao(r,s)))/1e3;return o<=t&&(s===11?(r+=1,s=0):s+=1,o=Date.UTC(r,s,Math.min(e,ao(r,s)))/1e3),o},bu=(e,t)=>{let n=new Date(t*1e3),r=n.getUTCMonth()===0?n.getUTCFullYear()-1:n.getUTCFullYear(),s=n.getUTCMonth()===0?11:n.getUTCMonth()-1;return Date.UTC(r,s,Math.min(e,ao(r,s)))/1e3},wu=async(e,t,n)=>{let r=await e(`${t}/v1/billing/budget`,{headers:{Authorization:`Bearer ${n}`,"User-Agent":at},signal:AbortSignal.timeout(15e3),redirect:"manual"});if(!r.ok)throw Rp(r.status);let s=await r.json();if(!lo(s))throw new TypeError("budget payload is not an object");return s},Op=async(e,t,n)=>{let r=new Error(`account ${n.name} has no keys configured`),s=Object.keys(n.keys).sort((o,i)=>(o==="vibe"?0:1)-(i==="vibe"?0:1));for(let o of s)try{return await wu(e,t.upstream,ve(n,o)??"")}catch(i){r=i}throw r},wr=async(e,t,n)=>{try{let r=await wu(e,t,n),s={};for(let[o,i]of Object.entries(yu)){let a=r[o];if(!lo(a)||Object.keys(a).length===0)continue;let u=Lt(a.initial_budget);s[i]={initial:u,used:Lt(a.usage_percentage)/100*u,currency:typeof a.currency=="string"?a.currency:null}}return{valid:!0,budgets:s}}catch(r){if(Tp(r)){if(r.status===401||r.status===403){try{if((await e(`${t}/v1/models`,{headers:{Authorization:`Bearer ${n}`,"User-Agent":at},signal:AbortSignal.timeout(15e3),redirect:"manual"})).status===200)return{valid:!0,budgets:{},note:"The key works, but it cannot read the budget overview."}}catch{}return{valid:!1,error:`Mistral rejected the key (${r.status}).`}}return{valid:!1,error:`Mistral returned an error (${r.status}).`}}return{valid:!1,error:`Could not reach Mistral: ${xp(r)}`}}},Cp=(e,t,n,r,s,o,i,a)=>{let u=e.latestSnapshot(t,n);if(u&&Math.abs(u.reset_at-o)<1&&a>u.ts&&e.canonical(t)===t){let l=r-u.used_eur,f=e.costBetween(e.members(t),n,u.ts,{upto:a}),d=l-f;d>5e-4&&e.addLedger({ts:a,account:t,pool:n,client:"(external)",model:null,endpoint:"sync",cost_eur:d,source:"sync",estimated:1})}e.addSnapshot({ts:a,account:t,pool:n,used_eur:r,initial_eur:s,reset_at:o,currency:i})},Pp=async(e,t,n,r)=>{let s={},o=null,i=Date.now()/1e3;try{o=await Op(e,t,r)}catch(a){console.warn(`budget sync failed for ${r.name}:`,a)}if(o!==null&&Object.keys(o).length>0)for(let[a,u]of Object.entries(yu)){let l=o[a];if(!(!lo(l)||Object.keys(l).length===0))try{let f=Lt(l.initial_budget),d=Lt(l.usage_percentage)/100*f,p=typeof l.reset_at=="string"&&l.reset_at?gu(l.reset_at):uo(1,i);Cp(n,r.name,u,d,f,p,typeof l.currency=="string"?l.currency:null,i),s[u]={used:d,initial:f,source:"mistral"}}catch(f){console.warn(`bad budget payload for ${r.name}/${u}:`,f instanceof Error?f.message:f)}}else for(let[a,u]of Object.entries(r.manual))try{let l=Lt(u.initial_eur),f=Math.trunc(Lt(u.reset_day??1)),d=uo(f,i),p=n.costBetween(r.name,a,bu(f,d),{inclusive:!0,upto:i});n.addSnapshot({ts:i,account:r.name,pool:a,used_eur:p,initial_eur:l,reset_at:d,currency:"EUR"}),s[a]={used:p,initial:l,source:"manual"}}catch(l){console.warn(`bad manual budget for ${r.name}/${a}:`,l instanceof Error?l.message:l)}return s},ut=async(e,t,n)=>{let r=[];for(let s of t.accounts)s.enabled&&r.push([s.name,await Pp(e,t,n,s)]);return gi(n,t.accounts.filter(s=>s.enabled)),Object.fromEntries(r)},co=e=>{let t=!1,n;return(async()=>{for(;!t;){try{await ut(e.fetch,e.cfg,e.db),e.lastSync=Date.now()/1e3,e.blockedUntil.clear(),await e.names.maybeRefresh(e.fetch,e.cfg.upstream,e.cfg.accounts)}catch(s){console.error("sync loop",s)}if(t)break;await new Promise(s=>{setTimeout(s,Math.min(Math.max(e.cfg.limits.sync_interval_s,1),2147483)*1e3).unref(),n=s}),n=void 0}})(),()=>{t=!0,n?.()}}});import{createHash as Ip,randomBytes as Su}from"node:crypto";var ne,xu,fo,$p,Lp,Np,Dp,vr,ku,Eu,_u,Mp,Au,Ru,po=E(()=>{"use strict";wn();ne=class extends Error{constructor(t){super(t),this.name="SignInError"}},xu="https://console.mistral.ai",fo=`${xu}/api`,$p=5,Lp=600,Np=9004,Dp="This workspace cannot be used for Vibe. Sign in again and choose a different workspace in the browser, or contact your administrator.",vr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ku=e=>e instanceof Error?e.name:"Error",Eu=e=>{let t=[];for(let n of e.split("/"))n===""||n==="."||(n===".."?t.pop():t.push(n));return`/${t.join("/")}`},_u=(e,t)=>{let n=()=>{throw new ne("Mistral returned an unexpected sign-in URL.")};if(typeof e!="string")return n();let r,s;try{r=new URL(e),s=new URL(t)}catch{return n()}if(r.protocol!=="https:"||r.username!==""||r.password!==""||r.origin!==s.origin)return n();let o=Eu(s.pathname).replace(/\/+$/,""),i=Eu(r.pathname);return o!==""&&i!==o&&!i.startsWith(`${o}/`)?n():e},Mp=()=>{let e=Su(64).toString("base64url"),t=Ip("sha256").update(e,"ascii").digest("base64url");return[e,t]},Au=e=>({id:e.id,account:e.account,pool:e.pool,status:e.status,message:e.message,sign_in_url:e.signInUrl,expires_at:e.expiresAt,synced:e.synced}),Ru=e=>{let t=e.pollIntervalS??3,n=new Map,r=new Set,s=(c,m,y="")=>{c.status=m,c.message=y,c.finishedAt=Date.now()/1e3},o=()=>{let c=Date.now()/1e3;for(let[m,y]of n)y.finishedAt!==0&&c-y.finishedAt>Lp&&n.delete(m)},i=c=>new Promise((m,y)=>{let b=setTimeout(m,t*1e3);b.unref(),c.ctrl.signal.addEventListener("abort",()=>{clearTimeout(b),y(c.ctrl.signal.reason)},{once:!0})}),a=async(c,m)=>{c.status="exchanging";let y;try{y=await e.fetch(`${fo}/vibe/sign-in/${c.processId}/exchange`,{method:"POST",redirect:"manual",headers:{"User-Agent":at,"Content-Type":"application/json"},body:JSON.stringify({exchange_token:m,code_verifier:c.verifier}),signal:AbortSignal.any([c.ctrl.signal,AbortSignal.timeout(2e4)])})}catch(v){return c.ctrl.signal.aborted?void 0:s(c,"error",`Exchanging for a key failed (${ku(v)}).`)}if(c.ctrl.signal.aborted)return;if(!y.ok){let v=!1;try{let h=await y.json();v=y.status===403&&vr(h)&&h.error_code===Np}catch{}return s(c,"error",v?Dp:`Exchanging for a key failed (HTTP ${y.status}).`)}let b;try{let v=await y.json();b=vr(v)?v.api_key:void 0}catch{b=void 0}if(!c.ctrl.signal.aborted){if(typeof b!="string"||b==="")return s(c,"error","Mistral did not return an API key.");try{e.store.setKey(c.account,c.pool,{value:b})}catch(v){return s(c,"error",v instanceof Error?v.message:String(v))}e.cfg.accounts.splice(0,e.cfg.accounts.length,...e.store.listAccounts()),e.blockedUntil?.clear();try{c.synced=(await ut(e.fetch,e.cfg,e.db))[c.account]??{},e.onSynced?.()}catch(v){console.error("sync after sign-in",v)}c.ctrl.signal.aborted||s(c,"done","Signed in.")}},u=async c=>{let m=0;try{for(;Date.now()/1e3<c.expiresAt;){let y;try{let v=await e.fetch(c.pollUrl,{redirect:"manual",headers:{"User-Agent":at},signal:AbortSignal.any([c.ctrl.signal,AbortSignal.timeout(2e4)])});if(v.status===410)return s(c,"expired","Sign-in expired.");if(!v.ok)throw new Error(`status ${v.status}`);let h=await v.json();if(!vr(h))throw new TypeError("bad poll payload");y=h,m=0}catch{if(c.ctrl.signal.aborted)return;if(m+=1,m>=3)return s(c,"error","Could not check the sign-in status.");await i(c);continue}let b=y.status;if(b==="pending")await i(c);else if(b==="completed"){let v=y.exchange_token;return typeof v!="string"||v===""?s(c,"error","Sign-in succeeded, but the token to finish it is missing."):await a(c,v)}else return b==="expired"?s(c,"expired","Sign-in expired."):b==="denied"?s(c,"denied","Sign-in was denied."):s(c,"error",typeof y.message=="string"&&y.message!==""?y.message:"Sign-in failed.")}s(c,"expired","Sign-in expired.")}catch(y){if(c.ctrl.signal.aborted||y instanceof DOMException&&y.name==="AbortError")return;console.error("sign-in task failed",y),s(c,"error","Unexpected error during sign-in.")}},l=async(c,m)=>{o();for(let v of[...n.values()])v.account===c&&v.pool===m&&(v.status==="pending"||v.status==="exchanging")&&p(v.id);for(let v of r)v.account===c&&v.pool===m&&v.ctrl.abort();let y=0;for(let v of r)v.ctrl.signal.aborted||(y+=1);for(let v of n.values())(v.status==="pending"||v.status==="exchanging")&&(y+=1);if(y>=$p)throw new ne("Too many sign-ins in progress.");let b={account:c,pool:m,ctrl:new AbortController};r.add(b);try{return await f(b)}finally{r.delete(b)}},f=async c=>{let{account:m,pool:y}=c,[b,v]=Mp(),h;try{h=await e.fetch(`${fo}/vibe/sign-in`,{method:"POST",redirect:"manual",headers:{"User-Agent":at,"Content-Type":"application/json"},body:JSON.stringify({code_challenge:v,code_challenge_method:"S256"}),signal:AbortSignal.any([c.ctrl.signal,AbortSignal.timeout(2e4)])})}catch(w){throw c.ctrl.signal.aborted?new ne("Replaced by a newer sign-in for this account."):new ne(`Cannot reach Mistral (${ku(w)}).`)}if(c.ctrl.signal.aborted)throw new ne("Replaced by a newer sign-in for this account.");if(!h.ok)throw new ne(`Mistral refused to start the sign-in (HTTP ${h.status}).`);let g;try{let w=await h.json();if(!vr(w))throw new TypeError("bad sign-in payload");if(w.process_id===void 0||w.process_id===null)throw new TypeError("missing process_id");if(typeof w.expires_at!="string")throw new TypeError("missing expires_at");let _=Date.parse(w.expires_at);if(Number.isNaN(_))throw new TypeError("bad expires_at");g={id:Su(12).toString("base64url"),account:m,pool:y,processId:String(w.process_id),signInUrl:_u(w.sign_in_url,xu),pollUrl:_u(w.poll_url,fo),verifier:b,expiresAt:_/1e3,status:"pending",message:"",synced:{},finishedAt:0,ctrl:new AbortController,task:null}}catch(w){throw w instanceof ne?w:new ne("Mistral returned an unexpected response.")}if(c.ctrl.signal.aborted)throw new ne("Replaced by a newer sign-in for this account.");return n.set(g.id,g),g.task=u(g),Au(g)},d=c=>{let m=n.get(c);return m===void 0?void 0:Au(m)},p=c=>{let m=n.get(c);return m?((m.status==="pending"||m.status==="exchanging")&&s(m,"cancelled","Sign-in cancelled."),m.ctrl.abort(),!0):!1};return{start:l,get:d,cancel:p}}});var Tu,lt,Ou,Nt,Cu,mo,kr=E(()=>{"use strict";et();Hn();rn();Mn();hu();po();nt();Tu=(e,t=fetch)=>{let n=Bn(e.db_path),r=an(n),s=new Map,o={cfg:e,db:n,engine:tn(n,e.limits),prices:mu(e.usd_to_eur,e.price_overrides),store:r,names:Dn(n),signin:Ru({cfg:e,db:n,store:r,fetch:t,blockedUntil:s,onSynced:()=>{o.lastSync=Date.now()/1e3}}),vibeRe:new RegExp(e.limits.vibe_user_agent_regex,"i"),blockedUntil:s,fetch:t,lastSync:0};return Gn(n),r.migrateConfig(e),lt(o),o},lt=e=>{e.cfg.accounts.splice(0,e.cfg.accounts.length,...e.store.listAccounts())},Ou=(e,t)=>e.vibeRe.test(t)?"vibe":"api",Nt=(e,t)=>`${e}\0${t}`,Cu=(e,t,n)=>{let r=e.cfg.limits.fallback_to_other_pool?[t,t==="vibe"?"api":"vibe"]:[t],s=[];for(let i of e.cfg.accounts)i.enabled&&r.forEach((a,u)=>{if(!(a in i.keys)||(e.blockedUntil.get(Nt(i.name,a))??0)>n)return;let l=e.engine.status(i.name,a,n);l&&ie(l)>0&&s.push({rank:u,account:i,pool:a,status:l})});let o=i=>ie(i.status);return s.sort(e.cfg.limits.strategy==="priority"?(i,a)=>i.rank-a.rank||i.account.priority-a.account.priority||o(a)-o(i):(i,a)=>i.rank-a.rank||o(a)-o(i)||i.account.priority-a.account.priority),s.map(({account:i,pool:a,status:u})=>({account:i,pool:a,status:u}))},mo=(e,t,n)=>{let r=n===void 0||e.cfg.limits.fallback_to_other_pool?["vibe","api"]:[n],s=[],o=[];for(let i of e.cfg.accounts)if(i.enabled)for(let a of r){if(!(a in i.keys))continue;let u=e.engine.status(i.name,a,t);if(!u)continue;let l=e.blockedUntil.get(Nt(i.name,a))??0,f=l>t,d=f?l:_t(u);s.push({account:i.name,pool:a,blocked_by:f?"temporarily-blocked":en(u)??(ie(u)>0?"insufficient-room":"temporarily-blocked"),retry_at:d}),d&&o.push(d)}return{pools:s,retry_after:o.length?Math.max(Math.trunc(Math.min(...o)-t),1):60}}});var jp,Up,Bp,Hp,Pu,Fp,qp,G,_r,ho,Ar,Lu,Wp,Er,Iu,$u,Kp,yo,Nu=E(()=>{"use strict";et();oo();W();kt();Wn();io();Ye();sn();kr();jp=8*1024*1024,Up=15,Bp=600,Hp=600,Pu=30,Fp=["/v1/chat/completions","/v1/fim/completions","/v1/agents/completions","/v1/embeddings","/v1/ocr","/v1/conversations","/v1/moderations"],qp=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EHOSTUNREACH","ENETUNREACH","UND_ERR_CONNECT_TIMEOUT"]),G=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_r=e=>{if(e==null)return 0;if(typeof e=="number")return Math.trunc(e);if(typeof e=="boolean")return e?1:0;if(typeof e=="string"&&/^[+-]?\d+$/.test(e.trim()))return Number.parseInt(e.trim(),10);throw new TypeError("int() failed")},ho=e=>Math.max(Math.floor(e/4),1),Ar=e=>{for(let t of e)if(Ee(t))return t;return 0},Lu=e=>{let t=e.usage;if(!G(t)||!("prompt_tokens"in t)&&!("completion_tokens"in t))return null;let n=G(t.prompt_tokens_details)?t.prompt_tokens_details:{},r=_r(Ar([t.num_cached_tokens,n.cached_tokens]));return[_r(Ar([t.prompt_tokens])),_r(Ar([t.completion_tokens])),r]},Wp=e=>e instanceof TypeError&&G(e.cause)&&typeof e.cause.code=="string"&&qp.has(e.cause.code),Er=(e,t,n)=>t===204||t===304?new Response(null,{status:t,headers:n}):new Response(e,{status:t,headers:n}),Iu=()=>{let e=()=>{},t=()=>{};return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}},$u=(e,t,n,r)=>{let s=e.body?.getReader(),o=!1,i=()=>{o||(o=!0,s?.cancel().catch(()=>{}),n())};return new ReadableStream({start(a){if(r.aborted){a.error(r.reason),i();return}r.addEventListener("abort",()=>{o||(a.error(r.reason),i())},{once:!0})},async pull(a){if(s===void 0){a.close(),i();return}try{let u=await s.read();if(u.done){a.close(),i();return}a.enqueue(u.value);try{t?.(u.value)}catch{}}catch(u){a.error(u),i()}},cancel(){i()}})},Kp=()=>{let e=new TextDecoder,t="",n=null,r=null,s=0,o=a=>{t+=e.decode(a,{stream:!0});let u=t.lastIndexOf(`
|
|
132
|
+
`);if(u<0)return;let l=t.slice(0,u);t=t.slice(u+1);for(let f of l.split(`
|
|
133
|
+
`)){let d=f.trim();if(!d.startsWith("data:")||d.endsWith("[DONE]"))continue;let p;try{p=JSON.parse(d.slice(5))}catch{continue}if(!G(p))continue;let c=p.model;typeof c=="string"&&c!==""&&(r=c);let m=Lu(p);m!==null&&(n=m);let y=p.choices;if(Array.isArray(y))for(let b of y){let v=G(b)&&G(b.delta)?b.delta.content:void 0;if(typeof v=="string")s+=Q(v);else if(Array.isArray(v))for(let g of v)G(g)&&typeof g.text=="string"&&(s+=Q(g.text));let h=G(b)&&G(b.delta)?b.delta.tool_calls:void 0;if(Array.isArray(h))for(let g of h){let w=G(g)&&G(g.function)?g.function:null;w!==null&&(typeof w.name=="string"&&(s+=Q(w.name)),typeof w.arguments=="string"&&(s+=Q(w.arguments)))}}}};return{feed:o,flush:()=>o(new Uint8Array([10])),usage:()=>n,model:()=>r,outChars:()=>s}},yo=(e,t={})=>{let n=e.cfg,r=t.bodyLimit??jp,s=(t.connectTimeoutS??Up)*1e3,o=(t.totalTimeoutS??Bp)*1e3,[i,a]=t.globalRate??[600,60],[u,l]=t.keyRate??[300,60],f=it({limit:i,windowS:a}),d=it({limit:u,windowS:l}),p=qn({concurrency:t.concurrency??8,maxPending:t.maxPending??64}),c=new AbortController,m=h=>Response.json(Zt(h),{status:h.status,headers:Qe(h)}),y=async h=>{if(!At({host:h.headers.get("host"),origin:h.headers.get("origin")},{port:n.port,extraHosts:n.allowed_hosts}))throw T(x.forbiddenHost(n.port));let g=new URL(h.url),w=g.pathname;if(w==="/api"||w.startsWith("/api/"))return Response.json(vt(M("mistwatch_not_found",404,"Not Found")),{status:404});let _=null;if(e.store.hasApiKeys()){let k=h.headers.get("authorization")??"",U=k.toLowerCase().startsWith("bearer ")?k.slice(7):h.headers.get("x-api-key")??"",ue=e.store.verifyApiKey(U.trim());if(ue===null)throw T(x.auth());_=ue}if(!Vn(h.headers.get("content-length"),r))throw T(x.tooLarge());let O=f.check("");if(!O.allowed)throw T(x.rateLimited(O.retryAfter));let L=d.check(_===null?"open":String(_.id));if(!L.allowed)throw T(x.rateLimited(L.retryAfter));let N=await Xn(h.body,r),V=Ou(e,h.headers.get("user-agent")??""),se=h.method==="POST"&&Fp.some(k=>w===k||w.startsWith(`${k}/`)),D={};if(N.length>0&&(h.headers.get("content-type")??"").includes("json"))try{let k=JSON.parse(new TextDecoder().decode(N));G(k)&&(D=k)}catch{}let he=typeof D.model=="string"?D.model:null,Ke=Ee(D.stream),_n=Date.now()/1e3,ze=se?Cu(e,V,_n):(()=>{let k=n.accounts.find(U=>U.enabled&&Object.keys(U.keys).length>0);return k===void 0?[]:[{account:k,pool:Object.keys(k.keys)[0]??V,status:null}]})();if(ze.length===0){let k=mo(e,_n,V);throw T(x.budget(k.retry_after,k.pools))}let ye=null,Ge=N;if(he!==null&&Cn.has(he)&&w==="/v1/chat/completions"&&Object.keys(D).length>0){let k=ze[0];if(k===void 0)throw T(x.internal());let U=null;if(n.router.llm_classifier){let ue=In(D)[0],X=null;if(ns(D,ue))try{X=ve(k.account,k.pool)}catch(P){console.error(`cannot resolve classifier key for ${k.account.name}:`,P)}if(X){let[P]=e.prices.lookup(n.router.classifier_model),j=((ho(Q(br(D))+Q(gr))+1)*P.input+24*P.output)/1e6*n.usd_to_eur,oe=k.status===null?null:e.engine.status(k.account.name,k.pool,Date.now()/1e3),ge=oe===null?null:e.engine.tryReserve(k.account.name,k.pool,j,Kn(oe));if(oe===null||ge!==null){let be=!1,le=async J=>{be=!0;try{let Bt=await so(e.fetch,n.upstream,X,D,n.router.classifier_model,n.router.classifier_timeout_s,J);if(Bt===null)return null;let[De,Sn,R]=Bt;if(Sn||R){let[S]=e.prices.costEur(n.router.classifier_model,Sn,R);e.db.addLedger({ts:Date.now()/1e3,account:k.account.name,pool:k.pool,client:"(router)",model:n.router.classifier_model,endpoint:"router",prompt_tokens:Sn,completion_tokens:R,cost_eur:S,source:"proxy",status:200})}return De}finally{ge?.settle()}};try{U=await p.run(le,{signal:AbortSignal.any([h.signal,c.signal]),timeoutMs:n.router.classifier_timeout_s*1e3})}catch(J){if(be||ge?.release(),h.signal.aborted)throw J}}}}ye=rs(D,he,k.status===null?1:fs(k.status),U),D=ss(D,ye),Ge=new TextEncoder().encode(JSON.stringify(D)),he=ye.model,console.info(`auto -> ${$n(ye)} | ${ye.reason}`)}let[ft]=e.prices.lookup(he),An=ho(Ge.length),Ir=_r(Ar([D.max_tokens,1024])),Io=Number.isFinite(Ir)&&Ir>0?Ir:1024,Dl=(An*ft.input+Io*ft.output)/1e6*n.usd_to_eur,Ml=xi(h.headers),jl=Date.now()/1e3,Ul=AbortSignal.any([h.signal,c.signal]),Ve=null,$o=0,$r=(k,U,ue,X,P={})=>{try{let j=P.model||k.model,oe,ge,be,le,J;if(P.pages!==null&&P.pages!==void 0)oe=e.prices.pagesCostEur(P.pages),ge=!0,be=P.pages,le=0,J=0;else if(U!==null)[be,le,J]=U,[oe,ge]=e.prices.costEur(j,be,le,J);else return;e.db.addLedger({ts:Date.now()/1e3,account:k.acct,pool:k.pool,client:k.client,model:j,endpoint:k.endpoint,prompt_tokens:be,completion_tokens:le,cached_tokens:J,cost_eur:oe,source:"proxy",estimated:X||!ge?1:0,status:ue,latency_ms:Math.trunc((Date.now()/1e3-k.t0)*1e3)})}finally{k.res.settle()}},Bl=(k,U,ue)=>{if(U>=400){k.res.release();return}let X=null;try{X=JSON.parse(new TextDecoder().decode(ue))}catch{}let P=G(X)?X:null,j=P!==null&&G(P.usage_info)?P.usage_info:null,oe=j!==null&&typeof j.pages_processed=="number"?j.pages_processed:null;$r(k,P===null?null:Lu(P),U,!1,{pages:oe,model:P!==null&&typeof P.model=="string"?P.model:null})};for(let k of ze){let U;try{U=ve(k.account,k.pool)}catch(S){console.error(`cannot resolve key for ${k.account.name}:`,S);continue}if(!U)continue;let ue=k.status===null?null:e.engine.status(k.account.name,k.pool,Date.now()/1e3),X=new Headers;try{for(let[S,we]of Ml)X.set(S,we);X.set("authorization",`Bearer ${U}`)}catch{console.error(`invalid key for ${k.account.name}/${k.pool}`);continue}let P=ue===null?null:e.engine.tryReserve(k.account.name,k.pool,Dl,Kn(ue));if(k.status!==null&&P===null){$o+=1;continue}let j=new AbortController,oe=S=>{S.aborted?j.abort(S.reason):S.addEventListener("abort",()=>j.abort(S.reason),{once:!0})};oe(h.signal);let ge=S=>de(S)?S:j.signal.aborted&&de(j.signal.reason)?j.signal.reason:T(x.upstream()),be=Iu(),le=Iu(),J,Bt=setTimeout(()=>j.abort(T(x.upstreamTimeout())),o);Bt.unref();let De=()=>be.resolve();p.run(async S=>{oe(S),J=setTimeout(()=>j.abort(T(x.upstreamTimeout())),Ke?s:o),J.unref();try{let we=await e.fetch(`${n.upstream}${w}${g.search}`,{method:h.method,headers:X,body:Ge.length===0||h.method==="GET"||h.method==="HEAD"?null:Ge,signal:j.signal,redirect:"manual"});le.resolve(we),await be.promise}catch(we){throw le.reject(we),we}finally{clearTimeout(J),clearTimeout(Bt)}},{signal:Ul,timeoutMs:o}).then(void 0,S=>le.reject(S));let R;try{R=await le.promise}catch(S){if(P?.release(),Wp(S)&&!h.signal.aborted){console.warn(`upstream connect error via ${k.account.name}:`,S);continue}throw ge(S)}clearTimeout(J);try{if(k.status!==null&&(R.status===401||R.status===402||R.status===403||R.status===429)){let Y=new Uint8Array(await R.arrayBuffer()),Nr=new TextDecoder().decode(Y);console.warn(`upstream ${R.status} via ${k.account.name}/${k.pool}:`,Pi(Nr.slice(0,300),[U])),e.blockedUntil.set(Nt(k.account.name,k.pool),Date.now()/1e3+(R.status===429?Pu:Hp)),Ve={status:R.status,body:Y,ct:R.headers.get("content-type")??"application/json",retryAfter:R.headers.get("retry-after")},P?.release(),De();continue}let S=new Headers;for(let[Y,Nr]of Ri(R.headers))S.set(Y,Nr);if(S.set("x-mw-account",k.account.name),S.set("x-mw-pool",k.pool),ye!==null&&S.set("x-mw-routed",$n(ye)),k.status!==null&&S.set("x-mw-room-eur",ie(k.status).toFixed(4)),k.status===null)return R.body===null||R.status===204||R.status===304?(De(),new Response(null,{status:R.status,headers:S})):Er($u(R,null,De,j.signal),R.status,S);if(P===null)throw T(x.internal());let we={res:P,acct:k.account.name,pool:k.pool,client:_?.name??null,model:he,endpoint:w,estIn:An,t0:jl};if(Ke&&R.status===200){let Y=Kp();return Er($u(R,Y.feed,()=>{try{Y.flush()}catch{}try{$r(we,Y.usage()??[An,ho(Y.outChars()),0],200,Y.usage()===null,{model:Y.model()})}finally{De()}},j.signal),R.status,S)}let Lr;try{Lr=new Uint8Array(await R.arrayBuffer())}catch(Y){throw R.status>=200&&R.status<300&&$r(we,[An,Io,0],R.status,!0),Y}return Bl(we,R.status,Lr),De(),Er(Lr,R.status,S)}catch(S){throw P?.release(),De(),ge(S)}}if(Ve!==null){let k=new Headers({"content-type":Ve.ct});return Ve.status===429&&k.set("retry-after",Ve.retryAfter??String(Pu)),Er(Ve.body,Ve.status,k)}if($o===ze.length){let k=mo(e,Date.now()/1e3,V);throw T(x.budget(k.retry_after,k.pools))}throw T(x.upstream())};return{handle:async h=>{try{return await y(h)}catch(g){return m(Fn(g))}},drain:async(h=5e3)=>{let g=Date.now()+h;for(;(p.active>0||p.pending>0)&&Date.now()<g;)await new Promise(_=>setTimeout(_,25));c.abort(T(x.shuttingDown()));let w=Date.now()+1e3;for(;p.active>0&&Date.now()<w;)await new Promise(_=>setTimeout(_,25))}}}});var Du,Mu=E(()=>{Du=e=>{let t=e.env.server?e.env.server:e.env,n=t.incoming.socket.remoteAddress,r=t.incoming.socket.remotePort,s=t.incoming.socket.remoteFamily;return{remote:{address:n,port:r,addressType:s==="IPv4"?"IPv4":s==="IPv6"?"IPv6":void 0}}}});var zp,Gp,Vp,ju,go,Xp,Sr,Uu=E(()=>{Ie();zp=/^[\w!#$%&'*.^`|~+-]+$/,Gp=/^[!#-:<>-[\]-~]+$/,Vp=/^[ !#-:<-[\]-~]*$/,ju=e=>{let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(r!==32&&r!==9)break;t++}for(;n>t;){let r=e.charCodeAt(n-1);if(r!==32&&r!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)},go=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.split(";"),r=Object.create(null);for(let s of n){let o=s.indexOf("=");if(o===-1)continue;let i=ju(s.substring(0,o));if(t&&t!==i||!Gp.test(i)||i in r)continue;let a=ju(s.substring(o+1));if(a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),Vp.test(a)&&(r[i]=Pt(a),t))break}return r},Xp=(e,t,n={})=>{if(!zp.test(e))throw new Error("Invalid cookie name");let r=`${e}=${t}`;if(/^__secure-/i.test(e)&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(/^__host-/i.test(e)){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(let s of["domain","path","sameSite","priority"])if(n[s]&&/[;\r\n]/.test(n[s]))throw new Error(`${s} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},Sr=(e,t,n)=>(t=encodeURIComponent(t),Xp(e,t,n))});var Dt,Jp,bo,Bu,Hu=E(()=>{Uu();Dt=(e,t,n)=>{let r=e.req.raw.headers.get("Cookie");if(typeof t=="string"){if(!r)return;let s=t;return n==="secure"?s="__Secure-"+t:n==="host"&&(s="__Host-"+t),go(r,s)[s]}return r?go(r):{}},Jp=(e,t,n)=>{let r;return n?.prefix==="secure"?r=Sr("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?r=Sr("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):r=Sr(e,t,{path:"/",...n}),r},bo=(e,t,n,r)=>{let s=Jp(t,n,r);e.header("Set-Cookie",s,{append:!0})},Bu=(e,t,n)=>{let r=Dt(e,t,n?.prefix);return bo(e,t,"",{...n,maxAge:0}),r}});function Fu(e){return!e&&!xr?Yp:{lang:e?.lang??xr?.lang,message:e?.message,abortEarly:e?.abortEarly??xr?.abortEarly,abortPipeEarly:e?.abortPipeEarly??xr?.abortPipeEarly}}function Qp(e){return Zp?.get(e)}function td(e){return ed?.get(e)}function rd(e,t){return nd?.get(e)?.get(t)}function sd(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function od(e,t,n,r,s){let o=s&&"input"in s?s.input:n.value,i=s?.expected??e.expects??null,a=s?.received??sd(o),u={kind:e.kind,type:e.type,input:o,expected:i,received:a,message:`Invalid ${t}: ${i?`Expected ${i} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind==="schema",f=s?.message??e.message??rd(e.reference,u.lang)??(l?td(u.lang):null)??r.message??Qp(u.lang);f!==void 0&&(u.message=typeof f=="function"?f(u):f),l&&(n.typed=!1),n.issues?n.issues.push(u):n.issues=[u]}function id(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Fu())},e}function wo(e,t){return id({kind:"schema",type:"custom",reference:wo,expects:"unknown",async:!1,check:e,message:t,"~run"(n,r){return this.check(n.value)?n.typed=!0:od(this,"type",n,r),n}})}function qu(e,t,n){let r=e["~run"]({value:t},Fu(n));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}var xr,Yp,Zp,ed,nd,vb,Wu=E(()=>{Yp={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};vb=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u")});var Rr,vo,Ku,ud,ld,cd,fd,zu,Gu=E(()=>{"use strict";Mn();Rr={"24h":[24,"hour"],"7d":[7,"day"],"30d":[30,"day"]},vo=["model","client","account","pool"],Ku=6,ud="other",ld=(e,t,n)=>{let r=new Date(e*1e3),s=[];if(n==="hour"){let o=new Date(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours());for(let i=t-1;i>=0;i--)s.push((o.getTime()-i*36e5)/1e3)}else{let o=new Date(r.getFullYear(),r.getMonth(),r.getDate());for(let i=t-1;i>=0;i--){let a=new Date(o);a.setDate(a.getDate()-i),s.push(a.getTime()/1e3)}}return s},cd=(e,t,n)=>t==="model"?e.model?n.display(e.model):e.source==="sync"?"(external)":"(unknown)":t==="client"?e.client||"\u2014":(t==="account"?e.account:e.pool)||"\u2014",fd=(e,t)=>{let n=0,r=e.length;for(;n<r;){let s=n+r>>1,o=e[s];if(o===void 0)break;t<o?r=s:n=s+1}return n},zu=(e,t,n,r,s)=>{let o=Object.hasOwn(Rr,t)?Rr[t]:void 0;if(!o)throw new Error("unknown range");if(!vo.includes(n))throw new Error("unknown grouping");let i=s??Dn(e),[a,u]=o,l=ld(r,a,u),f=l[0]??r,d=(l[l.length-1]??r)-f+(u==="hour"?3600:86400),p=e.usageRows(f,r+1),c=e.sumCost(f-d,f),m=new Map,y=new Map;for(let w of p){let _=fd(l,w.ts)-1;if(_<0)continue;let O=cd(w,n,i),L=y.get(O);L||(L=new Array(a).fill(0),y.set(O,L)),L[_]=(L[_]??0)+w.cost_eur,m.set(O,(m.get(O)??0)+w.cost_eur)}let b=[...m.keys()].sort((w,_)=>(m.get(_)??0)-(m.get(w)??0)),v=b.slice(0,Ku),h=b.slice(Ku),g=v.map(w=>({name:w,total:m.get(w)??0,values:y.get(w)??new Array(a).fill(0)}));if(h.length){let w=Array.from({length:a},(_,O)=>h.reduce((L,N)=>L+(y.get(N)?.[O]??0),0));g.push({name:ud,total:h.reduce((_,O)=>_+(m.get(O)??0),0),values:w})}return{range:t,by:n,unit:u,buckets:l,step:u==="hour"?3600:86400,series:g,total:p.reduce((w,_)=>w+_.cost_eur,0),prev_total:c,requests:p.filter(w=>w.source==="proxy"&&w.client!=="(router)").length}}});var Mt,Vu,pd,$,Tr,re,jt,dd,md,hd,Xu,yd,Ju,Yu=E(()=>{"use strict";Mu();ro();Hu();Wu();Yt();et();W();kt();rn();io();Ye();sn();po();kr();nt();wn();Gu();Mt="mw_session",Vu=256*1024,pd=wo(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"Request body must be a JSON object."),$=(e,t)=>T(M("mistwatch_http",e,t)),Tr=(e,t,n)=>{let r=M("mistwatch_http",e,t,n===void 0?{}:{retryAfter:n});return new Response(JSON.stringify(vt(r)),{status:r.status,headers:{"content-type":"application/json",...Qe(r)}})},re=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):"",jt=e=>typeof e=="boolean"?e?1:0:typeof e=="number"?Number.isFinite(e)?Math.trunc(e):null:typeof e=="bigint"?Number(e):typeof e=="string"&&/^[+-]?\d+$/.test(e.trim())?Number.parseInt(e.trim(),10):null,dd=e=>{if(typeof e=="boolean")return e;let t=jt(e);return t===null?null:t!==0},md=e=>e!==void 0&&["1","true","yes","on"].includes(e.toLowerCase()),hd=e=>e==="vibe"||e==="api",Xu=e=>Array.from(e).slice(0,256).join(""),yd=(e,t)=>{let n=[],r=new Map(e.cfg.accounts.map(s=>[s.name,s.enabled]));for(let s of e.cfg.accounts)for(let o of["vibe","api"]){let i=e.engine.status(s.name,o,t);if(!i)continue;let a=ps(i);n.push({...a,pool:o,blocked_temporarily:(e.blockedUntil.get(Nt(s.name,o))??0)>t,enabled:[s.name,...a.members].some(u=>r.get(u)===!0)})}return{now:t,last_sync:e.lastSync,pools:n,summary:ms(e.engine,e.cfg.accounts,t),by_client_7d:e.db.byClientSince(t-7*86400).flatMap(s=>hd(s.pool)?[{...s,pool:s.pool}]:[])}},Ju=(e,t={})=>{let n=new bn,r=t.apiLimit??it({limit:240,windowS:60}),s=t.upstreamLimit??it({limit:12,windowS:60}),o=t.loginLimit??it({limit:20,windowS:60}),i=du({maxFails:5,lockS:60,windowS:600,maxKeys:8192}),a=h=>{try{return Du(h).remote.address??"?"}catch{return"?"}},u=h=>{if(h.req.method!=="GET"&&h.req.method!=="HEAD"&&h.req.header("x-mw")!=="1")throw $(403,"Missing x-mw header (CSRF protection).")},l=h=>{let g=e.store.getSession(Dt(h,Mt));if(!g)throw $(401,"You are not signed in.");return u(h),g},f=h=>{let g=s.check(a(h));if(!g.allowed)throw T(x.rateLimited(g.retryAfter))},d=(h,g)=>{let w=i.check(h.username,a(g));if(w>0)throw T(x.locked(w))},p=async h=>{if(!Vn(h.req.header("content-length"),Vu))throw T(x.tooLarge());let g=await Xn(h.req.raw.body,Vu),w;try{w=JSON.parse(new TextDecoder().decode(g))}catch{throw $(400,"Request body must be a JSON object.")}let _=qu(pd,w);if(!_.success)throw $(400,_.issues[0]?.message??"Request body must be a JSON object.");return _.output},c=(h,g)=>{bo(h,Mt,g,{httpOnly:!0,sameSite:"Strict",path:"/",maxAge:er})};n.use("*",async(h,g)=>{if(!At({host:h.req.header("host"),origin:h.req.header("origin")},{port:e.cfg.port,extraHosts:e.cfg.allowed_hosts}))throw T(x.forbiddenHost(e.cfg.port));let w=r.check(a(h));if(!w.allowed)throw T(x.rateLimited(w.retryAfter));await g()}),n.onError(h=>h instanceof I?Tr(400,h.message):de(h)?Tr(h.status,h.message,h.retryAfter):(console.error("webapi: unhandled error:",h),Tr(500,"Internal server error."))),n.get("/session",h=>{let g=e.store.getSession(Dt(h,Mt));return h.json({setup_needed:e.store.countUsers()===0,user:g})});let m=Promise.resolve(),y=async h=>{if(e.store.countUsers()>0)throw $(409,"An account already exists, please sign in.");let g=await p(h),w=await e.store.createUserAsync(re(g.username),re(g.password));c(h,e.store.createSession(w));let _={ok:!0};if(!e.store.hasApiKeys()){let[O,L]=e.store.createApiKey("default");_.api_key={name:O.name,secret:L}}return h.json(_)};n.post("/setup",h=>{u(h);let g=m.then(()=>y(h));return m=g.catch(()=>{}),g}),n.post("/login",async h=>{u(h);let g=await p(h),w=re(g.username).trim(),_=a(h),O=o.check(_);if(!O.allowed)throw T(x.rateLimited(O.retryAfter));let L=i.check(w,_);if(L>0)throw T(x.locked(L));let N=await e.store.verifyLoginAsync(w,Xu(re(g.password)));if(!N)throw i.fail(w,_),$(401,"Wrong username or password.");return i.success(w,_),c(h,e.store.createSession(N.id)),h.json({ok:!0,user:N})}),n.post("/logout",h=>(u(h),e.store.deleteSession(Dt(h,Mt)),Bu(h,Mt,{path:"/"}),h.json({ok:!0}))),n.post("/password",async h=>{let g=l(h);d(g,h);let w=await p(h);if(!await e.store.checkUserPasswordAsync(g.id,Xu(re(w.old))))throw i.fail(g.username,a(h)),$(400,"Current password is incorrect.");return i.success(g.username,a(h)),await e.store.setPasswordAsync(g.id,re(w.new)),e.store.deleteOtherSessions(g.id,Dt(h,Mt)),h.json({ok:!0})}),n.get("/users",h=>(l(h),h.json(e.store.listUsers()))),n.post("/users",async h=>{l(h);let g=await p(h);return await e.store.createUserAsync(re(g.username),re(g.password)),h.json({ok:!0})}),n.delete("/users/:id",h=>{let g=l(h),w=jt(h.req.param("id"));if(w===null)throw $(400,"Invalid user id.");if(w===g.id)throw $(400,"You cannot delete yourself.");return e.store.deleteUser(w),h.json({ok:!0})}),n.get("/status",h=>(l(h),h.json(yd(e,Date.now()/1e3)))),n.get("/summary",h=>(l(h),h.json({last_sync:e.lastSync,...ms(e.engine,e.cfg.accounts)}))),n.get("/usage",h=>{l(h);let g=h.req.query("range")??"7d",w=h.req.query("by")??"model";if(!Object.hasOwn(Rr,g)||!vo.includes(w))throw $(400,"Unknown range or grouping.");return h.json(zu(e.db,g,w,Date.now()/1e3,e.names))}),n.get("/ledger",h=>{l(h);let g=jt(h.req.query("limit")??"40");if(g===null)throw $(400,"Invalid limit.");let w=e.db.recent(Math.max(1,Math.min(g,500)));return h.json(w.map(_=>({..._,model_name:_.model?e.names.display(_.model):null})))}),n.get("/models",h=>(l(h),h.json(e.names.listing(md(h.req.query("all")))))),n.put("/models/:key{.+}",async h=>{l(h);let g=await p(h);try{e.names.setOverride(h.req.param("key"),re(g.display))}catch(w){throw $(400,w instanceof Error?w.message:String(w))}return h.json({ok:!0})}),n.delete("/models/:key{.+}",h=>(l(h),e.names.clearOverride(h.req.param("key")),h.json({ok:!0}))),n.post("/models-refresh",async h=>{l(h),f(h);for(let g of e.cfg.accounts)for(let w of Object.keys(g.keys))try{let _=await e.names.refresh(e.fetch,e.cfg.upstream,ve(g,w)??"");return h.json({models:_})}catch{}throw $(502,"Could not load the model list from Mistral (is a key configured?).")}),n.post("/sync",async h=>{l(h),f(h);let g=await ut(e.fetch,e.cfg,e.db);return e.lastSync=Date.now()/1e3,e.blockedUntil.clear(),h.json(g)});let b=h=>{let g=e.store.keyInfo(h);return{name:h.name,priority:h.priority,enabled:h.enabled,keys:{vibe:g.vibe??null,api:g.api??null},shared_with:e.db.members(h.name).filter(w=>w!==h.name)}},v=h=>{let g=e.store.getAccount(h);if(!g)throw $(404,"Account does not exist.");return g};return n.get("/accounts",h=>(l(h),h.json({accounts:e.store.listAccounts().map(b),vibe_cli_available:xt()}))),n.post("/accounts",async h=>{l(h);let g=await p(h),w=g.priority===void 0||g.priority===null?100:jt(g.priority);if(w===null)throw $(400,"Invalid priority.");return e.store.createAccount(re(g.name),w),lt(e),h.json({ok:!0})}),n.patch("/accounts/:name",async h=>{l(h);let g=h.req.param("name");v(g);let w=await p(h),_=w.enabled===void 0||w.enabled===null?void 0:dd(w.enabled),O=w.priority===void 0||w.priority===null?void 0:jt(w.priority);if(_===null||O===null)throw $(400,"Invalid enabled or priority value.");return e.store.updateAccount(g,_,O),lt(e),h.json({ok:!0})}),n.delete("/accounts/:name",h=>{l(h);let g=h.req.param("name");return v(g),e.store.deleteAccount(g),lt(e),h.json({ok:!0})}),n.post("/keys/check",async h=>{l(h),f(h);let g=await p(h),w=re(g.key).trim();if(!w)throw $(400,"Key is missing.");return h.json(await wr(e.fetch,e.cfg.upstream,w))}),n.put("/accounts/:name/keys/:pool",async h=>{l(h),f(h);let g=h.req.param("name"),w=h.req.param("pool");v(g);let _=await p(h);if(_.source==="vibe-cli"){if(!xt())throw $(400,"No Vibe CLI sign-in in the keyring (run `vibe --setup`).");e.store.setKey(g,w,{ref:Re})}else{let N=re(_.key).trim();if(Ee(_.verify??!0)){let V=await wr(e.fetch,e.cfg.upstream,N);if(!V.valid)throw $(400,V.error??"Mistral rejected the key.")}e.store.setKey(g,w,{value:N})}lt(e),e.blockedUntil.clear();let O=v(g),L=(await ut(e.fetch,e.cfg,e.db))[g]??{};return e.lastSync=Date.now()/1e3,h.json({ok:!0,synced:L,account:b(O)})}),n.delete("/accounts/:name/keys/:pool",h=>{l(h);let g=h.req.param("name");return v(g),e.store.removeKey(g,h.req.param("pool")),lt(e),h.json({ok:!0})}),n.post("/accounts/:name/signin",async h=>{l(h),f(h);let g=h.req.param("name");v(g);try{return h.json(await e.signin.start(g,"vibe"))}catch(w){throw w instanceof ne?$(400,w.message):w}}),n.get("/signin/:id",h=>{l(h);let g=e.signin.get(h.req.param("id"));if(!g)throw $(404,"Sign-in attempt does not exist.");return h.json(g)}),n.delete("/signin/:id",h=>{if(l(h),!e.signin.cancel(h.req.param("id")))throw $(404,"Sign-in attempt does not exist.");return h.json({ok:!0})}),n.get("/agent-config",h=>{l(h);let g=new URL(h.req.url).origin;return h.json(ai.map(w=>ui(w,g)))}),n.get("/apikeys",h=>(l(h),h.json({keys:e.store.listApiKeys(),base_url:`${new URL(h.req.url).origin}/v1`}))),n.post("/apikeys",async h=>{l(h);let g=await p(h),[w,_]=e.store.createApiKey(re(g.name));return h.json({key:w,secret:_})}),n.delete("/apikeys/:id",h=>{l(h);let g=jt(h.req.param("id"));if(g===null)throw $(400,"Invalid key id.");if(!e.store.deleteApiKey(g))throw $(404,"Key does not exist.");return h.json({ok:!0})}),n.all("/*",()=>Tr(404,"Not Found")),n}});var ko={};Ae(ko,{createApp:()=>tl,defaultWebDir:()=>Ad,startServer:()=>_d});import{createHash as gd}from"node:crypto";import{readFileSync as Zu}from"node:fs";import{join as Qu}from"node:path";import{fileURLToPath as bd}from"node:url";var el,wd,vd,kd,tl,Ed,_d,Ad,Eo=E(()=>{"use strict";va();ro();Yt();W();kt();Nu();sn();kr();wn();Yu();el=bd(new URL("../dist/web",import.meta.url)),wd={"favicon.svg":"image/svg+xml","favicon.ico":"image/x-icon","apple-touch-icon.png":"image/png","icon-192.png":"image/png","icon-512.png":"image/png","logo.svg":"image/svg+xml","logo-dark.svg":"image/svg+xml","mark.svg":"image/svg+xml","site.webmanifest":"application/manifest+json"},vd=e=>`default-src 'none'; script-src ${e}; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; manifest-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`,kd=e=>[...e.matchAll(/<script(?![^>]*\ssrc=)[^>]*>([\s\S]*?)<\/script>/gi)].map(t=>`'sha256-${gd("sha256").update(t[1]??"","utf8").digest("base64")}'`),tl=(e,t={})=>{let n=t.proxy??yo(e),r=t.webDir??el,s=new bn;s.use("*",async(o,i)=>{await i(),o.header("X-Frame-Options","DENY"),o.header("Referrer-Policy","no-referrer")}),s.use("*",async(o,i)=>{let a={host:o.req.header("host"),origin:o.req.header("origin")};if(At(a,{port:e.cfg.port,extraHosts:e.cfg.allowed_hosts})){await i();return}let u=x.forbiddenHost(e.cfg.port),l=o.req.path==="/api"||o.req.path.startsWith("/api/");return new Response(JSON.stringify(l?vt(u):Zt(u)),{status:u.status,headers:{"content-type":"application/json",...Qe(u)}})}),s.route("/api",Ju(e,t.apiOpts)),s.get("/llms.txt",o=>{let i=new URL(o.req.url).origin;return o.body(li(i),200,{"content-type":"text/plain; charset=utf-8","Cache-Control":"no-cache"})}),s.get("/",o=>{let i;try{i=Zu(Qu(r,"index.html"),"utf8")}catch{return o.text("Mistwatch web UI is not built (run `npm run build`).",503)}return o.body(i,200,{"content-type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":vd(["'self'",...kd(i)].join(" "))})});for(let[o,i]of Object.entries(wd))Ii(o)&&s.get(`/${o}`,a=>{let u;try{u=Zu(Qu(r,o))}catch{return a.text("Not Found",404)}return a.body(new Uint8Array(u),200,{"content-type":i,"Cache-Control":"public, max-age=86400"})});return s.all("*",o=>n.handle(o.req.raw)),s.onError(o=>{let i=de(o)?o:Fn(o);return de(o)||console.error("app: unhandled error:",o),new Response(JSON.stringify(Zt(i)),{status:i.status,headers:{"content-type":"application/json",...Qe(i)}})}),s},Ed=e=>{"closeAllConnections"in e&&typeof e.closeAllConnections=="function"&&e.closeAllConnections()},_d=async(e,t={})=>{let n=Tu(e),r=yo(n),s=tl(n,{proxy:r}),o=co(n),i=wa({fetch:s.fetch,hostname:e.host,port:e.port});await new Promise((d,p)=>{i.once("listening",d),i.once("error",p)});let a=i.address(),u=typeof a=="object"&&a!==null?a.port:e.port;console.log(`mistwatch: open ${je({host:e.host,port:u},"/")} in your browser`);let l=null,f=()=>(l??=(async()=>{o();try{await r.drain(t.graceMs??1e4)}catch{}await new Promise(d=>{let p=setTimeout(()=>{Ed(i),d()},2e3);i.close(()=>{clearTimeout(p),d()})}),n.db.close()})(),l);if(t.signals!==!1){let d=()=>{f().catch(p=>console.error("shutdown error:",p)).finally(()=>process.exit(0))};process.once("SIGINT",d),process.once("SIGTERM",d)}return{port:u,close:f}},Ad=el});var vn={};Ae(vn,{HARNESSES:()=>$e,SETUP_USAGE:()=>pl,SetupArgError:()=>We,SetupError:()=>Le,applyFile:()=>Oo,backupFile:()=>kl,banner:()=>vl,createAsk:()=>Ol,createStyle:()=>bl,defaultSetupDeps:()=>ym,detectDepth:()=>wl,parseChoice:()=>Tl,parseHarnesses:()=>ml,parsePort:()=>hl,parseSetupArgs:()=>yl,planJson:()=>El,planPort:()=>xl,planToml:()=>Sl,runSetup:()=>hm});import{randomBytes as Sd}from"node:crypto";import{chmodSync as xd,constants as Rd,copyFileSync as Td,existsSync as Ro,lstatSync as Od,mkdirSync as Cd,readFileSync as Pd,readlinkSync as Id,realpathSync as $d,renameSync as Ld,rmSync as nl,statSync as Nd,writeFileSync as Dd}from"node:fs";import{homedir as Md}from"node:os";import{dirname as fl,join as Ao,resolve as jd}from"node:path";import{WriteStream as Ud}from"node:tty";import{parseArgs as Bd}from"node:util";var $e,We,Le,Hd,pl,dl,To,Cr,ml,hl,Fd,yl,qd,Wd,Kd,gl,rl,sl,ol,zd,_o,Gd,Ut,Or,bl,wl,So,Vd,il,vl,al,kl,Xd,Jd,Oo,El,_l,Yd,Al,ul,Zd,Qd,em,Sl,tm,ll,cl,xl,nm,xo,q,Rl,rm,sm,om,im,Tl,am,um,lm,cm,fm,pm,dm,mm,hm,Ol,ym,kn=E(()=>{"use strict";qr();Yt();et();W();nr();nt();zn();$e=["vibe","opencode","pi"],We=class extends Error{},Le=class extends Error{},Hd={yes:{type:"boolean",short:"y",default:!1},harness:{type:"string"},port:{type:"string"},"no-banner":{type:"boolean",default:!1},start:{type:"boolean",default:!1},json:{type:"boolean",default:!1},"show-token":{type:"boolean",default:!1},force:{type:"boolean",default:!1},help:{type:"boolean",short:"h",default:!1}},pl=`usage: mistwatch setup [options]
|
|
134
|
+
|
|
135
|
+
Creates the config, links your Vibe CLI login, makes a client token and writes the
|
|
136
|
+
provider config of the tools you pick. Safe to run again: nothing is overwritten
|
|
137
|
+
without a timestamped .bak copy, and unchanged files are left alone.
|
|
138
|
+
|
|
139
|
+
options:
|
|
140
|
+
-y, --yes never ask, use defaults (also when stdin is not a terminal)
|
|
141
|
+
--harness LIST comma-separated: vibe, opencode, pi or all (default: vibe)
|
|
142
|
+
--port N write this port into config.toml and the tool configs (default: keep the configured one, 8787 for a new config)
|
|
143
|
+
--start run the proxy when setup is done
|
|
144
|
+
--no-banner skip the logo
|
|
145
|
+
--json print what was done as JSON; no client token is created unless --show-token is also given
|
|
146
|
+
--show-token with --json: create the client token (if none exists) and include it in the output
|
|
147
|
+
--force replace an existing config.toml (a backup is kept)
|
|
148
|
+
-h, --help show this help`,dl=e=>$e.includes(e),To=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cr=e=>e instanceof Error?e.message:String(e),ml=e=>{let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);if(t.includes("all"))return[...$e];let n=t.filter(r=>!dl(r));if(t.length===0||n.length>0)throw new We(`--harness expects ${$e.join(", ")} or all (got '${n.join(",")||e}')`);return $e.filter(r=>t.includes(r))},hl=e=>{if(e===void 0)return null;let t=/^\d+$/.test(e.trim())?Number(e.trim()):0;if(t<1||t>65535)throw new We(`--port expects an integer from 1 to 65535 (got '${e}')`);return t},Fd=e=>{try{return Bd({args:e,options:Hd,strict:!0}).values}catch(t){throw new We(Cr(t))}},yl=e=>{let t=Fd(e);if(t.json&&t.start)throw new We("--json and --start cannot be combined (server logs would mix into the JSON)");return{yes:t.yes,harness:t.harness===void 0?null:ml(t.harness),port:hl(t.port),noBanner:t["no-banner"],start:t.start,json:t.json,showToken:t["show-token"],force:t.force,help:t.help}},qd=[255,130,4],Wd=[140,216,147],Kd=[227,198,0],gl=[255,140,130],rl=[[0,0,0],[205,49,49],[13,188,121],[229,229,16],[36,114,200],[188,63,188],[17,168,205],[229,229,229],[102,102,102],[241,76,76],[35,209,139],[245,245,67],[59,142,234],[214,112,214],[41,184,219],[255,255,255]],sl=[0,95,135,175,215,255],ol=(e,t)=>(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2,zd=e=>{let t=0;return rl.forEach((n,r)=>{ol(e,n)<ol(e,rl[t]??n)&&(t=r)}),t},_o=e=>{let t=0;return sl.forEach((n,r)=>{Math.abs(n-e)<Math.abs((sl[t]??0)-e)&&(t=r)}),t},Gd=e=>16+36*_o(e[0])+6*_o(e[1])+_o(e[2]),Ut=(e,t,n)=>{if(e===24)return`\x1B[${t};2;${n[0]};${n[1]};${n[2]}m`;if(e===8)return`\x1B[${t};5;${Gd(n)}m`;let r=zd(n);return`\x1B[${(t===38?r<8?30:82:r<8?40:92)+r}m`},Or="\x1B[0m",bl=e=>{let t=e>0,n=(s,o)=>t?`${s}${o}${Or}`:o;return{unicode:t,paint:(s,o)=>n(t?Ut(e,38,o):"",s),accent:s=>n(`\x1B[1m${t?Ut(e,38,qd):""}`,s),bold:s=>n("\x1B[1m",s),dim:s=>n("\x1B[2m",s),cell:(s,o)=>{if(!t)return" ";if(s&&o){let i=s[0]===o[0]&&s[1]===o[1]&&s[2]===o[2];return`${Ut(e,38,s)}${i?"":Ut(e,48,o)}${i?"\u2588":"\u2580"}${Or}`}return s?`${Ut(e,38,s)}\u2580${Or}`:o?`${Ut(e,38,o)}\u2584${Or}`:" "}}},wl=(e,t,n)=>{if(!t||e.NO_COLOR||e.TERM==="dumb")return 0;let r=n(e);return r>=24?24:r>=8?8:r>=4?4:0},So=["Y...Y.A.A.A","YY.AA.O.O.O","A.A.A.O.O.R","O...O..R.R.","O...R..E.E."],Vd={Y:[255,194,51],A:[255,162,31],O:[255,127,42],R:[249,90,59],E:[232,56,79]},il=(e,t)=>Vd[So[e]?.[t]??"."]??null,vl=(e,t)=>{let n=[e.accent("mistwatch"),e.dim(t),e.dim("setup")];return e.unicode?[0,1,2].map(r=>` ${Array.from({length:So[0]?.length??0},(o,i)=>e.cell(il(r*2,i),il(r*2+1,i))).join("")} ${n[r]??""}`):So.map(s=>s.replace(/\./g," ").replace(/[A-Z]/g,"##").trimEnd()).map((s,o)=>` ${s.padEnd(24)}${o>0&&o<4?n[o-1]??"":""}`.trimEnd())},al=e=>e.toISOString().replace(/\.\d+Z$/,"Z").replace(/[-:]/g,""),kl=(e,t)=>{let n=0,r=`${e}.${al(t)}.bak`;for(;Ro(r);)r=`${e}.${al(t)}-${++n}.bak`;return Td(e,r,Rd.COPYFILE_EXCL),r},Xd=e=>{try{return Od(e).isSymbolicLink()?jd(fl(e),Id(e)):e}catch{return e}},Jd=e=>{try{return $d(e)}catch{return Xd(e)}},Oo=(e,t,n)=>{let r=Jd(e),s=Ro(r)?Pd(r,"utf8"):null,o=t(s);if(o===null)return{action:"unchanged",backup:null};Cd(fl(r),{recursive:!0});let i=`${r}.${process.pid}-${Sd(4).toString("hex")}.mistwatch-tmp`,a=null;try{Dd(i,o,{encoding:"utf8",flag:"wx",mode:384}),s!==null&&(xd(i,Nd(r).mode&4095),a=kl(e,n)),Ld(i,r)}catch(u){throw nl(i,{force:!0}),a&&nl(a,{force:!0}),u}return{action:s===null?"created":"updated",backup:a}},El=(e,t)=>{let n={};if(e!==null&&e.trim()!==""){let s;try{s=JSON.parse(e.replace(/^/,""))}catch{throw new Le("not plain JSON (comments?), left untouched; merge the block by hand")}if(!To(s))throw new Le("not a JSON object, left untouched");n=s}let r=ls(structuredClone(n),t);return e!==null&&JSON.stringify(r)===JSON.stringify(n)?null:`${JSON.stringify(r,null,2)}
|
|
149
|
+
`},_l=/^\s*name\s*=\s*(["'])mistwatch\1\s*(#.*)?$/,Yd=/^\s*\[\[\s*providers\s*\]\]\s*(#.*)?$/,Al=e=>{let t=e.providers;return Array.isArray(t)?t.filter(n=>To(n)&&n.name==="mistwatch"):[]},ul=(e,t)=>{try{let n=Al(Me(e));return n.length>0&&n.every(r=>r.api_base===`${t}/v1`&&r.api_key_env_var===pe&&r.backend==="mistral")}catch{return!1}},Zd=e=>{let t=[];for(let[n,r]of e.entries()){if(!Yd.test(r))continue;let s=n+1;for(;s<e.length&&!/^\s*\[/.test(e[s]??"");)s++;e.slice(n+1,s).some(o=>_l.test(o))&&t.push([n,s])}return t},Qd=(e,t)=>{let n=new Map(Object.entries(t)),r=e.map(s=>{let o=/^(\s*)([A-Za-z_]+)\s*=/.exec(s),i=o?.[2]??"",a=n.get(i);return a===void 0?s:(n.delete(i),`${o?.[1]??""}${i} = ${JSON.stringify(a)}`)});return r.splice(r.findIndex(s=>_l.test(s))+1,0,...[...n].map(([s,o])=>`${s} = ${JSON.stringify(o)}`)),r},em=(e,t)=>{let[n,...r]=Zd(e);if(!n)return null;let s=e;for(let[o,i]of r.reverse())s=[...s.slice(0,o),...s.slice(i)];return[...s.slice(0,n[0]+1),...Qd(s.slice(n[0]+1,n[1]),t),...s.slice(n[1])]},Sl=(e,t)=>{let n=us(t);if(e===null||e.trim()==="")return n;try{Me(e)}catch{throw new Le("not valid TOML, left untouched; add the provider block by hand")}if(ul(e,t))return null;let r=e.includes(`\r
|
|
150
|
+
`)?`\r
|
|
151
|
+
`:`
|
|
152
|
+
`,s={api_base:`${t}/v1`,api_key_env_var:pe,backend:"mistral"},o=Al(Me(e)).length>0?em(e.split(/\r?\n/),s):null,i=o?o.join(r):`${e.trimEnd()}${r}${r}${n.replace(/\n/g,r)}`;if(!ul(i,t))throw new Le("could not edit the existing mistwatch provider; edit it by hand");return i},tm=/^\s*\[\s*server\s*\]\s*(#.*)?$/,ll=/^(\s*port\s*=\s*)\d+(\s*(?:#.*)?)$/,cl=e=>{let t=Me(e).server;return To(t)?t.port:void 0},xl=(e,t)=>{try{if(cl(e)===t)return null}catch{throw new Le("not valid TOML, left untouched; set [server] port by hand")}let n=e.includes(`\r
|
|
153
|
+
`)?`\r
|
|
154
|
+
`:`
|
|
155
|
+
`,r=e.split(/\r?\n/),s=r.findIndex(i=>tm.test(i)),o;if(s===-1)o=`${e.trimEnd()}${e.trim()===""?"":n+n}[server]${n}port = ${t}${n}`;else{let i=s+1;for(;i<r.length&&!/^\s*\[/.test(r[i]??"");)i++;let a=r.findIndex((u,l)=>l>s&&l<i&&ll.test(u));a===-1?r.splice(s+1,0,`port = ${t}`):r[a]=(r[a]??"").replace(ll,`$1${t}$2`),o=r.join(n)}try{if(cl(o)===t)return o}catch{}throw new Le("could not set [server] port in config.toml; edit it by hand")},nm={ok:{glyph:"\u2713",ascii:"[ok] ",color:Wd},warn:{glyph:"!",ascii:"[warn]",color:Kd},fail:{glyph:"\u2717",ascii:"[fail]",color:gl},skip:{glyph:"\xB7",ascii:"[skip]",color:null}},xo=(e,t)=>e.startsWith(t)?`~${e.slice(t.length)}`:e,q=(e,t,n,r)=>{e.report.steps.push({step:n,status:t,message:r}),t==="fail"&&(e.report.ok=!1);let s=nm[t],o=e.style.unicode?s.color?e.style.paint(s.glyph,s.color):e.style.dim(s.glyph):s.ascii;e.say(` ${o} ${e.style.bold(n.padEnd(13))} ${r}`)},Rl=async(e,t,n)=>{if(e.auto)return n;let r=n?"[Y/n]":"[y/N]";for(let s=0;s<3;s++){let o=await e.deps.io.ask(` ${e.style.accent("?")} ${t} ${e.style.dim(r)} `);if(o===null)return!1;let i=o.trim().toLowerCase();if(i==="")return n;if(i==="y"||i==="yes")return!0;if(i==="n"||i==="no")return!1}return n},rm=e=>{let t=zt(),n=xo(t,e.deps.home),r=Ro(t),{port:s}=e.opts,o=e.report.config;o.path=t;let i=!r||e.opts.force,u=Oo(t,l=>{let f=i?Qr:l??"",d=s===null?f:xl(f,s)??f;return i||d!==l?d:null},e.deps.now());o.backup=u.backup,u.action==="unchanged"?(o.action="kept",q(e,"ok","Config",`${n} already exists${s===null?"":` and uses port ${s}`}, keeping it`)):i?(o.action=r?"replaced":"created",q(e,"ok","Config",r?`replaced ${n} (backup kept)`:`created ${n}`)):(o.action="updated",q(e,"ok","Config",`set port ${s} in ${n} (backup kept)`))},sm=async(e,t)=>{let n=t.listAccounts().find(s=>s.keys.vibe===Re);if(n){e.report.vibe_login="linked",q(e,"ok","Vibe login",`account '${n.name}' already follows the Vibe CLI login`);return}if(!e.deps.vibeKeyPresent()){e.report.vibe_login="missing",q(e,"warn","Vibe login","not found in the keyring; run `vibe --setup`, then `mistwatch import-vibe`");return}if(!await Rl(e,"Found a Vibe CLI login. Import it as an account?",!0)){e.report.vibe_login="missing",q(e,"skip","Vibe login","not imported (run `mistwatch import-vibe` later)");return}let r=Ss(t);try{xs(t,r)}catch(s){if(!(s instanceof I))throw s;e.report.vibe_login="failed",q(e,"fail","Vibe login",s.message);return}e.report.vibe_login="imported",q(e,"ok","Vibe login",`imported as account '${r}'`)},om=(e,t)=>{let n=t.listApiKeys().length,r=e.report.client_token;if(r.existing_keys=n,n>0){q(e,"ok","Client token",`${n===1?"1 key already exists":`${n} keys already exist`}, not creating another`);return}if(e.opts.json&&!e.opts.showToken){r.token="skipped",r.hint="no client token created: --json without --show-token would lose it; add --show-token or run without --json",q(e,"skip","Client token","not created (--json without --show-token would lose it)");return}let[,s]=t.createApiKey("setup");e.newToken=s,r.created=!0,r.masked=tr(s),e.opts.showToken&&(r.token=s),q(e,"ok","Client token",`created key 'setup' (${r.masked}), shown once below`)},im=e=>{let t=Number(e),n=Number.isInteger(t)?$e[t-1]:void 0;if(n)return n;let r=e.toLowerCase();return dl(r)?r:null},Tl=e=>{let t=e.split(/[\s,]+/).filter(Boolean);if(t.includes("all"))return[...$e];let n=t.map(im);return t.length>0&&n.every(r=>r!==null)?$e.filter(r=>n.includes(r)):null},am=async e=>{if(e.opts.harness)return e.opts.harness;if(e.auto)return["vibe"];let{io:t}=e.deps;t.out(`
|
|
156
|
+
${e.style.accent("?")} Which tools should use Mistwatch?`);for(let[n,r]of $e.entries())t.out(` ${n+1} ${Un[r].label}${n===0?e.style.dim(" (default)"):""}`);for(let n=0;n<3;n++){let r=(await t.ask(" Numbers or names, comma-separated, 'all', or Enter for the default: ")??"").trim();if(r==="")return["vibe"];let s=Tl(r);if(s)return s;t.out(` ${e.style.paint("Not understood.",gl)}`)}return["vibe"]},um=e=>({vibe:Ao(e.vibeHome,"config.toml"),opencode:jn(e.home,e.platform),pi:Ao(e.home,".pi","agent","models.json")}),lm=(e,t,n)=>{let r=um(e.deps)[t],s=je(n),o=Un[t].label,i=xo(r,e.deps.home),a={harness:t,path:r,action:"failed",backup:null};e.report.harnesses.push(a);try{let l=Oo(r,d=>t==="vibe"?Sl(d,s):El(d,t==="pi"?Xt(s):Jt(s)),e.deps.now());a.action=l.action,a.backup=l.backup;let f=l.action==="unchanged"?`${i} is already up to date`:`${l.action==="created"?"wrote":"updated"} ${i}${l.backup?` (backup: ${xo(l.backup,e.deps.home)})`:""}`;q(e,"ok",o,f)}catch(u){q(e,"fail",o,`${i}: ${Cr(u)}`)}},cm=(e,t)=>{let n=tn(t.db,t.cfg.limits),r=t.store.listAccounts(),s=0;for(let a of r)for(let u of Ue)n.status(a.name,u)&&s++;let o=r.length;e.report.status={ok:!0,accounts:o,pools_with_budget:s};let i=o===0?"no account yet, add one in the web UI":`budgets load after the first sync (${s} pools so far)`;q(e,"ok","Status",`OK. ${o} account${o===1?"":"s"}; ${i}`)},fm=e=>e==="win32"?"setx MISTWATCH_TOKEN <token> (then open a new terminal)":"export MISTWATCH_TOKEN=<token> (add it to your shell profile)",pm={vibe:'In Vibe, set provider = "mistwatch" on the models you use.',opencode:'In OpenCode, pick a model of the "mistwatch" provider (start with auto).',pi:"In Pi, pick the mistwatch provider and the model auto."},dm=(e,t)=>{let{style:n,report:r}=e,s=[];e.newToken?(s.push("",` ${n.accent("Client token")} ${n.dim("(shown once, copy it now)")}`,` ${e.newToken}`,""),s.push(` ${n.accent("Make it available to your tools")}`,` ${fm(e.deps.platform)}`)):r.client_token.existing_keys>0&&s.push("",` Use one of your existing keys as ${pe}, or create another under "API keys" in the web UI.`),s.push("",` ${n.accent("Next steps")}`);let o=t?je(t,"/"):"http://127.0.0.1:8787/";r.vibe_login==="missing"&&s.push(" - Run `vibe --setup`, then `mistwatch import-vibe` (or add a key in the web UI)."),s.push(` - Start the proxy: mistwatch serve (web UI: ${o})`);for(let i of r.harnesses)i.action!=="failed"&&s.push(` - ${pm[i.harness]}`);return s},mm=async(e,t)=>{try{await e.deps.start(t),e.report.started=!0}catch(n){q(e,"fail","Serve",Cr(n))}},hm=async(e,t)=>{let{io:n}=t,r;try{r=yl(e)}catch(l){if(!(l instanceof We))throw l;return n.err(`mistwatch: ${l.message}`),n.err("usage: mistwatch setup [--yes] [--harness vibe,opencode,pi] [--port N] [--no-banner] [--start] [--json]"),2}if(r.help)return n.out(pl),0;let s=bl(n.depth),o={deps:t,opts:r,style:s,auto:r.yes||r.json||!n.interactive,report:{ok:!0,steps:[],config:{path:zt(),action:"failed",backup:null},vibe_login:"missing",client_token:{created:!1,existing_keys:0,masked:null},harnesses:[],status:null,started:!1},newToken:null,say:l=>{r.json||n.out(l)}},i=null;r.noBanner||o.say(`${vl(s,"Budget-aware proxy for Mistral").join(`
|
|
157
|
+
`)}
|
|
158
|
+
`);let a=null;try{rm(o),a=As(),i=a.cfg,await sm(o,a.store);let l=await am(o);om(o,a.store);for(let f of l)lm(o,f,a.cfg);cm(o,a)}catch(l){q(o,"fail","Setup",Cr(l))}finally{a?.db.close()}for(let l of dm(o,i))o.say(l);o.report.ok&&i&&(!r.start&&!o.auto&&o.say(""),(r.start||!o.auto&&await Rl(o,"Start Mistwatch now?",!0))&&(n.close(),await mm(o,i))),n.close();let u=o.report.steps.find(l=>l.status==="fail");return r.json&&n.out(JSON.stringify(o.report,null,2)),u&&n.err(`mistwatch: setup failed: ${u.step}: ${u.message}`),o.report.ok?0:1},Ol=(e=process.stdin,t=process.stdout)=>{let n=null,r=!1;return{ask:async s=>{if(r)return null;if(!n){let{createInterface:a}=await import("node:readline/promises"),u=a({input:e,output:t});n=u,u.on("SIGINT",()=>{t.write(`
|
|
159
|
+
`),process.exit(130)}),u.once("close",()=>{n===u&&(n=null,r=!0)})}let o=n,i=new Promise(a=>o.once("close",()=>a(null)));return Promise.race([o.question(s).catch(()=>null),i])},close:()=>{let s=n;n=null,s?.close()}}},ym=()=>{let e=!!process.stdout.isTTY,t=Md(),n=r=>process.stdout instanceof Ud?process.stdout.getColorDepth(r):1;return{io:{out:r=>process.stdout.write(`${r}
|
|
160
|
+
`),err:r=>process.stderr.write(`${r}
|
|
161
|
+
`),...Ol(),interactive:!!process.stdin.isTTY&&e,depth:wl(process.env,e,n)},home:t,vibeHome:process.env.VIBE_HOME||Ao(t,".vibe"),platform:process.platform,now:()=>new Date,vibeKeyPresent:()=>xt(),start:async r=>(await Promise.resolve().then(()=>(Eo(),ko))).startServer(r)}}});Yt();W();import{existsSync as gm,realpathSync as bm}from"node:fs";import{homedir as wm}from"node:os";import{join as vm,resolve as km}from"node:path";import{fileURLToPath as Em}from"node:url";import{parseArgs as _m}from"node:util";var Cl=`usage: mistwatch <command> [options]
|
|
162
|
+
|
|
163
|
+
commands:
|
|
164
|
+
setup one-step setup for your tools (--yes --harness --port --start --json)
|
|
165
|
+
init write the config template (--force, --import-vibe)
|
|
166
|
+
import-vibe add the Vibe CLI keyring login as an account (--name)
|
|
167
|
+
status budget status of every account/pool (--json)
|
|
168
|
+
sync pull budget usage from Mistral now
|
|
169
|
+
serve run the proxy and web UI (--port)
|
|
170
|
+
route dry-run the auto router on a prompt (--model --tools --llm --pressure)
|
|
171
|
+
passwd create a user / reset a password
|
|
172
|
+
vibe-config print the Vibe CLI provider block
|
|
173
|
+
agent-config provider config for pi|opencode (--write, --env)`,En=async()=>(await Promise.resolve().then(()=>(nr(),Rs))).openApp(),$l=e=>je(e),Co=null,Ll=async()=>{if(Co===null){let e="";process.stdin.setEncoding("utf8");for await(let t of process.stdin)e+=t;Co=e.split(`
|
|
174
|
+
`)}return Co},Am=async()=>(await Ll()).join(`
|
|
175
|
+
`).replace(/\r/g,""),Pl=async e=>{process.stderr.write(e);let t=process.stdin;return t.isTTY?new Promise(n=>{t.setRawMode(!0),t.resume();let r="",s=()=>{t.removeAllListeners("data"),t.setRawMode(!1),t.pause(),process.stderr.write(`
|
|
176
|
+
`),n(r)};t.on("data",o=>{for(let i of o.toString("utf8")){if(i==="\r"||i===`
|
|
177
|
+
`||i===""||i==="")return s();i===""?process.exit(130):i==="\b"||i==="\x7F"?r=r.slice(0,-1):r+=i}})}):((await Ll()).shift()??"").replace(/\r$/,"")},Po=e=>{if(!e)return"-";let t=new Date(e*1e3),n=r=>String(r).padStart(2,"0");return`${n(t.getDate())}.${n(t.getMonth()+1)}. ${n(t.getHours())}:${n(t.getMinutes())}`},Il=e=>e.toFixed(2),Ne=e=>e.toFixed(3),Sm=e=>{let t=[`sync: ${Po(e.last_sync)}`];for(let n of e.pools){let r=n.blocked_by?`BLOCKED(${n.blocked_by})`:"ok";t.push(`
|
|
178
|
+
[${n.account}/${n.pool}] ${r} used ${Il(n.used_eur)} / ${Il(n.initial_eur)} EUR (${(n.used_eur/n.initial_eur*100).toFixed(1)} %) reset in ${n.days_left.toFixed(1)} d`),t.push(` fair share/day: ${Ne(n.daily_fair_share_eur)} EUR room now: ${Ne(n.room_eur)} EUR`+(n.retry_at?` retry: ${Po(n.retry_at)}`:""));let s=n.month;t.push(` ${"month".padStart(6)} spent ${Ne(s.spent).padStart(8)} cap ${Ne(s.cap).padStart(8)} room ${Ne(s.room).padStart(8)}`);for(let[o,i]of Object.entries(n.windows))t.push(` ${o.padStart(6)} spent ${Ne(i.spent).padStart(8)} cap ${Ne(i.cap).padStart(8)} room ${Ne(i.room).padStart(8)}`+(i.retry_at?` free again ${Po(i.retry_at)}`:""))}if(e.by_client_7d.length){t.push(`
|
|
179
|
+
last 7 days by client:`);for(let n of e.by_client_7d)t.push(` ${n.client.padEnd(14)} ${n.account}/${n.pool.padEnd(5)} ${String(n.n).padStart(5)} req ${Ne(n.cost_eur)} EUR`)}return t.join(`
|
|
180
|
+
`)},Pr=class extends Error{},ct=e=>{try{return _m(e)}catch(t){throw console.error(`mistwatch: ${t instanceof Error?t.message:String(t)}`),new Pr}},xm=async e=>{let{values:t}=ct({args:e,options:{force:{type:"boolean",default:!1},"import-vibe":{type:"boolean",default:!1}},strict:!0}),{configPath:n,CONFIG_TEMPLATE:r}=await Promise.resolve().then(()=>(W(),mt)),s=n();if(gm(s)&&!t.force)return console.log(`${s} already exists (use --force)`),1;let{applyFile:o}=await Promise.resolve().then(()=>(kn(),vn)),i=o(s,()=>r,new Date);return console.log(`wrote ${s}${i.backup?` (backup: ${i.backup})`:""}`),t["import-vibe"]?Nl(["--name","vibe-login"]):(console.log("Next: `mistwatch serve`, then open the web UI to create your login and add keys."),0)},Nl=async e=>{let{values:t}=ct({args:e,options:{name:{type:"string",default:"vibe-login"}},strict:!0}),{StoreError:n,vibeCliKeyPresent:r}=await Promise.resolve().then(()=>(nt(),_s)),{linkVibeLogin:s}=await Promise.resolve().then(()=>(nr(),Rs));if(!r())return console.log("No Vibe CLI key found in the OS keyring (run `vibe --setup` first)."),1;let{store:o}=await En(),i=t.name;try{s(o,i)}catch(a){if(a instanceof n)return console.log(a.message),1;throw a}return console.log(`account '${i}' now follows the Vibe CLI login`),0},Rm=async e=>{let{runSetup:t,defaultSetupDeps:n}=await Promise.resolve().then(()=>(kn(),vn));return t(e,n())},Tm=async e=>{let{positionals:t}=ct({args:e,allowPositionals:!0,strict:!0}),[n]=t;if(!n)return console.error("mistwatch: passwd requires a username"),2;let{store:r}=await En(),{StoreError:s}=await Promise.resolve().then(()=>(nt(),_s)),o=await Pl("New password: ");if(o!==await Pl("Again: "))return console.log("Passwords differ."),1;try{let i=r.findUser(n);i?(r.setPassword(i.id,o),r.deleteOtherSessions(i.id,null)):r.createUser(n,o)}catch(i){if(i instanceof s)return console.log(i.message),1;throw i}return console.log("ok"),0},Om=async e=>{let{values:t}=ct({args:e,options:{json:{type:"boolean",default:!1}},strict:!0}),{createBudgetEngine:n,poolStatusDict:r}=await Promise.resolve().then(()=>(et(),mi)),{cfg:s,db:o}=await En(),i=n(o,s.limits),a=[],u=0;for(let f of s.accounts)for(let d of["vibe","api"])u=Math.max(u,o.latestSnapshot(f.name,d)?.ts??0);let l={last_sync:u,pools:a,by_client_7d:o.byClientSince(Date.now()/1e3-7*86400)};for(let f of s.accounts)for(let d of["vibe","api"]){let p=i.status(f.name,d);p&&l.pools.push(r(p))}return o.close(),console.log(t.json?yt(l):Sm(l)),0},Cm=async()=>{let{syncAll:e}=await Promise.resolve().then(()=>(wn(),vu)),{cfg:t,db:n}=await En(),r=await e(fetch,t,n);return n.close(),console.log(yt(r)),0},Pm=async e=>{let{values:t}=ct({args:e,options:{port:{type:"string"}},strict:!0}),{loadConfig:n}=await Promise.resolve().then(()=>(W(),mt)),{startServer:r}=await Promise.resolve().then(()=>(Eo(),ko)),s=n();if(t.port!==void 0){let{parsePort:o}=await Promise.resolve().then(()=>(kn(),vn));try{s.port=o(t.port)??s.port}catch(i){return console.error(`mistwatch: ${i instanceof Error?i.message:String(i)}`),2}}return await r(s),0},Im=async e=>{let{values:t,positionals:n}=ct({args:e,allowPositionals:!0,options:{model:{type:"string",default:"auto"},tools:{type:"boolean",default:!1},llm:{type:"boolean",default:!1},pressure:{type:"string",default:"1.0"}},strict:!0}),r=Number.parseFloat(t.pressure);if(!Number.isFinite(r))return console.error("mistwatch: --pressure must be a number"),2;let{decide:s}=await Promise.resolve().then(()=>(Ye(),Zo)),i={messages:[{role:"user",content:n.length?n.join(" "):await Am()}]};t.tools&&(i.tools=[{type:"function"}]);let a=null;if(t.llm){let{rate:l}=await Promise.resolve().then(()=>(oo(),pu)),{keyFor:f}=await Promise.resolve().then(()=>(W(),mt)),{cfg:d}=await En(),p=d.accounts.find(y=>Object.keys(y.keys).length>0);if(!p)return console.error("mistwatch: no account with keys configured"),1;let c="api"in p.keys?"api":Object.keys(p.keys)[0]??"api",m=await l(fetch,d.upstream,f(p,c)??"",i,d.router.classifier_model,d.router.classifier_timeout_s);a=m?m[0]:null,console.log(`tiny LLM (${d.router.classifier_model}): ${a??"None"}`)}let u=s(i,t.model,r,a);return console.log(`${u.model} effort=${u.effort??"None"} level=${u.level}/6 score=${u.score}/10`),console.log(` ${u.reason}`),0},$m=async()=>{let{loadConfig:e}=await Promise.resolve().then(()=>(W(),mt)),t=$l(e());return console.log(`Point Vibe CLI at the proxy: add to ~/.vibe/config.toml
|
|
181
|
+
|
|
182
|
+
[[providers]]
|
|
183
|
+
name = "mistwatch"
|
|
184
|
+
api_base = "${t}/v1"
|
|
185
|
+
api_key_env_var = "MISTWATCH_TOKEN"
|
|
186
|
+
backend = "mistral"
|
|
187
|
+
|
|
188
|
+
# then re-point your models' provider = "mistwatch" and set
|
|
189
|
+
# MISTWATCH_TOKEN=<a key generated on the "API keys" page of the web UI>
|
|
190
|
+
Other tools: base URL ${t}/v1, API key = that same key.`),0},Lm=async e=>{let{values:t,positionals:n}=ct({args:e,allowPositionals:!0,options:{write:{type:"boolean",default:!1},env:{type:"string",default:"MISTWATCH_TOKEN"}},strict:!0}),[r]=n;if(r!=="pi"&&r!=="opencode")return console.error("mistwatch: agent-config requires tool 'pi' or 'opencode'"),2;let{loadConfig:s}=await Promise.resolve().then(()=>(W(),mt)),o=t.env,i=$l(s()),a=wm(),u=r==="pi"?Xt(i,o):Jt(i,o),l=r==="pi"?vm(a,".pi","agent","models.json"):jn(a,process.platform);if(!t.write)return console.log(`# ${l}
|
|
191
|
+
${yt(u)}`),console.error(`
|
|
192
|
+
# set ${o}=<a key from the API keys page>; add --write to merge this into the file`),0;let{applyFile:f,planJson:d,SetupError:p}=await Promise.resolve().then(()=>(kn(),vn));try{let c=f(l,m=>d(m,u),new Date);console.log(c.action==="unchanged"?`${l} is already up to date`:`wrote ${l}${c.backup?` (backup: ${c.backup})`:""}. Set ${o}=<key from the API keys page>.`)}catch(c){if(!(c instanceof p))throw c;return console.log(`${l}: ${c.message}. Paste the block above manually.`),1}return 0},Nm=async e=>{let[t,...n]=e;try{return t===void 0?(console.error(Cl),2):t==="-h"||t==="--help"||t==="help"?(console.log(Cl),0):t==="setup"?await Rm(n):t==="init"?await xm(n):t==="import-vibe"?await Nl(n):t==="passwd"?await Tm(n):t==="status"?await Om(n):t==="sync"?await Cm():t==="serve"?await Pm(n):t==="route"?await Im(n):t==="vibe-config"?await $m():t==="agent-config"?await Lm(n):(console.error(`mistwatch: unknown command '${t}'`),2)}catch(r){if(r instanceof Pr)return 2;throw r}},Dm=()=>{let e=process.argv[1];if(!e)return!1;let t=n=>{try{return bm(n).toLowerCase()}catch{return km(n).toLowerCase()}};return t(e)===t(Em(import.meta.url))};if(Dm())try{process.exitCode=await Nm(process.argv.slice(2))}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1}export{Nm as main};
|