ezllm 0.0.47 → 0.0.48
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/dist/cli.js +24 -24
- package/dist/daemon.js +15 -14
- package/dist/plugin-host.js +3 -3
- package/dist/server.js +9 -9
- package/dist/web-ui/assets/{DashboardView-CqupMCmm.js → DashboardView-CJOcLFY-.js} +1 -1
- package/dist/web-ui/assets/{LayoutView-CyOrx1rA.js → LayoutView-DH55aSBP.js} +1 -1
- package/dist/web-ui/assets/{LoginView-YolyK2Q0.js → LoginView-Cp-a8Nds.js} +1 -1
- package/dist/web-ui/assets/{LogsView-E64a6PIt.js → LogsView-C1ImQHJ6.js} +1 -1
- package/dist/web-ui/assets/{ManagedServicesView-mk_mSWzE.js → ManagedServicesView-DIMY-j18.js} +1 -1
- package/dist/web-ui/assets/PluginsView-Bnwsd3-R.css +1 -0
- package/dist/web-ui/assets/PluginsView-CqmYhJ6G.js +2 -0
- package/dist/web-ui/assets/{ProvidersView-BrirhwQN.js → ProvidersView-uCjHMlHd.js} +1 -1
- package/dist/web-ui/assets/{SettingsView-p3uvWhGh.js → SettingsView-BbmPwJ-1.js} +1 -1
- package/dist/web-ui/assets/{SetupView-CGQibXHs.js → SetupView-WCA8Jeug.js} +1 -1
- package/dist/web-ui/assets/{config-Dzo6AFZx.js → config-BKCqJSgG.js} +1 -1
- package/dist/web-ui/assets/{index-wQG3qUgW.js → index-DNgY-btf.js} +1 -1
- package/dist/web-ui/assets/{message-C8pR37GK.js → message-Bqg-4z7y.js} +1 -1
- package/dist/web-ui/assets/pluginProviders-BGmYcLwJ.js +1 -0
- package/dist/web-ui/assets/{providers-Dbg0NkwB.js → providers-DRvT1zLg.js} +1 -1
- package/dist/web-ui/assets/{router-JpU_7F6L.js → router-CpkAp9dB.js} +2 -2
- package/dist/web-ui/assets/{useCopyToast-GaJ4QVNE.js → useCopyToast-DwJ3VhPN.js} +1 -1
- package/dist/web-ui/assets/{useManagerApi-DEPhOKWy.js → useManagerApi-Cf88mNiu.js} +1 -1
- package/dist/web-ui/assets/{useQuickRangeFilter-DeKORPZt.js → useQuickRangeFilter-BsOHHbog.js} +1 -1
- package/dist/web-ui/assets/useToast-IlI6ESuD.js +1 -0
- package/dist/web-ui/index.html +3 -3
- package/package.json +1 -1
- package/dist/web-ui/assets/PluginsView-DTJeufic.js +0 -2
- package/dist/web-ui/assets/PluginsView-DzHAW2gO.css +0 -1
- package/dist/web-ui/assets/pluginProviders-DeHPKGnd.js +0 -1
- package/dist/web-ui/assets/useToast-DVCDN-da.js +0 -1
package/dist/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import{createServer as t}from"http";import{Http2ServerRequest as n,constants as r}from"http2";import{Readable as i}from"stream";import a from"crypto";import{basename as o,dirname as s,join as c,resolve as l}from"node:path";import{cwd as u}from"node:process";import{closeSync as d,copyFileSync as f,existsSync as p,mkdirSync as m,openSync as h,readFileSync as g,readdirSync as _,renameSync as v,rmSync as y,rmdirSync as b,statSync as x,unlinkSync as S,writeFileSync as C}from"node:fs";import{homedir as w,hostname as T,networkInterfaces as ee,platform as te}from"node:os";import{fileURLToPath as ne,pathToFileURL as re}from"node:url";import{createHash as ie,randomBytes as ae,randomUUID as oe}from"node:crypto";import{Readable as se}from"node:stream";import{mkdir as ce,readFile as le,rename as ue,writeFile as de}from"node:fs/promises";import{DatabaseSync as fe}from"node:sqlite";import{brotliCompressSync as pe,brotliDecompressSync as me,constants as he}from"node:zlib";import{AsyncLocalStorage as ge}from"node:async_hooks";import{execFileSync as _e,spawn as ve}from"node:child_process";import{versions as ye}from"process";import{createReadStream as be,existsSync as xe,statSync as Se}from"fs";import{join as Ce}from"path";var E=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),we=e(import.meta.url),Te=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Ee=e=>e instanceof Te?e:new Te(e.message,{cause:e}),De=global.Request,Oe=class extends De{constructor(e,t){typeof e==`object`&&Me in e&&(e=e[Me]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},ke=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},Ae=Symbol(`wrapBodyStream`),je=(e,t,n,r,a)=>{let o={method:e,headers:n,signal:a.signal};if(e===`TRACE`){o.method=`GET`;let e=new Oe(t,o);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[Ae]){let e;o.body=new ReadableStream({async pull(t){try{e||=i.toWeb(r).getReader();let{done:n,value:a}=await e.read();n?t.close():t.enqueue(a)}catch(e){t.error(e)}}})}else o.body=i.toWeb(r)}return new Oe(t,o)},Me=Symbol(`getRequestCache`),Ne=Symbol(`requestCache`),Pe=Symbol(`incomingKey`),Fe=Symbol(`urlKey`),Ie=Symbol(`headersKey`),Le=Symbol(`abortControllerKey`),Re={get method(){return this[Pe].method||`GET`},get url(){return this[Fe]},get headers(){return this[Ie]||=ke(this[Pe])},[Symbol(`getAbortController`)](){return this[Me](),this[Le]},[Me](){return this[Le]||=new AbortController,this[Ne]||=je(this.method,this[Fe],this.headers,this[Pe],this[Le])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Re,e,{get(){return this[Me]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Re,e,{value:function(){return this[Me]()[e]()}})}),Object.defineProperty(Re,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[Ne]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Re,Oe.prototype);var ze=(e,t)=>{let r=Object.create(Re);r[Pe]=e;let i=e.url||``;if(i[0]!==`/`&&(i.startsWith(`http://`)||i.startsWith(`https://`))){if(e instanceof n)throw new Te(`Absolute URL for :path is not allowed in HTTP/2`);try{r[Fe]=new URL(i).href}catch(e){throw new Te(`Invalid absolute URL`,{cause:e})}return r}let a=(e instanceof n?e.authority:e.headers.host)||t;if(!a)throw new Te(`Missing host header`);let o;if(e instanceof n){if(o=e.scheme,o!==`http`&&o!==`https`)throw new Te(`Unsupported scheme`)}else o=e.socket&&e.socket.encrypted?`https`:`http`;let s=new URL(`${o}://${a}${i}`);if(s.hostname.length!==a.length&&s.hostname!==a.replace(/:\d+$/,``))throw new Te(`Invalid host header`);return r[Fe]=s.href,r},Be=Symbol(`responseCache`),Ve=Symbol(`getResponseCache`),He=Symbol(`cache`),Ue=global.Response,We=class e{#e;#t;[Ve](){return delete this[He],this[Be]||=new Ue(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Be];if(e){this.#t=e,this[Ve]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[He]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[He];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Ve]().headers}get status(){return this[He]?.[0]??this[Ve]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(We.prototype,e,{get(){return this[Ve]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(We.prototype,e,{value:function(){return this[Ve]()[e]()}})}),Object.defineProperty(We.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[Be]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(We,Ue),Object.setPrototypeOf(We.prototype,Ue.prototype);async function Ge(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Ke(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function qe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return Ke(e.getReader(),t)}var Je=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Ye=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=a);var Xe=Symbol(`outgoingEnded`),Ze=Symbol(`incomingDraining`),Qe=500,$e=67108864,et=e=>{let t=e;if(e.destroyed||t[Ze])return;if(t[Ze]=!0,e instanceof n){try{e.stream?.close?.(r.NGHTTP2_NO_ERROR)}catch{}return}let i=0,a=()=>{clearTimeout(s),e.off(`data`,c),e.off(`end`,a),e.off(`error`,a)},o=()=>{a();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},s=setTimeout(o,Qe);s.unref?.();let c=e=>{i+=e.length,i>$e&&o()};e.on(`data`,c),e.on(`end`,a),e.on(`error`,a),e.resume()},tt=()=>new Response(null,{status:400}),nt=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),rt=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},it=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},at=async(e,t)=>{let[n,r,i]=e[He],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=Je(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Je(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(it(t),await qe(r,t)?.catch(e=>rt(e,t))),t[Xe]?.()},ot=e=>typeof e.then==`function`,st=async(e,t,n={})=>{if(ot(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(nt)}if(He in e)return at(e,t);let r=Je(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Ge(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&it(t),await Ke(n,t,o))}else r[Ye]||(t.writeHead(e.status,r),t.end());t[Xe]?.()},ct=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Oe&&(Object.defineProperty(global,"Request",{value:Oe}),Object.defineProperty(global,"Response",{value:We})),async(i,a)=>{let o,s;try{s=ze(i,t.hostname);let c=!r||i.method===`GET`||i.method===`HEAD`;if(c||(i[Ae]=!0,i.on(`end`,()=>{c=!0}),i instanceof n&&(a[Xe]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{et(i)})})}),a.on(`finish`,()=>{c||et(i)})),a.on(`close`,()=>{s[Le]&&(i.errored?s[Le].abort(i.errored.toString()):a.writableFinished||s[Le].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{et(i)})})}),o=e(s,{incoming:i,outgoing:a}),He in o)return at(o,a)}catch(e){if(o)return rt(e,a);if(t.errorHandler){if(o=await t.errorHandler(s?e:Ee(e)),!o)return}else o=s?nt(e):tt()}try{return await st(o,a,t)}catch(e){return rt(e,a)}}},lt=e=>{let n=e.fetch,r=ct(n,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||t)(e.serverOptions||{},r)},ut=(e,t)=>{let n=lt(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function D(e,...t){console.log(e,...t)}function O(e,...t){console.warn(e,...t)}function k(e,...t){console.error(e,...t)}function dt(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function ft(e){let t=`--${e}`,n=`${t}=`,r=process.argv;for(let e=0;e<r.length;e+=1){let i=r[e]??``;if(i.startsWith(n))return dt(i.slice(n.length));if(i===t){let t=r[e+1]??``;return t.startsWith(`-`)?void 0:dt(t)}}}function pt(e,t){return ft(e)??dt(process.env[t])}var mt=65535;function ht(e){let t=dt(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0&&n<=mt?n:void 0}var gt=(()=>{let e=pt(`app-dir`,`ELLM_APP_DIR`),t=e===void 0?void 0:l(u(),e),n=ft(`port`),r=ht(n??dt(process.env.ELLM_PORT));n!==void 0&&r===void 0&&O(`--port=${n} 无效(需为 1-65535 的整数),已忽略:本次不生效、也不会写入配置文件。`);let i=pt(`node-mirror`,`ELLM_NODE_MIRROR`),a=pt(`node-bin`,`ELLM_NODE_BIN`);return t!==void 0&&(process.env.ELLM_APP_DIR=t),i!==void 0&&(process.env.ELLM_NODE_MIRROR=i),a!==void 0&&(process.env.ELLM_NODE_BIN=a),{appDir:t,port:r,nodeMirror:i,nodeBin:a}})(),_t=s(ne(import.meta.url)),vt=`runtime.json`,yt;function bt(e){try{let t=g(c(e,vt),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function xt(){let e=bt(Ct())?.source;return typeof e==`string`&&e!==``?e:void 0}function St(){return c(w(),`.ezllm`)}function Ct(){return yt===void 0&&(yt=gt.appDir??St()),yt}function wt(){return l(Ct(),`data`)}function Tt(){return l(Ct(),`ezllm.config.json`)}function Et(){return l(wt(),`ipinfo.json`)}function Dt(){return l(Ct(),`logs`)}function Ot(){return l(wt(),`updater.json`)}function kt(){return l(Ct(),`provider-auth.json`)}function At(){return l(Ct(),`plugin-auth.json`)}var jt=[`hook.cjs`,`hook.mjs`,`hook.js`];function Mt(){return jt.map(e=>c(Ct(),e))}var Nt=`ezllm`;function Pt(e=Ct()){return l(e,`node`,`node_modules`,Nt)}function Ft(e){try{let t=g(c(e,`package.json`),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function It(e,t){let n=_t;for(let r=0;r<t;r++){if(Ft(n)?.name===e)return n;n=s(n)}return null}var Lt=It(`ezllm`,5)??l(_t,`..`);It(`ellm`,6);function Rt(){return Ft(Lt)?.name===`ezllm`}function zt(){let e=Ft(Lt);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function Bt(){let e=wt();p(e)||m(e,{recursive:!0})}function Vt(e,t){let n=`${e}.${`${process.pid}.${ae(6).toString(`hex`)}`}.tmp`;try{C(n,JSON.stringify(t,null,2)+`
|
|
2
|
+
import{createRequire as e}from"node:module";import{createServer as t}from"http";import{Http2ServerRequest as n,constants as r}from"http2";import{Readable as i}from"stream";import a from"crypto";import{basename as o,dirname as s,join as c,resolve as l}from"node:path";import{cwd as u}from"node:process";import{closeSync as d,copyFileSync as f,existsSync as p,mkdirSync as m,openSync as h,readFileSync as g,readdirSync as _,renameSync as v,rmSync as y,rmdirSync as b,statSync as x,unlinkSync as S,writeFileSync as C}from"node:fs";import{homedir as w,hostname as T,networkInterfaces as ee,platform as te}from"node:os";import{fileURLToPath as ne,pathToFileURL as re}from"node:url";import{createHash as ie,randomBytes as ae,randomUUID as oe}from"node:crypto";import{execFileSync as se,spawn as ce}from"node:child_process";import{Readable as le}from"node:stream";import{mkdir as ue,readFile as de,rename as fe,writeFile as pe}from"node:fs/promises";import{DatabaseSync as me}from"node:sqlite";import{brotliCompressSync as he,brotliDecompressSync as ge,constants as _e}from"node:zlib";import{AsyncLocalStorage as ve}from"node:async_hooks";import{versions as ye}from"process";import{createReadStream as be,existsSync as xe,statSync as Se}from"fs";import{join as Ce}from"path";var E=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),we=e(import.meta.url),Te=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Ee=e=>e instanceof Te?e:new Te(e.message,{cause:e}),De=global.Request,Oe=class extends De{constructor(e,t){typeof e==`object`&&Me in e&&(e=e[Me]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},ke=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},Ae=Symbol(`wrapBodyStream`),je=(e,t,n,r,a)=>{let o={method:e,headers:n,signal:a.signal};if(e===`TRACE`){o.method=`GET`;let e=new Oe(t,o);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[Ae]){let e;o.body=new ReadableStream({async pull(t){try{e||=i.toWeb(r).getReader();let{done:n,value:a}=await e.read();n?t.close():t.enqueue(a)}catch(e){t.error(e)}}})}else o.body=i.toWeb(r)}return new Oe(t,o)},Me=Symbol(`getRequestCache`),Ne=Symbol(`requestCache`),Pe=Symbol(`incomingKey`),Fe=Symbol(`urlKey`),Ie=Symbol(`headersKey`),Le=Symbol(`abortControllerKey`),Re={get method(){return this[Pe].method||`GET`},get url(){return this[Fe]},get headers(){return this[Ie]||=ke(this[Pe])},[Symbol(`getAbortController`)](){return this[Me](),this[Le]},[Me](){return this[Le]||=new AbortController,this[Ne]||=je(this.method,this[Fe],this.headers,this[Pe],this[Le])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Re,e,{get(){return this[Me]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Re,e,{value:function(){return this[Me]()[e]()}})}),Object.defineProperty(Re,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[Ne]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Re,Oe.prototype);var ze=(e,t)=>{let r=Object.create(Re);r[Pe]=e;let i=e.url||``;if(i[0]!==`/`&&(i.startsWith(`http://`)||i.startsWith(`https://`))){if(e instanceof n)throw new Te(`Absolute URL for :path is not allowed in HTTP/2`);try{r[Fe]=new URL(i).href}catch(e){throw new Te(`Invalid absolute URL`,{cause:e})}return r}let a=(e instanceof n?e.authority:e.headers.host)||t;if(!a)throw new Te(`Missing host header`);let o;if(e instanceof n){if(o=e.scheme,o!==`http`&&o!==`https`)throw new Te(`Unsupported scheme`)}else o=e.socket&&e.socket.encrypted?`https`:`http`;let s=new URL(`${o}://${a}${i}`);if(s.hostname.length!==a.length&&s.hostname!==a.replace(/:\d+$/,``))throw new Te(`Invalid host header`);return r[Fe]=s.href,r},Be=Symbol(`responseCache`),Ve=Symbol(`getResponseCache`),He=Symbol(`cache`),Ue=global.Response,We=class e{#e;#t;[Ve](){return delete this[He],this[Be]||=new Ue(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Be];if(e){this.#t=e,this[Ve]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[He]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[He];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Ve]().headers}get status(){return this[He]?.[0]??this[Ve]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(We.prototype,e,{get(){return this[Ve]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(We.prototype,e,{value:function(){return this[Ve]()[e]()}})}),Object.defineProperty(We.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[Be]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(We,Ue),Object.setPrototypeOf(We.prototype,Ue.prototype);async function Ge(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Ke(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function qe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return Ke(e.getReader(),t)}var Je=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Ye=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=a);var Xe=Symbol(`outgoingEnded`),Ze=Symbol(`incomingDraining`),Qe=500,$e=67108864,et=e=>{let t=e;if(e.destroyed||t[Ze])return;if(t[Ze]=!0,e instanceof n){try{e.stream?.close?.(r.NGHTTP2_NO_ERROR)}catch{}return}let i=0,a=()=>{clearTimeout(s),e.off(`data`,c),e.off(`end`,a),e.off(`error`,a)},o=()=>{a();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},s=setTimeout(o,Qe);s.unref?.();let c=e=>{i+=e.length,i>$e&&o()};e.on(`data`,c),e.on(`end`,a),e.on(`error`,a),e.resume()},tt=()=>new Response(null,{status:400}),nt=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),rt=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},it=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},at=async(e,t)=>{let[n,r,i]=e[He],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=Je(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Je(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(it(t),await qe(r,t)?.catch(e=>rt(e,t))),t[Xe]?.()},ot=e=>typeof e.then==`function`,st=async(e,t,n={})=>{if(ot(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(nt)}if(He in e)return at(e,t);let r=Je(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Ge(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&it(t),await Ke(n,t,o))}else r[Ye]||(t.writeHead(e.status,r),t.end());t[Xe]?.()},ct=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Oe&&(Object.defineProperty(global,"Request",{value:Oe}),Object.defineProperty(global,"Response",{value:We})),async(i,a)=>{let o,s;try{s=ze(i,t.hostname);let c=!r||i.method===`GET`||i.method===`HEAD`;if(c||(i[Ae]=!0,i.on(`end`,()=>{c=!0}),i instanceof n&&(a[Xe]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{et(i)})})}),a.on(`finish`,()=>{c||et(i)})),a.on(`close`,()=>{s[Le]&&(i.errored?s[Le].abort(i.errored.toString()):a.writableFinished||s[Le].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{et(i)})})}),o=e(s,{incoming:i,outgoing:a}),He in o)return at(o,a)}catch(e){if(o)return rt(e,a);if(t.errorHandler){if(o=await t.errorHandler(s?e:Ee(e)),!o)return}else o=s?nt(e):tt()}try{return await st(o,a,t)}catch(e){return rt(e,a)}}},lt=e=>{let n=e.fetch,r=ct(n,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||t)(e.serverOptions||{},r)},ut=(e,t)=>{let n=lt(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function D(e,...t){console.log(e,...t)}function O(e,...t){console.warn(e,...t)}function k(e,...t){console.error(e,...t)}function dt(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function ft(e){let t=`--${e}`,n=`${t}=`,r=process.argv;for(let e=0;e<r.length;e+=1){let i=r[e]??``;if(i.startsWith(n))return dt(i.slice(n.length));if(i===t){let t=r[e+1]??``;return t.startsWith(`-`)?void 0:dt(t)}}}function pt(e,t){return ft(e)??dt(process.env[t])}var mt=65535;function ht(e){let t=dt(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0&&n<=mt?n:void 0}var gt=(()=>{let e=pt(`app-dir`,`ELLM_APP_DIR`),t=e===void 0?void 0:l(u(),e),n=ft(`port`),r=ht(n??dt(process.env.ELLM_PORT));n!==void 0&&r===void 0&&O(`--port=${n} 无效(需为 1-65535 的整数),已忽略:本次不生效、也不会写入配置文件。`);let i=pt(`node-mirror`,`ELLM_NODE_MIRROR`),a=pt(`node-bin`,`ELLM_NODE_BIN`);return t!==void 0&&(process.env.ELLM_APP_DIR=t),i!==void 0&&(process.env.ELLM_NODE_MIRROR=i),a!==void 0&&(process.env.ELLM_NODE_BIN=a),{appDir:t,port:r,nodeMirror:i,nodeBin:a}})(),_t=s(ne(import.meta.url)),vt=`runtime.json`,yt;function bt(e){try{let t=g(c(e,vt),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function xt(){let e=bt(Ct())?.source;return typeof e==`string`&&e!==``?e:void 0}function St(){return c(w(),`.ezllm`)}function Ct(){return yt===void 0&&(yt=gt.appDir??St()),yt}function wt(){return l(Ct(),`data`)}function Tt(){return l(Ct(),`ezllm.config.json`)}function Et(){return l(wt(),`ipinfo.json`)}function Dt(){return l(Ct(),`logs`)}function Ot(){return l(wt(),`updater.json`)}function kt(){return l(Ct(),`provider-auth.json`)}function At(){return l(Ct(),`plugin-auth.json`)}var jt=[`hook.cjs`,`hook.mjs`,`hook.js`];function Mt(){return jt.map(e=>c(Ct(),e))}var Nt=`ezllm`;function Pt(e=Ct()){return l(e,`node`,`node_modules`,Nt)}function Ft(e){try{let t=g(c(e,`package.json`),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function It(e,t){let n=_t;for(let r=0;r<t;r++){if(Ft(n)?.name===e)return n;n=s(n)}return null}var Lt=It(`ezllm`,5)??l(_t,`..`);It(`ellm`,6);function Rt(){return Ft(Lt)?.name===`ezllm`}function zt(){let e=Ft(Lt);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function Bt(){let e=wt();p(e)||m(e,{recursive:!0})}function Vt(e,t){let n=`${e}.${`${process.pid}.${ae(6).toString(`hex`)}`}.tmp`;try{C(n,JSON.stringify(t,null,2)+`
|
|
3
3
|
`,`utf-8`),v(n,e)}finally{try{y(n,{force:!0})}catch{}}}function Ht(e){Bt();let t=l(wt(),e),n=e=>e instanceof Error?e.message:String(e),r=()=>{if(!p(t))return null;try{return JSON.parse(g(t,`utf-8`))}catch(e){return k(`[store] 读取 ${t} 失败,按空数据处理(原内容将在下次写入时被覆盖):`,n(e)),null}},i=null,a=()=>(i===null&&(i=r()??{}),i),o=Promise.resolve(),s=()=>{o=o.then(()=>{Vt(t,{...a()})}).catch(e=>{k(`[store] 写入 ${t} 失败:`,n(e))})};return{get(e){return a()[e]},set(e,t){a()[e]=t,s()},getAll(){return{...a()}},setAll(e){i={...e},s()},filePath:t,flush(){return o}}}function Ut(){try{let e=JSON.parse(g(Ot(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?{}:e}catch{return{}}}function Wt(e){let t=e.now??Date.now,n=e.log??D,r=e.maxArmMs??6e4,i=e.onError??((e,t,r)=>{n(`[scheduler] 作业 ${e.name} 失败(${String(Math.round(r/6e4))} 分钟后重试):${t.message}`)}),a=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:null,o=(e,t)=>a(typeof e==`function`?e():e)??t,s=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,c=e.jobs.map(e=>({job:e,nextAt:t()+(e.firstDelayMs??o(e.everyMs,r)),running:!1})),l=null,u=!1;function d(){if(u||l!==null)return;let e=t(),n=1/0;for(let t of c){if(t.running)continue;let r=Math.max(0,t.nextAt-e);r<n&&(n=r)}Number.isFinite(n)&&(l=setTimeout(f,Math.min(n,r)),l.unref())}function f(){if(l=null,u)return;let e=t();for(let t of c)!t.running&&e>=t.nextAt&&m(t);d()}function p(e,n,a){e.running=!1;let s=o(e.job.retryMs??e.job.everyMs,r),c=n??o(e.job.everyMs,r);e.nextAt=t()+(a===null?c:s),a!==null&&i(e.job,a,s),d()}function m(e){e.running=!0;let t;try{t=e.job.run({log:n})}catch(t){p(e,null,t instanceof Error?t:Error(String(t)));return}if(!s(t)){p(e,a(t),null);return}t.then(t=>{p(e,a(t),null)},t=>{p(e,null,t instanceof Error?t:Error(String(t)))})}return d(),{stop(){u=!0,l!==null&&(clearTimeout(l),l=null)}}}var Gt=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},Kt=Symbol(),qt=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),Jt=32,Yt=1e4,Xt=e=>`headers`in e,Zt=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(Xt(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Qt(e,{all:n,dot:r}):{}};async function Qt(e,t){if(!Xt(e)&&e.bodyCache.formData)return $t(await e.bodyCache.formData,t);let n=Xt(e)?e.headers:e.raw.headers,r=qt(await e.arrayBuffer(),n.get(`Content-Type`)||``);Xt(e)||(e.bodyCache.formData=r);let i=await r;return i?$t(i,t):{}}function $t(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?en(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(tn(n,e,t,r),delete n[e])}),n}var en=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},tn=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,Jt+2);a.length>Jt+1&&nn(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=Yt&&nn(),i[e]=Object.create(null)),i=i[e])})},nn=()=>{throw Error(`Nesting limit exceeded`)},rn=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},an=e=>{let{groups:t,path:n}=on(e);return sn(rn(n),t)},on=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},sn=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},cn={},ln=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return cn[r]||(cn[r]=n[2]?t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:[e,n[1],!0]),cn[r]}return null},un=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},dn=e=>un(e,decodeURI),fn=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),o=t.slice(n,a);return dn(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}if(e===63||e===35)break}return t.slice(n,r)},pn=e=>{let t=fn(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},mn=(e,t,...n)=>(n.length&&(t=mn(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),hn=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e)){if(e.charCodeAt(e.length-1)===63){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.slice(0,-1);r+=`/`+t,n.push(r)}else r+=`/`+e}}),n.filter((e,t,n)=>n.indexOf(e)===t)},gn=e=>e.indexOf(`%`)===-1?e:un(e,xn),_n=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),gn(e)),vn=(e,t,n)=>{let r=e.indexOf(`#`,8);r!==-1&&(e=e.slice(0,r));let i;if(!n&&t&&t.indexOf(`%`)===-1&&t.indexOf(`+`)===-1){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return _n(e.slice(r,i===-1?void 0:i))}if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(i=/[%+]/.test(e),!i)return}let a=Object.create(null);i??=/[%+]/.test(e);let o=e.indexOf(`?`,8);for(;o!==-1;){let t=e.indexOf(`&`,o+1),r=e.indexOf(`=`,o);r>t&&t!==-1&&(r=-1);let s=e.slice(o+1,r===-1?t===-1?void 0:t:r);if(i&&(s=_n(s)),o=t,s===``)continue;let c;r===-1?c=``:(c=e.slice(r+1,t===-1?void 0:t),i&&(c=_n(c))),n?(a[s]&&Array.isArray(a[s])||(a[s]=[]),a[s].push(c)):a[s]??=c}return t?a[t]:a},yn=vn,bn=(e,t)=>vn(e,t,!0),xn=decodeURIComponent,Sn=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.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&gn(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=gn(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return yn(this.url,e)}queries(e){return bn(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((e,n)=>{t[n]=e}),t}async parseBody(e){return Zt(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let n in t)return t[n].then(t=>(n===`json`&&(t=JSON.stringify(t)),new Response(t)[e]()));return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`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[Kt](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},Cn={Stringify:1,BeforeStream:2,Stream:3},wn=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Tn=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>Tn(e,t,!1,r,i))).then(()=>i[0]));return n?wn(await o,a):o},En=`text/plain; charset=UTF-8`,Dn=(e,t)=>({"Content-Type":e,...t}),On=(e,t)=>new Response(e,t),kn=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new Sn(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=On(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=On(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=On(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=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):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return On(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,Dn(En,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,Dn(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,Dn(`text/html; charset=UTF-8`,n));return typeof e==`object`?Tn(e,Cn.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.#c??=()=>On(),this.#c(this))},An=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],jn=`Can not add a route since the matcher is already built.`,Mn=class extends Error{},Nn=`__COMPOSED_HANDLER`,Pn=e=>e.text(`404 Not Found`,404),Fn=(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)},In=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...An,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??fn:pn}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=Pn;errorHandler=Fn;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Fn?r=e.handler:(r=async(n,r)=>(await Gt([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Nn]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=mn(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=mn(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,mn(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){e=e.toUpperCase(),t=mn(this._basePath,t);let i={basePath:r===void 0?this._basePath:mn(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new kn(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=Gt(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${mn(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},A=()=>Object.create(null),Ln=[];function Rn(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Ln];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var zn=`[^/]+`,Bn=`(?:|/.*)`,Vn=Symbol(),Hn=new Set(`.\\+*[^]$()`);function Un(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 Wn=class e{#e;#t;#n=A();insert(t,n,r,i,a){let o=this;for(let n=0,a=t.length;n<a;n++){let s=t[n],c=s.length===1?s===`*`?n===a-1?[``,``,`.*`]:[``,``,zn]:null:s===`/*`?[``,``,Bn]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||`[^/]+`;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))||n.length===1&&Hn.has(n)))throw Vn;if(l=o.#n[n],!l){if(n!==`.*`&&n!==`(?:|/.*)`){for(let e in o.#n)if((n.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw Vn}l=o.#n[n]=new e}t!==``&&(l.#t??=i.varIndex++,r.push([t,l.#t]))}else if(l=o.#n[s],!l){for(let e in o.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw Vn;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw Vn;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Un).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Hn.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Gn=class{#e={varIndex:0};#t=new Wn;#n=0;paths=A();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Kn=A();function qn(e){return Kn[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Bn:e===`*`?`.*`:`/:${zn}`)}$`)}function Jn(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(qn(n).test(t))return[...e[n]]}var Yn=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:A()},this.#t={ALL:A()},this.#n={ALL:new Gn}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===Vn?new Mn(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(jn);if(!r[e]){this.#n[e]=new Gn;for(let t of[r,i]){t[e]=A();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=qn(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=Jn(r[e],t)||Jn(r.ALL,t)||[]);for(let o of[r,i])for(let r of a)for(let i in o[r])e.test(i)&&o[r][i].push([n,t]);return}let o=hn(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=Jn(r[t],e)||Jn(r.ALL,e)||[]),i[t][e].push([n,e])}match=Rn;buildAllMatchers(){let e=A();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Kn=A(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=A(),a=[],[o,s,c]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],o=r.paths[t];if(!o){i[t]=[n.map(([e])=>[e,A()]),Ln];continue}a[o[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=c[o[1][n][1]],e),A())])}return[o,s.map(e=>a[e]),i]}},Xn=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(jn);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof Mn)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},Zn=A(),Qn=0,$n=class e{#e=[];#t=A();#n=[];#r;#i=Zn;insert(t,n,r){let i=this,a=an(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=ln(t,n)||(n===void 0&&t&&t.indexOf(`*`)===t.length-1?t:null),c=Array.isArray(r),l=c?r[0]:r||t,u=i.#t[l]||=new e;r&&!u.#r&&(u.#r=r,i.#n.push(u)),i=u,c&&o.add(r[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...o],score:++Qn}})}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL;if(s){s.params=A(),e.push(s);for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e];s.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=Zn;let r=[this],i=rn(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r of p.#n){let f=r.#r,m=p.#i===Zn?{}:{...p.#i};if(typeof f==`string`){(f===`*`||l.startsWith(f.slice(0,-1)))&&(this.#a(n,r,e,p.#i),f===`*`&&(r.#i=m,d.push(r)));continue}let[,h,g]=f;if(l||g!==!0){if(g!==!0){if(!s){s=[];let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let l=t.slice(s[c]),u=g.exec(l);if(u){m[h]=u[0],this.#a(n,r,e,p.#i,m),u[0].length===l.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,p.#i,m);for(let e in r.#t){r.#i=m;let e=u[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,r,e,m,p.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,m,p.#i)):(r.#i=m,d.push(r)))}}}let f=a.shift();r=f?d.concat(f):d}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},er=class{name=`TrieRouter`;#e=new $n;add(e,t,n){for(let r of hn(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},j=class extends In{constructor(e={}){super(e),this.router=e.router??new Xn({routers:[new Yn,new er]})}},tr=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function nr(e){return{error:{message:`The model \`${e}\` does not exist or you do not have access to it.`,type:`invalid_request_error`,code:`model_not_found`}}}function rr(e){return{byName:new Map(e.map(e=>[e.name,e])),names:e.map(e=>e.name)}}function ir(e,t){return typeof t!=`string`||t===``?null:e.byName.get(t)??null}function M(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ar(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function or(e){return e instanceof Error?e.message:String(e)}function sr(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}var cr=[`openai`,`anthropic`,`openai-responses`],lr=class extends Error{issues;constructor(e){super(`配置校验失败:\n - ${e.join(`
|
|
4
4
|
- `)}`),this.name=`ConfigValidationError`,this.issues=e}};function ur(e){let t=(e,t,n,r)=>{e!==void 0&&typeof e!=`string`&&r.push(`${t}.${n} 必须是字符串,当前为 ${String(e)}`)},n=(e,t)=>{if(e===void 0)return[];if(!M(e))return[`${t}.headers 必须是键值均为字符串的对象`];let n=[];for(let[r,i]of Object.entries(e))typeof i!=`string`&&n.push(`${t}.headers["${r}"] 必须是字符串,当前为 ${String(i)}`);return n},r=(e,t)=>{let n={};for(let r of[e,t])if(M(r))for(let[e,t]of Object.entries(r))typeof t==`string`&&(n[e]=t);return n},i=[],a=[];if(typeof e!=`object`||!e||!Array.isArray(e.providers))throw new lr([`providers 必须是数组`]);e.providers.length===0&&i.push(`providers 不能为空(至少配置一个供应商)`),e.port!==void 0&&(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&i.push(`port 必须是 1-65535 的整数,当前为 ${String(e.port)}`);let o=new Set,s=new Map,c=new Map,l=[];for(let[u,d]of e.providers.entries()){let e=d?.name??`providers[${String(u)}]`;typeof d?.name!=`string`||d.name===``?i.push(`providers[${String(u)}].name 必须是非空字符串`):o.has(d.name)?i.push(`供应商名重复:${d.name}`):o.add(d.name);let f=d?.enabled!==!1;if(d?.enabled!==void 0&&typeof d.enabled!=`boolean`&&i.push(`${e}.enabled 必须是布尔值,当前为 ${String(d.enabled)}`),d?.alias!==void 0){if(typeof d.alias!=`string`||d.alias.trim()===``)i.push(`${e}.alias 若设置必须是非空字符串`);else{let t=d.alias.trim();if(f){let n=s.get(t);n===void 0?s.set(t,e):i.push(`供应商别名 "${t}" 重复(${n} 与 ${e})`)}}}let p=d?.customLlmProvider,m=cr.includes(p);m||i.push(`${e}.customLlmProvider 必须是 "openai" | "anthropic" | "openai-responses" 之一,当前为 ${String(p)}`);let h=m?p:`openai`;if(!Array.isArray(d?.models)||d.models.length===0){i.push(`${e}.models 必须是非空数组(至少配置一个模型)`);continue}d?.autoV1!==void 0&&typeof d.autoV1!=`boolean`&&i.push(`${e}.autoV1 必须是布尔值,当前为 ${String(d.autoV1)}`);let g=new Set;t(d?.apiKey,e,`apiKey`,i),t(d?.apiBase,e,`apiBase`,i),i.push(...n(d?.headers,e));for(let[o,s]of d.models.entries()){let u=`${e}.models[${String(o)}]`;if(typeof s?.modelName!=`string`||s.modelName===``){i.push(`${u}.modelName 必须是非空字符串`);continue}g.has(s.modelName)?i.push(`${u}.modelName "${s.modelName}" 在同一供应商内重复:模型名必须唯一`):g.add(s.modelName);let p=s?.enabled!==!1;if(s?.enabled!==void 0&&typeof s.enabled!=`boolean`&&i.push(`${u}.enabled 必须是布尔值,当前为 ${String(s.enabled)}`),f&&p){let t=c.get(s.modelName);t===void 0?c.set(s.modelName,e):i.push(`模型名 "${s.modelName}" 重复(${t} 与 ${e}):模型名必须全局唯一`)}if(typeof s?.model!=`string`||s.model===``){i.push(`${u}.model 必须是非空字符串`);continue}s.rawPassthrough!==void 0&&typeof s.rawPassthrough!=`boolean`&&i.push(`${u}.rawPassthrough 必须是布尔值,当前为 ${String(s.rawPassthrough)}`);let m=s.customLlmProvider===void 0?h:s.customLlmProvider;cr.includes(m)||i.push(`${u}.customLlmProvider 必须是 "openai" | "anthropic" | "openai-responses" 之一`),t(s.apiKey,u,`apiKey`,i),t(s.apiBase,u,`apiBase`,i),i.push(...n(s.headers,u));let _=dr(s.apiKey??d.apiKey,a,u),v=s.apiBase??d.apiBase,y=s.autoV1??d.autoV1;y!==void 0&&typeof y!=`boolean`&&i.push(`${u}.autoV1 必须是布尔值,当前为 ${String(y)}`);let b=r(d?.headers,s.headers),x=s.maxReasoningEffort??d.maxReasoningEffort;x!==void 0&&!tr.includes(x)&&i.push(`${u}.maxReasoningEffort 必须是 ${tr.join(` | `)} 之一,当前为 ${String(x)}`);let S=s.thinkingGuardMaxChars??d.thinkingGuardMaxChars;S!==void 0&&(!Number.isInteger(S)||S<0)&&i.push(`${u}.thinkingGuardMaxChars 必须是非负整数,当前为 ${String(S)}`),f&&p&&l.push({name:s.modelName,provider:m,modelName:s.model,apiKey:_,apiBase:v,autoV1:y,headers:Object.keys(b).length>0?b:void 0,maxReasoningEffort:x,thinkingGuardMaxChars:S,rawPassthrough:s.rawPassthrough})}}if(i.length>0)throw new lr(i);return{deployments:rr(l),port:e.port??29770,warnings:a}}function dr(e,t,n){if(e===void 0||typeof e!=`string`)return;if(!e.startsWith(`os.environ/`))return e;let r=e.slice(11),i=process.env[r];if(i===void 0||i===``){t.push(`${n}:环境变量 "${r}" 为空或不存在`);return}return i}function fr(e){return{kind:`ok`,value:e}}function pr(e,t){return{kind:`error`,status:e,message:t}}var N=class extends Error{status;constructor(e,t){super(e),this.name=`ProtocolError`,t?.status!==void 0&&(this.status=t.status)}};function mr(e){return e instanceof N&&e.status!==void 0?e.status:void 0}function hr(e){return typeof e.then==`function`}function gr(e){return e instanceof Error?e.message:String(e)}var _r=class{#e;constructor(e){this.#e=e}run(e,t){let n=-1,r=(e,i)=>{if(e<=n)return pr(500,`next() called multiple times`);n=e;let a=this.#e[e];if(a===void 0)return t(i);let o;try{o=a(i,t=>r(e+1,t))}catch(e){return pr(500,gr(e))}return hr(o)?o.then(void 0,e=>pr(500,gr(e))):o};return r(0,e)}};function vr(e,t){return e===`anthropic`?[{type:`error`,error:{type:t.status===429||t.status===529?`overloaded_error`:t.status!==void 0&&t.status>=400&&t.status<500?`invalid_request_error`:`api_error`,message:t.message}}]:e===`openai-responses`?[{type:`error`,error:{type:`InternalServerError`,code:String(t.status??500),message:t.message}}]:[{object:`chat.completion.chunk`,choices:[],error:{message:t.message,code:t.status??null}}]}function yr(e){return e===`openai`}var br=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},xr=10,Sr=13,Cr=32,wr=6;function Tr(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(`
|
|
5
5
|
`)===-1&&e.indexOf(`\r`)===-1){if(c<wr&&!b(s.join(``)+e.slice(0,wr-c))){s.length=0,c=0,h=!0;return}s.push(e),c+=e.length,x();return}s.push(e);let t=s.join(``);s.length=0,c=0,y(S(t)),x()}function v(e){if(e.length===0)return e;if(g)return g=!1,e.charCodeAt(0)===xr?e.slice(1):e;let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
@@ -12,17 +12,17 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
12
12
|
|
|
13
13
|
`),this.take()}take(){let e=this.collected;return this.collected=[],e}},Mr=new TextEncoder;function Nr(e,t){let n=[];e!==null&&n.push(`event: ${e}`);for(let e of t.split(`
|
|
14
14
|
`))n.push(`data: ${e}`);return Mr.encode(`${n.join(`
|
|
15
|
-
`)}\n\n`)}function Pr(e,t={}){let n=e.type;return Nr((t.protocol===void 0||t.protocol===`anthropic`)&&typeof n==`string`?n:null,JSON.stringify(e))}function Fr(){return Nr(null,kr)}async function*Ir(e,t){let n=(e,t)=>({event:e.event,data:e.data,done:t!==`anthropic`&&e.data===`[DONE]`}),r=e.getReader(),i=new TextDecoder,a=new jr,o=!1;try{for(;;){let{done:e,value:o}=await r.read();if(e)break;for(let e of a.push(i.decode(o,{stream:!0}))){let r=n(e,t);if(yield r,r.done)return}}for(let e of a.push(i.decode())){let r=n(e,t);if(yield r,r.done)return}for(let e of a.flush()){let r=n(e,t);if(yield r,r.done)return}o=!0}finally{o||r.cancel().catch(()=>{})}}function Lr(e){let t;try{t=JSON.parse(e.data)}catch{return null}return typeof t!=`object`||!t||Array.isArray(t)?null:t}function Rr(e,t){return Pr(e,{protocol:t})}function zr(e,t){let n=(e,t,n,r)=>e instanceof ReadableStream?e.pipeThrough(i(t,n,`upstream`,r)):e===null?null:t(e,r),r=(e,t,n,r)=>{if(e.kind===`error`)return e;let a=e.value;if(`stream`in a)return fr({...a,stream:a.stream.pipeThrough(i(t,n,`client`,r))});if(a.body===null||typeof a.body!=`object`)return e;let o=t(a.body,r);return fr(o===null?{...a,body:null}:{...a,body:o})},i=(e,t,n,r)=>{let i=new jr,a=new TextDecoder,o=!1,s=(i,a)=>{if(t!==`anthropic`&&i.data===`[DONE]`){a.enqueue(Fr());return}let s=Lr({event:i.event,data:i.data,done:!1});if(s===null){a.enqueue(Nr(i.event,i.data));return}let c;try{c=e(s,r)}catch(e){if(o=!0,n===`upstream`){a.error(e);return}for(let n of vr(t,{message:gr(e)}))a.enqueue(Pr(n,{protocol:t}));a.terminate();return}c!==null&&a.enqueue(Pr(c,{protocol:t}))};return new TransformStream({transform(e,t){if(!o){for(let n of i.push(a.decode(e,{stream:!0})))if(s(n,t),o)return}},flush(e){if(!o){for(let t of i.push(a.decode()))if(s(t,e),o)return;for(let t of i.flush())if(s(t,e),o)return}}})},a=[],o=[];if(e.request!==void 0){let n=e.request;a.push((e,r)=>n(e,r,t))}if(e.clientRequest!==void 0){let n=e.clientRequest;a.push((e,r)=>r(n(e,t)))}if(e.upstreamRequest!==void 0){let n=e.upstreamRequest;a.push((e,r)=>{let i=r(e);return hr(i)?i.then(a):a(i);function a(e){return e.kind===`error`?e:fr(n(e.value,t))}})}if(e.response!==void 0){let n=e.response;o.push((e,r)=>n(e,r,t))}if(e.upstreamResponse!==void 0){let r=e.upstreamResponse;o.push((e,i)=>{let a=e;return i({...a,body:n(a.body,r,t.pair.upstream,t)})})}if(e.clientResponse!==void 0){let n=e.clientResponse;o.push((e,i)=>{let a=i(e);return hr(a)?a.then(e=>r(e,n,t.pair.inbound,t)):r(a,n,t.pair.inbound,t)})}return{requestLayers:a,responseLayers:o}}function Br(e,t){let n=e=>(t,n)=>{let r;try{r=e.options.translate===!1?t.body:e.pair.translateRequest(t.body,e.options)}catch(e){return pr(mr(e)??500,gr(e))}let i={"content-type":`application/json`},a=r.stream===!0;return n({headers:i,body:r,stream:a})};return new _r([...t.specs.flatMap(e=>zr(e,t).requestLayers),n(t)]).run(e,e=>fr(e))}var Vr=class{stream;collectUsage=()=>this.#t;#e;#t=null;#n;#r;#i=!1;constructor(e){this.#e=e,this.#n=e.bridge(this.#a())[Symbol.asyncIterator](),this.#r=this.#o()[Symbol.asyncIterator]();let t=new se({objectMode:!0,highWaterMark:0,read:()=>{this.#r.next().then(e=>{e.done?t.push(null):t.push(e.value)},e=>{t.destroy(e instanceof Error?e:Error(String(e)))})},destroy:(e,t)=>{Promise.resolve(this.#r.return?.()).catch(()=>{}).then(()=>t())}});this.stream=se.toWeb(t)}async*#a(){for await(let e of Ir(this.#e.upstreamBytes,this.#e.upstreamProtocol)){if(e.done){this.#i=!0;return}let t=Lr(e);t!==null&&(yield t)}}async*#o(){try{for(;;){let e=await this.#n.next();if(e.done){if(this.#e.upstreamProtocol===`openai`&&!this.#i){for(let e of vr(this.#e.inboundProtocol,{status:502,message:`upstream stream ended before the [DONE] sentinel (truncated)`}))yield Rr(e,this.#e.inboundProtocol);return}yr(this.#e.inboundProtocol)&&(yield Fr());return}let t=e.value,n=this.#e.usageFromFrame;if(n!==void 0){let e=n(t);e!==null&&(this.#t={...this.#t??{},...e})}yield Rr(t,this.#e.inboundProtocol)}}catch(e){let t=gr(e);for(let n of vr(this.#e.inboundProtocol,{status:mr(e),message:t}))yield Rr(n,this.#e.inboundProtocol)}finally{await this.#n.return?.().catch(()=>{})}}};async function Hr(e,t){let n=e=>{let t={};if(e instanceof Headers)return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t;for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t},r=async(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i;try{i=r.status<200||r.status>299?e.pair.errorEnvelope(r.status,r.body):e.options.translate===!1?r.body:e.pair.translateResponse(r.body,e.options)}catch(e){return pr(mr(e)??500,gr(e))}return n({status:r.status,headers:r.headers,body:i})},i;try{i=await e.text()}catch(e){return pr(502,`failed to read upstream response body: ${gr(e)}`)}let a;try{let e=JSON.parse(i);if(typeof e!=`object`||!e)return pr(502,`upstream response is not a valid JSON object`);a=e}catch{return pr(502,`upstream response is not valid JSON`)}return new _r([...t.specs.flatMap(e=>zr(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:a},e=>fr(e))},i=(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i=new Vr({upstreamBytes:r.body,upstreamProtocol:e.pair.upstream,inboundProtocol:e.pair.inbound,bridge:e.options.translate===!1?e=>e:t=>e.pair.bridgeFrames(t,e.options,e.inboundBody??void 0),usageFromFrame:e.pair.usageFromFrame});return n({status:r.status,headers:r.headers,stream:i.stream,collectUsage:i.collectUsage})};return e.body===null?pr(502,`streaming response has no body`):new _r([...t.specs.flatMap(e=>zr(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:e.body},e=>fr(e))},a=n(e.headers),o=(a[`content-type`]??``).includes(`text/event-stream`);return e.status<200||e.status>299||!o?r(e,t,a):i(e,t,a)}var Ur=[],Wr=class{chainName;pair;options;state=new Map;getState(e){return this.state.get(e)}setState(e,t){this.state.set(e,t)}#e=null;#t=Ur;#n=null;#r=!1;#i=!1;#a;constructor(e){this.chainName=e.chainName,this.pair=e.pair,this.options=Object.freeze({...e.options}),this.#a=e.snapshot}get specs(){return this.#t}get inbound(){return this.#e}get inboundBody(){return this.#e===null?null:this.#e.body}get upstreamRequest(){return this.#n}request(e){if(this.#r)return pr(500,`RequestContext: request() can only be called once (one container per round trip)`);this.#r=!0,this.#e=e,this.#t=Gr(this.#a,e,this);let t=Br(e,this);return hr(t)?t.then(e=>(e.kind===`ok`&&(this.#n=e.value),e)):(t.kind===`ok`&&(this.#n=t.value),t)}response(e){if(this.#i)return Promise.resolve(pr(500,`RequestContext: response() can only be called once`));if(this.#i=!0,!this.#r){let e=[];for(let t of this.#a)t!==null&&t.runWhen===void 0&&e.push(t);this.#t=e}return Hr(e,this)}};function Gr(e,t,n){let r=[];for(let i of e)i!==null&&(i.runWhen===void 0||i.runWhen(t,n)===!0)&&r.push(i);return r}var Kr=class{#e=[];register(e){let t=this.#e.length;return this.#e.push(e),t}unregister(e){this.#e[e]=null}snapshot(){return[...this.#e]}},qr=class{#e;#t;#n;#r=new Kr;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}get name(){return this.#n}intercept(e){return this.#r.register(e)}unregister(e){this.#r.unregister(e)}begin(){return new Wr({chainName:this.#n,pair:this.#e,options:Object.freeze({...this.#t}),snapshot:this.#r.snapshot()})}};function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return P(e)?e:{}}function I(e){return Array.isArray(e)?e:[]}function L(e){return typeof e==`string`?e:null}function R(e){return typeof e==`string`?e:``}function Jr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Yr(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function z(){return crypto.randomUUID()}function Xr(){return Math.floor(Date.now()/1e3)}function Zr(...e){for(let t of e){let e=Yr(t);if(e>0)return e}return 0}function Qr(e){let t=F(e.prompt_tokens_details);return{cacheRead:Zr(e.cache_read_input_tokens,e.prompt_cache_hit_tokens,t.cached_tokens),cacheCreation:Zr(e.cache_creation_input_tokens,t.cache_creation_tokens,t.cache_write_tokens)}}function $r(e,t,n,r){let i={input_tokens:Math.max(e-n-r,0),output_tokens:t};return r>0&&(i.cache_creation_input_tokens=r),n>0&&(i.cache_read_input_tokens=n),i}var ei=new Set([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`refusal`]),ti=new Set([`stop`,`length`,`tool_calls`,`function_call`,`content_filter`]);function ni(e){return{stop:`end_turn`,length:`max_tokens`,tool_calls:`tool_use`}[e]??`end_turn`}function ri(e){let t=L(e)??``;return ei.has(t)?t:ni(t)}function ii(e){let t=L(e.stop_reason),n=L(F(e.provider_specific_fields).stop_reason),r=t??n;return r===null||r===``||ei.has(r)||ti.has(r)?null:r}function ai(e){let t=L(e.refusal);if(t!==null&&t!==``)return t;let n=L(F(e.provider_specific_fields).refusal);return n!==null&&n!==``?n:null}var oi={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`};function si(e){return oi[e]??`api_error`}function ci(e){let t=P(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function li(e){if(!P(e))return!1;let t=e.type===`error`?e.error:void 0;return P(t)&&typeof t.type==`string`&&typeof t.message==`string`}function ui(e,t){if(P(t)){let e=t.error;if(P(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(P(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return typeof t==`string`&&t!==``?t:`upstream error (HTTP ${e})`}function di(e,t){return li(t)?t:{type:`error`,error:{type:si(e),message:ui(e,t)}}}function fi(e){let t=F(e);if(t.type===`message_start`){let e=F(t.message).usage;return P(e)?e:null}if(t.type===`message_delta`){let e=t.usage;return P(e)?e:null}return null}function pi(e){if(typeof e!=`object`||!e||Array.isArray(e))return String(e);let t=F(e),n=t.message;return typeof n==`string`&&n!==``?n:JSON.stringify(t)}var mi=class{#e=0;#t=null;#n=null;#r=null;#i=0;#a=0;#o=0;#s=0;#c=!1;#l=!1;#u=null;#d=null;#f=``;#p=``;translateFrame(e){if(this.#l)return[];let t=e.error;if(t!=null)throw new N(pi(t),{status:ci(t)});let n=F(I(e.choices)[0]),r=F(n.delta),i=[];if(!this.#c){this.#c=!0;let t=e.id;this.#p=typeof t==`string`&&t!==``?t:z(),i.push(this.#m(L(e.model)))}let a=r.content;typeof a==`string`&&a!==``&&(i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:a})));let o=ai(r);o!==null&&(this.#f+=o,i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:o})));let s=r.reasoning_content===void 0?r.reasoning:r.reasoning_content;typeof s==`string`&&s!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`thinking_delta`,thinking:s})));for(let e of I(r.thinking_blocks)){let t=L(F(e).signature);t!==null&&t!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`signature_delta`,signature:t})))}for(let[e,t]of I(r.tool_calls).entries()){let n=F(t),r=F(n.function),a=typeof n.index==`number`?n.index:e,o=L(n.id)??``;(this.#t!==`tool_use`||this.#n!==a||o!==``&&this.#r!==null&&this.#r!==o)&&this.#t===`tool_use`&&i.push(...this.#g()),i.push(...this.#h(`tool_use`,{type:`tool_use`,id:o,name:L(r.name)??``,input:{}})),this.#n=a,o!==``&&(this.#r=o);let s=r.arguments;typeof s==`string`&&s!==``&&i.push(this.#_({type:`input_json_delta`,partial_json:s}))}let c=F(e.usage),l=Yr(c.prompt_tokens),u=Yr(c.completion_tokens);if(l>0){this.#i=l;let e=Qr(c);this.#o=e.cacheRead,this.#s=e.cacheCreation}u>0&&(this.#a=u);let d=n.finish_reason;typeof d==`string`&&d!==``&&(this.#u=d);let f=ii(n);return f!==null&&(this.#d=f),i}flush(){if(!this.#c||this.#l)return[];this.#l=!0;let e=[...this.#g()],t=this.#d===null?this.#u==null?`end_turn`:ri(this.#u):`stop_sequence`,n=this.#f!==``&&t!==`max_tokens`;return e.push({type:`message_delta`,delta:n?{stop_reason:`refusal`,stop_sequence:this.#d,stop_details:{type:`refusal`}}:{stop_reason:t,stop_sequence:this.#d},usage:$r(this.#i,this.#a,this.#o,this.#s)}),e.push({type:`message_stop`}),e}#m(e){return{type:`message_start`,message:{id:this.#p,type:`message`,role:`assistant`,...e===null?{}:{model:e},content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}}#h(e,t){if(this.#t===e)return[];let n=this.#g();this.#t=e;let r=t??{type:`text`,text:``},i=[...n,{type:`content_block_start`,index:this.#e,content_block:r}];return this.#e+=1,i}#g(){if(this.#t===null)return[];let e=this.#e-1;return this.#t=null,this.#n=null,this.#r=null,[{type:`content_block_stop`,index:e}]}#_(e){return{type:`content_block_delta`,index:this.#e-1,delta:e}}};async function*hi(e){let t=new mi;for await(let n of e)for(let e of t.translateFrame(F(n)))yield e;for(let e of t.flush())yield e}var gi=4096;function _i(e){return e.map(e=>{if(!P(e))return F(e);let t=!1,n={};for(let[r,i]of Object.entries(e)){if(r===`provider_specific_fields`){t=!0;continue}if(r===`content`&&Array.isArray(i)){let e=i.map(e=>{if(!P(e)||!(`provider_specific_fields`in e))return e;let{provider_specific_fields:t,...n}=e;return n});(e.length!==i.length||e.some((e,t)=>e!==i[t]))&&(t=!0),n[r]=e;continue}n[r]=i}return t?n:e})}function vi(e,t){let n=!1;for(let t of e){let e=t.content;if(Array.isArray(e)){for(let t of e)if(F(t).type===`container_upload`){n=!0;break}}if(n)break}if(!n)return t;for(let e of t){let n=e.type;if(typeof n==`string`&&n.startsWith(`code_execution`))return t}return[...t,{name:`code_execution`,type:`code_execution_20250522`}]}function yi(e){if(!P(e.metadata))return;let t=F(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function bi(e){let t=e.output_config;if(!P(t))return;let n=t.effort;if(typeof n==`string`&&n!==``&&![`high`,`medium`,`low`,`xhigh`,`max`].includes(n))throw new N(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function xi(e){let t=F(e),n=_i(I(t.messages)),r=I(t.tools).map(F),i=vi(n,r),a={...t,messages:n};return i!==r&&(a.tools=i),`max_tokens`in a||(a.max_tokens=gi),yi(a),delete a.is_vertex_request,delete a.client_metadata,bi(a),a}function Si(e){return typeof e==`number`&&Number.isFinite(e)?Math.floor(e):0}function Ci(e){let t=Si(e.input_tokens??0),n=Si(e.output_tokens??0),r=0,i=0,a=e.iterations,o=Array.isArray(a)?a.map(F):null;o!==null&&o.length>0&&(t=o.reduce((e,t)=>e+Si(t.input_tokens??0),0),n=o.reduce((e,t)=>e+Si(t.output_tokens??0),0),r=o.reduce((e,t)=>e+Si(t.cache_creation_input_tokens??0),0),i=o.reduce((e,t)=>e+Si(t.cache_read_input_tokens??0),0),t+=r+i),o===null&&(`cache_creation_input_tokens`in e&&e.cache_creation_input_tokens!==null&&typeof e.cache_creation_input_tokens==`number`&&(r=e.cache_creation_input_tokens,t+=r),`cache_read_input_tokens`in e&&e.cache_read_input_tokens!==null&&typeof e.cache_read_input_tokens==`number`&&(i=e.cache_read_input_tokens,t+=i));let s={cached_tokens:i,cache_creation_tokens:r,cache_write_tokens:r};return{prompt_tokens:t,completion_tokens:n,total_tokens:t+n,prompt_tokens_details:s,cache_creation_input_tokens:r,cache_read_input_tokens:i}}var wi=/^<(?:think|thinking|budget:thinking)>([\s\S]*?)<\/(?:think|thinking|budget:thinking)>([\s\S]*)/;function Ti(e){if(!e)return{reasoningContent:null,content:e};let t=wi.exec(e);return t===null?{reasoningContent:null,content:e}:{reasoningContent:t[1]??null,content:t[2]??null}}function Ei(e){let t=e.content,n=L(t);return`reasoning_content`in e?{reasoningContent:L(e.reasoning_content),content:n}:`reasoning`in e?{reasoningContent:L(e.reasoning),content:n}:typeof t==`string`?Ti(t):{reasoningContent:null,content:n}}function Di(e){let t=F(e),n=t.arguments,r;if(n==null){let e=t.parameters;r=P(e)?JSON.stringify(e):``}else r=P(n)?JSON.stringify(n):String(n);return{arguments:r,name:L(t.name)}}function Oi(e){return e.type===`custom`||e.custom!=null}function ki(e){return Oi(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`function`&&e!==`type`||t!=null)):{id:e.id==null?z():String(e.id),type:e.type==null?`function`:String(e.type),function:Di(e.function)}}function Ai(e){let t=new Map;for(let[n,r]of e.entries()){if(Oi(r))continue;let e=F(r.function),i=e.name,a=JSON.parse(typeof e.arguments==`string`?e.arguments:``);if(i!==`multi_tool_use.parallel`)continue;let o=F(a),s=(Array.isArray(o.tool_uses)?o.tool_uses:[]).map((e,t)=>{let n=F(e),i=String(n.recipient_name).replace(/^functions\./,``);return{id:`${String(r.id)}_${String(t)}`,type:`function`,function:{name:i,arguments:JSON.stringify(n.parameters)}}});t.set(n,s)}return t}function ji(e){try{let t=Ai(e),n=0,r=[...e];for(let[e,i]of t)r.splice(e+n,1,...i),n+=i.length;return r}catch{return e}}function Mi(e){return Array.isArray(e.tool_calls)?ji(e.tool_calls.map(e=>ki(F(e)))):[]}function Ni(e){if(typeof e!=`string`||e===``)return{};try{return F(JSON.parse(e))}catch{return{}}}function Pi(e){let t=[];for(let n of e.thinkingBlocks){let e=F(n);e.type===`thinking`?t.push({type:`thinking`,thinking:L(e.thinking)??``,signature:L(e.signature)}):e.type===`redacted_thinking`&&t.push({type:`redacted_thinking`,data:L(e.data)??``})}e.thinkingBlocks.length===0&&typeof e.reasoningContent==`string`&&e.reasoningContent!==``&&t.push({type:`thinking`,thinking:e.reasoningContent,signature:null}),typeof e.content==`string`&&e.content!==``&&t.push({type:`text`,text:e.content}),e.refusal!==null&&t.push({type:`text`,text:e.refusal});for(let n of e.toolCalls){let e=F(n),r=F(e.function);t.push({type:`tool_use`,id:L(e.id)??``,name:L(r.name)??``,input:Ni(r.arguments)})}return t}function Fi(e){let{cacheRead:t,cacheCreation:n}=Qr(e);return $r(Yr(e.prompt_tokens),Yr(e.completion_tokens),t,n)}function Ii(e){let t=F(e),n=t.error;if(n!=null){let e=F(n);throw new N(typeof e.message==`string`?e.message:JSON.stringify(n),{status:ci(n)})}let r=I(t.choices);if(r.length===0)throw Error(`upstream returned a response with no 'choices'. Raw keys: ${Object.keys(t).join(`, `)}`);let i=F(r[0]),a=F(i.message),o=Mi(a),{reasoningContent:s,content:c}=Ei(a),l=I(a.thinking_blocks),u=ai(a),d=L(i.finish_reason)??`stop`;d===`stop`&&o.length>0&&(d=`tool_calls`);let f=ii(i),p=f===null?ri(d):`stop_sequence`,m=u!==null&&p!==`max_tokens`;return m&&(p=`refusal`),{id:t.id,type:`message`,role:`assistant`,...t.model===void 0?{}:{model:t.model},content:Pi({thinkingBlocks:l,reasoningContent:s,content:c,refusal:u,toolCalls:o}),stop_reason:p,...m?{stop_details:{type:`refusal`}}:{},stop_sequence:f,usage:Fi(F(t.usage))}}function Li(e){return e===null?`None`:e===!0?`True`:e===!1?`False`:typeof e==`number`?String(e):typeof e==`string`?`'${e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`:Array.isArray(e)?`[${e.map(e=>Li(e)).join(`, `)}]`:P(e)?`{${Object.entries(e).map(([e,t])=>`'${e}': ${Li(t)}`).join(`, `)}}`:String(e)}function Ri(e){let t=``,n=[],r=null,i=[];if((Array.isArray(e.content)?e.content:[]).forEach((e,r)=>{let a=F(e),o=typeof a.type==`string`?a.type:``;if(o===`text`)t+=typeof a.text==`string`?a.text:``;else if(o===`tool_use`||o===`server_tool_use`){let e={id:a.id,type:`function`,function:{name:a.name,arguments:JSON.stringify(a.input??{})},index:r};i.push(e)}else(o===`thinking`||o===`redacted_thinking`)&&n.push(a)}),n.length>0){r=``;for(let e of n){let t=e.thinking;typeof t==`string`&&(r+=t)}}return{textContent:t,thinkingBlocks:n,reasoningContent:r,toolCalls:i}}function zi(e){let t=[];for(let n of e){let e=F(n),r=typeof e.type==`string`?e.type:``;(r===`tool_use`||r===`server_tool_use`)&&t.push(e.caller)}return t}function Bi(e,t){let n=zi(Array.isArray(t.content)?t.content:[]),r=Array.isArray(e.content)?e.content:[],i=0;for(let e of r){let t=F(e);if(t.type!==`tool_use`)continue;let r=n[i];i+=1,r!==void 0&&(t.caller=r)}}function Vi(e){let t=F(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new N(Li(t.error));let n=Ri(t),r={role:`assistant`,content:n.textContent===``?null:n.textContent,tool_calls:n.toolCalls.length>0?n.toolCalls:null};n.reasoningContent!==null&&(r.reasoning_content=n.reasoningContent),n.thinkingBlocks.length>0&&(r.thinking_blocks=n.thinkingBlocks);let i=F(Ii({id:z(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:L(t.stop_reason),message:r}],usage:Ci(F(t.usage))}));return Bi(i,t),{...i,...t.container===void 0?{}:{container:t.container},...`stop_details`in i?{stop_details:i.stop_details}:t.stop_details===void 0?{}:{stop_details:t.stop_details},...t.diagnostics===void 0?{}:{diagnostics:t.diagnostics}}}var Hi=class{contentBlocks=[];toolIndex=-1;currentContentBlockType=null;cumulativeUsage={};parse(e){let t=L(e.type)??``,n=``,r=null,i=``,a=null,o=null,s=null,c=null;if(t===`content_block_delta`){let t=F(e.delta);if(this.contentBlocks.push(e),typeof t.text==`string`)n=t.text;else if(`partial_json`in t)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&(r={id:null,type:`function`,function:{name:null,arguments:typeof t.partial_json==`string`?t.partial_json:``},index:this.toolIndex});else if(!(`citation`in t)&&(`thinking`in t||`signature`in t)){let e=t.thinking;typeof e==`string`&&e!==``&&(o=e,s=[{type:`thinking`,thinking:e}]);let n=t.signature;typeof n==`string`&&n!==``&&(s=[{type:`thinking`,thinking:this.contentBlocks.map(e=>F(e.delta)).filter(e=>typeof e.thinking==`string`).map(e=>e.thinking).join(``),signature:n}])}}else if(t===`content_block_start`){let t=F(e.content_block);if(this.contentBlocks.length=0,this.currentContentBlockType=L(t.type)??``,this.currentContentBlockType===`text`)n=typeof t.text==`string`?t.text:``;else if(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`){this.toolIndex+=1;let e=L(t.name)??``;r={id:L(t.id),type:`function`,function:{name:e,arguments:``},index:this.toolIndex}}else this.currentContentBlockType===`redacted_thinking`&&(s=[{type:`redacted_thinking`,data:t.data}])}else if(t===`content_block_stop`)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&this.contentBlocks.map(e=>F(e.delta)).filter(e=>e.type===`input_json_delta`).map(e=>typeof e.partial_json==`string`?e.partial_json:``).join(``)===``&&(r={id:null,type:`function`,function:{name:null,arguments:`{}`},index:this.toolIndex}),this.currentContentBlockType=null;else if(t===`message_delta`)i=L(F(e.delta).stop_reason)??``,`usage`in e&&(a=Ci(this.#e(e.usage)));else if(t===`message_start`){let t=F(e.message);c=L(t.model),`usage`in t&&(a=Ci(this.#e(t.usage)))}else if(t===`error`){let t=F(e.error);throw new N(typeof t.message==`string`&&t.message!==``?t.message:JSON.stringify(e),{status:500})}else return null;let l={content:n,tool_calls:r===null?null:[r]};o!==null&&(l.reasoning_content=o),s!==null&&(l.thinking_blocks=s);let u={choices:[{index:0,finish_reason:i===``?null:i,delta:l}]};return c!==null&&(u.model=c),a!==null&&(u.usage=a),u}#e(e){return this.cumulativeUsage={...this.cumulativeUsage,...F(e)},this.cumulativeUsage}},Ui=class{inbound=`anthropic`;upstream=`anthropic`;translateRequest(e){return xi(e)}translateResponse(e){return Vi(e)}async*bridgeFrames(e){let t=new Hi,n=new mi;for await(let r of e){let e=t.parse(F(r));if(e!==null)for(let t of n.translateFrame(e))yield t}for(let e of n.flush())yield e}usageFromFrame(e){return fi(e)}errorEnvelope(e,t){return di(e,t)}},Wi=`Operator note (not from the user): the following was originally a mid-conversation system-role reminder.`;function Gi(e){let t=e.role;return t===`system`?`system`:t===`tool`||t===`function`?`tool`:t===`user`?`user`:`other`}function Ki(e){let t=e.content;if(typeof t==`string`)return t===``?[]:[{type:`text`,text:t}];let n=[];for(let e of I(t)){let t=F(e);if(t.type!==`text`)continue;let r=L(t.text)??``;r!==``&&n.push({type:`text`,text:r})}return n}function qi(e){return{role:`user`,content:[{type:`text`,text:Wi},...Ki(e)]}}function Ji(e){return e.filter(e=>Ki(e).length>0).map(qi)}function Yi(e){let t=[],n=null,r=[];for(let i of e){let e=Gi(i);e!==n&&(r.length>0&&t.push(r),r=[],n=e),r.push(i)}return r.length>0&&t.push(r),t}function Xi(e){let t=Yi(e),n=[];for(let e=0;e<t.length;e++){let r=t[e]??[],i=Gi(r[0]??{}),a=t[e+1],o=a===void 0?null:Gi(a[0]??{});if(i===`system`){o!==`tool`&&n.push(...Ji(r));continue}let s=e>0?t[e-1]:void 0;if(i===`tool`&&s!==void 0&&Gi(s[0]??{})===`system`){n.push(...r,...Ji(s));continue}n.push(...r)}return n}function Zi(e){if(!e.some(e=>e.role===`system`))return e;let t=e.findIndex(e=>e.role!==`system`);return t===-1?e:[...e.slice(0,t),...Xi(e.slice(t))]}var Qi=new Set([`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`not`,`propertyNames`,`then`,`unevaluatedItems`,`unevaluatedProperties`]),$i=new Set([`allOf`,`anyOf`,`items`,`oneOf`,`prefixItems`]),ea=new Set([`$defs`,`definitions`,`dependentSchemas`,`patternProperties`,`properties`]),ta=1024;function na(e){if(e.includes(`\\p{`)||e.includes(`\\p<`))return!1;try{new RegExp(e)}catch{return!1}return!0}function ra(e,t){let n={},r=!1;for(let[i,a]of Object.entries(e)){if(i===`pattern`&&typeof a==`string`&&!na(a)){r=!0;continue}let e=ia(i,a,t);e!==a&&(r=!0),i===`__proto__`?Object.defineProperty(n,i,{value:e,enumerable:!0,writable:!0,configurable:!0}):n[i]=e}return r?n:e}function ia(e,t,n){if($i.has(e)&&Array.isArray(t)){let e=t.map(e=>P(e)?n.get(e)??e:e);return e.every((e,n)=>e===t[n])?t:e}if(!P(t))return t;if(ea.has(e)){let r={},i=!1;for(let[a,o]of Object.entries(t)){if(e===`patternProperties`&&typeof a==`string`&&!na(a)){i=!0;continue}if(P(o)){let e=n.get(o)??o;e!==o&&(i=!0),a===`__proto__`?Object.defineProperty(r,a,{value:e,enumerable:!0,writable:!0,configurable:!0}):r[a]=e}else r[a]=o}return i?r:t}return Qi.has(e)?n.get(t)??t:t}function aa(e,t){for(let[n,r]of Object.entries(e))if(ea.has(n)&&P(r))for(let e of Object.values(r))P(e)&&t.push(e);else if($i.has(n)&&Array.isArray(r))for(let e of r)P(e)&&t.push(e);else Qi.has(n)&&P(r)&&t.push(r)}function oa(e){let t=new Map,n=[],r=[e];for(;r.length>0&&n.length<ta;){n.push(r);let e=[];for(let t of r)aa(t,e);r=e}for(let e of n.reverse())for(let n of e){let e=ra(n,t);e!==n&&t.set(n,e)}return t.get(e)??e}function sa(e){if(P(e))return e;if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return P(t)?t:null}catch{return null}}function ca(e,t){if(typeof e==`string`)return e===``?null:e;let n=[];for(let r of I(e)){let e=F(r);if(e.type!==`text`)continue;let i=L(e.text)??``;(i!==``||t)&&n.push({type:`text`,text:i})}return n.length>0?n:null}function la(e){let t=ca(e,!0);return t===null?[]:[{role:`system`,content:t}]}function ua(e){return e.flatMap(e=>{let t=F(e),n=t.content;if(t.role===`system`){let e=ca(n,!1);return e===null?[]:[{role:`system`,content:e}]}return t.role===`user`?da(n):t.role===`assistant`?ha(n):[]})}function da(e){if(typeof e==`string`)return[{role:`user`,content:e}];let t=[],n=[];for(let r of I(e)){let e=F(r);if(e.type===`text`)t.push({type:`text`,text:L(e.text)??``});else if(e.type===`image`){let n=pa(e.source);n!==null&&t.push({type:`image_url`,image_url:{url:n}})}else e.type===`tool_result`&&n.push({role:`tool`,content:fa(e.content),tool_call_id:L(e.tool_use_id)??``})}let r=t.length>0?t:``;return n.length>0&&t.length===0?n:[...n,{role:`user`,content:r}]}function fa(e){return typeof e==`string`?e:I(e).map(e=>L(F(e).text)??``).join(``)}function pa(e){let t=F(e);return t.type===`base64`&&typeof t.data==`string`&&t.data!==``?`data:${typeof t.media_type==`string`?t.media_type:`image/jpeg`};base64,${t.data}`:t.type===`url`?L(t.url):null}function ma(e){return e.map(e=>e.type===`thinking`?L(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
15
|
+
`)}\n\n`)}function Pr(e,t={}){let n=e.type;return Nr((t.protocol===void 0||t.protocol===`anthropic`)&&typeof n==`string`?n:null,JSON.stringify(e))}function Fr(){return Nr(null,kr)}async function*Ir(e,t){let n=(e,t)=>({event:e.event,data:e.data,done:t!==`anthropic`&&e.data===`[DONE]`}),r=e.getReader(),i=new TextDecoder,a=new jr,o=!1;try{for(;;){let{done:e,value:o}=await r.read();if(e)break;for(let e of a.push(i.decode(o,{stream:!0}))){let r=n(e,t);if(yield r,r.done)return}}for(let e of a.push(i.decode())){let r=n(e,t);if(yield r,r.done)return}for(let e of a.flush()){let r=n(e,t);if(yield r,r.done)return}o=!0}finally{o||r.cancel().catch(()=>{})}}function Lr(e){let t;try{t=JSON.parse(e.data)}catch{return null}return typeof t!=`object`||!t||Array.isArray(t)?null:t}function Rr(e,t){return Pr(e,{protocol:t})}function zr(e,t){let n=(e,t,n,r)=>e instanceof ReadableStream?e.pipeThrough(i(t,n,`upstream`,r)):e===null?null:t(e,r),r=(e,t,n,r)=>{if(e.kind===`error`)return e;let a=e.value;if(`stream`in a)return fr({...a,stream:a.stream.pipeThrough(i(t,n,`client`,r))});if(a.body===null||typeof a.body!=`object`)return e;let o=t(a.body,r);return fr(o===null?{...a,body:null}:{...a,body:o})},i=(e,t,n,r)=>{let i=new jr,a=new TextDecoder,o=!1,s=(i,a)=>{if(t!==`anthropic`&&i.data===`[DONE]`){a.enqueue(Fr());return}let s=Lr({event:i.event,data:i.data,done:!1});if(s===null){a.enqueue(Nr(i.event,i.data));return}let c;try{c=e(s,r)}catch(e){if(o=!0,n===`upstream`){a.error(e);return}for(let n of vr(t,{message:gr(e)}))a.enqueue(Pr(n,{protocol:t}));a.terminate();return}c!==null&&a.enqueue(Pr(c,{protocol:t}))};return new TransformStream({transform(e,t){if(!o){for(let n of i.push(a.decode(e,{stream:!0})))if(s(n,t),o)return}},flush(e){if(!o){for(let t of i.push(a.decode()))if(s(t,e),o)return;for(let t of i.flush())if(s(t,e),o)return}}})},a=[],o=[];if(e.request!==void 0){let n=e.request;a.push((e,r)=>n(e,r,t))}if(e.clientRequest!==void 0){let n=e.clientRequest;a.push((e,r)=>r(n(e,t)))}if(e.upstreamRequest!==void 0){let n=e.upstreamRequest;a.push((e,r)=>{let i=r(e);return hr(i)?i.then(a):a(i);function a(e){return e.kind===`error`?e:fr(n(e.value,t))}})}if(e.response!==void 0){let n=e.response;o.push((e,r)=>n(e,r,t))}if(e.upstreamResponse!==void 0){let r=e.upstreamResponse;o.push((e,i)=>{let a=e;return i({...a,body:n(a.body,r,t.pair.upstream,t)})})}if(e.clientResponse!==void 0){let n=e.clientResponse;o.push((e,i)=>{let a=i(e);return hr(a)?a.then(e=>r(e,n,t.pair.inbound,t)):r(a,n,t.pair.inbound,t)})}return{requestLayers:a,responseLayers:o}}function Br(e,t){let n=e=>(t,n)=>{let r;try{r=e.options.translate===!1?t.body:e.pair.translateRequest(t.body,e.options)}catch(e){return pr(mr(e)??500,gr(e))}let i={"content-type":`application/json`},a=r.stream===!0;return n({headers:i,body:r,stream:a})};return new _r([...t.specs.flatMap(e=>zr(e,t).requestLayers),n(t)]).run(e,e=>fr(e))}var Vr=class{stream;collectUsage=()=>this.#t;#e;#t=null;#n;#r;#i=!1;constructor(e){this.#e=e,this.#n=e.bridge(this.#a())[Symbol.asyncIterator](),this.#r=this.#o()[Symbol.asyncIterator]();let t=new le({objectMode:!0,highWaterMark:0,read:()=>{this.#r.next().then(e=>{e.done?t.push(null):t.push(e.value)},e=>{t.destroy(e instanceof Error?e:Error(String(e)))})},destroy:(e,t)=>{Promise.resolve(this.#r.return?.()).catch(()=>{}).then(()=>t())}});this.stream=le.toWeb(t)}async*#a(){for await(let e of Ir(this.#e.upstreamBytes,this.#e.upstreamProtocol)){if(e.done){this.#i=!0;return}let t=Lr(e);t!==null&&(yield t)}}async*#o(){try{for(;;){let e=await this.#n.next();if(e.done){if(this.#e.upstreamProtocol===`openai`&&!this.#i){for(let e of vr(this.#e.inboundProtocol,{status:502,message:`upstream stream ended before the [DONE] sentinel (truncated)`}))yield Rr(e,this.#e.inboundProtocol);return}yr(this.#e.inboundProtocol)&&(yield Fr());return}let t=e.value,n=this.#e.usageFromFrame;if(n!==void 0){let e=n(t);e!==null&&(this.#t={...this.#t??{},...e})}yield Rr(t,this.#e.inboundProtocol)}}catch(e){let t=gr(e);for(let n of vr(this.#e.inboundProtocol,{status:mr(e),message:t}))yield Rr(n,this.#e.inboundProtocol)}finally{await this.#n.return?.().catch(()=>{})}}};async function Hr(e,t){let n=e=>{let t={};if(e instanceof Headers)return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t;for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t},r=async(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i;try{i=r.status<200||r.status>299?e.pair.errorEnvelope(r.status,r.body):e.options.translate===!1?r.body:e.pair.translateResponse(r.body,e.options)}catch(e){return pr(mr(e)??500,gr(e))}return n({status:r.status,headers:r.headers,body:i})},i;try{i=await e.text()}catch(e){return pr(502,`failed to read upstream response body: ${gr(e)}`)}let a;try{let e=JSON.parse(i);if(typeof e!=`object`||!e)return pr(502,`upstream response is not a valid JSON object`);a=e}catch{return pr(502,`upstream response is not valid JSON`)}return new _r([...t.specs.flatMap(e=>zr(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:a},e=>fr(e))},i=(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i=new Vr({upstreamBytes:r.body,upstreamProtocol:e.pair.upstream,inboundProtocol:e.pair.inbound,bridge:e.options.translate===!1?e=>e:t=>e.pair.bridgeFrames(t,e.options,e.inboundBody??void 0),usageFromFrame:e.pair.usageFromFrame});return n({status:r.status,headers:r.headers,stream:i.stream,collectUsage:i.collectUsage})};return e.body===null?pr(502,`streaming response has no body`):new _r([...t.specs.flatMap(e=>zr(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:e.body},e=>fr(e))},a=n(e.headers),o=(a[`content-type`]??``).includes(`text/event-stream`);return e.status<200||e.status>299||!o?r(e,t,a):i(e,t,a)}var Ur=[],Wr=class{chainName;pair;options;state=new Map;getState(e){return this.state.get(e)}setState(e,t){this.state.set(e,t)}#e=null;#t=Ur;#n=null;#r=!1;#i=!1;#a;constructor(e){this.chainName=e.chainName,this.pair=e.pair,this.options=Object.freeze({...e.options}),this.#a=e.snapshot}get specs(){return this.#t}get inbound(){return this.#e}get inboundBody(){return this.#e===null?null:this.#e.body}get upstreamRequest(){return this.#n}request(e){if(this.#r)return pr(500,`RequestContext: request() can only be called once (one container per round trip)`);this.#r=!0,this.#e=e,this.#t=Gr(this.#a,e,this);let t=Br(e,this);return hr(t)?t.then(e=>(e.kind===`ok`&&(this.#n=e.value),e)):(t.kind===`ok`&&(this.#n=t.value),t)}response(e){if(this.#i)return Promise.resolve(pr(500,`RequestContext: response() can only be called once`));if(this.#i=!0,!this.#r){let e=[];for(let t of this.#a)t!==null&&t.runWhen===void 0&&e.push(t);this.#t=e}return Hr(e,this)}};function Gr(e,t,n){let r=[];for(let i of e)i!==null&&(i.runWhen===void 0||i.runWhen(t,n)===!0)&&r.push(i);return r}var Kr=class{#e=[];register(e){let t=this.#e.length;return this.#e.push(e),t}unregister(e){this.#e[e]=null}snapshot(){return[...this.#e]}},qr=class{#e;#t;#n;#r=new Kr;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}get name(){return this.#n}intercept(e){return this.#r.register(e)}unregister(e){this.#r.unregister(e)}begin(){return new Wr({chainName:this.#n,pair:this.#e,options:Object.freeze({...this.#t}),snapshot:this.#r.snapshot()})}};function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return P(e)?e:{}}function I(e){return Array.isArray(e)?e:[]}function L(e){return typeof e==`string`?e:null}function R(e){return typeof e==`string`?e:``}function Jr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Yr(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function z(){return crypto.randomUUID()}function Xr(){return Math.floor(Date.now()/1e3)}function Zr(...e){for(let t of e){let e=Yr(t);if(e>0)return e}return 0}function Qr(e){let t=F(e.prompt_tokens_details);return{cacheRead:Zr(e.cache_read_input_tokens,e.prompt_cache_hit_tokens,t.cached_tokens),cacheCreation:Zr(e.cache_creation_input_tokens,t.cache_creation_tokens,t.cache_write_tokens)}}function $r(e,t,n,r){let i={input_tokens:Math.max(e-n-r,0),output_tokens:t};return r>0&&(i.cache_creation_input_tokens=r),n>0&&(i.cache_read_input_tokens=n),i}var ei=new Set([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`refusal`]),ti=new Set([`stop`,`length`,`tool_calls`,`function_call`,`content_filter`]);function ni(e){return{stop:`end_turn`,length:`max_tokens`,tool_calls:`tool_use`}[e]??`end_turn`}function ri(e){let t=L(e)??``;return ei.has(t)?t:ni(t)}function ii(e){let t=L(e.stop_reason),n=L(F(e.provider_specific_fields).stop_reason),r=t??n;return r===null||r===``||ei.has(r)||ti.has(r)?null:r}function ai(e){let t=L(e.refusal);if(t!==null&&t!==``)return t;let n=L(F(e.provider_specific_fields).refusal);return n!==null&&n!==``?n:null}var oi={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`};function si(e){return oi[e]??`api_error`}function ci(e){let t=P(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function li(e){if(!P(e))return!1;let t=e.type===`error`?e.error:void 0;return P(t)&&typeof t.type==`string`&&typeof t.message==`string`}function ui(e,t){if(P(t)){let e=t.error;if(P(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(P(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return typeof t==`string`&&t!==``?t:`upstream error (HTTP ${e})`}function di(e,t){return li(t)?t:{type:`error`,error:{type:si(e),message:ui(e,t)}}}function fi(e){let t=F(e);if(t.type===`message_start`){let e=F(t.message).usage;return P(e)?e:null}if(t.type===`message_delta`){let e=t.usage;return P(e)?e:null}return null}function pi(e){if(typeof e!=`object`||!e||Array.isArray(e))return String(e);let t=F(e),n=t.message;return typeof n==`string`&&n!==``?n:JSON.stringify(t)}var mi=class{#e=0;#t=null;#n=null;#r=null;#i=0;#a=0;#o=0;#s=0;#c=!1;#l=!1;#u=null;#d=null;#f=``;#p=``;translateFrame(e){if(this.#l)return[];let t=e.error;if(t!=null)throw new N(pi(t),{status:ci(t)});let n=F(I(e.choices)[0]),r=F(n.delta),i=[];if(!this.#c){this.#c=!0;let t=e.id;this.#p=typeof t==`string`&&t!==``?t:z(),i.push(this.#m(L(e.model)))}let a=r.content;typeof a==`string`&&a!==``&&(i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:a})));let o=ai(r);o!==null&&(this.#f+=o,i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:o})));let s=r.reasoning_content===void 0?r.reasoning:r.reasoning_content;typeof s==`string`&&s!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`thinking_delta`,thinking:s})));for(let e of I(r.thinking_blocks)){let t=L(F(e).signature);t!==null&&t!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`signature_delta`,signature:t})))}for(let[e,t]of I(r.tool_calls).entries()){let n=F(t),r=F(n.function),a=typeof n.index==`number`?n.index:e,o=L(n.id)??``;(this.#t!==`tool_use`||this.#n!==a||o!==``&&this.#r!==null&&this.#r!==o)&&this.#t===`tool_use`&&i.push(...this.#g()),i.push(...this.#h(`tool_use`,{type:`tool_use`,id:o,name:L(r.name)??``,input:{}})),this.#n=a,o!==``&&(this.#r=o);let s=r.arguments;typeof s==`string`&&s!==``&&i.push(this.#_({type:`input_json_delta`,partial_json:s}))}let c=F(e.usage),l=Yr(c.prompt_tokens),u=Yr(c.completion_tokens);if(l>0){this.#i=l;let e=Qr(c);this.#o=e.cacheRead,this.#s=e.cacheCreation}u>0&&(this.#a=u);let d=n.finish_reason;typeof d==`string`&&d!==``&&(this.#u=d);let f=ii(n);return f!==null&&(this.#d=f),i}flush(){if(!this.#c||this.#l)return[];this.#l=!0;let e=[...this.#g()],t=this.#d===null?this.#u==null?`end_turn`:ri(this.#u):`stop_sequence`,n=this.#f!==``&&t!==`max_tokens`;return e.push({type:`message_delta`,delta:n?{stop_reason:`refusal`,stop_sequence:this.#d,stop_details:{type:`refusal`}}:{stop_reason:t,stop_sequence:this.#d},usage:$r(this.#i,this.#a,this.#o,this.#s)}),e.push({type:`message_stop`}),e}#m(e){return{type:`message_start`,message:{id:this.#p,type:`message`,role:`assistant`,...e===null?{}:{model:e},content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}}#h(e,t){if(this.#t===e)return[];let n=this.#g();this.#t=e;let r=t??{type:`text`,text:``},i=[...n,{type:`content_block_start`,index:this.#e,content_block:r}];return this.#e+=1,i}#g(){if(this.#t===null)return[];let e=this.#e-1;return this.#t=null,this.#n=null,this.#r=null,[{type:`content_block_stop`,index:e}]}#_(e){return{type:`content_block_delta`,index:this.#e-1,delta:e}}};async function*hi(e){let t=new mi;for await(let n of e)for(let e of t.translateFrame(F(n)))yield e;for(let e of t.flush())yield e}var gi=4096;function _i(e){return e.map(e=>{if(!P(e))return F(e);let t=!1,n={};for(let[r,i]of Object.entries(e)){if(r===`provider_specific_fields`){t=!0;continue}if(r===`content`&&Array.isArray(i)){let e=i.map(e=>{if(!P(e)||!(`provider_specific_fields`in e))return e;let{provider_specific_fields:t,...n}=e;return n});(e.length!==i.length||e.some((e,t)=>e!==i[t]))&&(t=!0),n[r]=e;continue}n[r]=i}return t?n:e})}function vi(e,t){let n=!1;for(let t of e){let e=t.content;if(Array.isArray(e)){for(let t of e)if(F(t).type===`container_upload`){n=!0;break}}if(n)break}if(!n)return t;for(let e of t){let n=e.type;if(typeof n==`string`&&n.startsWith(`code_execution`))return t}return[...t,{name:`code_execution`,type:`code_execution_20250522`}]}function yi(e){if(!P(e.metadata))return;let t=F(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function bi(e){let t=e.output_config;if(!P(t))return;let n=t.effort;if(typeof n==`string`&&n!==``&&![`high`,`medium`,`low`,`xhigh`,`max`].includes(n))throw new N(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function xi(e){let t=F(e),n=_i(I(t.messages)),r=I(t.tools).map(F),i=vi(n,r),a={...t,messages:n};return i!==r&&(a.tools=i),`max_tokens`in a||(a.max_tokens=gi),yi(a),delete a.is_vertex_request,delete a.client_metadata,bi(a),a}function Si(e){return typeof e==`number`&&Number.isFinite(e)?Math.floor(e):0}function Ci(e){let t=Si(e.input_tokens??0),n=Si(e.output_tokens??0),r=0,i=0,a=e.iterations,o=Array.isArray(a)?a.map(F):null;o!==null&&o.length>0&&(t=o.reduce((e,t)=>e+Si(t.input_tokens??0),0),n=o.reduce((e,t)=>e+Si(t.output_tokens??0),0),r=o.reduce((e,t)=>e+Si(t.cache_creation_input_tokens??0),0),i=o.reduce((e,t)=>e+Si(t.cache_read_input_tokens??0),0),t+=r+i),o===null&&(`cache_creation_input_tokens`in e&&e.cache_creation_input_tokens!==null&&typeof e.cache_creation_input_tokens==`number`&&(r=e.cache_creation_input_tokens,t+=r),`cache_read_input_tokens`in e&&e.cache_read_input_tokens!==null&&typeof e.cache_read_input_tokens==`number`&&(i=e.cache_read_input_tokens,t+=i));let s={cached_tokens:i,cache_creation_tokens:r,cache_write_tokens:r};return{prompt_tokens:t,completion_tokens:n,total_tokens:t+n,prompt_tokens_details:s,cache_creation_input_tokens:r,cache_read_input_tokens:i}}var wi=/^<(?:think|thinking|budget:thinking)>([\s\S]*?)<\/(?:think|thinking|budget:thinking)>([\s\S]*)/;function Ti(e){if(!e)return{reasoningContent:null,content:e};let t=wi.exec(e);return t===null?{reasoningContent:null,content:e}:{reasoningContent:t[1]??null,content:t[2]??null}}function Ei(e){let t=e.content,n=L(t);return`reasoning_content`in e?{reasoningContent:L(e.reasoning_content),content:n}:`reasoning`in e?{reasoningContent:L(e.reasoning),content:n}:typeof t==`string`?Ti(t):{reasoningContent:null,content:n}}function Di(e){let t=F(e),n=t.arguments,r;if(n==null){let e=t.parameters;r=P(e)?JSON.stringify(e):``}else r=P(n)?JSON.stringify(n):String(n);return{arguments:r,name:L(t.name)}}function Oi(e){return e.type===`custom`||e.custom!=null}function ki(e){return Oi(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`function`&&e!==`type`||t!=null)):{id:e.id==null?z():String(e.id),type:e.type==null?`function`:String(e.type),function:Di(e.function)}}function Ai(e){let t=new Map;for(let[n,r]of e.entries()){if(Oi(r))continue;let e=F(r.function),i=e.name,a=JSON.parse(typeof e.arguments==`string`?e.arguments:``);if(i!==`multi_tool_use.parallel`)continue;let o=F(a),s=(Array.isArray(o.tool_uses)?o.tool_uses:[]).map((e,t)=>{let n=F(e),i=String(n.recipient_name).replace(/^functions\./,``);return{id:`${String(r.id)}_${String(t)}`,type:`function`,function:{name:i,arguments:JSON.stringify(n.parameters)}}});t.set(n,s)}return t}function ji(e){try{let t=Ai(e),n=0,r=[...e];for(let[e,i]of t)r.splice(e+n,1,...i),n+=i.length;return r}catch{return e}}function Mi(e){return Array.isArray(e.tool_calls)?ji(e.tool_calls.map(e=>ki(F(e)))):[]}function Ni(e){if(typeof e!=`string`||e===``)return{};try{return F(JSON.parse(e))}catch{return{}}}function Pi(e){let t=[];for(let n of e.thinkingBlocks){let e=F(n);e.type===`thinking`?t.push({type:`thinking`,thinking:L(e.thinking)??``,signature:L(e.signature)}):e.type===`redacted_thinking`&&t.push({type:`redacted_thinking`,data:L(e.data)??``})}e.thinkingBlocks.length===0&&typeof e.reasoningContent==`string`&&e.reasoningContent!==``&&t.push({type:`thinking`,thinking:e.reasoningContent,signature:null}),typeof e.content==`string`&&e.content!==``&&t.push({type:`text`,text:e.content}),e.refusal!==null&&t.push({type:`text`,text:e.refusal});for(let n of e.toolCalls){let e=F(n),r=F(e.function);t.push({type:`tool_use`,id:L(e.id)??``,name:L(r.name)??``,input:Ni(r.arguments)})}return t}function Fi(e){let{cacheRead:t,cacheCreation:n}=Qr(e);return $r(Yr(e.prompt_tokens),Yr(e.completion_tokens),t,n)}function Ii(e){let t=F(e),n=t.error;if(n!=null){let e=F(n);throw new N(typeof e.message==`string`?e.message:JSON.stringify(n),{status:ci(n)})}let r=I(t.choices);if(r.length===0)throw Error(`upstream returned a response with no 'choices'. Raw keys: ${Object.keys(t).join(`, `)}`);let i=F(r[0]),a=F(i.message),o=Mi(a),{reasoningContent:s,content:c}=Ei(a),l=I(a.thinking_blocks),u=ai(a),d=L(i.finish_reason)??`stop`;d===`stop`&&o.length>0&&(d=`tool_calls`);let f=ii(i),p=f===null?ri(d):`stop_sequence`,m=u!==null&&p!==`max_tokens`;return m&&(p=`refusal`),{id:t.id,type:`message`,role:`assistant`,...t.model===void 0?{}:{model:t.model},content:Pi({thinkingBlocks:l,reasoningContent:s,content:c,refusal:u,toolCalls:o}),stop_reason:p,...m?{stop_details:{type:`refusal`}}:{},stop_sequence:f,usage:Fi(F(t.usage))}}function Li(e){return e===null?`None`:e===!0?`True`:e===!1?`False`:typeof e==`number`?String(e):typeof e==`string`?`'${e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`:Array.isArray(e)?`[${e.map(e=>Li(e)).join(`, `)}]`:P(e)?`{${Object.entries(e).map(([e,t])=>`'${e}': ${Li(t)}`).join(`, `)}}`:String(e)}function Ri(e){let t=``,n=[],r=null,i=[];if((Array.isArray(e.content)?e.content:[]).forEach((e,r)=>{let a=F(e),o=typeof a.type==`string`?a.type:``;if(o===`text`)t+=typeof a.text==`string`?a.text:``;else if(o===`tool_use`||o===`server_tool_use`){let e={id:a.id,type:`function`,function:{name:a.name,arguments:JSON.stringify(a.input??{})},index:r};i.push(e)}else(o===`thinking`||o===`redacted_thinking`)&&n.push(a)}),n.length>0){r=``;for(let e of n){let t=e.thinking;typeof t==`string`&&(r+=t)}}return{textContent:t,thinkingBlocks:n,reasoningContent:r,toolCalls:i}}function zi(e){let t=[];for(let n of e){let e=F(n),r=typeof e.type==`string`?e.type:``;(r===`tool_use`||r===`server_tool_use`)&&t.push(e.caller)}return t}function Bi(e,t){let n=zi(Array.isArray(t.content)?t.content:[]),r=Array.isArray(e.content)?e.content:[],i=0;for(let e of r){let t=F(e);if(t.type!==`tool_use`)continue;let r=n[i];i+=1,r!==void 0&&(t.caller=r)}}function Vi(e){let t=F(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new N(Li(t.error));let n=Ri(t),r={role:`assistant`,content:n.textContent===``?null:n.textContent,tool_calls:n.toolCalls.length>0?n.toolCalls:null};n.reasoningContent!==null&&(r.reasoning_content=n.reasoningContent),n.thinkingBlocks.length>0&&(r.thinking_blocks=n.thinkingBlocks);let i=F(Ii({id:z(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:L(t.stop_reason),message:r}],usage:Ci(F(t.usage))}));return Bi(i,t),{...i,...t.container===void 0?{}:{container:t.container},...`stop_details`in i?{stop_details:i.stop_details}:t.stop_details===void 0?{}:{stop_details:t.stop_details},...t.diagnostics===void 0?{}:{diagnostics:t.diagnostics}}}var Hi=class{contentBlocks=[];toolIndex=-1;currentContentBlockType=null;cumulativeUsage={};parse(e){let t=L(e.type)??``,n=``,r=null,i=``,a=null,o=null,s=null,c=null;if(t===`content_block_delta`){let t=F(e.delta);if(this.contentBlocks.push(e),typeof t.text==`string`)n=t.text;else if(`partial_json`in t)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&(r={id:null,type:`function`,function:{name:null,arguments:typeof t.partial_json==`string`?t.partial_json:``},index:this.toolIndex});else if(!(`citation`in t)&&(`thinking`in t||`signature`in t)){let e=t.thinking;typeof e==`string`&&e!==``&&(o=e,s=[{type:`thinking`,thinking:e}]);let n=t.signature;typeof n==`string`&&n!==``&&(s=[{type:`thinking`,thinking:this.contentBlocks.map(e=>F(e.delta)).filter(e=>typeof e.thinking==`string`).map(e=>e.thinking).join(``),signature:n}])}}else if(t===`content_block_start`){let t=F(e.content_block);if(this.contentBlocks.length=0,this.currentContentBlockType=L(t.type)??``,this.currentContentBlockType===`text`)n=typeof t.text==`string`?t.text:``;else if(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`){this.toolIndex+=1;let e=L(t.name)??``;r={id:L(t.id),type:`function`,function:{name:e,arguments:``},index:this.toolIndex}}else this.currentContentBlockType===`redacted_thinking`&&(s=[{type:`redacted_thinking`,data:t.data}])}else if(t===`content_block_stop`)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&this.contentBlocks.map(e=>F(e.delta)).filter(e=>e.type===`input_json_delta`).map(e=>typeof e.partial_json==`string`?e.partial_json:``).join(``)===``&&(r={id:null,type:`function`,function:{name:null,arguments:`{}`},index:this.toolIndex}),this.currentContentBlockType=null;else if(t===`message_delta`)i=L(F(e.delta).stop_reason)??``,`usage`in e&&(a=Ci(this.#e(e.usage)));else if(t===`message_start`){let t=F(e.message);c=L(t.model),`usage`in t&&(a=Ci(this.#e(t.usage)))}else if(t===`error`){let t=F(e.error);throw new N(typeof t.message==`string`&&t.message!==``?t.message:JSON.stringify(e),{status:500})}else return null;let l={content:n,tool_calls:r===null?null:[r]};o!==null&&(l.reasoning_content=o),s!==null&&(l.thinking_blocks=s);let u={choices:[{index:0,finish_reason:i===``?null:i,delta:l}]};return c!==null&&(u.model=c),a!==null&&(u.usage=a),u}#e(e){return this.cumulativeUsage={...this.cumulativeUsage,...F(e)},this.cumulativeUsage}},Ui=class{inbound=`anthropic`;upstream=`anthropic`;translateRequest(e){return xi(e)}translateResponse(e){return Vi(e)}async*bridgeFrames(e){let t=new Hi,n=new mi;for await(let r of e){let e=t.parse(F(r));if(e!==null)for(let t of n.translateFrame(e))yield t}for(let e of n.flush())yield e}usageFromFrame(e){return fi(e)}errorEnvelope(e,t){return di(e,t)}},Wi=`Operator note (not from the user): the following was originally a mid-conversation system-role reminder.`;function Gi(e){let t=e.role;return t===`system`?`system`:t===`tool`||t===`function`?`tool`:t===`user`?`user`:`other`}function Ki(e){let t=e.content;if(typeof t==`string`)return t===``?[]:[{type:`text`,text:t}];let n=[];for(let e of I(t)){let t=F(e);if(t.type!==`text`)continue;let r=L(t.text)??``;r!==``&&n.push({type:`text`,text:r})}return n}function qi(e){return{role:`user`,content:[{type:`text`,text:Wi},...Ki(e)]}}function Ji(e){return e.filter(e=>Ki(e).length>0).map(qi)}function Yi(e){let t=[],n=null,r=[];for(let i of e){let e=Gi(i);e!==n&&(r.length>0&&t.push(r),r=[],n=e),r.push(i)}return r.length>0&&t.push(r),t}function Xi(e){let t=Yi(e),n=[];for(let e=0;e<t.length;e++){let r=t[e]??[],i=Gi(r[0]??{}),a=t[e+1],o=a===void 0?null:Gi(a[0]??{});if(i===`system`){o!==`tool`&&n.push(...Ji(r));continue}let s=e>0?t[e-1]:void 0;if(i===`tool`&&s!==void 0&&Gi(s[0]??{})===`system`){n.push(...r,...Ji(s));continue}n.push(...r)}return n}function Zi(e){if(!e.some(e=>e.role===`system`))return e;let t=e.findIndex(e=>e.role!==`system`);return t===-1?e:[...e.slice(0,t),...Xi(e.slice(t))]}var Qi=new Set([`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`not`,`propertyNames`,`then`,`unevaluatedItems`,`unevaluatedProperties`]),$i=new Set([`allOf`,`anyOf`,`items`,`oneOf`,`prefixItems`]),ea=new Set([`$defs`,`definitions`,`dependentSchemas`,`patternProperties`,`properties`]),ta=1024;function na(e){if(e.includes(`\\p{`)||e.includes(`\\p<`))return!1;try{new RegExp(e)}catch{return!1}return!0}function ra(e,t){let n={},r=!1;for(let[i,a]of Object.entries(e)){if(i===`pattern`&&typeof a==`string`&&!na(a)){r=!0;continue}let e=ia(i,a,t);e!==a&&(r=!0),i===`__proto__`?Object.defineProperty(n,i,{value:e,enumerable:!0,writable:!0,configurable:!0}):n[i]=e}return r?n:e}function ia(e,t,n){if($i.has(e)&&Array.isArray(t)){let e=t.map(e=>P(e)?n.get(e)??e:e);return e.every((e,n)=>e===t[n])?t:e}if(!P(t))return t;if(ea.has(e)){let r={},i=!1;for(let[a,o]of Object.entries(t)){if(e===`patternProperties`&&typeof a==`string`&&!na(a)){i=!0;continue}if(P(o)){let e=n.get(o)??o;e!==o&&(i=!0),a===`__proto__`?Object.defineProperty(r,a,{value:e,enumerable:!0,writable:!0,configurable:!0}):r[a]=e}else r[a]=o}return i?r:t}return Qi.has(e)?n.get(t)??t:t}function aa(e,t){for(let[n,r]of Object.entries(e))if(ea.has(n)&&P(r))for(let e of Object.values(r))P(e)&&t.push(e);else if($i.has(n)&&Array.isArray(r))for(let e of r)P(e)&&t.push(e);else Qi.has(n)&&P(r)&&t.push(r)}function oa(e){let t=new Map,n=[],r=[e];for(;r.length>0&&n.length<ta;){n.push(r);let e=[];for(let t of r)aa(t,e);r=e}for(let e of n.reverse())for(let n of e){let e=ra(n,t);e!==n&&t.set(n,e)}return t.get(e)??e}function sa(e){if(P(e))return e;if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return P(t)?t:null}catch{return null}}function ca(e,t){if(typeof e==`string`)return e===``?null:e;let n=[];for(let r of I(e)){let e=F(r);if(e.type!==`text`)continue;let i=L(e.text)??``;(i!==``||t)&&n.push({type:`text`,text:i})}return n.length>0?n:null}function la(e){let t=ca(e,!0);return t===null?[]:[{role:`system`,content:t}]}function ua(e){return e.flatMap(e=>{let t=F(e),n=t.content;if(t.role===`system`){let e=ca(n,!1);return e===null?[]:[{role:`system`,content:e}]}return t.role===`user`?da(n):t.role===`assistant`?ha(n):[]})}function da(e){if(typeof e==`string`)return[{role:`user`,content:e}];let t=[],n=[];for(let r of I(e)){let e=F(r);if(e.type===`text`)t.push({type:`text`,text:L(e.text)??``});else if(e.type===`image`){let n=pa(e.source);n!==null&&t.push({type:`image_url`,image_url:{url:n}})}else e.type===`tool_result`&&n.push({role:`tool`,content:fa(e.content),tool_call_id:L(e.tool_use_id)??``})}let r=t.length>0?t:``;return n.length>0&&t.length===0?n:[...n,{role:`user`,content:r}]}function fa(e){return typeof e==`string`?e:I(e).map(e=>L(F(e).text)??``).join(``)}function pa(e){let t=F(e);return t.type===`base64`&&typeof t.data==`string`&&t.data!==``?`data:${typeof t.media_type==`string`?t.media_type:`image/jpeg`};base64,${t.data}`:t.type===`url`?L(t.url):null}function ma(e){return e.map(e=>e.type===`thinking`?L(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
16
16
|
`)}function ha(e){if(typeof e==`string`)return[{role:`assistant`,content:e}];let t=[],n=[],r=[];for(let i of I(e)){let e=F(i);e.type===`text`?t.push(L(e.text)??``):e.type===`tool_use`?n.push({id:L(e.id)??``,type:`function`,function:{name:L(e.name)??``,arguments:JSON.stringify(e.input??{})}}):e.type===`thinking`?r.push({type:`thinking`,thinking:L(e.thinking)??``,signature:L(e.signature)??``}):e.type===`redacted_thinking`&&r.push({type:`redacted_thinking`,data:L(e.data)??``})}let i=ma(r);return[{role:`assistant`,content:t.length>0?t.join(``):null,...n.length>0?{tool_calls:n}:{},...r.length>0?{thinking_blocks:r}:{},...i===``?{}:{reasoning_content:i}}]}var ga=64;function _a(e){if(typeof e!=`string`)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=F(t).session_id;if(typeof n!=`string`)return null;let r=n.slice(0,ga);return r===``?null:r}function va(e,t){let n=new Set([`max_tokens`,`temperature`,`top_p`,`stop_sequences`,`stream`,`metadata`,`tool_choice`,`tools`,`thinking`,`reasoning_effort`,`system`,`context_management`,`output_config`]);t.topK!==`preserve`&&n.add(`top_k`);let r=Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=(e,t,n)=>{n&&(r[e]=t)},a=e.max_tokens;i(`max_tokens`,a,typeof a==`number`);let o=e.temperature;i(`temperature`,o,typeof o==`number`);let s=e.top_p;i(`top_p`,s,typeof s==`number`);let c=e.stop_sequences;i(`stop`,c,Array.isArray(c)&&c.length>0),i(`stream`,!0,e.stream===!0);let l=_a(F(e.metadata).user_id);i(`prompt_cache_key`,l,l!==null);let u=ya(e.tool_choice);i(`tool_choice`,u,u!==null);let d=e.tools;i(`tools`,I(d).map(ba),I(d).length>0);let f=xa(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function ya(e){let t=F(e);return t.type===`auto`?`auto`:t.type===`any`?`required`:t.type===`none`?`none`:t.type===`tool`&&typeof t.name==`string`?{type:`function`,function:{name:t.name}}:null}function ba(e){let t=F(e),n=t.input_schema,r=sa(n);if(r===null&&n!=null)throw new N(`Invalid type for tools[${String(t.name??``)}].input_schema: expected an object, but got ${typeof n} instead.`,{status:400});return{type:`function`,function:{name:t.name??``,description:t.description,parameters:oa(r!==null&&Object.keys(r).length>0?r:{type:`object`,properties:{}})}}}function xa(e,t=void 0){let n=F(e),r=L(n.type)??``;if(r===`disabled`)return null;if(r===`adaptive`)return L(F(n.output_config).effort)??L(F(t).effort)??null;if(r!==`enabled`)return null;let i=n.budget_tokens;return typeof i==`number`?i<=1024?`low`:i<=2048?`medium`:`high`:`medium`}function Sa(e,t){let n=F(e),r=Zi([...la(n.system),...ua(I(n.messages))]),i=va(n,t);if(i.messages=r,i.reasoning_effort===`none`){let e={...i};delete e.reasoning_effort,i=e}return i}var Ca=class{inbound=`anthropic`;upstream=`openai`;translateRequest(e,t){return Sa(e,t)}translateResponse(e){return Ii(e)}bridgeFrames(e){return hi(e)}usageFromFrame(e){return fi(e)}errorEnvelope(e,t){return di(e,t)}},wa={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`};function Ta(e){let t=wa[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function Ea(e,t){if(typeof t==`string`&&t!==``)return t;if(P(t)){let e=t.message;if(typeof e==`string`&&e!==``)return e;let n=JSON.stringify(t);if(n!==void 0&&n!==``)return n}return`upstream error (HTTP ${e})`}function Da(e,t){return P(t)&&P(t.error)?t:{error:{message:Ea(e,t),type:Ta(e),param:null,code:String(e)}}}function Oa(){return`chatcmpl-${z()}`}var ka={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,content_filtered:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`};function Aa(e){return ka[L(e)??``]??`stop`}function ja(e,t){let n=e.iterations,r=null;if(Array.isArray(n)&&n.length>0){let e=n.map(e=>{let t=F(F(e).output_tokens_details).thinking_tokens;return typeof t==`number`&&Number.isFinite(t)?t:null});r=e.every(e=>e!==null)?e.reduce((e,t)=>e+(t??0),0):null}if(r===null){let t=F(e.output_tokens_details).thinking_tokens;typeof t==`number`&&Number.isFinite(t)&&(r=t)}if(r===null)return{reasoning_tokens:0,text_tokens:t};let i=Math.min(Math.max(0,r),t);return{reasoning_tokens:i,text_tokens:t-i}}function Ma(e,t={}){let n=Yr(e.input_tokens),r=Yr(e.output_tokens),i=Yr(e.cache_creation_input_tokens),a=Yr(e.cache_read_input_tokens),o=n+i+a,s={cached_tokens:a,text_tokens:n,cache_write_tokens:i,cache_creation_tokens:i};if(P(e.cache_creation)){let t=e.cache_creation,n={};for(let e of[`ephemeral_5m_input_tokens`,`ephemeral_1h_input_tokens`]){let r=t[e];typeof r==`number`&&(n[e]=Yr(r))}s.cache_creation_token_details=n}let c={completion_tokens:r,prompt_tokens:o,total_tokens:o+r,completion_tokens_details:ja(e,r),prompt_tokens_details:s,cache_creation_input_tokens:i,cache_read_input_tokens:a},l=L(e.inference_geo);l!==null&&(c.inference_geo=l);let u=L(e.speed);if(u!==null&&(c.speed=u),t.fromStreamBuilder!==!0){let t=L(e.service_tier);t!==null&&(c.service_tier=t)}return c}function Na(e,t){return{...e??{},...t}}function Pa(e){return/claude-[a-z]+-(?:4[-._](?:[6-9]|[1-9]\d)(?!\d)|[5-9](?!\d)(?:[-._]\d{1,2}(?!\d))?)/.test(e)}function Fa(e){return/claude-[a-z]+-4[-._]6(?!\d)/.test(e)}function Ia(e){let t=e.toLowerCase();return![`fable`,`opus-4-7`,`opus_4_7`,`opus-4.7`,`opus_4.7`,`opus-4-8`,`opus_4_8`,`opus-4.8`,`opus_4.8`].some(e=>t.includes(e))}function La(e,t){if(typeof t==`string`&&t!==``)return t;if(P(t)){let e=t.error;if(P(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(P(n)&&typeof n.message==`string`&&n.message!==``)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return`upstream error (HTTP ${e})`}function Ra(e,t){if(P(t)){let e=t.error;if(P(e)&&t.type!==`error`&&typeof e.message==`string`)return t}return{error:{message:La(e,t),type:Ta(e),param:null,code:String(e)}}}var za={low:1024,medium:2048,high:4096,xhigh:8192,max:16384,minimal:1024},Ba={low:`low`,minimal:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`},Va=4096,Ha=1024,Ua=`[System: Empty message content sanitised to satisfy protocol]`,Wa=new Set([`type`,`properties`,`additionalProperties`,`required`,`$defs`,`strict`]);function Ga(e,t){if(e==null)return{type:`object`,properties:{}};if(!P(e))throw new N(`Invalid input_schema for tool "${t}": expected an object, got ${typeof e}`,{status:400});let n={};for(let[t,r]of Object.entries(e))Wa.has(t)&&(n[t]=r);return n.type!==`object`&&(n.type=`object`),n.properties===void 0&&(n.properties={}),n}function Ka(e){let t=F(e),n=F(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new N(`Unsupported tool type: ${String(r)}`,{status:400});let i=L(n.name)??``,a={name:i,input_schema:Ga(n.parameters,i),type:`custom`},o=n.description;o!=null&&(a.description=o);let s=t.eager_input_streaming??n.eager_input_streaming;typeof s==`boolean`&&(a.eager_input_streaming=s);let c=t.cache_control??n.cache_control;P(c)&&(a.cache_control=c);let l=t.defer_loading??n.defer_loading;typeof l==`boolean`&&(a.defer_loading=l);let u=t.allowed_callers??n.allowed_callers;Array.isArray(u)&&(a.allowed_callers=u);let d=t.input_examples??n.input_examples;return Array.isArray(d)&&(a.input_examples=d),a}function qa(e){return e.map(e=>{let t=F(e);return t.input_schema===void 0?Ka(e):t})}var Ja={name:`dummy_tool`,input_schema:{type:`object`,properties:{}},type:`custom`,description:`This is a dummy tool call`};function Ya(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)||`tool_use_id`}function Xa(e,t){if(typeof e!=`string`||e.trim()===``)return{};try{return JSON.parse(e)}catch(e){throw new N(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function Za(e){if(!P(e))return!1;let t=e.type,n=t===`thinking`?e.signature:t===`redacted_thinking`?e.data:void 0;if(typeof n==`string`&&n.startsWith(`litellm_encrypted_reasoning:`))return!0;if(t!==`thinking`)return!1;let r=e.signature;if(typeof r!=`string`||r.length===0)return!0;let i=e.thinking;return!(typeof i==`string`&&i.trim().length>0)}function Qa(e){let t=e.cache_control;return P(t)?t:void 0}function $a(e,t){return e===``?null:t===void 0?{type:`text`,text:e}:{type:`text`,text:e,cache_control:t}}function eo(e){let t=typeof e==`string`?e:L(F(e).url)??``,n=typeof e==`string`?null:L(F(e).format);if(t.startsWith(`https://`)||t.startsWith(`http://`))return{type:`image`,source:{type:`url`,url:t}};let r=/^data:([^;,]*);base64,(.*)$/s.exec(t);if(r===null)throw new N(`Image url not in expected format. Example Expected input - "image_url": "data:image/jpeg;base64,{base64_image}". Supported formats - ['image/jpeg', 'image/png', 'image/gif', 'image/webp']. Error: unsupported image url`,{status:400});return{type:`image`,source:{type:`base64`,media_type:n??(r[1]??``).replace(/\\\//g,`/`),data:r[2]??``}}}function to(e){let t=e.content,n=``;if(typeof t==`string`)n=t;else if(Array.isArray(t)){let e=[];for(let n of t){let t=F(n);if(t.type===`text`)e.push({type:`text`,text:L(t.text)??``});else if(t.type===`image_url`){let n=eo(t.image_url),r=Qa(t);r!==void 0&&(n.cache_control=r),e.push(n)}}n=e}let r={type:`tool_result`,tool_use_id:Ya(L(e.tool_call_id)??z()),content:n},i=Qa(e);return i!==void 0&&(r.cache_control=i),r}function no(e){let t=e.role;if(t!==`user`&&t!==`assistant`)return e;let n=e.content;if(typeof n==`string`)return n.trim()===``?{...e,content:Ua}:e;if(!Array.isArray(n))return e;let r=!1,i=n.map(e=>{let t=F(e);if(t.type!==`text`)return e;let n=t.text;return typeof n==`string`&&n.trim()!==``?e:(r=!0,{...t,text:Ua})});return r?{...e,content:i}:e}function ro(e){let t=[];for(let n of e){let e=n.role;if(e===`tool`||e===`function`){t.push(to(n));continue}let r=n.content;if(typeof r==`string`){let e=$a(r,void 0);e!==null&&t.push(e);continue}for(let e of I(r)){let n=F(e),r=Qa(n);if(n.type===`text`){let e=$a(L(n.text)??``,r);e!==null&&t.push(e)}else if(n.type===`image_url`){let e=eo(n.image_url);r!==void 0&&(e.cache_control=r),t.push(e)}else n.type===`document`&&t.push(r===void 0?n:{...n,cache_control:r})}}return t.length>0?{role:`user`,content:t}:null}function io(e){let t=[],n=new Set;for(let r of e){let e=r.content,i=Array.isArray(e)?e:null,a=i!==null&&i.some(e=>{let t=F(e).type;return t===`thinking`||t===`redacted_thinking`}),o=r.thinking_blocks;if(Array.isArray(o)&&!a)for(let e of o)Za(e)||t.push(F(e));if(i!==null)for(let e of i){let n=F(e),r=n.type;if(r===`thinking`){let e=n.thinking;typeof e==`string`&&e!==``&&!Za(n)&&t.push(n)}else if(r===`text`){let e=$a(L(n.text)??``,Qa(n));e!==null&&t.push(e)}else(r===`server_tool_use`||typeof r==`string`&&r.endsWith(`_tool_result`))&&t.push(n)}else if(typeof e==`string`){let n=$a(e,Qa(r));n!==null&&t.push(n)}let s=r.tool_calls;if(Array.isArray(s))for(let e of s){let r=F(e);if(r.type!==`function`)continue;let i=F(r.function),a=L(i.name)??``,o=Ya(L(r.id)??z());if(n.has(o))continue;n.add(o);let s={type:`tool_use`,id:o,name:a,input:Xa(i.arguments,a)},c=Qa(r);c!==void 0&&(s.cache_control=c),t.push(s)}}return t.length>0?{role:`assistant`,content:t}:null}function ao(e){let t=e.map(e=>no(F(e))),n=[],r=0;for(;r<t.length;){let e=t[r]?.role;if(e===`user`||e===`tool`||e===`function`){let e=[];for(;r<t.length;){let n=t[r]?.role;if(n!==`user`&&n!==`tool`&&n!==`function`)break;e.push(t[r]),r+=1}let i=ro(e);i!==null&&n.push(i);continue}if(e===`assistant`){let e=[];for(;r<t.length&&t[r]?.role===`assistant`;)e.push(t[r]),r+=1;let i=io(e);i!==null&&n.push(i);continue}r+=1}let i=n[n.length-1];if(i!==void 0&&i.role===`assistant`&&Array.isArray(i.content))for(let e of i.content)e.type===`text`&&typeof e.text==`string`&&(e.text=e.text.trimEnd());return n}function oo(e){let t=[];for(let n of e){let e=n.content;if(typeof e==`string`){let r=$a(e,Qa(n));r!==null&&t.push(r);continue}for(let n of I(e)){let e=F(n);if(e.type!==`text`)continue;let r=$a(L(e.text)??``,Qa(e));r!==null&&t.push(r)}}return t}var so=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,co=/^\+?[\d\s()-]{7,}$/;function lo(e){return!so.test(e)&&!co.test(e)}function uo(e){return typeof e!=`number`||!Number.isFinite(e)?null:Number.isInteger(e)?e:Math.max(1,Math.round(e))}function fo(e){let t=typeof e==`string`?[e]:I(e),n=[];for(let e of t)typeof e==`string`&&e.trim()!==``&&n.push(e);return n.length>0?n:null}function po(e,t){let n=null;if(e===`auto`)n={type:`auto`};else if(e===`required`)n={type:`any`};else if(e===`none`)n={type:`none`};else if(P(e)){let t=e.type;if(t===`auto`)n={type:`auto`};else if(t===`required`||t===`any`)n={type:`any`};else if(t===`none`)n={type:`none`};else{let t=F(e.function).name;typeof t==`string`&&(n={type:`tool`,name:t})}}if(t!=null){if(e===`none`)return n;let r=t!==!0;n===null?n={type:`auto`,disable_parallel_tool_use:r}:n.disable_parallel_tool_use=r}return n}function mo(e,t){let n=Pa(e)&&!Fa(e);return t>=8192&&n?`xhigh`:t>=4096?`high`:t>=2048?`medium`:`low`}function ho(e,t){if(!Pa(e)||Fa(e))return;let n=F(t.thinking);if(n.type!==`enabled`)return;let r=n.budget_tokens,i=mo(e,typeof r==`number`?r:0);t.thinking={type:`adaptive`};let a=t.output_config;t.output_config={effort:i,...P(a)?a:{}}}function go(e,t){let n=e.budget_tokens;return typeof t!=`number`||typeof n!=`number`?e:t<=Ha?null:n<t?e:{type:e.type??`enabled`,budget_tokens:t-1}}function _o(e,t){if(Pa(t))return{type:`adaptive`,display:`summarized`};let n=za[e];if(n===void 0)throw new N(`Unmapped reasoning effort: '${e}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'.`,{status:400});return{type:`enabled`,budget_tokens:n}}function vo(e,t,n,r){if(F(n).type===`adaptive`&&!Pa(r)){let n=e.max_completion_tokens??e.max_tokens,r=go({type:`enabled`,budget_tokens:za.medium??2048},n);r!==null&&(t.thinking=r);return}t.thinking=n,ho(r,t)}function yo(e,t,n){let r=typeof t==`string`?t:L(F(t).effort);if(r!==null){if(r===`none`){delete e.thinking,delete e.output_config;return}if(e.thinking=_o(r,n),Pa(n)){let t=Ba[r];if(t===void 0)throw new N(`Invalid reasoning_effort: '${r}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'`,{status:400});e.output_config={effort:t}}}}var bo=new Set([`model`,`messages`,`tools`,`tool_choice`,`parallel_tool_calls`,`max_tokens`,`max_completion_tokens`,`temperature`,`top_p`,`top_k`,`stop`,`stream`,`stream_options`,`thinking`,`reasoning_effort`,`user`,`metadata`,`extra_headers`,`cache_control`,`response_format`,`web_search_options`,`context_management`,`speed`]);function xo(e,t){let n=L(e.model)??``,r={};for(let[t,i]of Object.entries(e)){if(!bo.has(t)){r[t]=i;continue}switch(t){case`model`:r.model=i;break;case`max_tokens`:case`max_completion_tokens`:{let e=uo(i);e!==null&&(r.max_tokens=e);break}case`tools`:I(i).length>0&&(r.tools=qa(I(i)));break;case`tool_choice`:case`parallel_tool_calls`:{let t=po(e.tool_choice,e.parallel_tool_calls);t===null?delete r.tool_choice:r.tool_choice=t;break}case`stream`:i===!0&&(r.stream=!0);break;case`stream_options`:break;case`stop`:{let e=fo(i);e!==null&&(r.stop_sequences=e);break}case`temperature`:case`top_p`:(Ia(n)||t===`temperature`&&i===1)&&(r[t]=i);break;case`top_k`:Ia(n)&&(r.top_k=i);break;case`thinking`:vo(e,r,i,n);break;case`reasoning_effort`:yo(r,i,n);break;case`user`:{let e=L(i);e!==null&&lo(e)&&(r.metadata={user_id:e});break}case`metadata`:P(i)&&i.user_id!==null&&i.user_id!==void 0&&(r.metadata={user_id:i.user_id});break;case`cache_control`:P(i)&&(r.cache_control=i)}}return r.messages=t,r.tools===void 0&&So(e)&&(r.tools=[Ja]),r}function So(e){return I(e.messages).some(e=>`tool_calls`in F(e))}function Co(e){let t=F(e),n=I(t.messages),r=0;for(;r<n.length&&F(n[r]).role===`system`;)r+=1;let i=n.slice(0,r).map(e=>F(e)),a=xo(t,ao(Zi(n.slice(r).map(e=>F(e))))),o=oo(i);if(o.length>0&&(a.system=o),a.max_tokens===void 0){let e=F(a.thinking).budget_tokens;a.max_tokens=typeof e==`number`?e+Va:Va}return a}function wo(e){let t=``,n=[],r=null;for(let[i,a]of e.entries()){let e=F(a),o=L(e.type)??``;if(o===`text`)t+=L(e.text)??``;else if(o===`tool_use`||o===`server_tool_use`){let t={id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input??{})},index:i};P(e.caller)&&(t.caller=e.caller),n.push(t)}else(o===`thinking`||o===`redacted_thinking`)&&(r??=[],r.push(e))}let i=null;if(r!==null){i=``;for(let e of r){let t=e.thinking;typeof t==`string`&&(i+=t)}}return{content:t===``?null:t,role:`assistant`,...n.length>0?{tool_calls:n}:{},provider_specific_fields:{citations:null,thinking_blocks:r},...r===null?{}:{thinking_blocks:r},...i===null?{}:{reasoning_content:i}}}function To(e){let t=F(e),n=t.error;if(n!=null)throw new N(L(F(n).message)??JSON.stringify(n)??String(n),{status:ci(n)});let r=t.content;if(!Array.isArray(r))throw Error(`upstream returned a response with no 'content' array. Raw keys: ${Object.keys(t).join(`, `)}`);return{id:Oa(),created:Xr(),...t.model===void 0?{}:{model:t.model},object:`chat.completion`,choices:[{finish_reason:Aa(t.stop_reason),index:0,message:wo(I(r))}],usage:Ma(F(t.usage))}}var Eo=class{#e;#t;#n=null;#r=null;#i=!1;#a=!1;#o=!1;#s=!1;#c=null;#l=-1;#u=``;#d=``;constructor(){this.#e=Oa(),this.#t=Xr()}translateFrame(e){if(this.#o)return[];switch(L(e.type)??``){case`message_start`:return this.#f(e);case`content_block_start`:return this.#p(e);case`content_block_delta`:return this.#m(e);case`content_block_stop`:return this.#h();case`message_delta`:return this.#g(e);case`message_stop`:return this.#o=!0,[];case`error`:throw new N(L(F(e.error).message)??JSON.stringify(e),{status:500});default:return[]}}flush(){return this.#s||(this.#s=!0,this.#r===null||this.#i)?[]:(this.#i=!0,[this.#_({},{usage:Ma(this.#r,{fromStreamBuilder:!0})})])}#f(e){let t=F(e.message),n=L(t.model);n!==null&&(this.#n=n);let r=t.usage;return P(r)&&(this.#r=Na(this.#r,r)),[]}#p(e){let t=F(e.content_block),n=L(t.type)??``;if(this.#c=n,this.#u=``,this.#d=``,n===`text`){let e=L(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`tool_use`||n===`server_tool_use`){this.#l+=1;let e={id:t.id,function:{arguments:``,name:t.name},type:`function`,index:this.#l};return P(t.caller)&&(e.caller=t.caller),[this.#_({content:``,tool_calls:[e]})]}if(n===`redacted_thinking`){let e=[{type:`redacted_thinking`,data:t.data}];return[this.#_({content:``,thinking_blocks:e,provider_specific_fields:{thinking_blocks:e}})]}return[]}#m(e){let t=F(e.delta),n=L(t.type)??``;if(n===`text_delta`){let e=L(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`thinking_delta`){let e=L(t.thinking)??``;if(e===``)return[];this.#d+=e;let n=[{type:`thinking`,thinking:e}];return[this.#_({reasoning_content:e,thinking_blocks:n,provider_specific_fields:{thinking_blocks:n},content:``})]}if(n===`signature_delta`){let e=L(t.signature)??``;if(e===``)return[];let n=[{type:`thinking`,thinking:this.#d,signature:e}];return[this.#_({reasoning_content:``,thinking_blocks:n,provider_specific_fields:{thinking_blocks:n},content:``})]}if(n===`input_json_delta`){if(this.#c!==`tool_use`&&this.#c!==`server_tool_use`)return[];let e=L(t.partial_json)??``;return this.#u+=e,[this.#_({content:``,tool_calls:[{function:{arguments:e},type:`function`,index:this.#l}]})]}return[]}#h(){let e=(this.#c===`tool_use`||this.#c===`server_tool_use`)&&this.#u===``;return this.#c=null,e?[this.#_({content:``,tool_calls:[{function:{arguments:`{}`},type:`function`,index:this.#l}]})]:[]}#g(e){let t=e.usage;P(t)&&(this.#r=Na(this.#r,t));let n=Aa(F(e.delta).stop_reason??`stop`);return[this.#_({},{finishReason:n})]}#_(e,t={}){let n=this.#a?{...e}:{...e,role:`assistant`};this.#a=!0;let r={index:0,delta:n};t.finishReason!==void 0&&(r.finish_reason=t.finishReason);let i={id:this.#e,object:`chat.completion.chunk`,created:this.#t,...this.#n===null?{}:{model:this.#n},choices:[r]};return t.usage!==void 0&&(i.usage=t.usage),i}};async function*Do(e){let t=new Eo;for await(let n of e)for(let e of t.translateFrame(F(n)))yield e;for(let e of t.flush())yield e}var Oo=class{inbound=`openai`;upstream=`anthropic`;translateRequest(e){return Co(e)}translateResponse(e){return To(e)}bridgeFrames(e){return Do(e)}usageFromFrame(e){let t=e.usage;return P(t)?t:null}errorEnvelope(e,t){return Ra(e,t)}},ko=class{inbound=`openai`;upstream=`openai`;translateRequest(e){return e}translateResponse(e){return e}async*bridgeFrames(e){for await(let t of e)yield t}usageFromFrame(e){let t=e.usage;return P(t)?t:null}errorEnvelope(e,t){return Da(e,t)}};function Ao(e){let t=e;if(P(t.usage))return t.usage;let n=t.response;return P(n)&&P(n.usage)?n.usage:null}var jo=new Set([`text`,`image_url`,`input_audio`,`audio_url`,`document`,`guarded_text`,`grounding_source`,`query`,`video_url`,`file`,`thinking`,`redacted_thinking`]),Mo=new Set([`encrypted_content`,`redacted_thinking`]),No=new Set;function Po(e){return typeof e==`string`?e:I(e).flatMap(e=>{if(typeof e==`string`)return[e];let t=F(e);if(t.type===`input_file`){let e={},n=t.file_id||t.file_url;n!=null&&(e.file_id=n),t.file_data!=null&&(e.file_data=t.file_data);let r={type:`file`,file:e};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]}if(t.type===`input_image`){let e={type:`image_url`,image_url:{url:R(t.image_url),detail:t.detail??`auto`}};return`cache_control`in t&&(e.cache_control=t.cache_control),[e]}if(t.type===`encrypted_content`)return t.encrypted_content==null?[]:[{type:`text`,text:String(t.encrypted_content)}];let n=t.text;if(n==null)return[];let r={type:Fo(R(t.type)),text:n};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]})}function Fo(e){if(e.startsWith(`input_`)){let t=e.slice(6);return t===`audio`?`input_audio`:jo.has(t)?t:`text`}return e===`tool_result`||e===`output_text`?`text`:jo.has(e)?e:`text`}function Io(e){let t=e.arguments;if(!t&&e.type===`custom_tool_call`){let n=R(e.input);t=n===``?``:JSON.stringify({content:n})}return[{role:`assistant`,content:null,tool_calls:[{id:R(e.call_id??e.id),type:`function`,function:{name:R(e.name),arguments:String(t??``)},index:0}]}]}function Lo(e){let t=R(e.call_id);return t===``?[]:[{role:`tool`,content:Ro(e.output),tool_call_id:t}]}function Ro(e){if(e==null)return``;if(typeof e==`string`)return e;if(Array.isArray(e)){let t=[],n=[];for(let r of e){let e=F(r),i=e.type;if(i===`input_text`||i===`output_text`||i===`text`){let r=e.text;typeof r==`string`&&r!==``&&(n.push(r),t.push({type:`text`,text:r}))}else if(i===`input_image`||i===`image_url`){let n=e.image_url??e.url;if(P(n)){let e=n.url;typeof e==`string`&&e!==``&&t.push({type:`image_url`,image_url:{url:e}})}else typeof n==`string`&&n!==``&&t.push({type:`image_url`,image_url:{url:n}})}}if(t.some(e=>F(e).type===`image_url`))return t;if(n.length>0)return n.join(``)}try{return JSON.stringify(e)}catch{return String(e)}}function zo(e){return[`function_call_output`,`custom_tool_call_output`,`web_search_call`,`computer_call_output`,`tool_result`].includes(R(e.type))}function Bo(e){return R(e.type)===`function_call`||R(e.type)===`custom_tool_call`}function Vo(e,t){let n=[];if(typeof t==`string`&&t!==``&&n.push({role:`system`,content:t}),typeof e==`string`)return n.push({role:`user`,content:e}),n;for(let t of I(e)){let e=F(t);if(Bo(e)){let t=Io(e),r=n[n.length-1];if(r!==void 0&&r.role===`assistant`){n[n.length-1]={...r,tool_calls:[...Array.isArray(r.tool_calls)?r.tool_calls:[],...t[0]?.tool_calls]};continue}n.push(...t);continue}if(zo(e)){n.push(...Lo(e));continue}if(e.type===`reasoning`){n.push(...Yo(e));continue}let r=e.content;if(r==null)continue;let i=Uo(e),a=i,o=Po(r),s=n[n.length-1];i===`assistant`&&s?.role===`assistant`&&Array.isArray(s.tool_calls)?n[n.length-1]={...s,content:Ho(s.content,o)}:n.push({role:a,content:o})}return $o(n)}function Ho(e,t){if(e==null||e===``)return t;if(t==null||t===``)return e;if(typeof e==`string`&&typeof t==`string`)return e+t;let n=typeof e==`string`?[{type:`text`,text:e}]:I(e),r=typeof t==`string`?[{type:`text`,text:t}]:I(t);return[...n,...r]}function Uo(e){return R(e.role)===``?`user`:R(e.role)}function Wo(e){return Ko(e.content)??qo(e.summary)}function Go(e,t){let n=e.flatMap(e=>{let n=F(e);if(t.has(R(n.type)))return[];let r=n.text;return typeof r==`string`&&r.trim()!==``?[r.trim()]:[]});return n.length>0?n.join(`
|
|
17
17
|
`):null}function Ko(e){return typeof e==`string`&&e.trim()!==``?e:Array.isArray(e)?Go(e,Mo):null}function qo(e){return Array.isArray(e)?Go(e,No):null}function Jo(e){let t=e.encrypted_content;if(typeof t!=`string`||t.trim()===``)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Array.isArray(n))return null;let r=n.filter(e=>{let t=F(e);return t.type===`thinking`?!!t.signature:t.type===`redacted_thinking`&&!!t.data});return r.length>0?r:null}function Yo(e){let t=Wo(e),n=Jo(e);return t===null&&n===null?[]:[{role:`assistant`,content:null,...t===null?{}:{reasoning_content:t},...n===null?{}:{thinking_blocks:n}}]}function Xo(e){return typeof e==`string`&&e!==``}function Zo(e){return e.role===`assistant`&&e.content===null&&I(e.tool_calls).length===0&&(Xo(e.reasoning_content)||I(e.thinking_blocks).length>0)}function Qo(e,t){let n=t.map(e=>e.reasoning_content).filter(Xo),r=e.reasoning_content,i=n.length>0?[...n,...Xo(r)?[r]:[]].join(`
|
|
18
18
|
`):null,a=t.flatMap(e=>I(e.thinking_blocks));return{...e,...i===null?{}:{reasoning_content:i},...a.length>0?{thinking_blocks:[...a,...I(e.thinking_blocks)]}:{}}}function $o(e){let t=[],n=[];for(let r of e){if(Zo(r)){n.push(r);continue}if(n.length>0){if(r.role===`assistant`){t.push(Qo(r,n)),n=[];continue}t.push(...n),n=[]}t.push(r)}return t.push(...n),t}function es(e){if(e==null)return null;if(typeof e==`string`)return e;let t=F(e),n=F(t.function);if(P(t.function)&&R(n.name)!==``)return t;let r=R(t.type);if(r===`auto`)return`auto`;if(r===`none`)return`none`;if(r===`required`||r===`tool`||r===`any`)return`required`;if(r===`function`){let e=R(t.name);return e===``?`required`:{type:`function`,function:{name:e}}}if(r===`custom`){let e=F(t.custom),n=R(t.name)===``?R(e.name):R(t.name);return n===``?`required`:{type:`function`,function:{name:n}}}return e}function ts(e){let t=[],n=null,r=I(e);for(let e=0;e<r.length;e++){let i=F(r[e]),a=R(i.type);if(a===`mcp`)t.push(i);else if(a===`web_search_preview`||a===`web_search`)n={...i.search_context_size==null?{}:{search_context_size:i.search_context_size},...i.user_location==null?{}:{user_location:i.user_location}};else if(a===`function`){let n=i.parameters,r=sa(n);if(r===null&&n!=null)throw new N(`Invalid type for tools[${String(e)}].parameters: expected an object, but got ${typeof n} instead.`,{status:400});let a=r??{type:`object`};t.push({type:`function`,function:{name:R(i.name),description:R(i.description),parameters:oa(Object.keys(a).length>0&&`type`in a?a:{...a,type:`object`}),strict:i.strict===!0},...Object.fromEntries([`cache_control`,`defer_loading`,`allowed_callers`,`input_examples`].filter(e=>e in i).map(e=>[e,i[e]])),...i.eager_input_streaming!==null&&i.eager_input_streaming!==void 0?{eager_input_streaming:i.eager_input_streaming}:{}})}}return{tools:t,webSearchOptions:n}}function ns(e){let t=F(F(e).format);return R(t.type)===`json_schema`?{type:`json_schema`,json_schema:{name:t.name??`response_schema`,schema:t.schema??{},strict:t.strict??!1}}:R(t.type)===`json_object`?{type:`json_object`}:null}function rs(e){let t=e,{tools:n,webSearchOptions:r}=ts(t.tools??[]),i=ns(t.text),a=F(t.reasoning).effort,o=typeof a==`string`?a:null,s={messages:Vo(t.input,t.instructions),model:t.model??null,tool_choice:es(t.tool_choice),tools:n,top_p:t.top_p??null,user:t.user??null,temperature:t.temperature??null,parallel_tool_calls:t.parallel_tool_calls??null,max_tokens:t.max_output_tokens??null,stream:t.stream===!0,safety_identifier:t.safety_identifier??null,web_search_options:r,response_format:i,reasoning_effort:o},c=Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null));return I(c.tools).length===0?Object.fromEntries(Object.entries(c).filter(([e])=>e!==`tool_choice`&&e!==`tools`&&e!==`parallel_tool_calls`)):c}var is={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,COMPLETE:`stop`,ERROR_TOXIC:`content_filter`,ERROR:`stop`,eos_token:`stop`,eos:`stop`,STOP:`stop`,MAX_TOKENS:`length`,SAFETY:`content_filter`,RECITATION:`content_filter`,FINISH_REASON_UNSPECIFIED:`stop`,MALFORMED_FUNCTION_CALL:`stop`,LANGUAGE:`content_filter`,OTHER:`content_filter`,BLOCKLIST:`content_filter`,PROHIBITED_CONTENT:`content_filter`,SPII:`content_filter`,IMAGE_SAFETY:`content_filter`,IMAGE_PROHIBITED_CONTENT:`content_filter`,TOO_MANY_TOOL_CALLS:`stop`,MALFORMED_RESPONSE:`stop`,NO_IMAGE:`content_filter`,IMAGE_RECITATION:`content_filter`,IMAGE_OTHER:`content_filter`,ESCALATION:`content_filter`,UNEXPECTED_TOOL_CALL:`stop`,MISSING_THOUGHT_SIGNATURE:`stop`,network_error:`stop`,sensitive:`content_filter`,guardrail_intervened:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`,content_filtered:`content_filter`,error:`stop`};function as(e,t=()=>{}){let n=is[e];return n===void 0?(t(e),`stop`):n}function os(e){let t=F(e.message),n=Array.isArray(t.tool_calls)?t.tool_calls.map(e=>ki(F(e))):null;n!==null&&(n=ji(n));let{reasoningContent:r,content:i}=Ei(t),a={content:i,role:t.role==null?`assistant`:String(t.role),tool_calls:n};r!==null&&(a.reasoning_content=r);let o=L(e.finish_reason);if(o===null){let t=e.finish_details;o=typeof t==`string`&&t!==``?t:`stop`}return o===`stop`&&n!==null&&n.length>0&&(o=`tool_calls`),{finish_reason:as(o),message:a}}function ss(e){let t=F(e),n=e=>typeof e==`number`&&Number.isFinite(e)?e:null,r=n(t.completion_tokens)??0,i=n(t.prompt_tokens)??0,a=n(t.total_tokens)??0,o=P(t.completion_tokens_details)?{...t.completion_tokens_details}:null,s=n(t.reasoning_tokens);if(s!==null&&(o===null&&(o={}),n(o.reasoning_tokens)===null&&(o.reasoning_tokens=s),n(o.text_tokens)===null&&n(t.completion_tokens)!==null)){let e=r-s;o.image_tokens&&(e-=Number(o.image_tokens)),o.audio_tokens&&(e-=Number(o.audio_tokens)),o.text_tokens=Math.max(0,e)}let c=P(t.prompt_tokens_details)?{...t.prompt_tokens_details}:null,l=t.prompt_cache_hit_tokens,u=t.cache_read_input_tokens,d=typeof l==`number`?l:typeof u==`number`?u:null;if(d!==null&&(c===null&&(c={}),c.cached_tokens=d),c!==null)for(let e of[`audio_tokens`,`text_tokens`,`image_tokens`,`video_tokens`])c[e]===void 0&&(c[e]=null);if(o!==null)for(let e of[`text_tokens`,`image_tokens`,`video_tokens`,`accepted_prediction_tokens`,`rejected_prediction_tokens`])o[e]===void 0&&(o[e]=null);let f={completion_tokens:r,prompt_tokens:i,total_tokens:a,completion_tokens_details:o,prompt_tokens_details:c},p=new Set([`prompt_tokens`,`completion_tokens`,`total_tokens`,`reasoning_tokens`,`prompt_tokens_details`,`completion_tokens_details`,`server_tool_use`,`cost`]);for(let[e,n]of Object.entries(t))p.has(e)||(f[e]=n);let m=t.server_tool_use;m!=null&&(f.server_tool_use=m);let h=t.cost;return h!=null&&(f.cost=h),f}function cs(e){let t=e.error;if(t!=null){let e=F(t);throw new N(typeof e.message==`string`?e.message:JSON.stringify(t),{status:ci(t)})}let n=e.choices;if(!Array.isArray(n)||n.length===0)throw Error(`LiteLLM: provider returned a response with no 'choices'. Raw keys: ${Object.keys(e).join(`, `)}`);let r={choices:n.map(e=>os(F(e)))};return e.usage!=null&&(r.usage=ss(e.usage)),r}function ls(e){return e===`length`||e===`max_tokens`||e===`content_filter`?`incomplete`:`completed`}function us(e){return e===`content_filter`?`content_filter`:`max_output_tokens`}function ds(e){return typeof e==`string`?e:I(e).map(e=>typeof e==`string`?e:L(F(e).text)??``).join(``)}function fs(e){if(!P(e))return null;let t=Jr(e.prompt_tokens)??0,n=Jr(e.completion_tokens)??0,r=Jr(e.total_tokens)??t+n,i=F(e.prompt_tokens_details),a={},o=Jr(i.cached_tokens);o!==null&&(a.cached_tokens=o);let s=Jr(i.text_tokens);s!==null&&(a.text_tokens=s);let c=F(e.completion_tokens_details),l={},u=Jr(c.reasoning_tokens);return u!==null&&u>0&&(l.reasoning_tokens=u),{input_tokens:t,...Object.keys(a).length>0?{input_tokens_details:a}:{},output_tokens:n,...Object.keys(l).length>0?{output_tokens_details:l}:{},total_tokens:r}}function ps(e,t){let n=F(e.function);return{type:`function_call`,id:t,call_id:L(e.id)??`call_${z()}`,name:L(n.name)??``,arguments:L(n.arguments)??``,status:`completed`,namespace:null}}function ms(e,t,n,r,i){let a=t===`in_progress`,o=e.requestEcho??{};return{id:e.id,created_at:e.created,error:null,incomplete_details:t===`incomplete`?{reason:us(i)}:null,instructions:a?o.instructions??null:null,metadata:a?null:{},...e.model===void 0?{}:{model:e.model},object:`response`,output:n,parallel_tool_calls:a,temperature:a?o.temperature??null:0,tool_choice:`auto`,tools:a&&Array.isArray(o.tools)?o.tools:[],top_p:a?o.top_p??1:null,max_output_tokens:null,previous_response_id:null,reasoning:a?{effort:null,summary:null}:null,status:t,text:a?o.text??null:{},truncation:a?o.truncation??null:null,usage:r,user:a?o.user??null:null,store:a?!0:null}}function hs(e,t){let n=F(I(e.choices)[0]),r=F(n.message),i=L(n.finish_reason),a=ds(r.content),o=I(r.tool_calls),s=L(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${z()}`,status:ls(i),role:`assistant`,content:[{type:`output_text`,text:s,annotations:[]}],phase:null}),r.content!==null&&r.content!==void 0&&c.push({type:`message`,id:`msg_${z()}`,status:ls(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(ps(F(e),`fc_${z()}`));return ms(t,ls(i),c,fs(e.usage),i)}function gs(e){let t=F(e),n=L(t.model);return hs(cs(t),{id:`resp_${z()}`,created:Xr(),...n===null?{}:{model:n}})}function _s(e){let t=e.error;if(t)throw new N(typeof t!=`object`||!t||Array.isArray(t)?String(t):typeof F(t).message==`string`?F(t).message:JSON.stringify(t),{status:ci(t)});let n={choices:(Array.isArray(e.choices)?e.choices:[]).map(e=>{let t=F(e),n=t.finish_reason,r=F(t.delta);return{finish_reason:n?as(String(n)):null,index:typeof t.index==`number`?t.index:0,delta:{content:r.content==null?null:String(r.content),role:r.role==null?null:String(r.role),...r.reasoning_content==null?{}:{reasoning_content:String(r.reasoning_content)},tool_calls:Array.isArray(r.tool_calls)?r.tool_calls.map((e,t)=>{let n={...F(e)};return n.index===void 0&&(n.index=t),n.type===void 0&&(n.type=`function`),n}):null}}})};return typeof e.model==`string`&&(n.model=e.model),`usage`in e&&e.usage!=null&&(n.usage=e.usage),n}var vs=10;function ys(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function bs(e){if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var xs=class{#e=0;#t=!1;#n=!1;#r=`msg_${z()}`;#i=0;#a=``;#o=1;#s=new Map;#c=null;#l=null;#u=null;#d=``;#f;#p=null;constructor(e){this.#f=e}#m(){return this.#p===null?this.#f:{...this.#f,model:this.#p}}translateFrame(e){if(this.#n)return[];let t=L(e.model);t!==null&&(this.#p=t);let n=[];if(!this.#t){this.#t=!0;let e=ms(this.#m(),`in_progress`,[],null,null);n.push(this.#S({type:`response.created`,response:e})),n.push(this.#S({type:`response.in_progress`,response:e})),n.push(...this.#h())}P(e.usage)&&(this.#l=e.usage);let r=F(I(e.choices)[0]),i=F(r.delta),a=i.reasoning_content,o=typeof a==`string`&&a!==``?a:null;if(o!==null){n.push(...this.#g(o));let e=i.content;typeof e==`string`&&e!==``&&(this.#a+=e);let t=L(r.finish_reason);return t!==null&&t!==``&&(this.#c=t),n}let s=i.content;typeof s==`string`&&s!==``&&(this.#a+=s,n.push(this.#S({type:`response.output_text.delta`,item_id:this.#r,output_index:this.#i,content_index:0,delta:s})));for(let e of I(i.tool_calls))n.push(...this.#_(F(e)));let c=L(r.finish_reason);return c!==null&&c!==``&&(this.#c=c),n}flush(){if(!this.#t||this.#n)return[];this.#n=!0;let e=[];for(let t of this.#b())e.push(...this.#y(t));e.push(...this.#v());let t=ls(this.#c);return e.push(this.#S({type:`response.completed`,response:ms(this.#m(),t,this.#x(),fs(this.#l),this.#c)})),e}#h(){return[this.#S({type:`response.output_item.added`,output_index:this.#i,item:{type:`message`,id:this.#r,status:`in_progress`,role:`assistant`,content:[]}}),this.#S({type:`response.content_part.added`,item_id:this.#r,output_index:this.#i,content_index:0,part:{type:`output_text`,text:``,annotations:[]}})]}#g(e){return this.#u===null&&(this.#u=`rs_${z()}`),this.#d+=e,[this.#S({type:`response.reasoning_summary_text.delta`,item_id:this.#u,output_index:0,delta:e})]}#_(e){let t=Jr(e.index)??0,n=F(e.function),r=this.#s.get(t),i=[];if(r===void 0){let a=L(e.id)??`call_${z()}`;r={itemId:`fc_${a}`,outputIndex:this.#o,callId:a,name:L(n.name)??``,args:``},this.#o+=1,this.#s.set(t,r),i.push(this.#S({type:`response.output_item.added`,output_index:r.outputIndex,item:{type:`function_call`,id:r.itemId,call_id:r.callId,name:r.name,arguments:``,status:`in_progress`}}))}let a=L(n.name);a!==null&&a!==``&&r.name===``&&(r.name=a);let o=bs(n.arguments);if(o!==``){r.args+=o;for(let e=0;e<o.length;e+=vs)i.push(this.#S({type:`response.function_call_arguments.delta`,item_id:r.itemId,output_index:r.outputIndex,delta:o.slice(e,e+vs)}))}return i}#v(){let e=this.#r,t=this.#i,n={type:`output_text`,text:this.#a,annotations:[]};return[this.#S({type:`response.output_text.done`,item_id:e,output_index:t,content_index:0,text:this.#a}),this.#S({type:`response.content_part.done`,item_id:e,output_index:t,content_index:0,part:n}),this.#S({type:`response.output_item.done`,output_index:t,item:{type:`message`,id:e,status:`completed`,role:`assistant`,content:[n]}})]}#y(e){return[this.#S({type:`response.function_call_arguments.done`,item_id:e.itemId,output_index:e.outputIndex,arguments:e.args}),this.#S({type:`response.output_item.done`,output_index:e.outputIndex,item:{type:`function_call`,id:e.itemId,call_id:e.callId,name:e.name,arguments:e.args,status:`completed`}})]}#b(){return[...this.#s.values()].sort((e,t)=>e.outputIndex-t.outputIndex)}#x(){let e=[];this.#u!==null&&e.push({type:`reasoning`,id:this.#u,status:ls(this.#c),role:`assistant`,content:[{type:`output_text`,text:this.#d,annotations:[]}]}),this.#a!==``&&e.push({type:`message`,id:this.#r,status:`completed`,role:`assistant`,content:[{type:`output_text`,text:this.#a,annotations:[]}]});for(let t of this.#b())e.push({type:`function_call`,id:t.itemId,call_id:t.callId,name:t.name,arguments:t.args,status:`completed`});return e}#S(e){this.#e+=1;let t={...e,sequence_number:this.#e};return e.response!==void 0&&(t.response=ys(e.response)),t}},Ss=class{inbound=`openai-responses`;upstream=`openai`;translateRequest(e){return rs(e)}translateResponse(e){return gs(e)}async*bridgeFrames(e,t,n){let r=new xs({id:`resp_${z()}`,created:Xr(),...P(n)?{requestEcho:n}:{}});for await(let t of e)for(let e of r.translateFrame(_s(t)))yield e;for(let e of r.flush())yield e}usageFromFrame(e){return Ao(e)}errorEnvelope(e,t){return Da(e,t)}};function Cs(e){return Array.isArray(e)?e.map(e=>{if(!P(e)||e.type!==`reasoning`||`summary`in e)return e;let t=e.content,n=typeof t==`string`?t:``;return{...e,summary:n.length>100?n.slice(0,100):n}}):e}function ws(e){let t=e;return{...t,input:Cs(t.input)}}var Ts=[`error`,`incomplete_details`,`instructions`,`metadata`,`model`,`object`,`parallel_tool_calls`,`temperature`,`tool_choice`,`tools`,`top_p`,`max_output_tokens`,`previous_response_id`,`reasoning`,`status`,`text`,`truncation`,`usage`,`user`,`store`],Es=[`input_tokens_details`,`output_tokens_details`,`cost`],Ds={audio_tokens:null,cached_tokens:0,cached_tokens_details:null,image_tokens:null,text_tokens:null,video_tokens:null},Os={audio_tokens:null,reasoning_tokens:null,text_tokens:null};function ks(e,t){let n={...e};for(let[e,r]of Object.entries(t))e in n||(n[e]=r);return n}function As(e){let t=e.usage;if(!P(t))return;let n={...t};for(let e of Es)e in n||(n[e]=null);let r=n.input_tokens_details;P(r)&&(n.input_tokens_details=ks(r,Ds));let i=n.output_tokens_details;P(i)&&(n.output_tokens_details=ks(i,Os)),e.usage=n}function js(e){let t=e.tools;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!P(r)||r.type!==`function`)continue;let i=!(`strict`in r),a=!(`defer_loading`in r);if(!i&&!a)continue;let o={...r,...i?{strict:null}:{},...a?{defer_loading:null}:{}};(n??=[...t])[e]=o}n!==null&&(e.tools=n)}function Ms(e){let t=e.output;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!P(r))continue;let i=r.type===`function_call`&&!(`namespace`in r)?`namespace`:r.type===`message`&&!(`phase`in r)?`phase`:null;i!==null&&((n??=[...t])[e]={...r,[i]:null})}n!==null&&(e.output=n)}function Ns(e){for(let t of Ts)t in e||(e[t]=null);return js(e),Ms(e),As(e),e}function Ps(e){return Ns({...e})}function Fs(e){let t=e.error;if(P(t)&&t.code===null)return{...e,error:{...t,code:`unknown_error`}};let n=e.response;if(P(n)){let t=n.error;if(P(t)&&t.code===null)return{...e,response:{...n,error:{...t,code:`unknown_error`}}}}return null}function Is(e){if(!P(e))return e;let t=!1;for(let n of Object.values(e))if(n===null){t=!0;break}if(!t)return e;let n={};for(let[t,r]of Object.entries(e))r!==null&&(n[t]=r);return n}function Ls(e){let t=e.response;if(!P(t))return e;let n={...t},r=!1;for(let[e,i]of Object.entries(t))i===null&&(delete n[e],r=!0);let i=n.tools;if(Array.isArray(i)){let e=i.map(Is);e.some((e,t)=>e!==i[t])&&(n.tools=e,r=!0)}return r?{...e,response:n}:e}var Rs=class{inbound=`openai-responses`;upstream=`openai-responses`;translateRequest(e){return ws(e)}translateResponse(e){return Ps(e)}async*bridgeFrames(e){for await(let t of e){let e=t;yield Ls(Fs(e)??e)}}usageFromFrame(e){return Ao(e)}errorEnvelope(e,t){return Da(e,t)}},zs={anthropicToAnthropic:new Ui,anthropicToChatCompletions:new Ca,chatCompletionsToAnthropic:new Oo,chatCompletionsToChatCompletions:new ko,responsesToResponses:new Rs,responsesToChatCompletions:new Ss},Bs=class{anthropicToAnthropic(e){return this.#e(`anthropicToAnthropic`,e)}anthropicToChatCompletions(e){return this.#e(`anthropicToChatCompletions`,e)}chatCompletionsToAnthropic(e){return this.#e(`chatCompletionsToAnthropic`,e)}chatCompletionsToChatCompletions(e){return this.#e(`chatCompletionsToChatCompletions`,e)}responsesToResponses(e){return this.#e(`responsesToResponses`,e)}responsesToChatCompletions(e){return this.#e(`responsesToChatCompletions`,e)}#e(e,t){return new qr(zs[e],t??{},e)}};function Vs(){return new Bs}var Hs={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`},Us={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`},Ws=new Set([204,205,304]);function Gs(e){let t;try{t=JSON.parse(e)}catch{return null}return M(t)?t:null}function Ks(e){let t=e.type===`error`?e.error:void 0;return M(t)&&typeof t.type==`string`&&typeof t.message==`string`}function qs(e){let t=Gs(e);if(t===null)return e;if(Ks(t))return String(t.error.message);let n=t.detail;if(M(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;return typeof i==`string`&&i!==``?i:e}function Js(e,t,n){let r=t===``||Ws.has(e)?null:t;return new Response(r,{status:e,headers:{"content-type":n}})}function Ys(e,t,n){let r=e=>Hs[e]??`api_error`,i=Gs(t),a;if(i!==null&&Ks(i))a={...i},n!==void 0&&i.request_id===void 0&&(a.request_id=n);else{let i={type:`error`,error:{type:r(e),message:qs(t)}};n!==void 0&&(i.request_id=n),a=i}return Js(e,JSON.stringify(a),`application/json`)}function Xs(e,t){let n={error:{message:qs(t),type:(e=>{let t=Us[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t})(e),param:null,code:String(e)}};return Js(e,JSON.stringify(n),`application/json`)}function Zs(e,t,n,r){return e===`anthropic`?Ys(t,n,r):Xs(t,n)}function Qs(e,t,n,r){return e===`anthropic`?Ys(t,n,r):Xs(t,n)}var $s={openai:`chat/completions`,anthropic:`messages`,"openai-responses":`responses`},ec={openai:`https://api.openai.com`,anthropic:`https://api.anthropic.com`,"openai-responses":`https://api.openai.com`};function tc(e){let t=e.provider,n=(e.apiBase??ec[t]).replace(/\/+$/,``),r=$s[t];return t===`anthropic`?n.endsWith(`/v1/messages`)?n:e.autoV1!==!1&&!/\/v\d+$/i.test(n)?`${n}/v1/${r}`:`${n}/${r}`:n.includes(r)?n:e.autoV1!==!1&&!/\/v\d+$/i.test(n)?`${n}/v1/${r}`:`${n}/${r}`}var nc=6e5,rc=12e4,ic=65536,ac=4096,oc=class{#e;#t;#n;#r;#i;#a;#o=new AbortController;#s=new AbortController;#c=null;constructor(e,t){this.#e=e,this.#t=t.inbound,this.#n=t.requestId,this.#r=t.fetchFn??fetch,this.#i=t.timeouts?.firstByteMs??nc,this.#a=t.timeouts?.idleMs??rc;let n=t.signal;n!==void 0&&(n.aborted?this.#o.abort():n.addEventListener(`abort`,()=>this.#o.abort(),{once:!0}))}abort(){this.#o.abort()}async send(){let e;try{this.#u(this.#i),e=await this.#r(this.#e.url,{method:`POST`,headers:this.#e.headers,body:JSON.stringify(this.#e.body),signal:AbortSignal.any([this.#o.signal,this.#s.signal])})}catch(e){if(this.#l(),this.#s.signal.aborted&&!this.#o.signal.aborted){let e=`upstream timeout: no response headers within ${String(this.#i)}ms`;return this.#f(504,e)}return this.#f(502,or(e))}let t=e.body;if(t===null?this.#l():(this.#u(this.#a),t=this.#p(t)),!e.ok){let n=await cc(t,ic),r=n.length<=ac?n:n.slice(0,ac);return{kind:`error`,status:e.status,response:Zs(this.#t,e.status,r,this.#n)}}return{kind:`ok`,transport:{status:e.status,headers:sr(e.headers),stream:t,text:()=>t===null?e.text():new Response(t).text()}}}#l(){this.#c!==null&&(clearTimeout(this.#c),this.#c=null)}#u(e){this.#l(),this.#c=setTimeout(()=>{this.#c=null,this.#s.abort()},e),this.#c.unref()}#d(){return new N(`upstream timeout: no data for ${String(this.#a)}ms`,{status:504})}#f(e,t){return{kind:`error`,status:e,response:Qs(this.#t,e,t,this.#n)}}#p(e){let t=null;return new ReadableStream({start:async n=>{let r=e.getReader();t=r;let i=!1,a=()=>{try{n.close()}catch{}},o=e=>{try{n.error(e)}catch{}},s=e=>{i||(i=!0,this.#l(),o(e),r.cancel().catch(()=>{}))};if(this.#s.signal.aborted){s(this.#d());return}let c=()=>s(this.#d());this.#s.signal.addEventListener(`abort`,c,{once:!0});try{for(;;){let{done:e,value:t}=await r.read();if(i)return;if(e){this.#l(),a();return}this.#u(this.#a),n.enqueue(t)}}catch(e){this.#l(),i||o(e)}finally{this.#s.signal.removeEventListener(`abort`,c)}},cancel:e=>{this.#l(),t!==null&&t.cancel(e).catch(()=>{})}})}};function sc(e){e!==null&&e.cancel().catch(()=>{})}async function cc(e,t){if(e===null)return``;let n=e.getReader(),r=new TextDecoder(`utf-8`),i=``,a=0;try{for(;a<t;){let{done:e,value:t}=await n.read();if(e)break;a+=t.byteLength,i+=r.decode(t,{stream:!0})}return i+r.decode()}catch{return i}finally{n.cancel().catch(()=>{})}}var lc=new Set([`authorization`,`x-api-key`,`cookie`,`proxy-authorization`,`host`,`content-length`,`content-type`,`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`te`,`trailer`,`upgrade`,`expect`,`accept-encoding`,`x-real-ip`]),uc=`sk-ant-oat`,dc=`oauth-2025-04-20`,fc="Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params. Please set `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in your environment vars";function pc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();lc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function mc(e,t,n){let r=(e,t)=>e===void 0?t:e.split(`,`).map(e=>e.trim()).includes(t)?e:`${e}, ${t}`,i=(e,t)=>{let n={...e},i=t,a=Object.keys(n).find(e=>e.toLowerCase()===`authorization`),o=a===void 0?``:n[a]??``;if(o.startsWith(`Bearer ${uc}`)){i=o.replace(/^Bearer /,``);for(let e of Object.keys(n))(e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`)&&delete n[e];n.authorization=o,n[`anthropic-beta`]=r(n[`anthropic-beta`],dc),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(i===void 0)throw new N(fc,{status:401});let s=i.startsWith(uc),c={"anthropic-version":`2023-06-01`,accept:`application/json`,"content-type":`application/json`};return s?c.authorization=`Bearer ${i}`:c[`x-api-key`]=i,{...n,...c}},a=(e,t)=>{let n={...e};return t!==void 0&&(n={...n,Authorization:`Bearer ${t}`}),!(`content-type`in n)&&!(`Content-Type`in n)&&(n={...n,"Content-Type":`application/json`}),n},o={...pc(n),...t.headers??{}};return e===`anthropic`?i(o,t.apiKey):a(o,t.apiKey)}var hc=/<invoke\s+name=/g,gc=2;function _c(e,t){let n=mc(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function vc(e){return{clientRequest:t=>M(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function yc(e,t){let n=e=>M(e.error),r=t.name||t.modelName;switch(e){case`anthropicToChatCompletions`:return{clientResponse:e=>{let t=e;if(t.type===`message_start`){let n=t.message;return M(n)?{...t,message:{...n,model:r}}:e}return t.type===`message`?{...t,model:r}:e}};case`chatCompletionsToAnthropic`:return{clientResponse:e=>{let t=e;return n(t)?e:{...t,model:r}}};case`chatCompletionsToChatCompletions`:return{clientResponse:e=>{let t=e;return t.object===`chat.completion.chunk`?e:{...t,model:r}}};case`responsesToChatCompletions`:case`responsesToResponses`:return{clientResponse:e=>{let t=e;return n(t)?e:{...t,model:r}}}}}function bc(e){let t=(e,t)=>{let n=tr.indexOf(e),r=tr.indexOf(t);return n<0||r<0||n<=r?e:t};return{upstreamRequest:n=>{if(!M(n.body))return n;let r=n.body.reasoning_effort;if(typeof r!=`string`)return n;let i=t(r,e);return i===r?n:{...n,body:{...n.body,reasoning_effort:i}}}}}function xc(e){let t=0,n=0;return{clientResponse:r=>{let i=r;if(i.type!==`content_block_delta`)return r;let a=i.delta;if(!M(a)||a.type!==`thinking_delta`)return r;let o=a.thinking;if(typeof o!=`string`||o===``)return r;t+=o.length,hc.lastIndex=0;for(let e=hc.exec(o);e!==null;e=hc.exec(o))n+=1;if(t>e&&n>=gc)throw new N(`Upstream reasoning degraded: ${String(t)} reasoning chars containing ${String(n)} hand-written tool invocations and no tool_use block; stream aborted to avoid a long stall.`);return r}}}var Sc=()=>{let e=(e,t)=>{switch(e){case`tool_calls`:return Array.isArray(t)&&t.length===0;case`function_call`:return t===null;case`refusal`:return t===``;case`extra_fields`:return t===null;default:return!1}};return{upstreamResponse:t=>{if(!M(t))return t;let n=t.choices;if(!Array.isArray(n)||n.length===0)return t;let r=!1,i=n.map(t=>{if(!M(t))return t;let n=t.delta;if(!M(n))return t;let i=!1,a={};for(let[t,r]of Object.entries(n)){if(e(t,r)){i=!0;continue}a[t]=r}return i?(r=!0,{...t,delta:a}):t});return r?{...t,choices:i}:t}}};function Cc(e,t){let n=()=>({upstreamRequest:e=>{if(!e.stream||!M(e.body))return e;let t=e.body.stream_options;if(M(t)&&t.include_usage===!0)return e;let n={...M(t)?t:{},include_usage:!0};return{...e,body:{...e.body,stream_options:n}}}}),r=()=>({upstreamRequest:e=>{if(!M(e.body))return e;let t=e.body.tools;if(!Array.isArray(t)||t.length===0)return e;let n=!1,r=t.map(e=>{if(!M(e)||e.type!==`custom`)return e;let{type:t,...r}=e;return n=!0,r});return n?{...e,body:{...e.body,tools:r}}:e}}),i=[];(e===`anthropicToChatCompletions`||e===`chatCompletionsToChatCompletions`||e===`responsesToChatCompletions`)&&i.push(n()),e===`chatCompletionsToChatCompletions`&&i.push(Sc()),e===`chatCompletionsToAnthropic`&&i.push(r()),e===`anthropicToChatCompletions`&&t.maxReasoningEffort!==void 0&&i.push(bc(t.maxReasoningEffort));let a=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&a>0&&i.push(xc(a)),i}function wc(e){if(!M(e))return null;let t=ar(e.prompt_tokens),n=ar(e.completion_tokens);if(t===null&&n===null)return null;let r=M(e.prompt_tokens_details)?e.prompt_tokens_details:{};return{inputTokens:t??0,outputTokens:n??0,cacheReadInputTokens:ar(r.cached_tokens)??0,cacheCreationInputTokens:ar(r.cache_creation_tokens)??ar(e.cache_creation_input_tokens)??0}}function Tc(e){if(!M(e))return null;let t=ar(e.input_tokens),n=ar(e.output_tokens);if(t===null&&n===null)return null;let r=M(e.input_tokens_details)?e.input_tokens_details:{};return{inputTokens:t??0,outputTokens:n??0,cacheReadInputTokens:ar(r.cached_tokens)??0,cacheCreationInputTokens:0}}function Ec(e){return M(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?wc(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?Tc(e):(e=>{let t=ar(e.input_tokens),n=ar(e.output_tokens);if(t===null&&n===null)return null;let r=ar(e.cache_read_input_tokens),i=ar(e.cache_creation_input_tokens);return{inputTokens:(t??0)+(r??0)+(i??0),outputTokens:n??0,cacheReadInputTokens:r??0,cacheCreationInputTokens:i??0}})(e):null}var Dc=Vs();async function Oc(e,t,n,r,i){let a=(e,t,n)=>{let r=e=>{let t=null;try{t=new URL(tc(e)).hostname}catch{t=null}return t===null||t===``?`drop`:t!==`openai.com`&&!t.endsWith(`.openai.com`)?`preserve`:`drop`},i=t.rawPassthrough===!0,a=Dc[e]({...i?{translate:!1}:{},...e===`anthropicToChatCompletions`?{topK:r(t)}:{}});if(a.intercept(_c(t,n)),a.intercept(vc(t)),!i){e!==`anthropicToAnthropic`&&a.intercept(yc(e,t));for(let n of Cc(e,t))a.intercept(n)}return a},o=e=>(e.headers[`content-type`]??``).includes(`text/event-stream`),s;try{s=a(t,n,i.inboundHeaders)}catch(t){let n=mr(t)??500;return{kind:`error`,status:n,response:Qs(e,n,or(t),i.requestId)}}let c=s.begin(),l=await c.request({body:r});if(l.kind===`error`)return{kind:`error`,status:l.status,response:Qs(e,l.status,l.message,i.requestId)};let u=await new oc({url:tc(n),...l.value},{inbound:e,requestId:i.requestId,signal:i.signal,timeouts:i.timeouts,fetchFn:i.fetchFn}).send();if(u.kind===`error`)return u;let d=u.transport;if(!o(u.transport))try{let e=await u.transport.text();d={...u.transport,stream:null,text:()=>Promise.resolve(e)}}catch(t){let n=mr(t)??502;return{kind:`error`,status:n,response:Qs(e,n,or(t),i.requestId)}}let f;try{f=await c.response({status:d.status,headers:d.headers,body:d.stream,text:d.text})}catch(t){return sc(d.stream),{kind:`error`,status:500,response:Qs(e,500,or(t),i.requestId)}}if(f.kind===`error`)return sc(d.stream),{kind:`error`,status:f.status,response:Qs(e,f.status,f.message,i.requestId)};let p=f.value;return`stream`in p?{kind:`ok`,sse:!0,stream:p.stream,collectUsage:()=>Ec(p.collectUsage())}:{kind:`ok`,sse:!1,body:p.body,usage:Ec(M(p.body)?p.body.usage:void 0)}}function kc(e,t,n){return n?e===`anthropic`?t===`anthropic`?`anthropicToAnthropic`:null:e===`openai-responses`?t===`openai-responses`?`responsesToResponses`:null:t===`openai`?`chatCompletionsToChatCompletions`:null:e===`anthropic`?t===`anthropic`?`anthropicToAnthropic`:t===`openai`?`anthropicToChatCompletions`:null:e===`openai-responses`?t===`openai`?`responsesToChatCompletions`:t===`openai-responses`?`responsesToResponses`:null:t===`openai`?`chatCompletionsToChatCompletions`:t===`anthropic`?`chatCompletionsToAnthropic`:null}function Ac(e,t){return kc(e,t.provider,t.rawPassthrough===!0)!==null}async function jc(e,t,n){return Nc(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function Mc(e,t,n){return Nc(e,t,n,`openai-responses`)}async function Nc(e,t,n,r){let i=(e,t,n)=>{let r=mr(e)??500;return{kind:`error`,status:r,response:Qs(t,r,or(e),n)}};try{return await Pc(e,t,n,r)}catch(e){return i(e,r,n.requestId)}}async function Pc(e,t,n,r){let i=e=>e===`anthropic`?`Anthropic Messages`:e===`openai-responses`?`OpenAI Responses`:`OpenAI Chat Completions`,a=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),o=e.rawPassthrough===!0,s=kc(r,e.provider,o);if(s===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:Qs(r,400,o?`Model '${t}' has rawPassthrough enabled (upstream '${e.provider}'): ${i(r)} inbound requests cannot be forwarded as-is. Use a matching protocol or turn rawPassthrough off.`:`Model '${t}' (upstream '${e.provider}') does not accept ${i(r)} inbound requests`,n.requestId)}}let c=await Oc(r,s,e,r===`anthropic`?a(t,`inbound_format`):t,{signal:n.signal,requestId:n.requestId,inboundHeaders:n.inboundHeaders,timeouts:n.timeouts,fetchFn:n.deps.fetchFn});return c.kind===`error`?{kind:`error`,status:c.status,response:c.response}:c.sse?{kind:`ok`,status:200,sse:!0,body:c.stream,stream:c.stream,usage:null,collectUsage:c.collectUsage}:{kind:`ok`,status:200,sse:!1,body:c.body,usage:c.usage}}var Fc=[`x-litellm-trace-id`,`x-litellm-session-id`],Ic=new Set(Fc),Lc=/^x-.+-session-id$/,Rc=/^x-.+-conversation-id$/,zc=[`thread-id`,`conversation_id`],Bc=/^codex[-_ /]/i,Vc=/^[a-zA-Z0-9_-]{8,}$/,Hc=/^[a-zA-Z0-9_-]+$/,Uc=`_session_`;function Wc(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of Fc){let n=t.get(e);if(n!==void 0&&Vc.test(n))return n}let n=Ic;for(let[e,r]of t)if(!n.has(e)&&(Lc.test(e)||Rc.test(e))&&Vc.test(r))return r;for(let e of[`x-session-id`,`x-conversation-id`]){let n=t.get(e);if(n!==void 0&&Vc.test(n))return n}for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&Vc.test(n))return n}let r=t.get(`user-agent`);if(r!==void 0&&Bc.test(r))for(let e of zc){let n=t.get(e);if(n!==void 0&&Vc.test(n))return n}return``}function Gc(e){let t=e=>{let t=(e,t)=>{if(!M(e))return null;let n=e[t];return typeof n==`string`&&Hc.test(n)?n:null};if(M(e))return t(e,`session_id`);if(typeof e!=`string`)return null;if(e.startsWith(`{`))try{let n=t(JSON.parse(e),`session_id`);if(n!==null)return n}catch{}let n=e.lastIndexOf(Uc);return n===-1?null:t({session_id:e.slice(n+9)},`session_id`)};if(!M(e))return null;let n=e.metadata;return M(n)?t(n.user_id):null}var Kc=10485760;function qc(e){try{return JSON.parse(e)}catch{return e}}function Jc(e){for(let t of e.split(`
|
|
19
19
|
`)){let e=t.trim();if(!e.startsWith(`data: `))continue;let n;try{n=JSON.parse(e.slice(6))}catch{continue}let r=n.error;if(typeof r==`object`&&r&&typeof r.message==`string`)return{message:r.message,status:typeof r.status==`number`?r.status:200};if(typeof n.message==`string`&&typeof n.code==`string`&&!(`choices`in n)&&!(`type`in n))return{message:n.message,status:typeof n.status==`number`?n.status:200}}return null}var Yc=class{#e=0;#t;#n=!1;constructor(e){this.#t=e}get truncated(){return this.#n}append(e,t){return this.#n?e:this.#e+t.length>this.#t?(this.#n=!0,e):(this.#e+=t.length,(e??``)+t)}},Xc=class{text=null;#e;constructor(e){this.#e=e}add(e){this.text=this.#e.append(this.text,e)}},Zc=class{bodyText=null;streamText=null;#e;constructor(e){this.#e=e}addBody(e){this.bodyText=this.#e.append(this.bodyText,e)}addStream(e){this.streamText=this.#e.append(this.streamText,e)}},Qc=class{requestId;capture;startedAt=Date.now();http={method:``,url:``,path:``,clientIp:``,sessionId:``,userAgent:``};inboundHeaders=null;inboundBody=void 0;upstreamUrl=null;upstreamRequestHeaders=null;upstreamStatus=null;upstreamResponseHeaders=null;upstreamLatencyMs=null;upstreamFirstTokenMs=null;upstreamTotalMs=null;upstreamHeadAt=0;upstreamStreaming=!1;clientStatus=null;clientResponseHeaders=null;clientBody=void 0;clientError=null;#e;#t;#n;#r;#i;pending=[];constructor(e){this.requestId=e.requestId,this.capture=e.capture,this.#e=new Yc(e.maxBytes??Kc),this.#t=new Xc(this.#e),this.#n=new Xc(this.#e),this.#r=new Xc(this.#e),this.#i=new Zc(this.#e)}get inboundBodyText(){return this.#t.text}get upstreamRequestBody(){return this.#n.text}get upstreamResponseText(){return this.#r.text}get clientBodyText(){return this.#i.bodyText}get clientStreamText(){return this.#i.streamText}get truncated(){return this.#e.truncated}setHttpMeta(e){this.http=e}setSessionIdFallback(e){this.http.sessionId===``&&e!==null&&(this.http={...this.http,sessionId:e})}setInbound(e,t){this.capture&&(this.inboundHeaders=e,this.#t.add(t));try{return this.inboundBody=JSON.parse(t),this.setSessionIdFallback(Gc(this.inboundBody)),{body:this.inboundBody,parseError:null}}catch(e){return this.inboundBody={},{body:this.inboundBody,parseError:`invalid JSON body: ${e.message}`}}}setInboundHeaders(e){this.capture&&(this.inboundHeaders=e)}setUpstreamRequest(e,t,n){this.capture&&(this.upstreamUrl=e,this.upstreamRequestHeaders=t,n!==null&&this.#n.add(n))}setUpstreamResponseHead(e,t){this.upstreamHeadAt=Date.now(),this.upstreamStatus=e,this.upstreamResponseHeaders=t,this.upstreamLatencyMs=this.upstreamHeadAt-this.startedAt,this.upstreamStreaming=e>=200&&e<300&&(t[`content-type`]??``).includes(`text/event-stream`)}markUpstreamDrained(){this.upstreamTotalMs===null&&(this.upstreamTotalMs=Date.now()-this.upstreamHeadAt)}tapUpstreamStream(){let e=this,t=new TextDecoder;return new TransformStream({transform(n,r){r.enqueue(n),e.upstreamFirstTokenMs===null&&e.upstreamStreaming&&n.byteLength>0&&(e.upstreamFirstTokenMs=Date.now()-e.startedAt),e.capture&&e.#r.add(t.decode(n,{stream:!0}))},flush(){e.upstreamTotalMs=Date.now()-e.upstreamHeadAt}})}captureClientBody(e){let t=this;this.pending.push((async()=>{let n=await $c(e);t.#i.addBody(n),t.clientBody=qc(t.#i.bodyText??``)})().catch(()=>{}))}tapClientStream(){let e=this,t=new TextDecoder;return new TransformStream({transform(n,r){if(r.enqueue(n),!e.capture)return;let i=t.decode(n,{stream:!0});e.#i.addStream(i),e.clientError===null&&(i.includes(`"error"`)||i.includes(`"code"`))&&(e.clientError=Jc(i))}})}setClientResponse(e,t){this.clientStatus=e,this.clientResponseHeaders=t}async settle(){this.pending.length>0&&await Promise.all(this.pending)}upstreamFetch(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.href:t.url,i=n?.headers===void 0?{}:sr(new Headers(n.headers)),a=n?.body,o=typeof a==`string`?a:a==null?null:String(a);this.setUpstreamRequest(r,i,o);let s=await e(t,n);if(this.setUpstreamResponseHead(s.status,sr(s.headers)),s.body===null)return this.markUpstreamDrained(),s;let c=s.body.pipeThrough(this.tapUpstreamStream());return new Response(c,{status:s.status,statusText:s.statusText,headers:s.headers})}}toContentCapture(e){if(!this.capture)return null;let t=e=>e===null?null:e.split(`
|
|
20
20
|
|
|
21
|
-
`).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:qc(this.upstreamRequestBody??``)},upstreamResponseText:e?null:this.upstreamResponseText,upstreamStreamFrames:e?t(this.upstreamResponseText):null,clientResponse:e?void 0:this.clientBody,clientStreamFrames:e?t(this.clientStreamText):null,truncated:this.truncated}}toTrace(e){let t=e.hookCtx?.model!==null&&e.hookCtx?.model!==void 0?{name:e.hookCtx.model.name,provider:e.hookCtx.model.provider,upstreamModel:e.hookCtx.model.upstreamModel,apiBase:e.hookCtx.model.apiBase}:null;return{requestId:this.requestId,time:new Date().toISOString(),durationMs:Date.now()-this.startedAt,status:e.status,streaming:e.streaming,http:this.http,route:t,inbound:{headers:this.inboundHeaders,bodyText:this.inboundBodyText,body:this.truncated?null:this.inboundBody},upstream:{url:this.upstreamUrl,requestHeaders:this.upstreamRequestHeaders,requestBody:this.upstreamRequestBody,status:this.upstreamStatus,responseHeaders:this.upstreamResponseHeaders,responseText:this.upstreamResponseText,latencyMs:this.upstreamLatencyMs,firstTokenMs:this.upstreamFirstTokenMs,totalMs:this.upstreamTotalMs},client:{status:this.clientStatus,headers:this.clientResponseHeaders,body:this.clientBody,streamText:this.clientStreamText},usage:e.usage,stopReason:null,error:e.error,truncated:this.truncated}}};async function $c(e){let t=new TextDecoder,n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0})}return n+=t.decode(),n}var el=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function tl(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var nl=class{registry=new Map;addHook(e,t){let n=this.registry.get(e)??[];return n.push(t),this.registry.set(e,n),this}addAll(e){if(e===void 0)return this;for(let t of Object.keys(e)){let n=e[t];n!==void 0&&this.addHook(t,n)}return this}has(e){return(this.registry.get(e)?.length??0)>0}async run(e,t){let n=this.registry.get(e);if(n===void 0)return;let r=!el.includes(e),i;for(let a of n)try{i=await a(t)}catch(t){if(!r)throw t;O(`[gateway] hook ${e} threw, ignored:`,t)}return i}},rl=67108864,il=class{#e=!1;#t;#n;#r;#i;constructor(e,t,n){this.#t=e,this.#n=e.session,this.#r=t,this.#i=n}async finish(e){if(this.#e)return;this.#e=!0,await this.#n.settle();let t=this.#t.hookCtx??tl({requestId:this.#n.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:this.#n.startedAt,userAgent:this.#n.http.userAgent}),n=e.error??(this.#n.clientError===null?null:{stage:`stream`,message:this.#n.clientError.message,status:this.#n.clientError.status}),r={ctx:t,finishedAt:Date.now(),durationMs:Date.now()-this.#n.startedAt,streaming:e.streaming,status:e.status,stopReason:null,usage:e.usage,error:n===null?null:{message:n.message,status:n.status},capture:this.#n.toContentCapture(e.streaming)};if(n!==null&&await this.#r.run(`onError`,{error:n,ctx:t}),await this.#r.run(`onFinish`,r),this.#i.traceSink!==void 0)try{await this.#i.traceSink.write(this.#n.toTrace({status:e.status,streaming:e.streaming,error:n,usage:e.usage,hookCtx:t}))}catch(e){O(`[observability] trace sink failed:`,e)}}finishStream(e,t=null){this.#e||this.finish({status:e,streaming:!0,error:t,usage:this.#t.collectUsage===null?this.#t.traceUsage:this.#t.collectUsage()})}};function al(e,t){return async(n,r)=>{let i=e=>{let t=e.get(`content-length`);if(t===null)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null},a=async(e,t)=>{let n=e.body;if(n===null)return{kind:`ok`,text:``};let r=n.getReader(),i=new TextDecoder,a=``,o=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(o+=n.byteLength,o>t)return r.cancel().catch(()=>{}),{kind:`tooLarge`,totalBytes:o};a+=i.decode(n,{stream:!0})}return{kind:`ok`,text:a+i.decode()}},o=e=>{let t=e.get(`x-forwarded-for`)?.split(`,`)[0]?.trim();return t!==void 0&&t!==``?t.replace(/^::ffff:/,``):``},s=n.get(`gctx`),c=s.session,l=new il(s,e,t),u=new URL(n.req.url);c.setHttpMeta({method:n.req.method,url:u.toString(),path:u.pathname,clientIp:o(n.req.raw.headers),sessionId:Wc(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let d=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??rl,r=i(n.req.raw.headers),o=r!==null&&r>e?r:null;if(o===null)try{let t=await a(n.req.raw,e);if(t.kind===`tooLarge`)o=t.totalBytes;else{let{body:e,parseError:r}=c.setInbound(sr(n.req.raw.headers),t.text);d=r,s.inboundBody=e,n.req.bodyCache.text=t.text}}catch(e){s.inboundBody={},d=`invalid request body: ${e.message}`}if(o!==null){let t=`request body too large: ${String(o)} bytes exceeds limit ${String(e)}`;return n.header(`x-request-id`,s.requestId),await l.finish({status:413,streaming:!1,error:{stage:`route`,message:t,status:413},usage:null}),n.json({error:{message:t,type:`RequestTooLarge`,code:`413`}},413)}}else c.setInboundHeaders(sr(n.req.raw.headers));s.parseError=d;try{await r()}catch(e){throw await l.finish({status:500,streaming:!1,error:{stage:`handler`,message:or(e),status:500},usage:null}),e}if(n.header(`x-request-id`,s.requestId),(n.res.headers.get(`content-type`)??``).includes(`text/event-stream`)&&n.res.body!==null){c.setClientResponse(n.res.status,sr(n.res.headers));let e=(c.capture?n.res.body.pipeThrough(c.tapClientStream()):n.res.body).pipeThrough(new TransformStream({flush(){l.finishStream(200)}})).getReader(),t=new ReadableStream({async pull(t){try{let{done:n,value:r}=await e.read();if(n){try{t.close()}catch{}l.finishStream(200);return}try{t.enqueue(r)}catch{}}catch(e){try{t.close()}catch{}l.finishStream(200,{stage:`upstream`,message:`upstream stream interrupted: ${or(e)}`,status:200})}},cancel(){e.cancel().catch(()=>{}),l.finishStream(499)}},{highWaterMark:0});return n.res=new Response(t,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers}),n.res}if(c.capture&&n.res.body!==null){let[e,t]=n.res.body.tee();c.captureClientBody(t),n.res=new Response(e,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers})}let f=s.traceError??(d===null?null:{stage:`handler`,message:d,status:n.res.status});return await l.finish({status:n.res.status,streaming:!1,error:f,usage:s.traceUsage}),n.res}}var ol=3.5,sl=8,cl=24;function ll(e){let t=(e,n=0)=>{if(e==null||n>32)return 0;if(typeof e==`string`)return e.length;if(typeof e==`number`||typeof e==`boolean`)return String(e).length;if(Array.isArray(e)){let r=0;for(let i of e)r+=t(i,n+1);return r}if(typeof e==`object`){let r=0;for(let[i,a]of Object.entries(e))r+=i.length+t(a,n+1);return r}return 0},n=e=>e<=0?0:Math.max(1,Math.ceil(e/ol)),r=(e,n)=>{if(Array.isArray(e)){let r=0;for(let i of e)r+=t(i)+n;return r}return e===void 0?0:t(e)},i=0;return i+=r(e.messages,sl),i+=t(e.system),i+=t(e.thinking),i+=t(e.output_config),i+=r(e.tools,cl),{input_tokens:n(i)}}var ul=class{requestId;deployments;runner;dispatchCtx;session;inboundBody=void 0;parseError=null;hookCtx=null;traceError=null;traceUsage=null;collectUsage=null;constructor(e){this.requestId=e.requestId,this.deployments=e.deployments,this.runner=e.runner,this.dispatchCtx=e.dispatchCtx,this.session=e.session}},dl={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function fl(e){let t=new j,n=e.runner??new nl().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??oe(),o=new Qc({requestId:a,capture:r}),s=r?{...e.deps,fetchFn:o.upstreamFetch(e.deps?.fetchFn??fetch)}:e.deps??{},c={};t.req.raw.headers.forEach((e,t)=>c[t]=e),c[`x-request-id`]=a,t.set(`gctx`,new ul({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:pc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,al(n,{traceSink:e.traceSink,maxBodyBytes:i})),t.onError((e,t)=>{let n=typeof e?.status==`number`?e.status:500,r=or(e),i=e instanceof Error?e.name:`InternalServerError`;return t.get(`gctx`).traceError={stage:`handler`,message:r,status:n},t.json({error:{message:r,type:i,code:String(n)}},n)}),t.post(`/v1/chat/completions`,e=>vl(e,`openai`)),t.post(`/v1/messages`,e=>vl(e,`anthropic`)),t.post(`/v1/responses`,e=>gl(e)),t.post(`/v1/messages/count_tokens`,e=>_l(e)),t.post(`/responses`,e=>gl(e)),t.post(`/chat/completions`,e=>vl(e,`openai`)),t.post(`/messages`,e=>vl(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>_l(e)),t.get(`/v1/models`,e=>ml(e)),t.get(`/models`,e=>ml(e)),t}async function pl(e,t,n){let{response:r,reason:i}=await(async(e,t,n)=>{if(!e.has(`onAuthorize`))return{response:null,reason:null};let r=null,i={requestId:t.requestId,inboundProtocol:t.inboundProtocol,headers:n===void 0?{}:{authorization:n},principal:void 0,reject:e=>{r=e}};try{await e.run(`onAuthorize`,i)}catch(e){r=or(e)}return t.principal=i.principal,r===null?{response:null,reason:null}:{response:Response.json({error:{message:`Unauthorized: ${r}`,type:`authentication_error`,code:`401`}},{status:401}),reason:r}})(t,n,e.req.header(`authorization`));return r===null?null:(e.get(`gctx`).traceError={stage:`auth`,message:`Unauthorized: ${i??`rejected`}`,status:401},r)}async function ml(e){let t=e.get(`gctx`),n=t.runner,r=Math.floor(Date.now()/1e3),i=t.deployments.names.map(e=>({id:e,object:`model`,created:r,owned_by:`litellm-ts`}));if(n.has(`onModelList`)||n.has(`onAuthorize`)){let r=Object.assign(tl({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await pl(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function hl(e,t){let n=(e,t)=>{let n=nr(t);return e.get(`gctx`).traceError={stage:`route`,message:n.error.message,status:404},e.json(n,404)},r=e=>{let t=(e,t)=>(e.get(`gctx`).traceError={stage:`route`,message:t,status:400},e.json({error:{message:t,type:`invalid_request_error`,code:`400`}},400)),n=e.get(`gctx`).parseError;return n===null?null:t(e,n)},i=async(e,t,n,r,i)=>{if(!t.has(`onModelNotFound`))return null;let a=Object.assign(n??tl({requestId:e.get(`gctx`).requestId,inboundProtocol:i===`anthropic`?`anthropic`:`openai`,requestModel:r,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{requestedModel:r}),o=await t.run(`onModelNotFound`,a);if(typeof o!=`string`||o===``)return null;let s=ir(e.get(`gctx`).deployments,o);return s===null||!Ac(i,s)?null:o},a=e.get(`gctx`),o=a.runner,s={...a.inboundBody},c=typeof s.model==`string`?s.model:void 0,l=null;if(t.hookCtxWhen===`always`||o.has(`onAuthorize`)){l=tl({requestId:a.requestId,inboundProtocol:t.hookProtocol,requestModel:c??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),a.hookCtx=l;let n=await pl(e,o,l);if(n!==null)return n}let u=r(e);if(u!==null)return u;let d=ir(a.deployments,c);if(d===null){let n=await i(e,o,l,c??``,t.routableAs);n!==null&&(c=n,s.model=n,d=ir(a.deployments,n))}return d===null?n(e,c??``):(l!==null&&l.model===null&&(l.model=bl(c??``,d)),{body:s,model:c,deployment:d,hookCtx:l})}async function gl(e){let t=e.get(`gctx`),n=await hl(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return yl(e,await Mc(i,xl(r),t.dispatchCtx))}async function _l(e){let t=await hl(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(ll(n))}async function vl(e,t){let n=(e,t)=>t===`anthropic`?{...e,inbound_format:`anthropic`}:xl(e),r=e.get(`gctx`),i=r.runner,a=await hl(e,{hookProtocol:t,routableAs:t,hookCtxWhen:`always`});if(a instanceof Response)return a;let{body:o,deployment:s}=a,c=a.hookCtx,l=a.model,u=s;if(i.has(`onModel`)){let e=bl(l??``,u),n={...e},a=Object.assign(c,{model:e}),o=await i.run(`onModel`,a),s=a.model??e,d=typeof o==`string`&&o!==``?o:s.name;if(d!==(l??``)){let e=ir(r.deployments,d);e!==null&&Ac(t,e)?(l=d,u=e):O(`[gateway] onModel redirected "${n.name}" -> "${d}" but the target is missing from the deployment table or unroutable for ${t} inbound; keeping the original deployment`)}let f=s.provider===n.provider?u.provider:s.provider,p=s.upstreamModel===n.upstreamModel?u.modelName:s.upstreamModel,m=s.apiBase===n.apiBase?u.apiBase:s.apiBase;u={...u,provider:f,modelName:p,apiBase:m},c.model={name:l??u.name,provider:f,upstreamModel:p,apiBase:m}}if(i.has(`onModelRequest`)||i.has(`onModelResponse`)){let a=c.model,s=Object.assign(c,{model:a,request:{body:o,headers:{...e.req.header(`authorization`)?{authorization:e.req.header(`authorization`)}:{}}}});await i.run(`onModelRequest`,s);let l=r.dispatchCtx,d={...l,inboundHeaders:{...l.inboundHeaders,...s.request.headers}};return yl(e,await jc(u,n(s.request.body,t),d),{runner:i,hookCtx:c})}let d=n(o,t);return yl(e,await jc(u,d,r.dispatchCtx))}async function yl(e,t,n){let r=async e=>{let t=e.status,n=``;try{n=await e.clone().text()}catch{return{message:`upstream responded ${String(t)}`,status:t}}let r;try{r=JSON.parse(n)}catch{r=null}let i=r;return{message:typeof i==`object`&&i?typeof i.error?.message==`string`?i.error.message:typeof i.message==`string`?i.message:n.slice(0,500):n.slice(0,500),status:t}},i=e=>new Response(e.stream??e.body,{status:200,headers:{...dl}}),a=e.get(`gctx`);if(t.kind===`error`)return a.traceError={stage:`upstream`,...await r(t.response)},t.response;if(t.sse){if(a.collectUsage=t.collectUsage??null,n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!0,body:null}});await n.runner.run(`onModelResponse`,e)}return i(t)}a.traceUsage=t.usage??null;let o=t.body;if(n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!1,body:o}});await n.runner.run(`onModelResponse`,e),o=e.response.body}return e.json(o)}function bl(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function xl(e){let{inbound_format:t,...n}=e;return n}var Sl=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=ur(e.config),Cl(this._expanded.warnings),this.hookRunner=new nl().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=ur(e),Cl(this._expanded.warnings),this.options={...this.options,config:e},this}addHook(e,t){return this.hookRunner.addHook(e,t),this}async plugin(e,t){await e(this,t)}build(){let e=new j;return e.get(`/healthz`,e=>e.json({status:`ok`})),e.route(`/`,fl({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return lr}};function Cl(e){for(let t of e)O(`[ezllm] ${t}`)}var wl=`重启服务(CLI 会重新生成默认配置)`,Tl=class extends Error{constructor(e,t=Tt(),n=wl){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function El(){let e=Tt();if(!p(e))return null;let t;try{t=JSON.parse(g(e,`utf-8`))}catch(t){throw new Tl(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new Tl(`顶层必须是 JSON 对象`,e);return t}function Dl(){try{return El()}catch(e){throw e instanceof Tl&&(k(`[ezllm] ${e.message}`),process.exit(1)),e}}function Ol(e){Vt(Tt(),e)}function kl(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function Al(e){return ur(kl(e))}var jl=`0.0.0.0`,Ml=`127.0.0.1`,Nl=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function Pl(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function Fl(){return Pl(El())}function Il(){try{return{config:El(),broken:!1}}catch(e){if(!(e instanceof Tl))throw e;return{config:null,broken:!0}}}function Ll(e){let t=e?.[`web-ui`]?.[`login-account`],n=typeof t?.username==`string`?t.username.trim():``,r=typeof t?.password==`string`?t.password:``;if(n!==``&&r!==``)return{username:n,password:r}}function Rl(e){let t=e?.[`web-ui`]?.[`login-enabled`];return t===!1?!1:t!==void 0||Ll(e)!==void 0}function zl(e){return Rl(e)?Ll(e):void 0}function Bl(){let{config:e,broken:t}=Il();if(t)return{required:!0,configBroken:!0,username:``,password:``};if(!Rl(e))return{required:!1,configBroken:!1,username:``,password:``};let n=Ll(e);return n===void 0?{required:!0,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function Vl(){let{config:e,broken:t}=Il();if(t)return{completed:!1,deployment:void 0};let n=e?.setup;return n===void 0?{completed:!0,deployment:void 0}:{completed:n.completed===!0,deployment:n.deployment===`server`?`server`:`local`}}function Hl(e){return(e=>Pl(e)!==``||zl(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?jl:Ml,source:`config`}:{hostname:Ml,source:`credentials`}}function Ul(){try{return Hl(El())}catch{return Hl(null)}}function Wl(e,t){return Hl(e).hostname!==Hl(t).hostname||e?.port!==t.port}function Gl(){return El()?.logs}function Kl(e){return typeof e==`number`&&Number.isFinite(e)}function ql(){let e=Gl(),t=(e,t)=>Kl(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function Jl(){let e=Gl(),t=(e,t)=>Kl(e)&&e>0?e:t,n=t(e?.[`payload-quality`],9),r=Math.min(11,Math.max(5,Math.round(n)));return{syncIntervalMs:Math.floor(t(e?.[`spool-sync-interval-ms`],5e3)),maxBytes:Math.floor(t(e?.[`spool-max-mb`],256))*1024*1024,payloadQuality:r===10?9:r}}var Yl=`__blob`,Xl=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Zl=1e3,Ql=134217728;function $l(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function eu(e){return e instanceof Error?e.message:String(e)}var tu=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function nu(e){if(typeof e!=`string`||e===``)return``;let t;try{t=JSON.parse(e)}catch{return``}if(typeof t!=`object`||!t||Array.isArray(t))return``;for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`user-agent`&&typeof n==`string`)return n;return``}function ru(){return c(wt(),`spool`)}var iu=/^(\d+)\.jsonl$/,au=`.tmp`,ou=268435456;function su(){return new Promise(e=>setImmediate(e))}function cu(e){return c(ru(),`${String(e)}.jsonl`)}function lu(e){return cu(e)+au}function uu(){Bt(),m(ru(),{recursive:!0})}function du(){try{return _(ru()).map(e=>iu.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function fu(e){let t;try{t=g(cu(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function pu(){let e=0;try{for(let t of _(ru()))if(t.endsWith(au))try{S(c(ru(),t)),e++}catch{}}catch{return 0}return e}var mu=class{#e;#t=0;#n=-1;#r=[];#i=Promise.resolve();#a=0;constructor(e={}){let t=e.maxBytes;this.#e=typeof t==`number`&&Number.isFinite(t)&&t>0?t:ou}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of _(ru()))if(iu.test(t))try{e+=x(c(ru(),t)).size}catch{}}catch{e=0}return this.#n=e,e}resetTotalBytes(){this.#n=-1}get droppedCount(){return this.#t}resetDroppedCount(){this.#t=0}listIds(){return du()}readRecord(e){return fu(e)}deleteFile(e){try{let t=x(cu(e)).size;S(cu(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){uu();let t=lu(e.id);C(t,e.line,`utf-8`),v(t,cu(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await ce(ru(),{recursive:!0});let t=lu(e.id);await de(t,e.line,`utf-8`),await ue(t,cu(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){k(`[spool] 写入失败:`,eu(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>su()).then(async()=>{for(this.#a--;this.#r.length>0;)await this.#l(this.#r.shift())}))}write(e,t){let n=JSON.stringify(t);if(this.totalBytes()+Buffer.byteLength(n)>this.#e){this.#t++,(this.#t===1||this.#t%100==0)&&O(`[spool] 已达磁盘上界(${String(Math.round(this.#e/1024/1024))}MB),累计丢弃 ${String(this.#t)} 条——日志入库可能长期失败`);return}this.#r.push({id:e,line:n}),this.#u()}async flush(){for(;this.#r.length>0||this.#a>0;)this.#u(),await Promise.race([this.#i,su()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){k(`[spool] 崩溃前写入失败:`,eu(e))}}}};function hu(e){let t=fu(e);if(t.kind!==`ok`)return null;let n=t.entry,{response:r,time:i,method:a,path:o,model:s,status:c,stream:l,error:u,ip:d,session_id:f}=n;return{detail:{...n,response:r??null},meta:{_id:e,_spool:`${String(e)}.jsonl`,time:i??null,model:s??``,method:a??null,path:o??null,status:c??null,stream:!!l,error:u??null,ip:d??null,session_id:f??null,headers:n.headers??null,client:n.client??null,input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,cache_read_tokens:n.cache_read_tokens??0,cache_creation_tokens:n.cache_creation_tokens??0,duration:n.duration??0,ttft:n.ttft??null}}}function gu(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function _u(e){return e.map(gu)}function vu(e){return{text:e,values:[]}}function yu(e,...t){let n=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.text==`string`&&Array.isArray(t.values)},r=``,i=[];for(let a=0;a<e.length;a+=1)if(r+=e[a],a<t.length){let e=t[a];n(e)?(r+=e.text,i.push(...e.values)):(r+=`?`,i.push(e))}return{text:r,values:i}}var B=Object.assign(yu,{raw:vu}),bu=Symbol(`ezllm-db:table`);function xu(e){return e[bu]}function Su(e){return`"${e.replaceAll(`"`,`""`)}"`}function Cu(e){return e.map(e=>Su(e)).join(`, `)}function wu(e){let t={kind:e,notNull:!1,primaryKey:!1,autoIncrement:!1,unique:!1,hasDefault:!1,defaultValue:null,name:``,table:``},n={meta:t,notNull(){return t.notNull=!0,n},primaryKey(r){if(r?.autoIncrement){if(e!==`integer`)throw Error(`SQLite 的 AUTOINCREMENT 只支持 INTEGER 主键,当前列类型为 ${e.toUpperCase()}`);t.autoIncrement=!0}return t.primaryKey=!0,n},default(e){return t.hasDefault=!0,t.defaultValue=e,n},unique(){return t.unique=!0,n}};return n}function V(){return wu(`text`)}function H(){return wu(`integer`)}function Tu(){return wu(`blob`)}function Eu(e){return{on(...t){return{name:e,columns:t}}}}function Du(e,t,n=[],r={}){for(let[n,r]of Object.entries(t)){let t=r.meta.table===``&&r.meta.name===``?null:`${r.meta.table}.${r.meta.name}`;if(t!==null&&t!==`${e}.${n}`)throw Error(`表 ${e} 的列 ${n} 复用了已登记给 ${t} 的列 builder;一个列 builder 只能用于一张表的一列,请为每列单独调用 text()/integer() 等创建`);r.meta.name=n,r.meta.table=e}for(let r of n)for(let n of r.columns)if(!(n in t))throw Error(`索引 ${r.name} 引用了表 ${e} 中不存在的列:${n}`);let i=r.primaryKey;if(i!==void 0){if(i.length<2)throw Error(`表 ${e} 的表级主键至少需要两列(单列请用列级 .primaryKey())`);if(Object.values(t).some(e=>e.meta.primaryKey))throw Error(`表 ${e} 同时声明了列级主键与表级复合主键,二者只能取其一`);for(let n of i)if(!(n in t))throw Error(`表 ${e} 的复合主键引用了不存在的列:${n}`)}return{...t,[bu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Ou(e){return e.map(e=>{let t=(e,t)=>{let n=e=>e===null?`NULL`:typeof e==`boolean`?e?`1`:`0`:typeof e==`number`?String(e):`'${e.replaceAll(`'`,`''`)}'`,r=[Su(e),t.kind.toUpperCase()];return t.primaryKey&&t.autoIncrement?r.push(`PRIMARY KEY AUTOINCREMENT`):t.primaryKey&&r.push(`PRIMARY KEY`),t.notNull&&r.push(`NOT NULL`),t.hasDefault&&r.push(`DEFAULT`,n(t.defaultValue)),r.join(` `)},n=(e,t)=>{let n=Cu(t.columns);return`CREATE INDEX IF NOT EXISTS ${Su(t.name)} ON ${Su(e)} (${n})`},r=xu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${Su(e)})`);let o=[...i,...a].join(`,
|
|
21
|
+
`).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:qc(this.upstreamRequestBody??``)},upstreamResponseText:e?null:this.upstreamResponseText,upstreamStreamFrames:e?t(this.upstreamResponseText):null,clientResponse:e?void 0:this.clientBody,clientStreamFrames:e?t(this.clientStreamText):null,truncated:this.truncated}}toTrace(e){let t=e.hookCtx?.model!==null&&e.hookCtx?.model!==void 0?{name:e.hookCtx.model.name,provider:e.hookCtx.model.provider,upstreamModel:e.hookCtx.model.upstreamModel,apiBase:e.hookCtx.model.apiBase}:null;return{requestId:this.requestId,time:new Date().toISOString(),durationMs:Date.now()-this.startedAt,status:e.status,streaming:e.streaming,http:this.http,route:t,inbound:{headers:this.inboundHeaders,bodyText:this.inboundBodyText,body:this.truncated?null:this.inboundBody},upstream:{url:this.upstreamUrl,requestHeaders:this.upstreamRequestHeaders,requestBody:this.upstreamRequestBody,status:this.upstreamStatus,responseHeaders:this.upstreamResponseHeaders,responseText:this.upstreamResponseText,latencyMs:this.upstreamLatencyMs,firstTokenMs:this.upstreamFirstTokenMs,totalMs:this.upstreamTotalMs},client:{status:this.clientStatus,headers:this.clientResponseHeaders,body:this.clientBody,streamText:this.clientStreamText},usage:e.usage,stopReason:null,error:e.error,truncated:this.truncated}}};async function $c(e){let t=new TextDecoder,n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0})}return n+=t.decode(),n}var el=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function tl(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var nl=class{registry=new Map;addHook(e,t){let n=this.registry.get(e)??[];return n.push(t),this.registry.set(e,n),this}addAll(e){if(e===void 0)return this;for(let t of Object.keys(e)){let n=e[t];n!==void 0&&this.addHook(t,n)}return this}has(e){return(this.registry.get(e)?.length??0)>0}async run(e,t){let n=this.registry.get(e);if(n===void 0)return;let r=!el.includes(e),i;for(let a of n)try{i=await a(t)}catch(t){if(!r)throw t;O(`[gateway] hook ${e} threw, ignored:`,t)}return i}},rl=67108864,il=class{#e=!1;#t;#n;#r;#i;constructor(e,t,n){this.#t=e,this.#n=e.session,this.#r=t,this.#i=n}async finish(e){if(this.#e)return;this.#e=!0,await this.#n.settle();let t=this.#t.hookCtx??tl({requestId:this.#n.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:this.#n.startedAt,userAgent:this.#n.http.userAgent}),n=e.error??(this.#n.clientError===null?null:{stage:`stream`,message:this.#n.clientError.message,status:this.#n.clientError.status}),r={ctx:t,finishedAt:Date.now(),durationMs:Date.now()-this.#n.startedAt,streaming:e.streaming,status:e.status,stopReason:null,usage:e.usage,error:n===null?null:{message:n.message,status:n.status},capture:this.#n.toContentCapture(e.streaming)};if(n!==null&&await this.#r.run(`onError`,{error:n,ctx:t}),await this.#r.run(`onFinish`,r),this.#i.traceSink!==void 0)try{await this.#i.traceSink.write(this.#n.toTrace({status:e.status,streaming:e.streaming,error:n,usage:e.usage,hookCtx:t}))}catch(e){O(`[observability] trace sink failed:`,e)}}finishStream(e,t=null){this.#e||this.finish({status:e,streaming:!0,error:t,usage:this.#t.collectUsage===null?this.#t.traceUsage:this.#t.collectUsage()})}};function al(e,t){return async(n,r)=>{let i=e=>{let t=e.get(`content-length`);if(t===null)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null},a=async(e,t)=>{let n=e.body;if(n===null)return{kind:`ok`,text:``};let r=n.getReader(),i=new TextDecoder,a=``,o=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(o+=n.byteLength,o>t)return r.cancel().catch(()=>{}),{kind:`tooLarge`,totalBytes:o};a+=i.decode(n,{stream:!0})}return{kind:`ok`,text:a+i.decode()}},o=e=>{let t=e.get(`x-forwarded-for`)?.split(`,`)[0]?.trim();return t!==void 0&&t!==``?t.replace(/^::ffff:/,``):``},s=n.get(`gctx`),c=s.session,l=new il(s,e,t),u=new URL(n.req.url);c.setHttpMeta({method:n.req.method,url:u.toString(),path:u.pathname,clientIp:o(n.req.raw.headers),sessionId:Wc(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let d=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??rl,r=i(n.req.raw.headers),o=r!==null&&r>e?r:null;if(o===null)try{let t=await a(n.req.raw,e);if(t.kind===`tooLarge`)o=t.totalBytes;else{let{body:e,parseError:r}=c.setInbound(sr(n.req.raw.headers),t.text);d=r,s.inboundBody=e,n.req.bodyCache.text=t.text}}catch(e){s.inboundBody={},d=`invalid request body: ${e.message}`}if(o!==null){let t=`request body too large: ${String(o)} bytes exceeds limit ${String(e)}`;return n.header(`x-request-id`,s.requestId),await l.finish({status:413,streaming:!1,error:{stage:`route`,message:t,status:413},usage:null}),n.json({error:{message:t,type:`RequestTooLarge`,code:`413`}},413)}}else c.setInboundHeaders(sr(n.req.raw.headers));s.parseError=d;try{await r()}catch(e){throw await l.finish({status:500,streaming:!1,error:{stage:`handler`,message:or(e),status:500},usage:null}),e}if(n.header(`x-request-id`,s.requestId),(n.res.headers.get(`content-type`)??``).includes(`text/event-stream`)&&n.res.body!==null){c.setClientResponse(n.res.status,sr(n.res.headers));let e=(c.capture?n.res.body.pipeThrough(c.tapClientStream()):n.res.body).pipeThrough(new TransformStream({flush(){l.finishStream(200)}})).getReader(),t=new ReadableStream({async pull(t){try{let{done:n,value:r}=await e.read();if(n){try{t.close()}catch{}l.finishStream(200);return}try{t.enqueue(r)}catch{}}catch(e){try{t.close()}catch{}l.finishStream(200,{stage:`upstream`,message:`upstream stream interrupted: ${or(e)}`,status:200})}},cancel(){e.cancel().catch(()=>{}),l.finishStream(499)}},{highWaterMark:0});return n.res=new Response(t,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers}),n.res}if(c.capture&&n.res.body!==null){let[e,t]=n.res.body.tee();c.captureClientBody(t),n.res=new Response(e,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers})}let f=s.traceError??(d===null?null:{stage:`handler`,message:d,status:n.res.status});return await l.finish({status:n.res.status,streaming:!1,error:f,usage:s.traceUsage}),n.res}}var ol=3.5,sl=8,cl=24;function ll(e){let t=(e,n=0)=>{if(e==null||n>32)return 0;if(typeof e==`string`)return e.length;if(typeof e==`number`||typeof e==`boolean`)return String(e).length;if(Array.isArray(e)){let r=0;for(let i of e)r+=t(i,n+1);return r}if(typeof e==`object`){let r=0;for(let[i,a]of Object.entries(e))r+=i.length+t(a,n+1);return r}return 0},n=e=>e<=0?0:Math.max(1,Math.ceil(e/ol)),r=(e,n)=>{if(Array.isArray(e)){let r=0;for(let i of e)r+=t(i)+n;return r}return e===void 0?0:t(e)},i=0;return i+=r(e.messages,sl),i+=t(e.system),i+=t(e.thinking),i+=t(e.output_config),i+=r(e.tools,cl),{input_tokens:n(i)}}var ul=class{requestId;deployments;runner;dispatchCtx;session;inboundBody=void 0;parseError=null;hookCtx=null;traceError=null;traceUsage=null;collectUsage=null;constructor(e){this.requestId=e.requestId,this.deployments=e.deployments,this.runner=e.runner,this.dispatchCtx=e.dispatchCtx,this.session=e.session}},dl={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function fl(e){let t=new j,n=e.runner??new nl().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??oe(),o=new Qc({requestId:a,capture:r}),s=r?{...e.deps,fetchFn:o.upstreamFetch(e.deps?.fetchFn??fetch)}:e.deps??{},c={};t.req.raw.headers.forEach((e,t)=>c[t]=e),c[`x-request-id`]=a,t.set(`gctx`,new ul({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:pc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,al(n,{traceSink:e.traceSink,maxBodyBytes:i})),t.onError((e,t)=>{let n=typeof e?.status==`number`?e.status:500,r=or(e),i=e instanceof Error?e.name:`InternalServerError`;return t.get(`gctx`).traceError={stage:`handler`,message:r,status:n},t.json({error:{message:r,type:i,code:String(n)}},n)}),t.post(`/v1/chat/completions`,e=>vl(e,`openai`)),t.post(`/v1/messages`,e=>vl(e,`anthropic`)),t.post(`/v1/responses`,e=>gl(e)),t.post(`/v1/messages/count_tokens`,e=>_l(e)),t.post(`/responses`,e=>gl(e)),t.post(`/chat/completions`,e=>vl(e,`openai`)),t.post(`/messages`,e=>vl(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>_l(e)),t.get(`/v1/models`,e=>ml(e)),t.get(`/models`,e=>ml(e)),t}async function pl(e,t,n){let{response:r,reason:i}=await(async(e,t,n)=>{if(!e.has(`onAuthorize`))return{response:null,reason:null};let r=null,i={requestId:t.requestId,inboundProtocol:t.inboundProtocol,headers:n===void 0?{}:{authorization:n},principal:void 0,reject:e=>{r=e}};try{await e.run(`onAuthorize`,i)}catch(e){r=or(e)}return t.principal=i.principal,r===null?{response:null,reason:null}:{response:Response.json({error:{message:`Unauthorized: ${r}`,type:`authentication_error`,code:`401`}},{status:401}),reason:r}})(t,n,e.req.header(`authorization`));return r===null?null:(e.get(`gctx`).traceError={stage:`auth`,message:`Unauthorized: ${i??`rejected`}`,status:401},r)}async function ml(e){let t=e.get(`gctx`),n=t.runner,r=Math.floor(Date.now()/1e3),i=t.deployments.names.map(e=>({id:e,object:`model`,created:r,owned_by:`litellm-ts`}));if(n.has(`onModelList`)||n.has(`onAuthorize`)){let r=Object.assign(tl({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await pl(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function hl(e,t){let n=(e,t)=>{let n=nr(t);return e.get(`gctx`).traceError={stage:`route`,message:n.error.message,status:404},e.json(n,404)},r=e=>{let t=(e,t)=>(e.get(`gctx`).traceError={stage:`route`,message:t,status:400},e.json({error:{message:t,type:`invalid_request_error`,code:`400`}},400)),n=e.get(`gctx`).parseError;return n===null?null:t(e,n)},i=async(e,t,n,r,i)=>{if(!t.has(`onModelNotFound`))return null;let a=Object.assign(n??tl({requestId:e.get(`gctx`).requestId,inboundProtocol:i===`anthropic`?`anthropic`:`openai`,requestModel:r,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{requestedModel:r}),o=await t.run(`onModelNotFound`,a);if(typeof o!=`string`||o===``)return null;let s=ir(e.get(`gctx`).deployments,o);return s===null||!Ac(i,s)?null:o},a=e.get(`gctx`),o=a.runner,s={...a.inboundBody},c=typeof s.model==`string`?s.model:void 0,l=null;if(t.hookCtxWhen===`always`||o.has(`onAuthorize`)){l=tl({requestId:a.requestId,inboundProtocol:t.hookProtocol,requestModel:c??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),a.hookCtx=l;let n=await pl(e,o,l);if(n!==null)return n}let u=r(e);if(u!==null)return u;let d=ir(a.deployments,c);if(d===null){let n=await i(e,o,l,c??``,t.routableAs);n!==null&&(c=n,s.model=n,d=ir(a.deployments,n))}return d===null?n(e,c??``):(l!==null&&l.model===null&&(l.model=bl(c??``,d)),{body:s,model:c,deployment:d,hookCtx:l})}async function gl(e){let t=e.get(`gctx`),n=await hl(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return yl(e,await Mc(i,xl(r),t.dispatchCtx))}async function _l(e){let t=await hl(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(ll(n))}async function vl(e,t){let n=(e,t)=>t===`anthropic`?{...e,inbound_format:`anthropic`}:xl(e),r=e.get(`gctx`),i=r.runner,a=await hl(e,{hookProtocol:t,routableAs:t,hookCtxWhen:`always`});if(a instanceof Response)return a;let{body:o,deployment:s}=a,c=a.hookCtx,l=a.model,u=s;if(i.has(`onModel`)){let e=bl(l??``,u),n={...e},a=Object.assign(c,{model:e}),o=await i.run(`onModel`,a),s=a.model??e,d=typeof o==`string`&&o!==``?o:s.name;if(d!==(l??``)){let e=ir(r.deployments,d);e!==null&&Ac(t,e)?(l=d,u=e):O(`[gateway] onModel redirected "${n.name}" -> "${d}" but the target is missing from the deployment table or unroutable for ${t} inbound; keeping the original deployment`)}let f=s.provider===n.provider?u.provider:s.provider,p=s.upstreamModel===n.upstreamModel?u.modelName:s.upstreamModel,m=s.apiBase===n.apiBase?u.apiBase:s.apiBase;u={...u,provider:f,modelName:p,apiBase:m},c.model={name:l??u.name,provider:f,upstreamModel:p,apiBase:m}}if(i.has(`onModelRequest`)||i.has(`onModelResponse`)){let a=c.model,s=Object.assign(c,{model:a,request:{body:o,headers:{...e.req.header(`authorization`)?{authorization:e.req.header(`authorization`)}:{}}}});await i.run(`onModelRequest`,s);let l=r.dispatchCtx,d={...l,inboundHeaders:{...l.inboundHeaders,...s.request.headers}};return yl(e,await jc(u,n(s.request.body,t),d),{runner:i,hookCtx:c})}let d=n(o,t);return yl(e,await jc(u,d,r.dispatchCtx))}async function yl(e,t,n){let r=async e=>{let t=e.status,n=``;try{n=await e.clone().text()}catch{return{message:`upstream responded ${String(t)}`,status:t}}let r;try{r=JSON.parse(n)}catch{r=null}let i=r;return{message:typeof i==`object`&&i?typeof i.error?.message==`string`?i.error.message:typeof i.message==`string`?i.message:n.slice(0,500):n.slice(0,500),status:t}},i=e=>new Response(e.stream??e.body,{status:200,headers:{...dl}}),a=e.get(`gctx`);if(t.kind===`error`)return a.traceError={stage:`upstream`,...await r(t.response)},t.response;if(t.sse){if(a.collectUsage=t.collectUsage??null,n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!0,body:null}});await n.runner.run(`onModelResponse`,e)}return i(t)}a.traceUsage=t.usage??null;let o=t.body;if(n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!1,body:o}});await n.runner.run(`onModelResponse`,e),o=e.response.body}return e.json(o)}function bl(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function xl(e){let{inbound_format:t,...n}=e;return n}var Sl=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=ur(e.config),Cl(this._expanded.warnings),this.hookRunner=new nl().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=ur(e),Cl(this._expanded.warnings),this.options={...this.options,config:e},this}addHook(e,t){return this.hookRunner.addHook(e,t),this}async plugin(e,t){await e(this,t)}build(){let e=new j;return e.get(`/healthz`,e=>e.json({status:`ok`})),e.route(`/`,fl({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return lr}};function Cl(e){for(let t of e)O(`[ezllm] ${t}`)}var wl=`重启服务(CLI 会重新生成默认配置)`,Tl=class extends Error{constructor(e,t=Tt(),n=wl){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function El(){let e=Tt();if(!p(e))return null;let t;try{t=JSON.parse(g(e,`utf-8`))}catch(t){throw new Tl(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new Tl(`顶层必须是 JSON 对象`,e);return t}function Dl(){try{return El()}catch(e){throw e instanceof Tl&&(k(`[ezllm] ${e.message}`),process.exit(1)),e}}function Ol(e){Vt(Tt(),e)}function kl(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function Al(e){return ur(kl(e))}var jl=`0.0.0.0`,Ml=`127.0.0.1`,Nl=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function Pl(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function Fl(){return Pl(El())}function Il(){try{return{config:El(),broken:!1}}catch(e){if(!(e instanceof Tl))throw e;return{config:null,broken:!0}}}function Ll(e){let t=e?.[`web-ui`]?.[`login-account`],n=typeof t?.username==`string`?t.username.trim():``,r=typeof t?.password==`string`?t.password:``;if(n!==``&&r!==``)return{username:n,password:r}}function Rl(e){let t=e?.[`web-ui`]?.[`login-enabled`];return t===!1?!1:t!==void 0||Ll(e)!==void 0}function zl(e){return Rl(e)?Ll(e):void 0}function Bl(){let{config:e,broken:t}=Il();if(t)return{required:!0,configBroken:!0,username:``,password:``};if(!Rl(e))return{required:!1,configBroken:!1,username:``,password:``};let n=Ll(e);return n===void 0?{required:!0,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function Vl(){let{config:e,broken:t}=Il();if(t)return{completed:!1,deployment:void 0};let n=e?.setup;return n===void 0?{completed:!0,deployment:void 0}:{completed:n.completed===!0,deployment:n.deployment===`server`?`server`:`local`}}function Hl(e){return(e=>Pl(e)!==``||zl(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?jl:Ml,source:`config`}:{hostname:Ml,source:`credentials`}}function Ul(){try{return Hl(El())}catch{return Hl(null)}}function Wl(e,t){return Hl(e).hostname!==Hl(t).hostname||e?.port!==t.port}function Gl(){return El()?.logs}function Kl(e){return typeof e==`number`&&Number.isFinite(e)}function ql(){let e=Gl(),t=(e,t)=>Kl(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function Jl(){let e=Gl(),t=(e,t)=>Kl(e)&&e>0?e:t,n=t(e?.[`payload-quality`],9),r=Math.min(11,Math.max(5,Math.round(n)));return{syncIntervalMs:Math.floor(t(e?.[`spool-sync-interval-ms`],5e3)),maxBytes:Math.floor(t(e?.[`spool-max-mb`],256))*1024*1024,payloadQuality:r===10?9:r}}var Yl=`__blob`,Xl=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Zl=1e3,Ql=134217728;function $l(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function eu(e){return e instanceof Error?e.message:String(e)}var tu=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function nu(e){if(typeof e!=`string`||e===``)return``;let t;try{t=JSON.parse(e)}catch{return``}if(typeof t!=`object`||!t||Array.isArray(t))return``;for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`user-agent`&&typeof n==`string`)return n;return``}function ru(){return c(wt(),`spool`)}var iu=/^(\d+)\.jsonl$/,au=`.tmp`,ou=268435456;function su(){return new Promise(e=>setImmediate(e))}function cu(e){return c(ru(),`${String(e)}.jsonl`)}function lu(e){return cu(e)+au}function uu(){Bt(),m(ru(),{recursive:!0})}function du(){try{return _(ru()).map(e=>iu.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function fu(e){let t;try{t=g(cu(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function pu(){let e=0;try{for(let t of _(ru()))if(t.endsWith(au))try{S(c(ru(),t)),e++}catch{}}catch{return 0}return e}var mu=class{#e;#t=0;#n=-1;#r=[];#i=Promise.resolve();#a=0;constructor(e={}){let t=e.maxBytes;this.#e=typeof t==`number`&&Number.isFinite(t)&&t>0?t:ou}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of _(ru()))if(iu.test(t))try{e+=x(c(ru(),t)).size}catch{}}catch{e=0}return this.#n=e,e}resetTotalBytes(){this.#n=-1}get droppedCount(){return this.#t}resetDroppedCount(){this.#t=0}listIds(){return du()}readRecord(e){return fu(e)}deleteFile(e){try{let t=x(cu(e)).size;S(cu(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){uu();let t=lu(e.id);C(t,e.line,`utf-8`),v(t,cu(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await ue(ru(),{recursive:!0});let t=lu(e.id);await pe(t,e.line,`utf-8`),await fe(t,cu(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){k(`[spool] 写入失败:`,eu(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>su()).then(async()=>{for(this.#a--;this.#r.length>0;)await this.#l(this.#r.shift())}))}write(e,t){let n=JSON.stringify(t);if(this.totalBytes()+Buffer.byteLength(n)>this.#e){this.#t++,(this.#t===1||this.#t%100==0)&&O(`[spool] 已达磁盘上界(${String(Math.round(this.#e/1024/1024))}MB),累计丢弃 ${String(this.#t)} 条——日志入库可能长期失败`);return}this.#r.push({id:e,line:n}),this.#u()}async flush(){for(;this.#r.length>0||this.#a>0;)this.#u(),await Promise.race([this.#i,su()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){k(`[spool] 崩溃前写入失败:`,eu(e))}}}};function hu(e){let t=fu(e);if(t.kind!==`ok`)return null;let n=t.entry,{response:r,time:i,method:a,path:o,model:s,status:c,stream:l,error:u,ip:d,session_id:f}=n;return{detail:{...n,response:r??null},meta:{_id:e,_spool:`${String(e)}.jsonl`,time:i??null,model:s??``,method:a??null,path:o??null,status:c??null,stream:!!l,error:u??null,ip:d??null,session_id:f??null,headers:n.headers??null,client:n.client??null,input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,cache_read_tokens:n.cache_read_tokens??0,cache_creation_tokens:n.cache_creation_tokens??0,duration:n.duration??0,ttft:n.ttft??null}}}function gu(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function _u(e){return e.map(gu)}function vu(e){return{text:e,values:[]}}function yu(e,...t){let n=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.text==`string`&&Array.isArray(t.values)},r=``,i=[];for(let a=0;a<e.length;a+=1)if(r+=e[a],a<t.length){let e=t[a];n(e)?(r+=e.text,i.push(...e.values)):(r+=`?`,i.push(e))}return{text:r,values:i}}var B=Object.assign(yu,{raw:vu}),bu=Symbol(`ezllm-db:table`);function xu(e){return e[bu]}function Su(e){return`"${e.replaceAll(`"`,`""`)}"`}function Cu(e){return e.map(e=>Su(e)).join(`, `)}function wu(e){let t={kind:e,notNull:!1,primaryKey:!1,autoIncrement:!1,unique:!1,hasDefault:!1,defaultValue:null,name:``,table:``},n={meta:t,notNull(){return t.notNull=!0,n},primaryKey(r){if(r?.autoIncrement){if(e!==`integer`)throw Error(`SQLite 的 AUTOINCREMENT 只支持 INTEGER 主键,当前列类型为 ${e.toUpperCase()}`);t.autoIncrement=!0}return t.primaryKey=!0,n},default(e){return t.hasDefault=!0,t.defaultValue=e,n},unique(){return t.unique=!0,n}};return n}function V(){return wu(`text`)}function H(){return wu(`integer`)}function Tu(){return wu(`blob`)}function Eu(e){return{on(...t){return{name:e,columns:t}}}}function Du(e,t,n=[],r={}){for(let[n,r]of Object.entries(t)){let t=r.meta.table===``&&r.meta.name===``?null:`${r.meta.table}.${r.meta.name}`;if(t!==null&&t!==`${e}.${n}`)throw Error(`表 ${e} 的列 ${n} 复用了已登记给 ${t} 的列 builder;一个列 builder 只能用于一张表的一列,请为每列单独调用 text()/integer() 等创建`);r.meta.name=n,r.meta.table=e}for(let r of n)for(let n of r.columns)if(!(n in t))throw Error(`索引 ${r.name} 引用了表 ${e} 中不存在的列:${n}`);let i=r.primaryKey;if(i!==void 0){if(i.length<2)throw Error(`表 ${e} 的表级主键至少需要两列(单列请用列级 .primaryKey())`);if(Object.values(t).some(e=>e.meta.primaryKey))throw Error(`表 ${e} 同时声明了列级主键与表级复合主键,二者只能取其一`);for(let n of i)if(!(n in t))throw Error(`表 ${e} 的复合主键引用了不存在的列:${n}`)}return{...t,[bu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Ou(e){return e.map(e=>{let t=(e,t)=>{let n=e=>e===null?`NULL`:typeof e==`boolean`?e?`1`:`0`:typeof e==`number`?String(e):`'${e.replaceAll(`'`,`''`)}'`,r=[Su(e),t.kind.toUpperCase()];return t.primaryKey&&t.autoIncrement?r.push(`PRIMARY KEY AUTOINCREMENT`):t.primaryKey&&r.push(`PRIMARY KEY`),t.notNull&&r.push(`NOT NULL`),t.hasDefault&&r.push(`DEFAULT`,n(t.defaultValue)),r.join(` `)},n=(e,t)=>{let n=Cu(t.columns);return`CREATE INDEX IF NOT EXISTS ${Su(t.name)} ON ${Su(e)} (${n})`},r=xu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${Su(e)})`);let o=[...i,...a].join(`,
|
|
22
22
|
`),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${Cu(r.tablePrimaryKey)})`);let c=[`CREATE TABLE IF NOT EXISTS ${Su(r.name)} (\n${s}\n)`];for(let e of r.indexes)c.push(n(r.name,e));return c.map(e=>`${e};`).join(`
|
|
23
23
|
`)}).join(`
|
|
24
|
-
`)}function ku(e){return`${Su(e.meta.table)}.${Su(e.meta.name)}`}function U(e,t){return{kind:`condition`,text:e,values:t}}function Au(e,t){return U(`${ku(e)} = ?`,[t])}function ju(e,t){return U(`${ku(e)} <> ?`,[t])}function Mu(e,t){return U(`${ku(e)} > ?`,[t])}function Nu(e,t){return U(`${ku(e)} >= ?`,[t])}function Pu(e,t){return U(`${ku(e)} < ?`,[t])}function Fu(e,t){return U(`${ku(e)} <= ?`,[t])}function Iu(e,t){return U(`${ku(e)} LIKE ?`,[t])}function Lu(e,t){if(t.length===0)return U(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return U(`${ku(e)} IN (${n})`,t)}function Ru(e){return U(`${ku(e)} IS NULL`,[])}function zu(e){return U(`${ku(e)} IS NOT NULL`,[])}function Bu(e,t,n){return e.length===0?U(n,[]):U(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function Vu(...e){return Bu(e,`AND`,`1 = 1`)}function Hu(...e){return Bu(e,`OR`,`1 = 0`)}function Uu(e){return U(`NOT (${e.text})`,e.values)}function Wu(e,t){return{kind:`sort`,text:`${ku(e)} ${t}`,values:[]}}function Gu(e){return Wu(e,`ASC`)}function Ku(e){return Wu(e,`DESC`)}function qu(e){return{kind:`aggregation`,text:e,values:[]}}function Ju(e,t){return qu(`${e}(${ku(t)})`)}function Yu(e){return Ju(`SUM`,e)}function Xu(e){return Ju(`MIN`,e)}function Zu(e){return Ju(`MAX`,e)}function Qu(e){return e?Ju(`COUNT`,e):qu(`COUNT(*)`)}var W={eq:Au,ne:ju,gt:Mu,gte:Nu,lt:Pu,lte:Fu,like:Iu,in:Lu,isNull:Ru,isNotNull:zu,and:Vu,or:Hu,not:Uu,asc:Gu,desc:Ku,sum:Yu,count:Qu,min:Xu,max:Zu},$u=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return xu(this.table).name}get tableColumns(){return xu(this.table).columns}get quotedTable(){return Su(this.tableName)}},ed=class extends $u{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=Vu(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},td=class extends ed{allowAllRows=!1;allRows(){return this.allowAllRows=!0,this}assertWhereOrAllRows(e,t){if(this.conds.length===0&&!this.allowAllRows)throw Error(`${e} ${this.tableName}:无 where 条件会${t}全表;确需全表${t}请显式调用 .allRows()`)}};function nd(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var rd=class extends $u{rows=[];conflictMode=``;orIgnore(){return this.conflictMode=` OR IGNORE`,this}orReplace(){return this.conflictMode=` OR REPLACE`,this}values(e){let t=Array.isArray(e)?e:[e];return this.rows=[...this.rows,...t],this}run(){if(this.rows.length===0)throw Error(`insert ${this.tableName}:未提供数据,请先调用 .values(...)`);let e=Object.keys(this.tableColumns),t=new Map;for(let n of this.rows){let r=e.filter(e=>n[e]!==void 0);if(r.length===0)throw Error(`insert ${this.tableName}:.values(...) 的行不含任何 schema 列`);let i=JSON.stringify(r),a=t.get(i);a===void 0?t.set(i,{columns:r,rows:[n]}):a.rows.push(n)}let n=0,r=0;for(let e of t.values()){let t=[],i=e.rows.map(n=>`(${e.columns.map(e=>(t.push(gu(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${Cu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=nd(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},id=class extends ed{orders=[];groupCols=[];projection={kind:`all`};limitValue;offsetValue;orderBy(...e){return this.orders.push(...e),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}groupBy(...e){return this.groupCols.push(...e),this}columns(e){if(Array.isArray(e)){let t=e;if(t.length===0)throw Error(`select ${this.tableName}:columns([]) 至少要指定一列`);for(let e of t)if(!(e in this.tableColumns))throw Error(`select ${this.tableName}:columns 引用了不存在的列 ${String(e)}`);this.projection={kind:`subset`,columns:t}}else{let t=Object.entries(e);if(t.length===0)throw Error(`select ${this.tableName}:columns({}) 至少要有一个聚合表达式`);this.projection={kind:`aggregate`,entries:t}}return this}build(){let e;switch(this.projection.kind){case`subset`:e=Cu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${Su(e)}`).join(`, `);break;default:e=Cu(Object.keys(this.tableColumns))}let t=[];if(e.length===0)throw Error(`select ${this.tableName}:该表没有声明任何列,无法生成 SELECT 列清单`);let n=this.appendWhere(`SELECT ${e} FROM ${this.quotedTable}`,t);if(this.groupCols.length>0&&(n+=` GROUP BY ${this.groupCols.map(e=>ku(e)).join(`, `)}`),this.orders.length>0){n+=` ORDER BY ${this.orders.map(e=>e.text).join(`, `)}`;for(let e of this.orders)t.push(...e.values)}return this.limitValue!==void 0&&(n+=` LIMIT ?`,t.push(this.limitValue)),this.offsetValue!==void 0&&(this.limitValue===void 0&&(n+=` LIMIT -1`),n+=` OFFSET ?`,t.push(this.offsetValue)),{text:n,values:t}}all(){return this.executor.all(this.build())}get(){return this.executor.get(this.build())}values(){return this.executor.values(this.build())}},ad=class extends td{patchEntries=[];set(e){return this.patchEntries=Object.entries(e),this}run(){if(this.patchEntries.length===0)throw Error(`update ${this.tableName}:缺少 set(...),没有要写入的列`);this.assertWhereOrAllRows(`update`,`更新`);let e=[],t=this.tableColumns,n=this.patchEntries.map(([n,r])=>{if(!Object.hasOwn(t,n))throw Error(`update ${this.tableName}:set({ ${n}: ... }) 的 \`${n}\` 不是该表的列`);return e.push(gu(r)),`${Su(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},od=class extends td{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},sd=new Map,cd=class{name;native;statements=new Map;closed=!1;constructor(e,t){this.name=e,this.native=t}stmt(e){let t=this.statements.get(e);if(t!==void 0)return t;let n=this.native.prepare(e);return this.statements.set(e,n),n}runPrepared(e,t){return{...e.run(..._u(t))}}getPrepared(e,t){return e.get(..._u(t))}allPrepared(e,t){return e.all(..._u(t))}all(e){return this.allPrepared(this.stmt(e.text),e.values)}get(e){return this.getPrepared(this.stmt(e.text),e.values)}values(e){let t=this.stmt(e.text);t.setReturnArrays(!0);try{return this.allPrepared(t,e.values)}finally{t.setReturnArrays(!1)}}run(e){return this.runPrepared(this.stmt(e.text),e.values)}exec(e){this.native.exec(e)}createTables(e){e.length!==0&&this.native.exec(Ou(e))}insert(e){return new rd(this,e)}select(e){return new id(this,e)}update(e){return new ad(this,e)}delete(e){return new od(this,e)}transaction(e){if(this.inTransaction)throw Error(`transaction ${this.name}:不支持嵌套事务`);this.native.exec(`BEGIN`),this.inTransaction=!0;try{let t=e(this.txView);return this.native.exec(`COMMIT`),t}catch(e){try{this.native.exec(`ROLLBACK`)}catch{}throw e}finally{this.inTransaction=!1}}inTransaction=!1;txViewValue=null;get txView(){if(this.txViewValue===null){let e=this;this.txViewValue={insert:t=>e.insert(t),select:t=>e.select(t),update:t=>e.update(t),delete:t=>e.delete(t),all:t=>e.all(t),get:t=>e.get(t),values:t=>e.values(t),run:t=>e.run(t),exec:t=>e.exec(t)}}return this.txViewValue}prepare(e){let t=this.stmt(e);return{run:(...e)=>this.runPrepared(t,e),get:(...e)=>this.getPrepared(t,e),all:(...e)=>this.allPrepared(t,e)}}close(){this.closed||(this.closed=!0,this.statements.clear(),this.native.close(),sd.get(this.name)===this&&sd.delete(this.name))}};function ld(e){let t=sd.get(e);if(t!==void 0)return t;Bt();let n=new
|
|
25
|
-
`).filter(e=>e.startsWith(`data: `)&&e.slice(6).trimEnd()!==`[DONE]`);if(t.length>0)try{let e=JSON.parse(t[0].slice(6)).choices?.[0]?.delta;return e?.content||e?.reasoning_content||`(SSE)`}catch{return`(SSE `+e.length+` chars)`}return`(SSE `+e.length+` chars)`}let t=e;if(t.error)return`错误: `+(t.error.message||JSON.stringify(t.error));let n=t.choices?.[0];return n?n.message?.content?.slice(0,100)||n.delta?.content||`(流式)`:JSON.stringify(e).slice(0,100)}function Ad(e,t,n=9){let r=(e,t=9)=>{let n=
|
|
24
|
+
`)}function ku(e){return`${Su(e.meta.table)}.${Su(e.meta.name)}`}function U(e,t){return{kind:`condition`,text:e,values:t}}function Au(e,t){return U(`${ku(e)} = ?`,[t])}function ju(e,t){return U(`${ku(e)} <> ?`,[t])}function Mu(e,t){return U(`${ku(e)} > ?`,[t])}function Nu(e,t){return U(`${ku(e)} >= ?`,[t])}function Pu(e,t){return U(`${ku(e)} < ?`,[t])}function Fu(e,t){return U(`${ku(e)} <= ?`,[t])}function Iu(e,t){return U(`${ku(e)} LIKE ?`,[t])}function Lu(e,t){if(t.length===0)return U(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return U(`${ku(e)} IN (${n})`,t)}function Ru(e){return U(`${ku(e)} IS NULL`,[])}function zu(e){return U(`${ku(e)} IS NOT NULL`,[])}function Bu(e,t,n){return e.length===0?U(n,[]):U(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function Vu(...e){return Bu(e,`AND`,`1 = 1`)}function Hu(...e){return Bu(e,`OR`,`1 = 0`)}function Uu(e){return U(`NOT (${e.text})`,e.values)}function Wu(e,t){return{kind:`sort`,text:`${ku(e)} ${t}`,values:[]}}function Gu(e){return Wu(e,`ASC`)}function Ku(e){return Wu(e,`DESC`)}function qu(e){return{kind:`aggregation`,text:e,values:[]}}function Ju(e,t){return qu(`${e}(${ku(t)})`)}function Yu(e){return Ju(`SUM`,e)}function Xu(e){return Ju(`MIN`,e)}function Zu(e){return Ju(`MAX`,e)}function Qu(e){return e?Ju(`COUNT`,e):qu(`COUNT(*)`)}var W={eq:Au,ne:ju,gt:Mu,gte:Nu,lt:Pu,lte:Fu,like:Iu,in:Lu,isNull:Ru,isNotNull:zu,and:Vu,or:Hu,not:Uu,asc:Gu,desc:Ku,sum:Yu,count:Qu,min:Xu,max:Zu},$u=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return xu(this.table).name}get tableColumns(){return xu(this.table).columns}get quotedTable(){return Su(this.tableName)}},ed=class extends $u{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=Vu(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},td=class extends ed{allowAllRows=!1;allRows(){return this.allowAllRows=!0,this}assertWhereOrAllRows(e,t){if(this.conds.length===0&&!this.allowAllRows)throw Error(`${e} ${this.tableName}:无 where 条件会${t}全表;确需全表${t}请显式调用 .allRows()`)}};function nd(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var rd=class extends $u{rows=[];conflictMode=``;orIgnore(){return this.conflictMode=` OR IGNORE`,this}orReplace(){return this.conflictMode=` OR REPLACE`,this}values(e){let t=Array.isArray(e)?e:[e];return this.rows=[...this.rows,...t],this}run(){if(this.rows.length===0)throw Error(`insert ${this.tableName}:未提供数据,请先调用 .values(...)`);let e=Object.keys(this.tableColumns),t=new Map;for(let n of this.rows){let r=e.filter(e=>n[e]!==void 0);if(r.length===0)throw Error(`insert ${this.tableName}:.values(...) 的行不含任何 schema 列`);let i=JSON.stringify(r),a=t.get(i);a===void 0?t.set(i,{columns:r,rows:[n]}):a.rows.push(n)}let n=0,r=0;for(let e of t.values()){let t=[],i=e.rows.map(n=>`(${e.columns.map(e=>(t.push(gu(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${Cu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=nd(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},id=class extends ed{orders=[];groupCols=[];projection={kind:`all`};limitValue;offsetValue;orderBy(...e){return this.orders.push(...e),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}groupBy(...e){return this.groupCols.push(...e),this}columns(e){if(Array.isArray(e)){let t=e;if(t.length===0)throw Error(`select ${this.tableName}:columns([]) 至少要指定一列`);for(let e of t)if(!(e in this.tableColumns))throw Error(`select ${this.tableName}:columns 引用了不存在的列 ${String(e)}`);this.projection={kind:`subset`,columns:t}}else{let t=Object.entries(e);if(t.length===0)throw Error(`select ${this.tableName}:columns({}) 至少要有一个聚合表达式`);this.projection={kind:`aggregate`,entries:t}}return this}build(){let e;switch(this.projection.kind){case`subset`:e=Cu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${Su(e)}`).join(`, `);break;default:e=Cu(Object.keys(this.tableColumns))}let t=[];if(e.length===0)throw Error(`select ${this.tableName}:该表没有声明任何列,无法生成 SELECT 列清单`);let n=this.appendWhere(`SELECT ${e} FROM ${this.quotedTable}`,t);if(this.groupCols.length>0&&(n+=` GROUP BY ${this.groupCols.map(e=>ku(e)).join(`, `)}`),this.orders.length>0){n+=` ORDER BY ${this.orders.map(e=>e.text).join(`, `)}`;for(let e of this.orders)t.push(...e.values)}return this.limitValue!==void 0&&(n+=` LIMIT ?`,t.push(this.limitValue)),this.offsetValue!==void 0&&(this.limitValue===void 0&&(n+=` LIMIT -1`),n+=` OFFSET ?`,t.push(this.offsetValue)),{text:n,values:t}}all(){return this.executor.all(this.build())}get(){return this.executor.get(this.build())}values(){return this.executor.values(this.build())}},ad=class extends td{patchEntries=[];set(e){return this.patchEntries=Object.entries(e),this}run(){if(this.patchEntries.length===0)throw Error(`update ${this.tableName}:缺少 set(...),没有要写入的列`);this.assertWhereOrAllRows(`update`,`更新`);let e=[],t=this.tableColumns,n=this.patchEntries.map(([n,r])=>{if(!Object.hasOwn(t,n))throw Error(`update ${this.tableName}:set({ ${n}: ... }) 的 \`${n}\` 不是该表的列`);return e.push(gu(r)),`${Su(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},od=class extends td{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},sd=new Map,cd=class{name;native;statements=new Map;closed=!1;constructor(e,t){this.name=e,this.native=t}stmt(e){let t=this.statements.get(e);if(t!==void 0)return t;let n=this.native.prepare(e);return this.statements.set(e,n),n}runPrepared(e,t){return{...e.run(..._u(t))}}getPrepared(e,t){return e.get(..._u(t))}allPrepared(e,t){return e.all(..._u(t))}all(e){return this.allPrepared(this.stmt(e.text),e.values)}get(e){return this.getPrepared(this.stmt(e.text),e.values)}values(e){let t=this.stmt(e.text);t.setReturnArrays(!0);try{return this.allPrepared(t,e.values)}finally{t.setReturnArrays(!1)}}run(e){return this.runPrepared(this.stmt(e.text),e.values)}exec(e){this.native.exec(e)}createTables(e){e.length!==0&&this.native.exec(Ou(e))}insert(e){return new rd(this,e)}select(e){return new id(this,e)}update(e){return new ad(this,e)}delete(e){return new od(this,e)}transaction(e){if(this.inTransaction)throw Error(`transaction ${this.name}:不支持嵌套事务`);this.native.exec(`BEGIN`),this.inTransaction=!0;try{let t=e(this.txView);return this.native.exec(`COMMIT`),t}catch(e){try{this.native.exec(`ROLLBACK`)}catch{}throw e}finally{this.inTransaction=!1}}inTransaction=!1;txViewValue=null;get txView(){if(this.txViewValue===null){let e=this;this.txViewValue={insert:t=>e.insert(t),select:t=>e.select(t),update:t=>e.update(t),delete:t=>e.delete(t),all:t=>e.all(t),get:t=>e.get(t),values:t=>e.values(t),run:t=>e.run(t),exec:t=>e.exec(t)}}return this.txViewValue}prepare(e){let t=this.stmt(e);return{run:(...e)=>this.runPrepared(t,e),get:(...e)=>this.getPrepared(t,e),all:(...e)=>this.allPrepared(t,e)}}close(){this.closed||(this.closed=!0,this.statements.clear(),this.native.close(),sd.get(this.name)===this&&sd.delete(this.name))}};function ld(e){let t=sd.get(e);if(t!==void 0)return t;Bt();let n=new me(c(wt(),`${e}.db`));try{n.exec(`PRAGMA busy_timeout = 5000`),n.exec(`PRAGMA journal_mode = WAL`),n.exec(`PRAGMA journal_size_limit = 67108864`)}catch(e){throw n.close(),e}let r=new cd(e,n);return sd.set(e,r),r}var G=Du(`logs`,{id:H().primaryKey({autoIncrement:!0}),time:V().notNull(),date:V().notNull(),method:V(),path:V(),model:V(),status:H(),stream:H(),error:V(),preview:V(),input_tokens:H().default(0),output_tokens:H().default(0),cache_read_tokens:H().default(0),cache_creation_tokens:H().default(0),ip:V(),session_id:V(),duration:H().default(0),headers:V(),client:V(),ttft:H()},[Eu(`idx_logs_date`).on(`date`),Eu(`idx_logs_time`).on(`time`),Eu(`idx_logs_model`).on(`model`),Eu(`idx_logs_session`).on(`session_id`),Eu(`idx_logs_client`).on(`client`)]),ud=Du(`log_details`,{log_id:H().primaryKey(),detail:Tu().notNull()}),dd=Du(`log_blobs`,{hash:V().primaryKey(),content:Tu().notNull()}),fd=Du(`log_id_alloc`,{next_id:H().notNull()}),K=Du(`client_names`,{ua:V().primaryKey(),client:V(),source:V(),attempts:H().notNull().default(0),created_at:V().notNull(),updated_at:V().notNull()}),pd=[G,fd,K],md=[ud,dd],hd=[[`headers`,`TEXT`],[`client`,`TEXT`],[`ttft`,`INTEGER`]],gd=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${tu})`];function _d(e){let t=e.native.prepare(`PRAGMA table_info(logs)`).all();if(t.length===0)return;let n=new Set(t.map(e=>String(e.name)));for(let[t,r]of hd)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function vd(e){for(let t of gd)e.exec(t)}var yd=null;function bd(){return xd().native}function xd(){if(yd!==null)return yd;let e=ld(`logs`);return _d(e),e.createTables(pd),vd(e),yd=e,e}function q(){return xd()}function Sd(e){return q().transaction(e)}var Cd=1e3,wd=!1,Td=0,Ed=0;function Dd(){let e=e=>{let t=e.get(B`SELECT seq FROM sqlite_sequence WHERE name = 'logs'`);return t===void 0?0:Number(t.seq)},t=(t,n)=>{if(e(t)>=n)return;let r=t.run(B`UPDATE sqlite_sequence SET seq = ${n} WHERE name = 'logs'`);Number(r.changes)===0&&t.run(B`INSERT INTO sqlite_sequence (name, seq) VALUES ('logs', ${n})`)},n=t=>{if(t.select(fd).columns([`next_id`]).limit(1).get()!==void 0)return;let n=t.select(G).columns({m:W.max(G.id)}).get(),r=Math.max(Number(n?.m??0),e(t))+1;t.insert(fd).values({next_id:r}).run()};if(Td>=Ed){let e=q();Sd(()=>{wd||=(n(e),!0);let r=e.select(fd).columns([`next_id`]).limit(1).get();Td=Number(r.next_id),Ed=Td+Cd,e.update(fd).set({next_id:Ed}).allRows().run(),t(e,Ed-1)})}return Td++}function Od(e){return he(e,{params:{[_e.BROTLI_PARAM_QUALITY]:9}})}function kd(e){if(!e)return`-`;if(typeof e==`string`){let t=e.split(`
|
|
25
|
+
`).filter(e=>e.startsWith(`data: `)&&e.slice(6).trimEnd()!==`[DONE]`);if(t.length>0)try{let e=JSON.parse(t[0].slice(6)).choices?.[0]?.delta;return e?.content||e?.reasoning_content||`(SSE)`}catch{return`(SSE `+e.length+` chars)`}return`(SSE `+e.length+` chars)`}let t=e;if(t.error)return`错误: `+(t.error.message||JSON.stringify(t.error));let n=t.choices?.[0];return n?n.message?.content?.slice(0,100)||n.delta?.content||`(流式)`:JSON.stringify(e).slice(0,100)}function Ad(e,t,n=9){let r=(e,t=9)=>{let n=he(Buffer.from(e,`utf-8`),{params:{[_e.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])},i=e=>ie(`sha256`).update(e,`utf-8`).digest(`hex`),a=(e,t)=>{if(typeof e==`string`){if(e.length<8192)return e;let n=i(e);return t.has(n)||t.set(n,e),{[Yl]:n}}if(Array.isArray(e))return e.map(e=>a(e,t));if(typeof e==`object`&&e){let n={};for(let[r,i]of Object.entries(e))n[r]=a(i,t);return n}return e},o=e.time||new Date().toISOString(),s=new Map,c=a(e,s);return{id:t,time:o,date:$l(o),preview:kd(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function jd(e){return{method:e.method||null,path:e.path||null,model:e.model||null,status:e.status??null,stream:+!!e.stream,error:e.error||null,input_tokens:e.input_tokens||0,output_tokens:e.output_tokens||0,cache_read_tokens:e.cache_read_tokens||0,cache_creation_tokens:e.cache_creation_tokens||0,ip:e.ip||null,session_id:e.session_id||null,duration:e.duration||0,ttft:e.ttft??null,headers:e.headers||null,client:e.client||null}}function Md(e,t){let n=t.time||new Date().toISOString(),r=$l(n),i=q();return Sd(()=>{i.insert(G).values({id:e,time:n,date:r,preview:kd(t.response),...jd(t)}).run()}),e}var Nd=4,Pd=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,Fd=/^\d{6}$/;function Id(){return c(wt(),`details`)}function Ld(e){return c(Id(),e.slice(0,7).replace(/-/g,``))}function Rd(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function zd(e){return c(Ld(e),`logs-${e.replace(/-/g,``)}.db`)}var Bd=new class{#e=new Map;#t(e,t){let n=this.#e.get(e);if(n!==void 0)return this.#e.delete(e),this.#e.set(e,n),n;if(t.create)m(Ld(e),{recursive:!0});else if(!p(zd(e)))return null;let r=ld(Rd(e));return r.createTables(md),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>Nd;){let e=this.#e.keys().next().value;this.#r(e)}return t}#r(e){let t=this.#e.get(e);if(t!==void 0){this.#e.delete(e);try{t.close()}catch{}}}open(e){return this.#t(e,{create:!0})}openIfExists(e){return this.#t(e,{create:!1})}closeAll(){for(let e of[...this.#e.keys()])this.#r(e)}listDetailDates(){let e;try{e=_(Id())}catch{return[]}let t=[];for(let n of e){if(!Fd.test(n))continue;let e;try{e=_(c(Id(),n))}catch{continue}for(let n of e){let e=Pd.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=zd(e),n=!1;p(t)&&(y(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])y(t+e,{force:!0});try{b(Ld(e))}catch{}return n}};function Vd(e){if(e.length===0)return 0;let t=new Map;for(let n of e){let e=t.get(n.date);e===void 0?t.set(n.date,[n]):e.push(n)}let n=q();for(let[e,r]of t){Sd(()=>{for(let e of r)n.insert(G).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...jd(e.entry)}).orIgnore().run()});let t=Bd.open(e);t.transaction(()=>{for(let e of r){t.insert(ud).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(dd).values({hash:n,content:Od(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function Hd(e){return ge(Buffer.from(e)).toString(`utf-8`)}function Ud(e){if(e.length>0&&e[0]===2)return ge(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function Wd(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[Yl];return typeof n==`string`?n:null}function Gd(e,t){if(Array.isArray(e))return e.map(e=>Gd(e,t));if(typeof e==`object`&&e){let n=e,r=Wd(n);if(r!==null){let n=t.get(r);return n===void 0?e:n}let i={};for(let[e,r]of Object.entries(n))i[e]=Gd(r,t);return i}return e}function Kd(e,t){if(Array.isArray(e)){for(let n of e)Kd(n,t);return}if(typeof e==`object`&&e){let n=e,r=Wd(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))Kd(e,t)}}function qd(e,t){let n=new Map,r=[...e];if(r.length===0)return n;for(let e=0;e<r.length;e+=400){let i=r.slice(e,e+400),a=t.select(dd).columns([`hash`,`content`]).where(W.in(dd.hash,i)).all();for(let e of a)n.set(e.hash,Hd(e.content))}return n}function Jd(e){let t=q().select(G).where(W.eq(G.id,Number(e))).get();if(t===void 0)return null;let n=Bd.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(ud).columns([`detail`]).where(W.eq(ud.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(Ud(i.detail).toString(`utf-8`)),t=new Set;Kd(e,t),r=Gd(e,qd(t,n))}catch(e){k(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,eu(e))}return r===null?null:{detail:r,meta:{_id:t.id,time:t.time,model:t.model||``,method:t.method||null,path:t.path||null,status:t.status??null,stream:!!t.stream,error:t.error||null,ip:t.ip||null,session_id:t.session_id||null,headers:t.headers||null,client:t.client||null,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,cache_read_tokens:t.cache_read_tokens??0,cache_creation_tokens:t.cache_creation_tokens??0,duration:t.duration??0,ttft:t.ttft??null}}}var Yd=B.raw(`AVG(CASE WHEN stream = 1 THEN ttft END) AS avg_ttft,
|
|
26
26
|
SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN NULL
|
|
27
27
|
WHEN stream = 1 THEN duration - ttft
|
|
28
28
|
ELSE duration END) AS tps_window_ms,
|
|
@@ -81,7 +81,7 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
81
81
|
AND headers IS NOT NULL
|
|
82
82
|
ORDER BY id
|
|
83
83
|
LIMIT ${cp}
|
|
84
|
-
`);if(o.length===0)break;let s=[];for(let e of o){a=Number(e.id),i.scanned++;let o=t(e.headers);o!==``&&(s.push({id:Number(e.id),sessionId:o}),i.filled++,s.length>=lp&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function dp(e){let t=()=>{for(let e of Mt())if(p(e))return e;return null},n=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=n.default??n[`module.exports`]??n;if(typeof r!=`object`||!r)return null;let i=r;return typeof i.onModelRequest==`function`?{onModelRequest:i.onModelRequest}:(O(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)},r=t();if(r===null)return;let i;try{i=await import(re(r).href)}catch(e){k(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${r}`),k(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),k(`[ezllm] 提示:模块写法与文件扩展名不匹配。CJS 内容(module.exports)请用 hook.cjs,ESM 内容(export default)请用 hook.mjs——这两个扩展名强制解析模式,不受任何 package.json 的 type 影响`);return}let a=n(i,r);a?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,a.onModelRequest),D(`[ezllm] 已加载用户钩子:${r}(onModelRequest)`))}function fp(e){return gt.port??e.port}async function pp(e,t,n={}){let r=new Sl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Dd())}});t.register(r),await dp(r);let i={current:r,port:r.expanded.port,rebuild(e){i.current.reload(e),i.port=i.current.expanded.port;let t=i.current.expanded.deployments.names.length,n=e.providers.filter(e=>e.enabled===!1).length,r=n>0?`(${String(n)} 个已停用)`:``;D(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new j},a=async e=>{let t=new URL(e.req.url),n=new Headers(e.req.raw.headers);if(!n.has(`x-forwarded-for`)){let t=e.env?.incoming?.socket?.remoteAddress??``;t!==``&&n.set(`x-forwarded-for`,t)}if(!n.has(`authorization`)&&n.has(`x-api-key`)){let e=n.get(`x-api-key`)??``;e!==``&&n.set(`authorization`,`Bearer ${e}`)}return i.current.build().fetch(new Request(t.toString(),{method:e.req.raw.method,headers:n,body:e.req.raw.body,duplex:`half`}))};return i.proxy.use(`/v1/models`,async(e,n)=>{let r=e.req.header(`authorization`)??(e.req.header(`x-api-key`)===null?``:`Bearer ${e.req.header(`x-api-key`)}`);if(!await t.authorize(r))return Response.json({error:{message:`Unauthorized: invalid api key`,type:`authentication_error`,code:`401`}},{status:401});await n()}),i.proxy.all(`/v1/*`,e=>a(e)),i.proxy.all(`/v1`,e=>a(e)),i.proxy.all(`/responses`,e=>a(e)),i.proxy.all(`/chat/completions`,e=>a(e)),i.proxy.all(`/messages`,e=>a(e)),i.proxy.all(`/messages/count_tokens`,e=>a(e)),i.proxy.all(`/models`,e=>a(e)),i.proxy.all(`/healthz`,e=>a(e)),i}var mp=64;function hp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>mp;){let e=r.keys().next().value;if(e===void 0)break;r.delete(e)}}function a(){return new Set(t.knownModelNames?t.knownModelNames():e.expanded.deployments.names)}e.plugin(e=>{e.addHook(`onFinish`,e=>{if(e.status!==200||e.ctx.model===null)return;let t=n(e.ctx.userAgent);t!==``&&i(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(a().has(t.requestedModel))return;let i=n(t.userAgent);if(i===``)return;let o=r.get(i);if(o!==void 0){if(!e.expanded.deployments.byName.has(o)){r.delete(i);return}return o}})})}var gp=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};async function _p(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var vp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,yp=`已启用管理台登录但未设置账号密码,请修改配置文件补充凭据或关闭登录开关`,bp=new j;function xp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}bp.post(`/login`,async e=>{let t=Bl();if(t.configBroken)return e.json({error:vp},503);if(t.required&&(t.username===``||t.password===``))return e.json({error:yp},503);if(!t.required)return e.json({error:`当前未启用管理台登录,管理台免登录访问(如需启用请在设置中打开登录开关)`},400);let n=await _p(e);if(n===null)return e.json({error:`请求体格式错误`},400);let{username:r,password:i}=n;return(r??``).trim()!==t.username||i!==t.password?e.json({error:`用户名或密码错误`},401):e.json({token:xp(t)})});async function Sp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Bl();if(!n.required)return await t();if(n.configBroken)return e.json({error:vp},401);if(n.username===``||n.password===``)return e.json({error:yp},503);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==xp(n))return e.json({error:`token 无效或已过期`},401);await t()}var Cp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function wp(e,t){return e instanceof Cp?(e.status>=500&&k(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(k(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e instanceof Error?e.message:e),t.json({ok:!1,error:e instanceof Error?e.message:String(e)},500))}function Tp(e){return async t=>{try{return await e(t)}catch(e){throw new Cp(500,e.message)}}}var Ep=8;function Dp(){let e=()=>{let e=El();if(e===null)throw new Cp(500,`配置文件不存在`);return e},t=new j;return t.onError(wp),t.use(`*`,async(e,t)=>{if(e.req.method===`GET`)return t();let n=e.req.header(`sec-fetch-site`);if(n===`same-origin`||n===`none`)return t();let r=e.req.header(`origin`);return r===void 0||r.toLowerCase()===new URL(e.req.url).origin.toLowerCase()?t():e.json({error:`已拒绝跨站写请求`},403)}),t.get(`/status`,e=>{let t=Vl(),n=!1;try{n=Fl()!==``}catch(e){if(!(e instanceof Tl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:Bl().required,version:zt(),buildSource:xt()})}),t.post(`/master-key`,async t=>{if(Vl().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await _p(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r;if(n.mode===`generate`)r=ae(32).toString(`base64url`);else if(n.mode===`custom`){if(r=(n.masterKey??``).trim(),r.length<Ep)return t.json({error:`主密钥至少 ${String(Ep)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return Ol(a),t.json({masterKey:r,...Wl(i,a)?{restartHint:Nl}:{}})}),t.post(`/finish`,async t=>{if(Vl().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await _p(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r=n.deployment;if(r!==`local`&&r!==`server`)return t.json({error:`deployment 必须是 local 或 server`},400);if(n.masterKey!==void 0&&typeof n.masterKey!=`string`)return t.json({error:`masterKey 必须是字符串`},400);let i=(n.masterKey??``).trim();if(i!==``&&i.length<Ep)return t.json({error:`主密钥至少 ${String(Ep)} 位`},400);if(r===`server`&&i===``&&Fl()===``)return t.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);if(n.loginEnabled!==void 0&&typeof n.loginEnabled!=`boolean`)return t.json({error:`loginEnabled 必须是布尔值`},400);if(n.username!==void 0&&typeof n.username!=`string`)return t.json({error:`username 必须是字符串`},400);if(n.password!==void 0&&typeof n.password!=`string`)return t.json({error:`password 必须是字符串`},400);let a=(n.username??``).trim(),o=n.password??``;if(n.loginEnabled===void 0&&a!==``!=(o!==``))return t.json({error:`用户名和密码需同时提供`},400);let s=typeof n.loginEnabled==`boolean`?n.loginEnabled:a!==``&&o!==``;if(s){if(a===``||o===``)return t.json({error:`启用管理台登录时必须填写用户名和密码(长度与字符不限)`},400)}else if(r===`server`)return t.json({error:`服务器部署必须启用管理台登录并设置账号密码,防止管理台被陌生人登录`},400);let c=e(),l={...c,...i===``?{}:{masterKey:i},setup:{completed:!0,deployment:r},allowLan:r===`server`,"web-ui":{...c[`web-ui`],"login-enabled":s,...s?{"login-account":{username:a,password:o}}:{}}};return Ol(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...Wl(c,l)?{restartHint:Nl}:{}})}),t}var Op=new Map,kp=1;function Ap(){return typeof process.send==`function`}function jp(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=kp++;return new Promise((i,a)=>{let o=setTimeout(()=>{Op.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);Op.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function Mp(e){typeof process.send==`function`&&(process.connected===!1?e():process.connected===!0&&process.once(`disconnect`,e)),process.on(`message`,e=>{let t=e;if(!t?.type||typeof t.id!=`number`)return;let n=Op.get(t.id);n&&(Op.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}function Np(e){let t=new j;return t.onError(wp),t.get(`/`,Tp(e=>{let t=El();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Tp(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);let r=n[`web-ui`],i=r?.[`login-enabled`];if(i!==void 0&&typeof i!=`boolean`)return t.json({error:`web-ui.login-enabled 必须是布尔值`},400);if(i===!0){let e=r[`login-account`],n=typeof e?.username==`string`?e.username.trim():``,i=typeof e?.password==`string`?e.password:``;if(n===``||i===``)return t.json({error:`启用管理台登录时必须设置用户名和密码(长度与字符不限)`},400)}try{Al(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let a=null;try{a=El()}catch{a=null}if(Ol(n),e.runtime.rebuild(kl(n)),Ap())try{await jp(`plugin.sync`)}catch(e){O(`[ezllm] 插件服务同步失败(配置已保存,重启主进程后会按配置恢复):${e instanceof Error?e.message:String(e)}`)}return t.json({message:`配置已保存并生效`,...Wl(a,n)?{restartHint:Nl}:{}})})),t}var Pp=`直接回复我 ok,不要思考不要解释`;function Fp(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function Ip(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Lp(e){for(let t of e.split(/\r?\n/)){if(!t.startsWith(`data:`))continue;let e=t.slice(5).trim();if(e!==``&&e!==`[DONE]`)try{let t=JSON.parse(e);if(typeof t==`object`&&t&&!Array.isArray(t))return t}catch{}}return null}async function Rp(e,t){if(!(e.headers.get(`content-type`)??``).toLowerCase().includes(`text/event-stream`)){let n=await e.text().catch(()=>``),r=null;try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(r=e)}catch{}return{streamed:!1,latencyMs:Date.now()-t,payload:r}}let n=e.body?.getReader();if(n===void 0)return{streamed:!0,latencyMs:Date.now()-t,payload:null};let r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;a!==void 0&&(i+=r.decode(a,{stream:!0}));let o=Lp(i);if(o!==null)return{streamed:!0,latencyMs:Date.now()-t,payload:o}}}finally{await n.cancel().catch(()=>void 0)}return{streamed:!0,latencyMs:Date.now()-t,payload:null}}function zp(e){let t=new j;t.onError(wp);let n=Ht(`test-results.json`),r=Ht(`models-cache.json`);function i(e,t=`openai`,n=!0){let r=e.replace(/\/+$/,``);return t===`anthropic`&&r.endsWith(`/anthropic`)&&(r=r.slice(0,-10)),`${Fp(r,n)}/models`}function a(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();if(e.includes(`authorization`)||e.includes(`api-key`)||e.includes(`token`)){let e=String(r);t[n]=e.length>8?`${e.slice(0,3)}****${e.slice(-4)}`:`****`}else t[n]=r}return t}async function o(e,t,n,r){return fetch(i(e,n,r),{headers:Ip(t,n),signal:AbortSignal.timeout(1e4)})}async function s(e,t){if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`});let n=await o(t.api_base,t.api_key,t.protocol??`openai`,t.autoV1??!0);return n.ok?await n.json():e.json({status:`error`,message:`HTTP ${String(n.status)}`})}function c(e){let{response:t,read:n,url:r,headers:i,payload:o}=e,s={method:`POST`,url:r,headers:a(i),body:o},c=n.payload??{};if(n.streamed){if(!t.ok)return{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}};let e=n.payload!==null;return{status:e?`ok`:`error`,message:e?`流式首帧正常`:`流式响应未收到数据帧`,latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}}}return t.ok&&(c.choices!==void 0||c.output!==void 0||c.content!==void 0)?{status:`ok`,message:`${String(c.usage?.completion_tokens??c.usage?.output_tokens??0)} tokens`,latency:n.latencyMs,request:s,response:{status:t.status,body:c}}:{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:c}}}function l(e,t){let n=e.error,r=typeof n==`object`&&n&&`message`in n?String(n.message):typeof n==`string`?n:null;if(r!==null)return u(r);if(typeof e.msg==`string`&&e.msg.trim()!==``){let t=e.code===void 0||e.code===null?``:` (${String(e.code)})`;return u(`${e.msg.trim()}${t}`)}return u(`HTTP ${String(t)}`)}function u(e){let t=e;for(let[e,n]of[[/Weekly usage limit reached/i,`每周使用限额已达上限`],[/Resets in (\d+) day/i,`$1 天后重置`],[/RateLimitError:?\s*OpenAIException\s*-?\s*/gi,``],[/RateLimitError/g,`频率限制`],[/Rate limit/gi,`请求频率超限`],[/Invalid.*api.?key/i,`API Key 无效`],[/Unauthorized/i,`认证失败`],[/Not found/i,`模型或端点不存在`],[/Timeout/i,`请求超时`],[/Connection refused/i,`连接被拒绝`],[/ECONNREFUSED/i,`连接被拒绝`],[/ENOTFOUND/i,`域名无法解析`],[/model.*not.*found/i,`模型不存在`],[/context length exceeded/i,`上下文长度超限`],[/maximum context length/i,`超过最大上下文长度`],[/overloaded/i,`服务过载`],[/internal server error/i,`服务器内部错误`],[/bad gateway/i,`网关错误`],[/OpenAIException\s*-?\s*/i,``],[/To continue using[\s\S]*$/i,``],[/Received Model Group[\s\S]*$/i,``],[/Available Model Group[\s\S]*$/i,``],[/HTTP (\d+)/,`HTTP 错误 $1`]])t=t.replace(e,n);return t=t.replace(/\s+/g,` `).replace(/^[.:;\s-]+|[.:;\s-]+$/g,``).trim(),t||=e,t.length>120&&(t=t.substring(0,120)+`...`),t}t.get(`/results`,Tp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Tp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Tp(async e=>{let{keyId:t,models:n}=await e.req.json();return!t||!Array.isArray(n)?e.json({error:`缺少必要参数: keyId, models`},400):(r.set(t,n),e.json({message:`模型缓存已更新`,keyId:t,count:n.length}))})),t.post(`/`,async e=>{try{let t=await s(e,await e.req.json());return t instanceof Response?t:e.json({status:`ok`,models:t.data?.length||0,protocol:`openai`})}catch(t){return e.json({status:`error`,message:t.message})}}),t.post(`/fetch-models`,async e=>{try{let t=await e.req.json(),n=await s(e,t);if(n instanceof Response)return n;let i=(n.data||[]).map(e=>e.id||e.name).filter(e=>!!e);if(t.keyId){let e=r.get(t.keyId)??[],n=[...new Set([...e,...i])];r.set(t.keyId,n)}return e.json({status:`ok`,models:i})}catch(t){return e.json({status:`error`,message:t.message})}});function d(e,t){return t===`anthropic`?{model:e,messages:[{role:`user`,content:Pp}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:Pp,stream:!0}:{model:e,messages:[{role:`user`,content:Pp}],stream:!0}}async function f(e){let t=e.protocol||`openai`,n=e.autoV1??!0,r=e.api_base.replace(/\/+$/,``);if(!r)throw Error(`api_base 不能为空`);let i={"Content-Type":`application/json`,...Ip(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Fp(r,n)}${a}`,s=d(e.model,t),l=Date.now(),u=await fetch(o,{method:`POST`,headers:i,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)});return c({response:u,read:await Rp(u,l),url:o,headers:i,payload:s})}function p(e){let t=El();for(let n of t?.providers??[]){let t=n.models?.find(t=>t?.modelName===e);if(t)return t.customLlmProvider??n.customLlmProvider??`openai`}return`openai`}async function m(t,n){let r=Fl(),i=fp(e),a=`http://127.0.0.1:${String(i)}`,o={"Content-Type":`application/json`};r&&(o.Authorization=`Bearer ${r}`);let s=`${a}${n===`anthropic`?`/v1/messages`:n===`openai-responses`?`/v1/responses`:`/v1/chat/completions`}`,l=d(t,n),u=Date.now(),f;try{f=await fetch(s,{method:`POST`,headers:o,body:JSON.stringify(l),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e;throw k(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}return c({response:f,read:await Rp(f,u),url:s,headers:o,payload:l})}return t.post(`/model`,async e=>{try{let t=await e.req.json(),r=t.model;if(!r)return e.json({status:`error`,message:`缺少 model 参数`},400);if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`},400);let i;try{i=await f({model:r,api_base:t.api_base,api_key:t.api_key,protocol:t.protocol,autoV1:t.autoV1})}catch(e){i={status:`error`,message:u(e.message),latency:0}}return n.set(r,{...i,time:new Date().toISOString()}),e.json(i)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t.post(`/proxy`,async e=>{try{let t=(await e.req.json()).model;if(!t)return e.json({status:`error`,message:`缺少 model 参数`},400);let r=await m(t,p(t));return n.set(t,{...r,time:new Date().toISOString()}),e.json(r)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t}var Bp=Du(`latency_probes`,{id:H().primaryKey({autoIncrement:!0}),model:V().notNull(),time:H().notNull(),latency_ms:H().notNull(),ok:H().notNull(),error:V()},[Eu(`idx_latency_probes_model_time`).on(`model`,`time`),Eu(`idx_latency_probes_time`).on(`time`)]),Vp=2592e6,Hp=null;function Up(){let e=Hp;if(e!==null)return e;let t=ld(`latency`);return t.createTables([Bp]),Hp=t,t}function Wp(){return Up().native}function Gp(e){if(e.length!==0)try{Up().insert(Bp).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){k(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function Kp(){let e=Date.now()-Vp;return Up().select(Bp).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(W.gt(Bp.time,e)).orderBy(W.asc(Bp.time)).all().map(e=>({model:e.model,time:Number(e.time),latencyMs:Number(e.latency_ms),ok:e.ok===1,error:e.error??void 0}))}function qp(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=Up().select(Bp).columns([`time`,`latency_ms`,`ok`]).where(W.and(W.eq(Bp.model,e),W.gt(Bp.time,a),W.lte(Bp.time,r))).all();if(o.length===0)return[];let s=e=>{let n=new Date(e);return t===`hour`?new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()).getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()},c=[];for(let e=s(r);e>=s(a);e-=i)c.unshift(e);let l=new Map;for(let e of c)l.set(e,{total:0,success:0,latencySum:0});for(let e of o){let t=l.get(s(Number(e.time)));t&&(t.total+=1,e.ok===1&&(t.success+=1,t.latencySum+=Number(e.latency_ms)))}return c.map(e=>{let t=l.get(e);return{bucketStart:e,total:t.total,success:t.success,failed:t.total-t.success,successRate:t.total===0?null:Math.round(t.success/t.total*1e3)/10,avgLatencyMs:t.success===0?null:Math.round(t.latencySum/t.success)}})}function Jp(){let e=Up().select(Bp).columns({t:W.max(Bp.time)}).get();return e?.t==null?null:Number(e.t)}function Yp(e){try{let t=Date.now()-e;Up().delete(Bp).where(W.lte(Bp.time,t)).run()}catch(e){k(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Xp=3e4,Zp=4,Qp=!1;function $p(){return Qp}function em(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function tm(e){let t=async e=>{let t=Fp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Ip(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Pp}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Pp,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Pp}],max_tokens:1,stream:!0});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Xp)});if(!t.ok){let n=await t.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,120)).catch(()=>``);return{model:e.name,time:a,latencyMs:0,ok:!1,error:n?`HTTP ${String(t.status)}: ${n}`:`HTTP ${String(t.status)}`}}let o=await Rp(t,a);return o.streamed&&o.payload===null?{model:e.name,time:a,latencyMs:0,ok:!1,error:`HTTP ${String(t.status)}: 流式响应未收到数据帧`}:{model:e.name,time:a,latencyMs:o.latencyMs,ok:!0}}catch(t){return{model:e.name,time:a,latencyMs:0,ok:!1,error:t.message}}},n=async e=>{let n=[],r=0,i=Array.from({length:Math.max(1,Math.min(Zp,e.length))},async()=>{for(;;){let i=r++;if(i>=e.length)return;n.push(await t(e[i]))}});return await Promise.all(i),n};if(Qp)return!1;Qp=!0;try{let t=await n(em(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));Gp(t),Yp(Vp);let r=t.filter(e=>e.ok).length;return D(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(r)}),数据已入库 latency.db`),!0}catch(e){return k(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Qp=!1}}function nm(e){return em(e).length}var rm=[{key:`avg10m`,ms:6e5},{key:`avg30m`,ms:18e5},{key:`avg1h`,ms:36e5},{key:`avg2h`,ms:72e5},{key:`avg5h`,ms:18e6},{key:`avg8h`,ms:288e5},{key:`avg12h`,ms:432e5},{key:`avg24h`,ms:864e5}];function im(e,t,n){return n.map(n=>{let r=e.filter(e=>e.model===n),i={model:n,avg10m:null,avg30m:null,avg1h:null,avg2h:null,avg5h:null,avg8h:null,avg12h:null,avg24h:null,lastTestAt:null,lastOk:null,lastLatencyMs:null,lastError:null},a=r.reduce((e,t)=>e===null||t.time>e.time?t:e,null);a!==null&&(i.lastTestAt=a.time,i.lastOk=a.ok,a.ok&&(i.lastLatencyMs=a.latencyMs),a.ok||(i.lastError=a.error??null));for(let{key:e,ms:n}of rm){let a=r.filter(e=>e.ok&&e.time>t-n&&e.time<=t);a.length!==0&&(i[e]=Math.round(a.reduce((e,t)=>e+t.latencyMs,0)/a.length))}return i})}function am(e){let t=new j;return t.get(`/history`,t=>{let n=Kp(),r=Date.now();return t.json({running:$p(),lastRunAt:Jp(),models:im(n,r,e.current.expanded.deployments.names)})}),t.get(`/trend`,e=>{let t=e.req.query(`model`);if(!t)return e.json({ok:!1,error:`缺少 model 参数`},400);let n=e.req.query(`granularity`)===`day`?`day`:`hour`,r=qp(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>$p()?t.json({ok:!1,error:`测试进行中,请稍候`},409):nm(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(tm(e),t.json({ok:!0,running:!0}))),t}function om(){let e=t=>{let n=0;if(!p(t))return 0;for(let r of _(t)){let i=c(t,r),a;try{a=x(i)}catch{continue}a.isDirectory()?n+=e(i):n+=a.size}return n},t=()=>Math.round(e(wt())/1024/1024*10)/10,n=new j;return n.onError(wp),n.get(`/`,Tp(e=>{let n=e.req.query(),r=lf({startDate:n.startDate,endDate:n.endDate,model:n.model});return e.json({...r,logStorageMB:t()})})),n}function J(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function X(e){return typeof e==`string`?e:null}function sm(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function cm(e,t){let n=sm(e,t);return n===void 0?void 0:e[n]}function lm(e,t){if(e===void 0)return null;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}return null}function um(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function dm(e){let t=(e,t)=>{let n=e[t];if(n!==`"`&&n!==`'`&&n!=="`")return null;let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t===`\\`){i+=e[r+1]??``,r+=2;continue}if(t===n)return{value:i,end:r+1};i+=t,r+=1}return null},n=(e,n)=>{let r=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n},i=(e,n)=>{if(e[n]!==`{`)return null;let r=0,i=n;for(;i<e.length;){let a=e[i];if(a===`"`||a===`'`||a==="`"){let n=t(e,i);if(n===null)return null;i=n.end;continue}if(a===`{`)r+=1;else if(a===`}`&&(--r,r===0))return{raw:e.slice(n,i+1),end:i+1};i+=1}return null},a=e=>{let n=e=>{let n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`||i===`'`||i==="`"){let i=t(e,r);if(i===null){n+=e.slice(r);break}n+=e.slice(r,i.end),r=i.end;continue}if(i===`,`){let t=r+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;let n=e[t];if(n===`}`||n===`]`){r+=1;continue}}n+=i,r+=1}return n},r;try{r=JSON.parse(n(e))}catch{return null}let i=J(r);if(i===null)return null;let a={},o=J(i.headers);if(o!==null)for(let[e,t]of Object.entries(o))typeof t==`string`&&(a[e]=t);return{method:typeof i.method==`string`?i.method.toUpperCase():`GET`,headers:a,body:typeof i.body==`string`?i.body:null}},o=r(e,n),s=t(e,o);if(s===null)return null;let c=s.value,l=r(e,s.end);if(e[l]!==`,`)return{url:c,method:`GET`,headers:{},body:null};let u=i(e,r(e,l+1));if(u===null)return{url:c,method:`GET`,headers:{},body:null};let d=a(u.raw);if(d===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:c,method:d.method,headers:d.headers,body:d.body}},r=e=>{let t=new Map;for(let n of e){let e=sm(n.headers,`cookie`);if(e===void 0)continue;let r=um(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(sm(e.headers,`cookie`)!==void 0)return e;let n=um(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})},i=[],a=/\bfetch\s*\(/g,o;for(;(o=a.exec(e))!==null;){let t=n(e,o.index+o[0].length);t!==null&&i.push(t)}return r(i)}function fm(e){return e.some(e=>sm(e.headers,`cookie`)!==void 0)}var pm=0xe8d4a51000,mm=3e4;async function hm(e,t){let n=e=>{let t={...e};for(let e of Object.keys(t)){let n=e.toLowerCase();(n===`content-length`||n===`host`||n===`connection`)&&delete t[e]}return t},r=await fetch(e,{...t,headers:n(t.headers),signal:AbortSignal.timeout(mm)});if(!r.ok){let e=await r.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(r.status)}${e===``?``:`: ${e}`}`)}let i=J(await r.json());if(i===null)throw Error(`响应不是 JSON 对象`);return i}function gm(e){return e===null||e<=0?null:Math.round(e<pm?e*1e3:e)}function _m(e){return Math.round(e*100)/100}function vm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function ym(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function bm(e,t){let n=J(e);if(n===null)return null;let r=Y(n[t.used])??0,i=Y(n[t.cap]),a=t.exceeded!==void 0&&n[t.exceeded]===!0||i!==null&&r>=i;return{used:r,cap:i,resetAt:t.resetAt===void 0?null:gm(Y(n[t.resetAt])),exceeded:a}}var xm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await hm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await hm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},Sm=`https://api.commandcode.ai`,Cm=`/alpha/billing/credits`,wm=`/alpha/usage/summary`,Tm=`/alpha/billing/subscriptions`,Em={"individual-pro-v1":80,"individual-goat":70},Dm=/^user_[A-Za-z0-9_-]+$/,Om={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function km(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:vm(t)}]}function Am(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var jm=class extends xm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=Dm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!Dm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(Sm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(wm),this.get(Cm),this.get(Tm).catch(()=>null)]),r=J(t.windowLimits),i=J(t.credits),a=n===null?null:J(n.data),o=a===null?null:X(a.planId),s=o===null?null:Em[o]??null,c=i===null?null:Y(i.monthlyCredits),l=s===null||c===null?null:{used:_m(Math.max(0,s-c)),cap:s,resetAt:a===null?null:Am(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:bm(r.fiveHour,Om),weekly:r===null?null:bm(r.weekly,Om),monthly:l,totalTokens:Y(e.totalTokens),totalRuns:Y(e.totalCount),voucherBalance:null,balance:null,extraStats:km(l,c)}}},Mm=`https://api.deepseek.com`,Nm=`/user/balance`,Pm=`余额不足,无法调用 API`;function Fm(e){let t=Y(e);if(t!==null)return t;let n=X(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Im(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function Lm(e){let t=[];if(!Array.isArray(e))return t;let n=new Set;for(let r of e){let e=J(r);if(e===null)continue;let i=X(e.currency);if(i===null||i.trim()===``)continue;let a=i.trim();if(n.has(a))continue;let o=Fm(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:Fm(e.granted_balance),toppedUp:Fm(e.topped_up_balance)}))}return t}function Rm(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>e.currency===`CNY`)??[...e].sort((e,t)=>e.currency.localeCompare(t.currency))[0]}var zm=class extends xm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(Mm,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Nm),t=Rm(Lm(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=Im(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${vm(_m(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${vm(_m(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:Pm}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:_m(t.total),extraStats:r.length===0?null:r}}},Bm=`https://amr-api.open-design.ai`,Vm=`ezllm-quota`,Hm=86400,Um=691200;function Wm(e){return{accept:`application/json`,"user-agent":Vm,authorization:`Bearer ${e}`}}function Gm(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}function Km(e){let t=Y(e);if(t!==null)return t;let n=X(e);if(n===null||n.trim()===``)return null;let r=Number(n);return Number.isFinite(r)?r:null}function qm(e){let t=Gm(e);if(t!==null)return t;let n=Km(e);return n===null?null:gm(n)}function Jm(e){let t=J(e);if(t===null)return null;let n=Km(t.usedCredits),r=Km(t.limitCredits);return n===null||r===null?null:{used:n,cap:r,resetAt:qm(t.resetsAt),exceeded:n>=r}}function Ym(e){let t={fiveHour:null,weekly:null,monthly:null},n=e?.windows;if(!Array.isArray(n))return t;for(let e of n){let n=Jm(e);if(n===null)continue;let r=Km(J(e)?.durationSeconds)??0;r>0&&r<Hm?t.fiveHour??=n:r>=Hm&&r<Um?t.weekly??=n:r>=Um&&(t.monthly??=n)}return t}function Xm(e){if(e===null||e.trim()===``)return null;let t=e.trim();return`Design Plan ${t[0].toUpperCase()}${t.slice(1)}`}var Zm=class extends xm{static vendorId=`opendesign`;static vendorLabel=`Open Design`;static apiHosts=[`amr-link.open-design.ai`];static credentialSource=`deviceAuth`;static authKey=`opendesign`;static authCredentialField=`control`;constructor(e){let t=e.trim();if(t===``)throw Error(`授权凭据为空,请重新发起「登录授权」`);super(Bm,Wm(t))}async fetchQuota(){let e=await this.get(`/api/v1/workspaces/current`),t=X(e.activeWorkspaceId)??X(e.workspaceId);if(t===null||t===``)throw Error(`授权账号没有可用工作区(workspaces/current 未返回 activeWorkspaceId)`);let n=await this.get(`/api/v1/workspaces/${encodeURIComponent(t)}/billing/preflight`),r=await this.get(`/api/v1/billing/summary`).catch(()=>null),i=J(n.codingPlan),a=Ym(i),o=Km(n.balanceUsd)??Km(r?.balanceUsd??null),s=X(r?.membershipTier??null)??X(e.personalMembershipTier??null),c=[],l=Xm(s);return l!==null&&c.push({label:`套餐`,value:l}),i!==null&&i.eligible===!1&&c.push({label:`套餐额度`,value:`未生效(走钱包余额)`}),o!==null&&c.push({label:`钱包余额`,value:`$${o.toFixed(2)}`}),{fiveHour:a.fiveHour,weekly:a.weekly,monthly:a.monthly,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,extraStats:c.length>0?c:null}}},Qm=[`127.0.0.1`,`localhost`,`[::1]`],$m=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function eh(e){let t;try{t=new URL(e)}catch{return null}if(!Qm.some(e=>e===t.hostname.toLowerCase()))return null;let n=$m.exec(t.pathname);if(n===null)return null;let r;try{r=decodeURIComponent(n[1])}catch{return null}return r.trim()===``?null:{origin:t.origin,providerId:r}}function th(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){let e=J(n);if(e===null)continue;let r=X(e.name),i=X(e.display);r!==null&&r.trim()!==``&&i!==null&&i.trim()!==``&&t.push({name:r,usedPercent:Y(e.used)??0,display:i,amount:Y(e.amount),limit:Y(e.limit),unit:X(e.unit)})}return t}var nh=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=Qm;#e;#t;constructor(e){let t=eh(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await hm(`${this.#e}/p/${encodeURIComponent(this.#t)}/usage`,{method:`GET`,headers:{accept:`application/json`}}),t=X(e.error);if(t!==null&&t.trim()!==``)throw Error(t);let n=X(e.plan);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,windows:th(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},rh=`/api/user/self`,ih=`/api/user/subscription/current_cycle`,ah={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function oh(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=J(e);if(n!==null&&n.key===t)return n}return null}function sh(e){return e===null||Y(e.total_count)===null?null:bm(e,ah)}function ch(e){let t=J(e.account_info),n=t===null?null:t.vouchers;if(!Array.isArray(n))return null;let r=0,i=!1;for(let e of n){let t=J(e),n=t===null?null:Y(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function lh(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var uh=class extends xm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=dm(e),n=lh(t,rh),r=lh(t,ih);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>cm(e.headers,`authorization`)!==void 0))throw Error(`复制的请求里没有 authorization 头(登录凭据在它里面)——请从已登录的 senseaudio.cn 页面重新复制 fetch 调用`);let i=n??r;super(new URL(i.url).origin,i.headers)}async fetchQuota(){let[e,t]=await Promise.all([this.get(rh),this.get(ih).catch(()=>null)]),n=sh(oh(e,`credit_5h_limit`)),r=sh(oh(e,`credit_7d_limit`)),i=sh(oh(e,`credit_30d_limit`));if(i===null&&t!==null){let e=Y(t.plan_points),n=Y(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:gm(Y(t.plan_points_reset_at)),exceeded:e-n>=e})}if(n===null&&r===null&&i===null)throw Error(`上游未返回任何额度窗口(该账号可能尚未登录或未订阅套餐)`);return{fiveHour:n,weekly:r,monthly:i,totalTokens:null,totalRuns:null,voucherBalance:ch(e),balance:null}}},dh=`GetAgentPlanAFPUsage`,fh=`GetAgentPlanUsageDetails`,ph=`console.volcengine.com`,mh=`2024-01-01`,hh=`cn-beijing`,gh={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function _h(e){return e.find(e=>e.url.includes(dh))}function vh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??hh}/${mh}`:t}function yh(e){return e.find(e=>um(e.url)===ph)}var bh=class extends xm{static vendorId=`volc-ark`;static vendorLabel=`火山方舟`;static hosts=[`console.volcengine.com`];static apiHosts=[`ark.cn-beijing.volces.com`];static credentialSource=`fetchText`;#e;#t;constructor(e){let t=dm(e),n=_h(t)??yh(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!fm(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==ph)throw Error(`非方舟控制台域`);r=e.origin,i=vh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=lm(cm(n.headers,`cookie`),`csrfToken`)??cm(n.headers,`x-csrf-token`)??null;if(a===null)throw Error(`缺少 CSRF 凭据:请求头需含 x-csrf-token,或 Cookie 里需有 csrfToken (两者都来自已登录的控制台会话,请在登录页面上重新复制)`);super(r,{...n.headers,"x-csrf-token":a}),this.#e=`${i}/${dh}`,this.#t=`${i}/${fh}`}envelope(e){let t=J(e.ResponseMetadata),n=t===null?null:J(t.Error);if(n!==null){let e=X(n.Code)??`Unknown`,t=X(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=J((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=bm(e.AFPFiveHour,gh),n=bm(e.AFPWeekly,gh),r=bm(e.AFPMonthly,gh);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=J(e.AFPMonthly),a=i===null?null:Y(i.SubscribeTime);return{fiveHour:t,weekly:n,monthly:r,totalTokens:await this.#n(a),totalRuns:null,voucherBalance:null,balance:null}}async#n(e){let t=Date.now(),n=e!==null&&e>0?e:t-2592e6;try{let e=J((await this.post(this.#t,{Filter:{StartTime:ym(new Date(n)),EndTime:ym(new Date(t)),ObjectType:1,BillingType:[`WithinPlan`]},QueryInterval:`Day`})).Result),r=e===null?null:e.Details;return Array.isArray(r)?r.reduce((e,t)=>{let n=J(t);return n===null||n.Unit!==`Tokens`?e:e+(Y(n.Usage)??0)},0):null}catch{return null}}},xh=`/api/biz/account/query-customer-account-report`,Sh=`/api/finance/expenseBill/expenseBillListByDay`,Ch=200,wh=`bigmodel_token_production`;function Th(e){let t=lm(cm(e.headers,`cookie`),wh);if(t!==null&&t.trim()!==``)return t.trim();let n=cm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var Eh=class extends xm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=dm(e);if(t.length===0)throw Error(`未找到可用的智谱请求:请在已登录的 bigmodel.cn(财务中心 / 资源包 / 任意控制台页面)里复制任意请求的 fetch 调用粘贴进来,额度端点会自动换算`);let n=t[0],r;try{r=new URL(n.url).origin}catch{throw Error(`粘贴的请求 URL 不是绝对地址,无法换算出额度接口——请粘贴浏览器里完整的 fetch(https://…)`)}let i=Th(n);if(i===null)throw Error(`复制的请求里没有登录凭据(需要 Cookie 里的 bigmodel_token_production,或显式的 authorization 头)——请从已登录的 bigmodel.cn 页面用「以 fetch (Node.js) 格式复制」重新复制`);let a={...n.headers,authorization:i.toLowerCase().startsWith(`bearer `)?i:`Bearer ${i}`};super(r,a)}envelope(e){let t=Y(e.code);if(t!==200){let n=X(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=ym(e).slice(0,7),n=ym(new Date(e.getFullYear(),e.getMonth(),e.getDate()-(e.getDay()+6)%7));try{let e=1,r=0,i=0,a=1/0,o=[];for(;o.length<a;){let s=await this.get(Sh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(Ch)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=Y(l)??o.length,o=o.concat(c);for(let e of c){let t=J(e);if(t===null)continue;let a=Y(t.originalAmount),o=X(t.billingDate);a!==null&&o!==null&&(r+=a,o>=n&&(i+=a))}if(e+=1,c.length===0)break}return{weekly:{used:i,cap:null,resetAt:null,exceeded:!1},monthly:{used:r,cap:null,resetAt:null,exceeded:!1}}}catch{return null}}async fetchQuota(){let[e,t]=await Promise.all([this.get(xh),this.#e()]),n=J(e.data),r=(n===null?null:Y(n.availableBalance))??(n===null?null:Y(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=Y(n.totalSpendAmount);return{fiveHour:null,weekly:t?.weekly??null,monthly:t?.monthly??null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:r,totalCost:i,totalCostCurrency:i===null?null:`CNY`,extraStats:Dh(n)}}};function Dh(e){let t=e=>`${vm(e)} 元`,n=[],r=Y(e.rechargeAmount);r!==null&&n.push({label:`累计充值`,value:t(r)});let i=Y(e.giveAmount);i!==null&&n.push({label:`赠送金额`,value:t(i)});let a=Y(e.creditBalance);return a===null?e.creditStatus===`NOT_OPEN`&&n.push({label:`信用余额`,value:`未开通`}):n.push({label:`信用余额`,value:t(a)}),n}var Oh=[jm,zm,Zm,uh,bh,Eh,nh];function kh(){return Oh}function Ah(e){if(e===void 0)return null;let t=um(e);if(t===``)return null;for(let e of Oh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function jh(e,t){let n=Ah(t);if(n===null)throw Error(`该供应商未支持用 API key 自动查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`该供应商的 apiKey 为空,无法查询额度——请在供应商配置里填入 API key`);if(n.apiKeyPattern?.test(r)===!1)throw Error(`配置里的 apiKey 不是 ${n.vendorLabel} 的 API key 形态——请检查该供应商配置的 apiKey 字段`);return{vendorId:n.vendorId,vendor:new n(r)}}function Mh(e){if(e===void 0)return null;let t=um(e);if(t===``)return null;for(let e of Oh)if(e.credentialSource===`deviceAuth`&&e.apiHosts?.some(e=>e===t))return e;return null}function Nh(e,t){let n=Mh(t);if(n===null)throw Error(`该供应商未支持授权登录查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);return{vendorId:n.vendorId,vendor:new n(r)}}function Ph(e){return e===void 0||eh(e)===null?null:nh}function Fh(e){if(Ph(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:nh.vendorId,vendor:new nh(e)}}function Ih(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of dm(e)){let e=um(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of Oh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=um(t);if(e!==``){for(let t of Oh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of Oh)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>i.has(e))===!0)return e;return null};if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let r=n(e,t);if(r===null){let e=Oh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=Oh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=Ah(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var Lh=20,Rh=2e3,zh=1e4,Bh=3e4;function Vh(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Hh(e){return e instanceof Error?e.message:String(e)}var Uh=class extends Error{constructor(){super(`凭据文件内容异常(非合法 JSON 或形状不符),已拒绝写入以免覆盖现有凭据;请修复或备份后删除该文件`),this.name=`AuthFileCorruptError`}};function Wh(e){let t;try{t=g(e,`utf-8`)}catch{throw new Uh}let n;try{n=JSON.parse(t)}catch{throw new Uh}if(typeof n!=`object`||!n||Array.isArray(n))throw new Uh;let r={};for(let[e,t]of Object.entries(n)){if(typeof t!=`object`||!t||Array.isArray(t))throw new Uh;r[e]=t}return r}function Gh(e){try{let t=JSON.parse(g(e,`utf-8`));if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))typeof r==`object`&&r&&!Array.isArray(r)&&(n[e]=r);return n}catch{return{}}}function Kh(e,t){let n=`${e}.${`${process.pid}.${ae(6).toString(`hex`)}`}.tmp`;try{m(s(e),{recursive:!0}),C(n,`${JSON.stringify(t,null,2)}\n`,{encoding:`utf-8`,mode:384}),v(n,e)}finally{try{y(n,{force:!0})}catch{}}}function qh(e,t){return p(e)?e:t.find(e=>p(e))??null}var Jh=class{#e;#t;#n;#r=null;#i=null;#a=-1;#o=!1;#s=0;constructor(e){this.#e=e.file,this.#t=e.legacyFiles??[],this.#n=e.log,this.#l()}get path(){return this.#e}read(){this.#o&&Date.now()>=this.#s&&this.#l();let e=qh(this.#e,this.#t);if(e===null)return{};try{let t=x(e).mtimeMs;if(this.#r!==null&&this.#i===e&&this.#a===t)return{...this.#r};let n=Gh(e);return this.#r=n,this.#i=e,this.#a=t,{...n}}catch{return{}}}invalidate(){this.#r=null,this.#i=null,this.#a=-1}mutate(e){return this.#d(()=>{let t=e(this.#c());return t===null?null:(Kh(this.#e,t),this.#u(),this.#r=t,this.#i=this.#e,this.#a=x(this.#e).mtimeMs,{...t})})}#c(){let e=qh(this.#e,this.#t);return e===null?{}:Wh(e)}#l(){let e=this.#t.find(e=>p(e));if(e===void 0){this.#o=!1;return}try{let t=this.#d(()=>p(e)?p(this.#e)?(y(e,{force:!0}),this.#n?.(`[auth] 已清理旧凭据文件:${e}(新文件已存在)`),!0):(v(e,this.#e),this.#n?.(`[auth] 凭据文件已迁移:${e} → ${this.#e}`),!0):!0);this.#o=!t,this.#s=t?0:Date.now()+Bh}catch(e){this.#o=!0,this.#s=Date.now()+Bh,this.#n?.(`[auth] 旧凭据文件处理失败(继续只读旧文件,${String(Bh/1e3)}s 后重试):${Hh(e)}`)}}#u(){for(let e of this.#t)if(p(e))try{y(e,{force:!0}),this.#n?.(`[auth] 已清理旧凭据文件:${e}`)}catch{}this.#o=!1}#d(e){let t=`${this.#e}.lock`,n=`${process.pid}.${ae(8).toString(`hex`)}`;m(s(t),{recursive:!0});let r=Date.now()+Rh;for(;;)try{m(t),C(c(t,`owner`),n,`utf-8`);break}catch(e){if(e.code!==`EEXIST`)throw e;try{if(Date.now()-x(t).mtimeMs>zh&&this.#m(t))continue}catch{}if(Date.now()>r)throw Error(`获取凭据文件锁超时:${o(t)}`);Vh(Lh)}try{return e()}finally{this.#p(t,n)}}#f(e){try{return g(c(e,`owner`),`utf-8`)}catch{return null}}#p(e,t){try{if(this.#f(e)!==t)return;y(e,{recursive:!0,force:!0})}catch{}}#m(e){let t=this.#f(e),n=`${e}.stale.${ae(4).toString(`hex`)}`;try{v(e,n)}catch{return!1}let r=this.#f(n);if(t!==null&&r!==null&&t!==r){try{v(n,e)}catch{}return!1}try{y(n,{recursive:!0,force:!0})}catch{}return!0}},Yh=new ge;function Xh(e,t,n){return Yh.run({providerId:e,generation:t},n)}var Zh=3e5,Qh=864e5,$h=15e3,eg=3e4,tg=new class{renewing=new Map;failed=new Map;clear(e){let t=`${e}\0`;for(let e of[...this.renewing.keys()])e.startsWith(t)&&this.renewing.delete(e);for(let e of[...this.failed.keys()])e.startsWith(t)&&this.failed.delete(e)}};function ng(e){let t=`${String(e?.refresh??``)}\0${String(e?.access??``)}`;return ie(`sha256`).update(t).digest(`hex`).slice(0,16)}function rg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.min(e,Qh):Zh}function ig(e,t){if(t.type!==`oauth`)return 0;let n=Number(t.expires);return Number.isFinite(n)&&n>0?Math.max(1,n-e):0}var ag=class{#e;constructor(e){this.#e=e}clear(e){(this.#e.registry??tg).clear(e)}async ensureFresh(e){let t=this.#e.get(e),n=this.#e.refreshOf(e);if(t===void 0||n===void 0)return;let r=this.#n(),i=ig(rg(this.#e.leadOf(e)),t);if(!i||r<i)return;let a=this.#r(),o=`${e}\0${ng(t)}`,s=a.failed.get(o);if(s!==void 0){if(r-s<eg)return;a.failed.delete(o)}let c=a.renewing.get(o);c===void 0&&(c=this.#t(e,t,n,o).finally(()=>a.renewing.delete(o)),a.renewing.set(o,c));let l;await Promise.race([c,new Promise(e=>{l=setTimeout(e,$h)})]),clearTimeout(l)}async#t(e,t,n,r){let i=this.#r(),a=this.#e.generation(e);try{let o=await Xh(e,a,()=>n({...t}));if(typeof o!=`object`||!o||Array.isArray(o)){i.failed.delete(r);return}let s=this.#e.get(e);if(s===void 0||this.#e.generation(e)!==a){i.failed.delete(r),this.#e.log?.(`[auth] 已丢弃过期的续期结果:${e}`);return}if(ng(s)!==ng(t)){i.failed.delete(r),this.#e.log?.(`[auth] 凭据已由供应商续期:${e}`);return}if(!this.#e.save(e,{...t,...o},{generation:a})){i.failed.delete(r),this.#e.log?.(`[auth] 已丢弃过期的续期结果:${e}`);return}i.failed.delete(r),this.#e.log?.(`[auth] 凭据已续期:${e}`)}catch(t){i.failed.set(r,this.#n()),this.#e.log?.(`[auth] 凭据续期失败:${e}(${t instanceof Error?t.message:String(t)})`)}}#n(){return this.#e.now?.()??Date.now()}#r(){return this.#e.registry??tg}},og=class extends Error{status;constructor(e,t){super(t),this.name=`AuthError`,this.status=e}},sg=class extends Error{constructor(e){super(e),this.name=`AuthFailure`}},cg=2e3,lg=6e5;function ug(e){return e instanceof Error?e.message:String(e)}function dg(e){return`auth`in e}function fg(e,t){let n=e.when;if(n!==void 0){let e=typeof n.key==`string`?t[n.key]:void 0;if(e===void 0)return!1;let r=e===n.value;if(n.op===`eq`?!r:r)return!1}return!(typeof e.condition==`function`&&!e.condition(t))}function pg(e,t){let n=[];for(let r of e.prompts??[])typeof r.key!=`string`||r.key===``||r.key in t||fg(r,t)&&n.push(r);return n}function mg(e){return e.map(e=>({type:typeof e.type==`string`?e.type:`text`,key:typeof e.key==`string`?e.key:``,message:typeof e.message==`string`?e.message:``,placeholder:typeof e.placeholder==`string`?e.placeholder:``,options:Array.isArray(e.options)?e.options:[]}))}function hg(e){for(let t of[`accountId`,`email`,`name`,`account`,`uid`]){let n=e[t];if(typeof n==`string`&&n.trim()!==``)return n}return null}function gg(e,t){return t==null||t===``||typeof e.accountId==`string`&&e.accountId!==``?e:{...e,accountId:t}}var _g=class{#e;#t;#n;#r;#i=new Map;#a=new Set;#o=new Map;#s=new Map;constructor(e){this.#e=new Jh({file:e.file,legacyFiles:e.legacyFiles??[],log:e.log}),this.#t=e.now??Date.now,this.#n=e.log,this.#r=new ag({get:e=>this.get(e),generation:e=>this.generation(e),save:(e,t,n)=>this.save(e,t,n),refreshOf:e=>this.#c(e)?.refresh,leadOf:e=>this.#c(e)?.refreshLead,now:e.now,log:e.log,registry:e.registry});for(let t of e.adapters??[])this.register(t)}register(e){let t=this.#s.get(e.id)??[];return this.#s.set(e.id,[...t,e].sort((e,t)=>(t.priority??10)-(e.priority??10))),()=>{let t=this.#s.get(e.id);if(t===void 0)return;let n=t.filter(t=>t!==e);if(n.length===0?this.#s.delete(e.id):this.#s.set(e.id,n),n.length===0){let t=this.#o.get(e.id);t!==void 0&&this.#u(t),this.#o.delete(e.id),this.#r.clear(e.id)}e.dispose?.()}}#c(e){return this.#s.get(e)?.[0]}hasAdapter(e){return this.#c(e)!==void 0}methodsOf(e){return(this.#c(e)?.methods()??[]).map(e=>({type:e.type,label:e.label??``}))}reload(){this.#e.invalidate()}generation(e){return this.#i.get(e)??0}locked(e){return this.#a.has(e)}lock(e){this.#a.add(e)}beginLogin(e){let t=this.generation(e)+1;return this.#i.set(e,t),this.#a.delete(e),t}get(e){let t=this.#e.read()[e];return t===void 0?void 0:{...t}}has(e){return e in this.#e.read()}providers(){return Object.keys(this.#e.read())}save(e,t,n){return n?.generation!==void 0&&n.generation!==this.generation(e)||this.#a.has(e)?!1:(this.#e.mutate(n=>({...n,[e]:{...t}})),!0)}saveFromPlugin(e,t){let n=Yh.getStore(),r=n?.providerId===e?{generation:n.generation}:void 0;return this.save(e,t,r)}remove(e){let t=this.generation(e)+1;return this.#i.set(e,t),this.#a.add(e),this.#e.mutate(t=>{if(!(e in t))return null;let n={...t};return delete n[e],n}),t}status(e){let t=this.get(e),n=t!==void 0&&typeof t.expires==`number`&&Number.isFinite(t.expires)?t.expires:null;return{provider:e,signedIn:t!==void 0,type:t!==void 0&&typeof t.type==`string`?t.type:null,account:t===void 0?null:hg(t),expires:n,expiresInMs:n===null?null:Math.max(0,n-this.#t())}}list(){return[...new Set([...this.#s.keys(),...this.providers()])].sort().map(e=>this.status(e))}view(e){let t=this.#o.get(e);return{provider:e,signedIn:this.has(e),methods:this.methodsOf(e),state:t?.state??`idle`,...t===void 0?{}:{url:t.url,instructions:t.instructions,...t.error===void 0?{}:{error:t.error},...t.accountId===void 0?{}:{accountId:t.accountId},...t.expiresAt===null?{}:{expiresAt:t.expiresAt}}}}async signIn(e,t={}){let n=this.#c(e),r=n?.methods()??[];if(n===void 0||r.length===0)throw new og(400,`${e} 未声明登录方式(auth.methods),无法登录;该供应商可能不需要登录`);if(t.restart!==!0&&this.#o.get(e)?.state===`pending`)return this.view(e);let i=t.method??``,a=t.inputs??{};if(i===``&&r.length>1)return{...this.view(e),needMethod:!0};let o=i===``?r[0]:r.find(e=>(e.label??e.type)===i);if(o===void 0)throw new og(400,`未知登录方式:${i}(可选:${r.map(e=>e.label??`(未命名)`).join(`、`)})`);let s=pg(o,a);if(s.length>0)return{...this.view(e),needInputs:mg(s),inputs:a};let c=(t.key??``).trim();if(o.type===`api`&&c===``)return{...this.view(e),needKey:!0,placeholder:o.placeholder??``,label:o.label??o.type,inputs:a};let l=this.beginLogin(e),u;try{let t={key:c,inputs:a};u=await Xh(e,l,()=>n.authorize(o,t))}catch(t){if(this.#p(e,l),t instanceof sg)return this.#o.set(e,{state:`failed`,url:``,instructions:``,expiresAt:null,attempt:null,error:t.message,generation:l}),this.#n?.(`[auth] ✗ ${e} 登录失败:${t.message}`),this.view(e);throw t instanceof og?t:new og(502,`起登录流程失败:${ug(t)}`)}if(dg(u))return this.save(e,gg(u.auth,u.account),{generation:l})?(this.#o.set(e,{state:`success`,url:``,instructions:``,expiresAt:null,attempt:null,generation:l,...u.account===void 0||u.account===null||u.account===``?{}:{accountId:u.account}}),this.#n?.(`[auth] ✓ ${e} 登录完成${u.account?`(${u.account})`:``}`),this.view(e)):(this.#o.set(e,{state:`failed`,url:``,instructions:``,expiresAt:null,attempt:null,error:`登录结果已过期(已登出或被新的登录流程取代)`,generation:l}),this.view(e));let d={state:`pending`,url:u.url,instructions:u.instructions,expiresAt:u.expiresAt,attempt:u,generation:l};return this.#o.set(e,d),this.#l(e,d),this.#n?.(`[auth] ▶ ${e} 登录已发起(${o.label??o.type}${u.url===``?``:`,等待浏览器完成`})`),this.view(e)}async poll(e){let t=this.#o.get(e);return t===void 0||t.state!==`pending`||t.attempt===null?this.view(e):this.#d(e,t)}#l(e,t){t.deadline=t.expiresAt??this.#t()+lg;let n=()=>{if(this.#o.get(e)!==t||t.state!==`pending`)return;let r=setTimeout(()=>{this.#o.get(e)===t&&t.state===`pending`&&this.#d(e,t).catch(()=>void 0).finally(n)},cg);r.unref?.(),t.timer=r};n()}#u(e){e.timer!==null&&e.timer!==void 0&&clearTimeout(e.timer),e.timer=null}#d(e,t){if(t.polling!==null&&t.polling!==void 0)return t.polling;let n=this.#f(e,t).finally(()=>{t.polling===n&&(t.polling=null)});return t.polling=n,n}async#f(e,t){let n=t.deadline??t.expiresAt;if(n!=null&&this.#t()>n)return this.#u(t),this.#o.delete(e),this.#n?.(`[auth] ✗ ${e} 授权已超时`),{...this.view(e),state:`failed`,error:`授权已超时,请重新发起`};let r=t.attempt;if(r===null)return this.view(e);let i;try{i=await r.poll()}catch(n){let r=ug(n);return this.#o.get(e)===t?(this.#p(e,t.generation),this.#u(t),this.#o.delete(e),this.#n?.(`[auth] ✗ ${e} 登录失败:${r}`),{...this.view(e),state:`failed`,error:r}):this.view(e)}return this.#o.get(e)!==t||i===null?this.view(e):this.save(e,gg(i.auth,i.account),{generation:t.generation})?(t.state=`success`,t.attempt=null,t.error=void 0,this.#u(t),i.account!==void 0&&i.account!==null&&i.account!==``&&(t.accountId=i.account),this.#n?.(`[auth] ✓ ${e} 登录完成${t.accountId?`(${t.accountId})`:``}`),this.view(e)):(t.state=`failed`,t.error=`登录结果已过期(已登出或被新的登录流程取代)`,t.attempt=null,this.#u(t),this.view(e))}signOut(e){let t=this.has(e),n=this.#o.get(e);return n!==void 0&&this.#u(n),this.remove(e),this.#r.clear(e),this.#o.delete(e),this.#c(e)?.dispose?.(),t&&this.#n?.(`[auth] ⏏ ${e} 已退出登录`),this.view(e)}async ensureFresh(e){await this.#r.ensureFresh(e)}#p(e,t){this.generation(e)===t&&this.get(e)===void 0&&this.#a.add(e)}},vg=`https://amr-api.open-design.ai`,yg=`/api/v1/cli/device-authorizations`,bg=`0.1.4`,xg=`ezllm-auth`,Sg=6e5,Cg=3e4;function wg(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Tg(e){return typeof e==`string`?e:null}function Eg(e,t){let n=e.error,r=((typeof n==`string`?n:Tg(wg(n)?.message))??``).replace(/\s+/g,` `).trim();return r===``||r.startsWith(`<`)?t:r.length>160?`${r.slice(0,160)}…`:r}async function Dg(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(Cg)});if(!n.ok){let e=await n.text().then(e=>{let t=e.replace(/\s+/g,` `).trim();return t.startsWith(`<`)?``:t.slice(0,160)}).catch(()=>``);throw Error(`HTTP ${String(n.status)}${e===``?``:`: ${e}`}`)}let r=wg(await n.json());if(r===null)throw Error(`响应不是 JSON 对象`);return r}function Og(e){let t=Tg(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}async function kg(){let e=await Dg(`${vg}${yg}`,{method:`POST`,headers:{accept:`application/json`,"user-agent":xg},body:JSON.stringify({cliVersion:bg,host:T()||`ezllm`,profile:`prod`})}),t=Tg(e.deviceId),n=Tg(e.deviceSecret),r=Tg(e.activationUrl);if(t===null||n===null||r===null)throw Error(`授权接口返回缺少必要字段(${Eg(e,`device authorization`)})`);let i=Tg(e.userCode),a=Og(e.expiresAt)??Date.now()+Sg;return{url:r,instructions:`已发起 Open Design 授权${i===null||i===``?``:`(设备码 ${i})`}:在打开的页面确认 CLI 登录,完成后这里会自动继续。`,expiresAt:a,poll:async()=>{let e;try{e=await Dg(`${vg}${yg}/${encodeURIComponent(t)}/token`,{method:`POST`,headers:{accept:`application/json`,"user-agent":xg},body:JSON.stringify({deviceSecret:n})})}catch(e){let t=e instanceof Error?e.message:String(e);throw/^HTTP 40[134]/u.test(t)?Error(`授权码已失效,请重新发起授权`):e}let r=Tg(e.controlKey);if(r!==null&&r!==``){let t=wg(e.user);return{auth:{type:`api`,key:r},account:t===null?null:Tg(t.email)}}let i=(Tg(e.status)??``).toLowerCase();if([`expired`,`canceled`,`cancelled`,`denied`,`rejected`].includes(i))throw Error(`授权被${i===`expired`?`超时作废`:`拒绝或撤销`},请重新发起`);return null}}}var Ag={id:`opendesign`,priority:50,methods:()=>[{type:`oauth`,label:`登录授权`}],authorize:()=>kg()},jg=null;function Mg(){return jg===null&&(jg=new _g({file:kt(),legacyFiles:[At()],adapters:[Ag],log:e=>D(e)})),jg}function Ng(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function Pg(){let e=e=>{let t=typeof e==`object`&&e?e:{},n=typeof t.apiBase==`string`&&t.apiBase.trim()!==``?t.apiBase:void 0,r=typeof t.apiKey==`string`&&t.apiKey.trim()!==``?t.apiKey:void 0;return{apiBase:n,apiKey:r===void 0?void 0:Ng(r)}};try{let t=El();if(t===null||!Array.isArray(t.providers))return null;let n=new Map;for(let r of t.providers){let t=typeof r==`object`&&r?r.name:void 0;typeof t==`string`&&t!==``&&n.set(t,e(r))}return n}catch{return null}}function Fg(e){return Pg()?.get(e)??null}function Ig(e){let t=Fg(e);if(t===null)return null;let n=Mh(t.apiBase);return n===null?null:n.authKey??e}function Lg(e){let t=Fg(e);return t===null?`key`:Mh(t.apiBase)?.authCredentialField??`key`}var Rg=Ht(`quota.json`);function zg(e){let t=e=>{let t=e=>{let t=J(e);if(t===null)return null;let n=t.used;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=t.cap,i=t.resetAt;return{used:n,cap:typeof r==`number`&&Number.isFinite(r)?r:null,resetAt:typeof i==`number`&&Number.isFinite(i)?i:null,exceeded:t.exceeded===!0}},n=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null},r=e=>{let t=J(e);if(t===null)return null;let r=n(t.cost),i=n(t.requests);if(r===null&&i===null)return null;let a=t.currency;return{cost:r,currency:typeof a==`string`&&a!==``?a:null,requests:i}},i=e=>{if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=J(n);if(e===null)continue;let r=e.label,i=e.value;typeof r==`string`&&r!==``&&typeof i==`string`&&i!==``&&t.push({label:r,value:i})}return t.length>0?t:null},a=e=>{if(!Array.isArray(e))return null;let t=[];for(let r of e){let e=J(r);if(e===null)continue;let i=e.name,a=e.display;if(typeof i!=`string`||i===``||typeof a!=`string`||a===``)continue;let o=e.usedPercent;t.push({name:i,usedPercent:typeof o==`number`&&Number.isFinite(o)?o:0,display:a,amount:n(e.amount),limit:n(e.limit),unit:typeof e.unit==`string`&&e.unit!==``?e.unit:null})}return t.length>0?t:null},o=J(e);if(o===null)return null;let s=o.totalTokens,c=o.totalRuns,l=o.voucherBalance,u=o.balance,d=o.totalCost,f=o.totalCostCurrency;return{fiveHour:t(o.fiveHour),weekly:t(o.weekly),monthly:t(o.monthly),totalTokens:typeof s==`number`&&Number.isFinite(s)?s:null,totalRuns:typeof c==`number`&&Number.isFinite(c)?c:null,voucherBalance:typeof l==`number`&&Number.isFinite(l)?l:null,balance:typeof u==`number`&&Number.isFinite(u)?u:null,totalCost:n(d),totalCostCurrency:typeof f==`string`&&f!==``?f:null,today:r(o.today),yesterday:r(o.yesterday),extraStats:i(o.extraStats),windows:a(o.windows)}},n=J(Rg.get(e));if(n===null)return null;let r=n.fetchText,i=n.authCredential,a=n.authAccount,o=n.vendorId,s=n.fetchedAt,c=n.error;return{fetchText:typeof r==`string`&&r.trim()!==``?r:void 0,authCredential:typeof i==`string`&&i.trim()!==``?i:void 0,authAccount:typeof a==`string`&&a.trim()!==``?a:void 0,vendorId:typeof o==`string`?o:void 0,snapshot:t(n.snapshot)??void 0,fetchedAt:typeof s==`number`&&Number.isFinite(s)?s:void 0,error:typeof c==`string`&&c!==``?c:void 0}}function Bg(e,t){Rg.set(e,t)}function Vg(e){Rg.get(e)!==void 0&&Rg.set(e,void 0)}function Hg(){let e=Rg.getAll(),t={};for(let n of Object.keys(e)){let e=zg(n);e!==null&&(t[n]=e)}return t}function Ug(e,t,n,r){let i=zg(e);Bg(e,{fetchText:i?.fetchText,authCredential:i?.authCredential,authAccount:i?.authAccount,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function Wg(e,t){let n=zg(e);if(n===null){Bg(e,{error:t});return}Bg(e,{...n,error:t})}var Gg=!1;function Kg(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function qg(e){let t=Ig(e);if(t===null)return;let n=Mg(),r=n.get(t),i=Lg(e),a=r?.[i],o=typeof a==`string`&&a.trim()!==``?a:void 0;if(o!==void 0)return o;let s=i===`key`?void 0:r?.key,c=typeof s==`string`&&s.trim()!==``?s:void 0;if(c!==void 0)return c;if(n.locked(t))return;let l=zg(e),u=l?.authCredential;if(u!==void 0){if(r!==void 0)return u;try{let r=l?.authAccount;if(n.save(t,{type:`api`,[i]:u,...r!==void 0&&r.trim()!==``?{accountId:r}:{}})){let t=zg(e);t!==null&&Bg(e,{...t,authCredential:void 0,authAccount:void 0})}}catch{}return u}}function Jg(e){return qg(e)!==void 0}async function Yg(e){try{let t=Fg(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&Ph(t.apiBase)!==null)({vendorId:n,vendor:r}=Fh(t.apiBase));else if(Mh(t.apiBase)!==null){let i=qg(e);if(i===void 0)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);({vendorId:n,vendor:r}=Nh(i,t.apiBase))}else if(Ah(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=jh(t.apiKey,t.apiBase))}else{let i=zg(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=Ih(i,t.apiBase))}let i=await r.fetchQuota();Ug(e,n,i,Date.now())}catch(t){Wg(e,Kg(t))}return zg(e)}async function Xg(){let e=()=>{let e=Pg();return e===null?null:new Set(e.keys())};if(!Gg){Gg=!0;try{let t=Pg(),n=[];for(let[e,r]of t??[]){if(Ah(r.apiBase)!==null||Ph(r.apiBase)!==null){n.push(e);continue}Mh(r.apiBase)!==null&&qg(e)!==void 0&&n.push(e)}for(let e of n)await Yg(e);let r=e();for(let[e,t]of Object.entries(Hg()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){Vg(e);continue}n.includes(e)||await Yg(e)}}catch(e){k(`[quota] 刷新失败:`,Kg(e))}finally{Gg=!1}}}var Zg=new Set;function Qg(e){let t=Ig(e);if(t===null)throw Error(`该供应商未支持授权登录查询额度`);return t}async function $g(e){if(Fg(e)===null)throw Error(`供应商配置不存在(可能已被删除)`);let t=Qg(e);Zg.delete(e);let n;try{n=await Mg().signIn(t,{restart:!0})}catch(e){throw e instanceof og?Error(e.message):e}if(n.needMethod===!0||n.needKey===!0||n.needInputs!==void 0)throw Error(`该供应商的登录需要额外输入,请在「插件」页面完成登录`);return{url:n.url??``,instructions:n.instructions??``,expiresAt:n.expiresAt??null}}async function e_(e){let t=Ig(e);if(t===null)return{status:`idle`};let n=Mg(),r=await n.poll(t);if(r.state===`failed`)return{status:`error`,error:r.error??`授权失败`};if(r.state===`pending`)return{status:`pending`};if(!n.has(t)&&!Jg(e))return{status:`idle`};let i=n.status(t).account??r.accountId??null;return r.state===`success`&&!Zg.has(e)?(Zg.add(e),{status:`authorized`,account:i,entry:await Yg(e)}):{status:`authorized`,account:i,entry:zg(e)}}function t_(e){let t=Ig(e);t!==null&&Mg().signOut(t),Zg.delete(e);let n=zg(e);return n===null?null:(Bg(e,{...n,authCredential:void 0,authAccount:void 0,error:void 0}),zg(e))}function n_(){let e=async e=>{let t=(await _p(e))?.fetchText;return typeof t==`string`?t:null},t=()=>kh().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource,...e.matchMode===void 0?{}:{matchMode:e.matchMode},...e.pathPrefix===void 0?{}:{pathPrefix:e.pathPrefix},...e.credentialSource===`deviceAuth`?{authLabel:`登录授权`}:{}})),n=(e,t)=>{if(t===null)return null;let n=Ig(e);if(n===null)return t;let r=Mg().status(n);return{...t,authCredential:void 0,authSignedIn:r.signedIn,authAccount:r.account??t.authAccount}},r=()=>{let e={};for(let[t,r]of Object.entries(Hg())){let i=n(t,r);i!==null&&(e[t]=i)}return e},i=new j;return i.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:r()})),i.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),i.put(`/:provider`,async t=>{let r=t.req.param(`provider`),i=Fg(r)?.apiBase;if(Ph(i)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(Ah(i)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);if(Mh(i)!==null)return t.json({ok:!1,error:`该供应商的额度需先「登录授权」,无需粘贴凭据`},400);let a=await e(t);if(a===null)return t.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let o=zg(r);Bg(r,{fetchText:a,vendorId:o?.vendorId,snapshot:o?.snapshot,fetchedAt:o?.fetchedAt,error:void 0});let s=await Yg(r);return t.json({ok:!0,entry:n(r,s)})}),i.delete(`/:provider`,e=>(Vg(e.req.param(`provider`)),e.json({ok:!0}))),i.post(`/:provider/refresh`,async e=>{let t=e.req.param(`provider`),r=await Yg(t);return e.json({ok:!0,entry:n(t,r)})}),i.post(`/:provider/auth`,async e=>{let t=e.req.param(`provider`);try{let n=await $g(t);return e.json({ok:!0,auth:n})}catch(t){let n=t instanceof Error?t.message:String(t);return e.json({ok:!1,error:n},400)}}),i.get(`/:provider/auth`,async e=>{let t=e.req.param(`provider`),r=await e_(t);return e.json({ok:!0,auth:r.entry===void 0?r:{...r,entry:n(t,r.entry)}})}),i.delete(`/:provider/auth`,e=>{let t=e.req.param(`provider`),r=t_(t);return e.json({ok:!0,entry:n(t,r)})}),i}function r_(){let e=new j;return e.get(`/`,e=>e.json({ok:!0,providers:Mg().list()})),e}function i_(e){return e===`0.0.0.0`||e===`::`}function a_(e=ee()){let t=[];for(let n of Object.values(e))for(let e of n??[])e.internal||e.family!==`IPv4`||t.includes(e.address)||t.push(e.address);return t}function o_(e,t){let n=new j;return n.get(`/`,n=>n.json({listenPort:fp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&i_(t.hostname)?{lanAddresses:a_()}:{},masterKey:Fl()})),n}var s_=864e5,c_=3e5,l_=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,u_=new Map;try{let e=g(Et(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;u_.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function d_(){let e=e=>({model:e.model,client:e.client,sessionId:e.sessionId,noSession:e.noSession===`1`||void 0,startDate:e.startDate||e.date,endDate:e.endDate||e.date,status:e.status,pathGroup:e.pathGroup,keyword:e.keyword}),t=e=>{let t=u_.get(e);if(!t)return null;let n=t.value.error===void 0?s_:c_;return Date.now()-t.at>=n?(u_.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of u_)e[t]={...n,_ts:r};C(Et(),JSON.stringify(e))}catch(e){k(`保存 IP 缓存失败:`,e.message)}},r=async e=>{let r=t(e);if(r)return r;let i=await(await fetch(l_.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return u_.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return u_.set(e,{value:a,at:Date.now()}),n(),a},i=new j;return i.onError(wp),i.get(`/dates`,e=>{let t=uf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=df();return e.json({clients:t})}),i.get(`/ipinfo`,async e=>{let t=e.req.query(`ip`)||``;if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return e.json({error:`invalid ip`},400);try{let n=await r(t);return e.json({ip:t,...n})}catch(e){throw new Cp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Jd(t);return n||=(await Of(),Jd(t)??hu(Number(t))),n?e.json({...n,meta:{...n.meta,tps:Zd(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Tp(async t=>{let n=t.req.query(),r=cf({...e(n),sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize}),i=(n.keyword??``).trim();return i.length>=2&&r.total===0&&(r=hf({...e(n),keyword:i,sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize})),t.json({...r,items:r.items.map(e=>({...e,user_agent:nu(e.headers),tps:Zd(e)}))})})),i.get(`/sessions`,Tp(t=>{let n=t.req.query(),r=pf({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Tp(async t=>{await Af();let n=du().length;n>0&&O(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=_f(e(r));return D(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var f_=3e4,p_=12e4,m_=5242880,h_=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],g_=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function __(e){let t=e.toLowerCase();return t===``||t.startsWith(`text/`)||t.startsWith(`application/json`)||t.endsWith(`+json`)||t.startsWith(`application/xml`)||t.endsWith(`+xml`)||t.startsWith(`application/javascript`)||t.startsWith(`application/x-www-form-urlencoded`)||t.startsWith(`application/x-ndjson`)||t.startsWith(`application/graphql`)}function v_(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(g_.includes(n.toLowerCase())||(t[n]=r));return t}function y_(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?f_:Math.min(Math.floor(e),p_)}function b_(e){if(typeof e!=`string`||e.trim()===``)throw new Cp(400,`缺少 url(要转发的目标地址)`);let t=e.trim(),n=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)?t:`https://${t}`,r;try{r=new URL(n)}catch{throw new Cp(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new Cp(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function x_(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function S_(e){let t=e.body;if(t===null)return{text:``,truncated:!1};let n=t.getReader(),r=[],i=0,a=!1;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(t===void 0)continue;let o=m_-i;if(t.byteLength>=o){r.push(t.subarray(0,o)),i+=o,a=!0;break}r.push(t),i+=t.byteLength}}finally{await n.cancel().catch(()=>void 0)}let o=new Uint8Array(i),s=0;for(let e of r)o.set(e,s),s+=e.byteLength;return{text:new TextDecoder(`utf-8`).decode(o),truncated:a}}function C_(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function w_(e){let{url:t,method:n,headers:r,body:i,timeoutMs:a}=e,o=i!==void 0&&n!==`GET`&&n!==`HEAD`,s=Date.now(),c;try{c=await fetch(t,{method:n,headers:r,...o?{body:i}:{},signal:AbortSignal.timeout(a),redirect:`follow`})}catch(e){let n=e instanceof Error?e.message:String(e);throw new Cp(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=__(l),{text:d,truncated:f}=u?await S_(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:C_(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function T_(){let e=new j;return e.onError(wp),e.post(`/`,async e=>{let t=await _p(e);if(t===null)throw new Cp(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!h_.includes(n))throw new Cp(400,`不支持的请求方法:${n}(可用 ${h_.join(` / `)})`);return await w_({url:b_(t.url),method:n,headers:v_(t.headers),body:x_(t.body),timeoutMs:y_(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await w_({url:b_(t.url),method:`GET`,headers:v_(void 0),body:void 0,timeoutMs:y_(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function E_(e){return`http://127.0.0.1:${String(e.port)}`}var D_=`daemon.json`;function O_(e){let t=e=>{let t=e.port??null;return{role:`main`,pid:e.pid??null,status:e.status??`stopped`,port:t,address:t?`http://127.0.0.1:${String(t)}`:null,startedAt:e.startedAt??null,restarts:null}},n=e=>{try{let t=JSON.parse(g(c(e,D_),`utf-8`))?.children;if(typeof t!=`object`||!t)return null;for(let e of Object.values(t)){let t=e;if(t?.pid===process.pid)return typeof t.startedAt==`number`?{pid:t.pid,startedAt:t.startedAt}:null}return null}catch{return null}},r=new j;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:E_(e)})),r.get(`/processes`,r=>{let i=n(e.appDir);return r.json({ok:!0,processes:[t({pid:i?.pid??process.pid,status:`online`,port:e.port,startedAt:i?.startedAt??e.startedAt})]})}),r}var k_=`ezllm-autostart.vbs`,A_=`ezllm-autostart.cmd`,j_=`com.ezllm.autostart`,M_=`ezllm.service`,N_=`autostart.opt-out`,P_=`ezllm-v2`,F_=`Auto-generated by "npx ezllm install" (${P_}). Managed automatically by ezllm. To remove it, run \`npx ezllm uninstall\`.`;function I_(e){return c(e,N_)}function L_(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),k_)}function R_(){return c(w(),`Library`,`LaunchAgents`,`${j_}.plist`)}function z_(){return c(w(),`.config`,`systemd`,`user`,M_)}var B_=3e4;function V_(e,t){return new Promise(n=>{let r=ve(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},B_),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var H_={win32:{itemPath:L_,on:q_,off:X_},darwin:{itemPath:R_,on:J_,off:Z_},linux:{itemPath:z_,on:Y_,off:Q_}};function U_(e){return H_[e]??null}function W_(e,t){return[e,t.entryJs,...t.args??[]]}function G_(e){return c(e,`logs`,`autostart.log`)}async function K_(e,t,n=V_){try{C(e,t,`utf16le`);return}catch(r){if(await n(`powershell`,[`-NoProfile`,`-Command`,`$bytes=[Convert]::FromBase64String('${Buffer.from(t,`utf16le`).toString(`base64`)}');[IO.File]::WriteAllBytes('${e.replace(/'/g,`''`)}', $bytes)`])!==0)throw r}}async function q_(e,t){let n=(e,t)=>{let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 npx ezllm install`)},r=(e,t)=>{let r=G_(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${F_}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${W_(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
84
|
+
`);if(o.length===0)break;let s=[];for(let e of o){a=Number(e.id),i.scanned++;let o=t(e.headers);o!==``&&(s.push({id:Number(e.id),sessionId:o}),i.filled++,s.length>=lp&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function dp(e){let t=()=>{for(let e of Mt())if(p(e))return e;return null},n=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=n.default??n[`module.exports`]??n;if(typeof r!=`object`||!r)return null;let i=r;return typeof i.onModelRequest==`function`?{onModelRequest:i.onModelRequest}:(O(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)},r=t();if(r===null)return;let i;try{i=await import(re(r).href)}catch(e){k(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${r}`),k(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),k(`[ezllm] 提示:模块写法与文件扩展名不匹配。CJS 内容(module.exports)请用 hook.cjs,ESM 内容(export default)请用 hook.mjs——这两个扩展名强制解析模式,不受任何 package.json 的 type 影响`);return}let a=n(i,r);a?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,a.onModelRequest),D(`[ezllm] 已加载用户钩子:${r}(onModelRequest)`))}function fp(e){return gt.port??e.port}async function pp(e,t,n={}){let r=new Sl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Dd())}});t.register(r),await dp(r);let i={current:r,port:r.expanded.port,rebuild(e){i.current.reload(e),i.port=i.current.expanded.port;let t=i.current.expanded.deployments.names.length,n=e.providers.filter(e=>e.enabled===!1).length,r=n>0?`(${String(n)} 个已停用)`:``;D(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new j},a=async e=>{let t=new URL(e.req.url),n=new Headers(e.req.raw.headers);if(!n.has(`x-forwarded-for`)){let t=e.env?.incoming?.socket?.remoteAddress??``;t!==``&&n.set(`x-forwarded-for`,t)}if(!n.has(`authorization`)&&n.has(`x-api-key`)){let e=n.get(`x-api-key`)??``;e!==``&&n.set(`authorization`,`Bearer ${e}`)}return i.current.build().fetch(new Request(t.toString(),{method:e.req.raw.method,headers:n,body:e.req.raw.body,duplex:`half`}))};return i.proxy.use(`/v1/models`,async(e,n)=>{let r=e.req.header(`authorization`)??(e.req.header(`x-api-key`)===null?``:`Bearer ${e.req.header(`x-api-key`)}`);if(!await t.authorize(r))return Response.json({error:{message:`Unauthorized: invalid api key`,type:`authentication_error`,code:`401`}},{status:401});await n()}),i.proxy.all(`/v1/*`,e=>a(e)),i.proxy.all(`/v1`,e=>a(e)),i.proxy.all(`/responses`,e=>a(e)),i.proxy.all(`/chat/completions`,e=>a(e)),i.proxy.all(`/messages`,e=>a(e)),i.proxy.all(`/messages/count_tokens`,e=>a(e)),i.proxy.all(`/models`,e=>a(e)),i.proxy.all(`/healthz`,e=>a(e)),i}var mp=64;function hp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>mp;){let e=r.keys().next().value;if(e===void 0)break;r.delete(e)}}function a(){return new Set(t.knownModelNames?t.knownModelNames():e.expanded.deployments.names)}e.plugin(e=>{e.addHook(`onFinish`,e=>{if(e.status!==200||e.ctx.model===null)return;let t=n(e.ctx.userAgent);t!==``&&i(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(a().has(t.requestedModel))return;let i=n(t.userAgent);if(i===``)return;let o=r.get(i);if(o!==void 0){if(!e.expanded.deployments.byName.has(o)){r.delete(i);return}return o}})})}var gp=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};async function _p(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var vp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,yp=`已启用管理台登录但未设置账号密码,请修改配置文件补充凭据或关闭登录开关`,bp=new j;function xp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}bp.post(`/login`,async e=>{let t=Bl();if(t.configBroken)return e.json({error:vp},503);if(t.required&&(t.username===``||t.password===``))return e.json({error:yp},503);if(!t.required)return e.json({error:`当前未启用管理台登录,管理台免登录访问(如需启用请在设置中打开登录开关)`},400);let n=await _p(e);if(n===null)return e.json({error:`请求体格式错误`},400);let{username:r,password:i}=n;return(r??``).trim()!==t.username||i!==t.password?e.json({error:`用户名或密码错误`},401):e.json({token:xp(t)})});async function Sp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Bl();if(!n.required)return await t();if(n.configBroken)return e.json({error:vp},401);if(n.username===``||n.password===``)return e.json({error:yp},503);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==xp(n))return e.json({error:`token 无效或已过期`},401);await t()}var Cp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function wp(e,t){return e instanceof Cp?(e.status>=500&&k(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(k(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e instanceof Error?e.message:e),t.json({ok:!1,error:e instanceof Error?e.message:String(e)},500))}function Tp(e){return async t=>{try{return await e(t)}catch(e){throw new Cp(500,e.message)}}}var Ep=8;function Dp(){let e=()=>{let e=El();if(e===null)throw new Cp(500,`配置文件不存在`);return e},t=new j;return t.onError(wp),t.use(`*`,async(e,t)=>{if(e.req.method===`GET`)return t();let n=e.req.header(`sec-fetch-site`);if(n===`same-origin`||n===`none`)return t();let r=e.req.header(`origin`);return r===void 0||r.toLowerCase()===new URL(e.req.url).origin.toLowerCase()?t():e.json({error:`已拒绝跨站写请求`},403)}),t.get(`/status`,e=>{let t=Vl(),n=!1;try{n=Fl()!==``}catch(e){if(!(e instanceof Tl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:Bl().required,version:zt(),buildSource:xt()})}),t.post(`/master-key`,async t=>{if(Vl().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await _p(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r;if(n.mode===`generate`)r=ae(32).toString(`base64url`);else if(n.mode===`custom`){if(r=(n.masterKey??``).trim(),r.length<Ep)return t.json({error:`主密钥至少 ${String(Ep)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return Ol(a),t.json({masterKey:r,...Wl(i,a)?{restartHint:Nl}:{}})}),t.post(`/finish`,async t=>{if(Vl().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await _p(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r=n.deployment;if(r!==`local`&&r!==`server`)return t.json({error:`deployment 必须是 local 或 server`},400);if(n.masterKey!==void 0&&typeof n.masterKey!=`string`)return t.json({error:`masterKey 必须是字符串`},400);let i=(n.masterKey??``).trim();if(i!==``&&i.length<Ep)return t.json({error:`主密钥至少 ${String(Ep)} 位`},400);if(r===`server`&&i===``&&Fl()===``)return t.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);if(n.loginEnabled!==void 0&&typeof n.loginEnabled!=`boolean`)return t.json({error:`loginEnabled 必须是布尔值`},400);if(n.username!==void 0&&typeof n.username!=`string`)return t.json({error:`username 必须是字符串`},400);if(n.password!==void 0&&typeof n.password!=`string`)return t.json({error:`password 必须是字符串`},400);let a=(n.username??``).trim(),o=n.password??``;if(n.loginEnabled===void 0&&a!==``!=(o!==``))return t.json({error:`用户名和密码需同时提供`},400);let s=typeof n.loginEnabled==`boolean`?n.loginEnabled:a!==``&&o!==``;if(s){if(a===``||o===``)return t.json({error:`启用管理台登录时必须填写用户名和密码(长度与字符不限)`},400)}else if(r===`server`)return t.json({error:`服务器部署必须启用管理台登录并设置账号密码,防止管理台被陌生人登录`},400);let c=e(),l={...c,...i===``?{}:{masterKey:i},setup:{completed:!0,deployment:r},allowLan:r===`server`,"web-ui":{...c[`web-ui`],"login-enabled":s,...s?{"login-account":{username:a,password:o}}:{}}};return Ol(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...Wl(c,l)?{restartHint:Nl}:{}})}),t}var Op=new Map,kp=1;function Ap(){return typeof process.send==`function`}function jp(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=kp++;return new Promise((i,a)=>{let o=setTimeout(()=>{Op.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);Op.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function Mp(e){typeof process.send==`function`&&(process.connected===!1?e():process.connected===!0&&process.once(`disconnect`,e)),process.on(`message`,e=>{let t=e;if(!t?.type||typeof t.id!=`number`)return;let n=Op.get(t.id);n&&(Op.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}function Np(e){let t=new j;return t.onError(wp),t.get(`/`,Tp(e=>{let t=El();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Tp(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);let r=n[`web-ui`],i=r?.[`login-enabled`];if(i!==void 0&&typeof i!=`boolean`)return t.json({error:`web-ui.login-enabled 必须是布尔值`},400);if(i===!0){let e=r[`login-account`],n=typeof e?.username==`string`?e.username.trim():``,i=typeof e?.password==`string`?e.password:``;if(n===``||i===``)return t.json({error:`启用管理台登录时必须设置用户名和密码(长度与字符不限)`},400)}try{Al(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let a=null;try{a=El()}catch{a=null}if(Ol(n),e.runtime.rebuild(kl(n)),Ap())try{await jp(`plugin.sync`)}catch(e){O(`[ezllm] 插件服务同步失败(配置已保存,重启主进程后会按配置恢复):${e instanceof Error?e.message:String(e)}`)}return t.json({message:`配置已保存并生效`,...Wl(a,n)?{restartHint:Nl}:{}})})),t}var Pp=`直接回复我 ok,不要思考不要解释`;function Fp(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function Ip(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Lp(e){for(let t of e.split(/\r?\n/)){if(!t.startsWith(`data:`))continue;let e=t.slice(5).trim();if(e!==``&&e!==`[DONE]`)try{let t=JSON.parse(e);if(typeof t==`object`&&t&&!Array.isArray(t))return t}catch{}}return null}async function Rp(e,t){if(!(e.headers.get(`content-type`)??``).toLowerCase().includes(`text/event-stream`)){let n=await e.text().catch(()=>``),r=null;try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(r=e)}catch{}return{streamed:!1,latencyMs:Date.now()-t,payload:r}}let n=e.body?.getReader();if(n===void 0)return{streamed:!0,latencyMs:Date.now()-t,payload:null};let r=new TextDecoder,i=``;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;a!==void 0&&(i+=r.decode(a,{stream:!0}));let o=Lp(i);if(o!==null)return{streamed:!0,latencyMs:Date.now()-t,payload:o}}}finally{await n.cancel().catch(()=>void 0)}return{streamed:!0,latencyMs:Date.now()-t,payload:null}}function zp(e){let t=new j;t.onError(wp);let n=Ht(`test-results.json`),r=Ht(`models-cache.json`);function i(e,t=`openai`,n=!0){let r=e.replace(/\/+$/,``);return t===`anthropic`&&r.endsWith(`/anthropic`)&&(r=r.slice(0,-10)),`${Fp(r,n)}/models`}function a(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();if(e.includes(`authorization`)||e.includes(`api-key`)||e.includes(`token`)){let e=String(r);t[n]=e.length>8?`${e.slice(0,3)}****${e.slice(-4)}`:`****`}else t[n]=r}return t}async function o(e,t,n,r){return fetch(i(e,n,r),{headers:Ip(t,n),signal:AbortSignal.timeout(1e4)})}async function s(e,t){if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`});let n=await o(t.api_base,t.api_key,t.protocol??`openai`,t.autoV1??!0);return n.ok?await n.json():e.json({status:`error`,message:`HTTP ${String(n.status)}`})}function c(e){let{response:t,read:n,url:r,headers:i,payload:o}=e,s={method:`POST`,url:r,headers:a(i),body:o},c=n.payload??{};if(n.streamed){if(!t.ok)return{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}};let e=n.payload!==null;return{status:e?`ok`:`error`,message:e?`流式首帧正常`:`流式响应未收到数据帧`,latency:n.latencyMs,request:s,response:{status:t.status,body:n.payload}}}return t.ok&&(c.choices!==void 0||c.output!==void 0||c.content!==void 0)?{status:`ok`,message:`${String(c.usage?.completion_tokens??c.usage?.output_tokens??0)} tokens`,latency:n.latencyMs,request:s,response:{status:t.status,body:c}}:{status:`error`,message:l(c,t.status),latency:n.latencyMs,request:s,response:{status:t.status,body:c}}}function l(e,t){let n=e.error,r=typeof n==`object`&&n&&`message`in n?String(n.message):typeof n==`string`?n:null;if(r!==null)return u(r);if(typeof e.msg==`string`&&e.msg.trim()!==``){let t=e.code===void 0||e.code===null?``:` (${String(e.code)})`;return u(`${e.msg.trim()}${t}`)}return u(`HTTP ${String(t)}`)}function u(e){let t=e;for(let[e,n]of[[/Weekly usage limit reached/i,`每周使用限额已达上限`],[/Resets in (\d+) day/i,`$1 天后重置`],[/RateLimitError:?\s*OpenAIException\s*-?\s*/gi,``],[/RateLimitError/g,`频率限制`],[/Rate limit/gi,`请求频率超限`],[/Invalid.*api.?key/i,`API Key 无效`],[/Unauthorized/i,`认证失败`],[/Not found/i,`模型或端点不存在`],[/Timeout/i,`请求超时`],[/Connection refused/i,`连接被拒绝`],[/ECONNREFUSED/i,`连接被拒绝`],[/ENOTFOUND/i,`域名无法解析`],[/model.*not.*found/i,`模型不存在`],[/context length exceeded/i,`上下文长度超限`],[/maximum context length/i,`超过最大上下文长度`],[/overloaded/i,`服务过载`],[/internal server error/i,`服务器内部错误`],[/bad gateway/i,`网关错误`],[/OpenAIException\s*-?\s*/i,``],[/To continue using[\s\S]*$/i,``],[/Received Model Group[\s\S]*$/i,``],[/Available Model Group[\s\S]*$/i,``],[/HTTP (\d+)/,`HTTP 错误 $1`]])t=t.replace(e,n);return t=t.replace(/\s+/g,` `).replace(/^[.:;\s-]+|[.:;\s-]+$/g,``).trim(),t||=e,t.length>120&&(t=t.substring(0,120)+`...`),t}t.get(`/results`,Tp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Tp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Tp(async e=>{let{keyId:t,models:n}=await e.req.json();return!t||!Array.isArray(n)?e.json({error:`缺少必要参数: keyId, models`},400):(r.set(t,n),e.json({message:`模型缓存已更新`,keyId:t,count:n.length}))})),t.post(`/`,async e=>{try{let t=await s(e,await e.req.json());return t instanceof Response?t:e.json({status:`ok`,models:t.data?.length||0,protocol:`openai`})}catch(t){return e.json({status:`error`,message:t.message})}}),t.post(`/fetch-models`,async e=>{try{let t=await e.req.json(),n=await s(e,t);if(n instanceof Response)return n;let i=(n.data||[]).map(e=>e.id||e.name).filter(e=>!!e);if(t.keyId){let e=r.get(t.keyId)??[],n=[...new Set([...e,...i])];r.set(t.keyId,n)}return e.json({status:`ok`,models:i})}catch(t){return e.json({status:`error`,message:t.message})}});function d(e,t){return t===`anthropic`?{model:e,messages:[{role:`user`,content:Pp}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:Pp,stream:!0}:{model:e,messages:[{role:`user`,content:Pp}],stream:!0}}async function f(e){let t=e.protocol||`openai`,n=e.autoV1??!0,r=e.api_base.replace(/\/+$/,``);if(!r)throw Error(`api_base 不能为空`);let i={"Content-Type":`application/json`,...Ip(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Fp(r,n)}${a}`,s=d(e.model,t),l=Date.now(),u=await fetch(o,{method:`POST`,headers:i,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)});return c({response:u,read:await Rp(u,l),url:o,headers:i,payload:s})}function p(e){let t=El();for(let n of t?.providers??[]){let t=n.models?.find(t=>t?.modelName===e);if(t)return t.customLlmProvider??n.customLlmProvider??`openai`}return`openai`}async function m(t,n){let r=Fl(),i=fp(e),a=`http://127.0.0.1:${String(i)}`,o={"Content-Type":`application/json`};r&&(o.Authorization=`Bearer ${r}`);let s=`${a}${n===`anthropic`?`/v1/messages`:n===`openai-responses`?`/v1/responses`:`/v1/chat/completions`}`,l=d(t,n),u=Date.now(),f;try{f=await fetch(s,{method:`POST`,headers:o,body:JSON.stringify(l),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e;throw k(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}return c({response:f,read:await Rp(f,u),url:s,headers:o,payload:l})}return t.post(`/model`,async e=>{try{let t=await e.req.json(),r=t.model;if(!r)return e.json({status:`error`,message:`缺少 model 参数`},400);if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`},400);let i;try{i=await f({model:r,api_base:t.api_base,api_key:t.api_key,protocol:t.protocol,autoV1:t.autoV1})}catch(e){i={status:`error`,message:u(e.message),latency:0}}return n.set(r,{...i,time:new Date().toISOString()}),e.json(i)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t.post(`/proxy`,async e=>{try{let t=(await e.req.json()).model;if(!t)return e.json({status:`error`,message:`缺少 model 参数`},400);let r=await m(t,p(t));return n.set(t,{...r,time:new Date().toISOString()}),e.json(r)}catch(t){return e.json({status:`error`,message:u(t.message)})}}),t}var Bp=Du(`latency_probes`,{id:H().primaryKey({autoIncrement:!0}),model:V().notNull(),time:H().notNull(),latency_ms:H().notNull(),ok:H().notNull(),error:V()},[Eu(`idx_latency_probes_model_time`).on(`model`,`time`),Eu(`idx_latency_probes_time`).on(`time`)]),Vp=2592e6,Hp=null;function Up(){let e=Hp;if(e!==null)return e;let t=ld(`latency`);return t.createTables([Bp]),Hp=t,t}function Wp(){return Up().native}function Gp(e){if(e.length!==0)try{Up().insert(Bp).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){k(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function Kp(){let e=Date.now()-Vp;return Up().select(Bp).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(W.gt(Bp.time,e)).orderBy(W.asc(Bp.time)).all().map(e=>({model:e.model,time:Number(e.time),latencyMs:Number(e.latency_ms),ok:e.ok===1,error:e.error??void 0}))}function qp(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=Up().select(Bp).columns([`time`,`latency_ms`,`ok`]).where(W.and(W.eq(Bp.model,e),W.gt(Bp.time,a),W.lte(Bp.time,r))).all();if(o.length===0)return[];let s=e=>{let n=new Date(e);return t===`hour`?new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()).getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()},c=[];for(let e=s(r);e>=s(a);e-=i)c.unshift(e);let l=new Map;for(let e of c)l.set(e,{total:0,success:0,latencySum:0});for(let e of o){let t=l.get(s(Number(e.time)));t&&(t.total+=1,e.ok===1&&(t.success+=1,t.latencySum+=Number(e.latency_ms)))}return c.map(e=>{let t=l.get(e);return{bucketStart:e,total:t.total,success:t.success,failed:t.total-t.success,successRate:t.total===0?null:Math.round(t.success/t.total*1e3)/10,avgLatencyMs:t.success===0?null:Math.round(t.latencySum/t.success)}})}function Jp(){let e=Up().select(Bp).columns({t:W.max(Bp.time)}).get();return e?.t==null?null:Number(e.t)}function Yp(e){try{let t=Date.now()-e;Up().delete(Bp).where(W.lte(Bp.time,t)).run()}catch(e){k(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Xp=3e4,Zp=4,Qp=!1;function $p(){return Qp}function em(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function tm(e){let t=async e=>{let t=Fp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Ip(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Pp}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Pp,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Pp}],max_tokens:1,stream:!0});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Xp)});if(!t.ok){let n=await t.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,120)).catch(()=>``);return{model:e.name,time:a,latencyMs:0,ok:!1,error:n?`HTTP ${String(t.status)}: ${n}`:`HTTP ${String(t.status)}`}}let o=await Rp(t,a);return o.streamed&&o.payload===null?{model:e.name,time:a,latencyMs:0,ok:!1,error:`HTTP ${String(t.status)}: 流式响应未收到数据帧`}:{model:e.name,time:a,latencyMs:o.latencyMs,ok:!0}}catch(t){return{model:e.name,time:a,latencyMs:0,ok:!1,error:t.message}}},n=async e=>{let n=[],r=0,i=Array.from({length:Math.max(1,Math.min(Zp,e.length))},async()=>{for(;;){let i=r++;if(i>=e.length)return;n.push(await t(e[i]))}});return await Promise.all(i),n};if(Qp)return!1;Qp=!0;try{let t=await n(em(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));Gp(t),Yp(Vp);let r=t.filter(e=>e.ok).length;return D(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(r)}),数据已入库 latency.db`),!0}catch(e){return k(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Qp=!1}}function nm(e){return em(e).length}var rm=[{key:`avg10m`,ms:6e5},{key:`avg30m`,ms:18e5},{key:`avg1h`,ms:36e5},{key:`avg2h`,ms:72e5},{key:`avg5h`,ms:18e6},{key:`avg8h`,ms:288e5},{key:`avg12h`,ms:432e5},{key:`avg24h`,ms:864e5}];function im(e,t,n){return n.map(n=>{let r=e.filter(e=>e.model===n),i={model:n,avg10m:null,avg30m:null,avg1h:null,avg2h:null,avg5h:null,avg8h:null,avg12h:null,avg24h:null,lastTestAt:null,lastOk:null,lastLatencyMs:null,lastError:null},a=r.reduce((e,t)=>e===null||t.time>e.time?t:e,null);a!==null&&(i.lastTestAt=a.time,i.lastOk=a.ok,a.ok&&(i.lastLatencyMs=a.latencyMs),a.ok||(i.lastError=a.error??null));for(let{key:e,ms:n}of rm){let a=r.filter(e=>e.ok&&e.time>t-n&&e.time<=t);a.length!==0&&(i[e]=Math.round(a.reduce((e,t)=>e+t.latencyMs,0)/a.length))}return i})}function am(e){let t=new j;return t.get(`/history`,t=>{let n=Kp(),r=Date.now();return t.json({running:$p(),lastRunAt:Jp(),models:im(n,r,e.current.expanded.deployments.names)})}),t.get(`/trend`,e=>{let t=e.req.query(`model`);if(!t)return e.json({ok:!1,error:`缺少 model 参数`},400);let n=e.req.query(`granularity`)===`day`?`day`:`hour`,r=qp(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>$p()?t.json({ok:!1,error:`测试进行中,请稍候`},409):nm(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(tm(e),t.json({ok:!0,running:!0}))),t}function om(){let e=t=>{let n=0;if(!p(t))return 0;for(let r of _(t)){let i=c(t,r),a;try{a=x(i)}catch{continue}a.isDirectory()?n+=e(i):n+=a.size}return n},t=()=>Math.round(e(wt())/1024/1024*10)/10,n=new j;return n.onError(wp),n.get(`/`,Tp(e=>{let n=e.req.query(),r=lf({startDate:n.startDate,endDate:n.endDate,model:n.model});return e.json({...r,logStorageMB:t()})})),n}function J(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function X(e){return typeof e==`string`?e:null}function sm(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function cm(e,t){let n=sm(e,t);return n===void 0?void 0:e[n]}function lm(e,t){if(e===void 0)return null;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}return null}function um(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function dm(e){let t=(e,t)=>{let n=e[t];if(n!==`"`&&n!==`'`&&n!=="`")return null;let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t===`\\`){i+=e[r+1]??``,r+=2;continue}if(t===n)return{value:i,end:r+1};i+=t,r+=1}return null},n=(e,n)=>{let r=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n},i=(e,n)=>{if(e[n]!==`{`)return null;let r=0,i=n;for(;i<e.length;){let a=e[i];if(a===`"`||a===`'`||a==="`"){let n=t(e,i);if(n===null)return null;i=n.end;continue}if(a===`{`)r+=1;else if(a===`}`&&(--r,r===0))return{raw:e.slice(n,i+1),end:i+1};i+=1}return null},a=e=>{let n=e=>{let n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`||i===`'`||i==="`"){let i=t(e,r);if(i===null){n+=e.slice(r);break}n+=e.slice(r,i.end),r=i.end;continue}if(i===`,`){let t=r+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;let n=e[t];if(n===`}`||n===`]`){r+=1;continue}}n+=i,r+=1}return n},r;try{r=JSON.parse(n(e))}catch{return null}let i=J(r);if(i===null)return null;let a={},o=J(i.headers);if(o!==null)for(let[e,t]of Object.entries(o))typeof t==`string`&&(a[e]=t);return{method:typeof i.method==`string`?i.method.toUpperCase():`GET`,headers:a,body:typeof i.body==`string`?i.body:null}},o=r(e,n),s=t(e,o);if(s===null)return null;let c=s.value,l=r(e,s.end);if(e[l]!==`,`)return{url:c,method:`GET`,headers:{},body:null};let u=i(e,r(e,l+1));if(u===null)return{url:c,method:`GET`,headers:{},body:null};let d=a(u.raw);if(d===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:c,method:d.method,headers:d.headers,body:d.body}},r=e=>{let t=new Map;for(let n of e){let e=sm(n.headers,`cookie`);if(e===void 0)continue;let r=um(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(sm(e.headers,`cookie`)!==void 0)return e;let n=um(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})},i=[],a=/\bfetch\s*\(/g,o;for(;(o=a.exec(e))!==null;){let t=n(e,o.index+o[0].length);t!==null&&i.push(t)}return r(i)}function fm(e){return e.some(e=>sm(e.headers,`cookie`)!==void 0)}var pm=0xe8d4a51000,mm=3e4;async function hm(e,t){let n=e=>{let t={...e};for(let e of Object.keys(t)){let n=e.toLowerCase();(n===`content-length`||n===`host`||n===`connection`)&&delete t[e]}return t},r=await fetch(e,{...t,headers:n(t.headers),signal:AbortSignal.timeout(mm)});if(!r.ok){let e=await r.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(r.status)}${e===``?``:`: ${e}`}`)}let i=J(await r.json());if(i===null)throw Error(`响应不是 JSON 对象`);return i}function gm(e){return e===null||e<=0?null:Math.round(e<pm?e*1e3:e)}function _m(e){return Math.round(e*100)/100}function vm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function ym(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function bm(e,t){let n=J(e);if(n===null)return null;let r=Y(n[t.used])??0,i=Y(n[t.cap]),a=t.exceeded!==void 0&&n[t.exceeded]===!0||i!==null&&r>=i;return{used:r,cap:i,resetAt:t.resetAt===void 0?null:gm(Y(n[t.resetAt])),exceeded:a}}var xm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await hm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await hm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},Sm=`https://api.commandcode.ai`,Cm=`/alpha/billing/credits`,wm=`/alpha/usage/summary`,Tm=`/alpha/billing/subscriptions`,Em={"individual-pro-v1":80,"individual-goat":70},Dm=/^user_[A-Za-z0-9_-]+$/,Om={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function km(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:vm(t)}]}function Am(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var jm=class extends xm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=Dm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!Dm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(Sm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(wm),this.get(Cm),this.get(Tm).catch(()=>null)]),r=J(t.windowLimits),i=J(t.credits),a=n===null?null:J(n.data),o=a===null?null:X(a.planId),s=o===null?null:Em[o]??null,c=i===null?null:Y(i.monthlyCredits),l=s===null||c===null?null:{used:_m(Math.max(0,s-c)),cap:s,resetAt:a===null?null:Am(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:bm(r.fiveHour,Om),weekly:r===null?null:bm(r.weekly,Om),monthly:l,totalTokens:Y(e.totalTokens),totalRuns:Y(e.totalCount),voucherBalance:null,balance:null,extraStats:km(l,c)}}},Mm=`https://api.deepseek.com`,Nm=`/user/balance`,Pm=`余额不足,无法调用 API`;function Fm(e){let t=Y(e);if(t!==null)return t;let n=X(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Im(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function Lm(e){let t=[];if(!Array.isArray(e))return t;let n=new Set;for(let r of e){let e=J(r);if(e===null)continue;let i=X(e.currency);if(i===null||i.trim()===``)continue;let a=i.trim();if(n.has(a))continue;let o=Fm(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:Fm(e.granted_balance),toppedUp:Fm(e.topped_up_balance)}))}return t}function Rm(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>e.currency===`CNY`)??[...e].sort((e,t)=>e.currency.localeCompare(t.currency))[0]}var zm=class extends xm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(Mm,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Nm),t=Rm(Lm(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=Im(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${vm(_m(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${vm(_m(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:Pm}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:_m(t.total),extraStats:r.length===0?null:r}}},Bm=`https://amr-api.open-design.ai`,Vm=`ezllm-quota`,Hm=86400,Um=691200;function Wm(e){return{accept:`application/json`,"user-agent":Vm,authorization:`Bearer ${e}`}}function Gm(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}function Km(e){let t=Y(e);if(t!==null)return t;let n=X(e);if(n===null||n.trim()===``)return null;let r=Number(n);return Number.isFinite(r)?r:null}function qm(e){let t=Gm(e);if(t!==null)return t;let n=Km(e);return n===null?null:gm(n)}function Jm(e){let t=J(e);if(t===null)return null;let n=Km(t.usedCredits),r=Km(t.limitCredits);return n===null||r===null?null:{used:n,cap:r,resetAt:qm(t.resetsAt),exceeded:n>=r}}function Ym(e){let t={fiveHour:null,weekly:null,monthly:null},n=e?.windows;if(!Array.isArray(n))return t;for(let e of n){let n=Jm(e);if(n===null)continue;let r=Km(J(e)?.durationSeconds)??0;r>0&&r<Hm?t.fiveHour??=n:r>=Hm&&r<Um?t.weekly??=n:r>=Um&&(t.monthly??=n)}return t}function Xm(e){if(e===null||e.trim()===``)return null;let t=e.trim();return`Design Plan ${t[0].toUpperCase()}${t.slice(1)}`}var Zm=class extends xm{static vendorId=`opendesign`;static vendorLabel=`Open Design`;static apiHosts=[`amr-link.open-design.ai`];static credentialSource=`deviceAuth`;static authKey=`opendesign`;static authCredentialField=`control`;constructor(e){let t=e.trim();if(t===``)throw Error(`授权凭据为空,请重新发起「登录授权」`);super(Bm,Wm(t))}async fetchQuota(){let e=await this.get(`/api/v1/workspaces/current`),t=X(e.activeWorkspaceId)??X(e.workspaceId);if(t===null||t===``)throw Error(`授权账号没有可用工作区(workspaces/current 未返回 activeWorkspaceId)`);let n=await this.get(`/api/v1/workspaces/${encodeURIComponent(t)}/billing/preflight`),r=await this.get(`/api/v1/billing/summary`).catch(()=>null),i=J(n.codingPlan),a=Ym(i),o=Km(n.balanceUsd)??Km(r?.balanceUsd??null),s=X(r?.membershipTier??null)??X(e.personalMembershipTier??null),c=[],l=Xm(s);return l!==null&&c.push({label:`套餐`,value:l}),i!==null&&i.eligible===!1&&c.push({label:`套餐额度`,value:`未生效(走钱包余额)`}),o!==null&&c.push({label:`钱包余额`,value:`$${o.toFixed(2)}`}),{fiveHour:a.fiveHour,weekly:a.weekly,monthly:a.monthly,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,extraStats:c.length>0?c:null}}},Qm=[`127.0.0.1`,`localhost`,`[::1]`],$m=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function eh(e){let t;try{t=new URL(e)}catch{return null}if(!Qm.some(e=>e===t.hostname.toLowerCase()))return null;let n=$m.exec(t.pathname);if(n===null)return null;let r;try{r=decodeURIComponent(n[1])}catch{return null}return r.trim()===``?null:{origin:t.origin,providerId:r}}function th(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){let e=J(n);if(e===null)continue;let r=X(e.name),i=X(e.display);r!==null&&r.trim()!==``&&i!==null&&i.trim()!==``&&t.push({name:r,usedPercent:Y(e.used)??0,display:i,amount:Y(e.amount),limit:Y(e.limit),unit:X(e.unit)})}return t}var nh=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=Qm;#e;#t;constructor(e){let t=eh(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await hm(`${this.#e}/p/${encodeURIComponent(this.#t)}/usage`,{method:`GET`,headers:{accept:`application/json`}}),t=X(e.error);if(t!==null&&t.trim()!==``)throw Error(t);let n=X(e.plan);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,windows:th(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},rh=`/api/user/self`,ih=`/api/user/subscription/current_cycle`,ah={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function oh(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=J(e);if(n!==null&&n.key===t)return n}return null}function sh(e){return e===null||Y(e.total_count)===null?null:bm(e,ah)}function ch(e){let t=J(e.account_info),n=t===null?null:t.vouchers;if(!Array.isArray(n))return null;let r=0,i=!1;for(let e of n){let t=J(e),n=t===null?null:Y(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function lh(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var uh=class extends xm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=dm(e),n=lh(t,rh),r=lh(t,ih);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>cm(e.headers,`authorization`)!==void 0))throw Error(`复制的请求里没有 authorization 头(登录凭据在它里面)——请从已登录的 senseaudio.cn 页面重新复制 fetch 调用`);let i=n??r;super(new URL(i.url).origin,i.headers)}async fetchQuota(){let[e,t]=await Promise.all([this.get(rh),this.get(ih).catch(()=>null)]),n=sh(oh(e,`credit_5h_limit`)),r=sh(oh(e,`credit_7d_limit`)),i=sh(oh(e,`credit_30d_limit`));if(i===null&&t!==null){let e=Y(t.plan_points),n=Y(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:gm(Y(t.plan_points_reset_at)),exceeded:e-n>=e})}if(n===null&&r===null&&i===null)throw Error(`上游未返回任何额度窗口(该账号可能尚未登录或未订阅套餐)`);return{fiveHour:n,weekly:r,monthly:i,totalTokens:null,totalRuns:null,voucherBalance:ch(e),balance:null}}},dh=`GetAgentPlanAFPUsage`,fh=`GetAgentPlanUsageDetails`,ph=`console.volcengine.com`,mh=`2024-01-01`,hh=`cn-beijing`,gh={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function _h(e){return e.find(e=>e.url.includes(dh))}function vh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??hh}/${mh}`:t}function yh(e){return e.find(e=>um(e.url)===ph)}var bh=class extends xm{static vendorId=`volc-ark`;static vendorLabel=`火山方舟`;static hosts=[`console.volcengine.com`];static apiHosts=[`ark.cn-beijing.volces.com`];static credentialSource=`fetchText`;#e;#t;constructor(e){let t=dm(e),n=_h(t)??yh(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!fm(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==ph)throw Error(`非方舟控制台域`);r=e.origin,i=vh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=lm(cm(n.headers,`cookie`),`csrfToken`)??cm(n.headers,`x-csrf-token`)??null;if(a===null)throw Error(`缺少 CSRF 凭据:请求头需含 x-csrf-token,或 Cookie 里需有 csrfToken (两者都来自已登录的控制台会话,请在登录页面上重新复制)`);super(r,{...n.headers,"x-csrf-token":a}),this.#e=`${i}/${dh}`,this.#t=`${i}/${fh}`}envelope(e){let t=J(e.ResponseMetadata),n=t===null?null:J(t.Error);if(n!==null){let e=X(n.Code)??`Unknown`,t=X(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=J((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=bm(e.AFPFiveHour,gh),n=bm(e.AFPWeekly,gh),r=bm(e.AFPMonthly,gh);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=J(e.AFPMonthly),a=i===null?null:Y(i.SubscribeTime);return{fiveHour:t,weekly:n,monthly:r,totalTokens:await this.#n(a),totalRuns:null,voucherBalance:null,balance:null}}async#n(e){let t=Date.now(),n=e!==null&&e>0?e:t-2592e6;try{let e=J((await this.post(this.#t,{Filter:{StartTime:ym(new Date(n)),EndTime:ym(new Date(t)),ObjectType:1,BillingType:[`WithinPlan`]},QueryInterval:`Day`})).Result),r=e===null?null:e.Details;return Array.isArray(r)?r.reduce((e,t)=>{let n=J(t);return n===null||n.Unit!==`Tokens`?e:e+(Y(n.Usage)??0)},0):null}catch{return null}}},xh=`/api/biz/account/query-customer-account-report`,Sh=`/api/finance/expenseBill/expenseBillListByDay`,Ch=200,wh=`bigmodel_token_production`;function Th(e){let t=lm(cm(e.headers,`cookie`),wh);if(t!==null&&t.trim()!==``)return t.trim();let n=cm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var Eh=class extends xm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=dm(e);if(t.length===0)throw Error(`未找到可用的智谱请求:请在已登录的 bigmodel.cn(财务中心 / 资源包 / 任意控制台页面)里复制任意请求的 fetch 调用粘贴进来,额度端点会自动换算`);let n=t[0],r;try{r=new URL(n.url).origin}catch{throw Error(`粘贴的请求 URL 不是绝对地址,无法换算出额度接口——请粘贴浏览器里完整的 fetch(https://…)`)}let i=Th(n);if(i===null)throw Error(`复制的请求里没有登录凭据(需要 Cookie 里的 bigmodel_token_production,或显式的 authorization 头)——请从已登录的 bigmodel.cn 页面用「以 fetch (Node.js) 格式复制」重新复制`);let a={...n.headers,authorization:i.toLowerCase().startsWith(`bearer `)?i:`Bearer ${i}`};super(r,a)}envelope(e){let t=Y(e.code);if(t!==200){let n=X(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=ym(e).slice(0,7),n=ym(new Date(e.getFullYear(),e.getMonth(),e.getDate()-(e.getDay()+6)%7));try{let e=1,r=0,i=0,a=1/0,o=[];for(;o.length<a;){let s=await this.get(Sh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(Ch)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=Y(l)??o.length,o=o.concat(c);for(let e of c){let t=J(e);if(t===null)continue;let a=Y(t.originalAmount),o=X(t.billingDate);a!==null&&o!==null&&(r+=a,o>=n&&(i+=a))}if(e+=1,c.length===0)break}return{weekly:{used:i,cap:null,resetAt:null,exceeded:!1},monthly:{used:r,cap:null,resetAt:null,exceeded:!1}}}catch{return null}}async fetchQuota(){let[e,t]=await Promise.all([this.get(xh),this.#e()]),n=J(e.data),r=(n===null?null:Y(n.availableBalance))??(n===null?null:Y(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=Y(n.totalSpendAmount);return{fiveHour:null,weekly:t?.weekly??null,monthly:t?.monthly??null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:r,totalCost:i,totalCostCurrency:i===null?null:`CNY`,extraStats:Dh(n)}}};function Dh(e){let t=e=>`${vm(e)} 元`,n=[],r=Y(e.rechargeAmount);r!==null&&n.push({label:`累计充值`,value:t(r)});let i=Y(e.giveAmount);i!==null&&n.push({label:`赠送金额`,value:t(i)});let a=Y(e.creditBalance);return a===null?e.creditStatus===`NOT_OPEN`&&n.push({label:`信用余额`,value:`未开通`}):n.push({label:`信用余额`,value:t(a)}),n}var Oh=[jm,zm,Zm,uh,bh,Eh,nh];function kh(){return Oh}function Ah(e){if(e===void 0)return null;let t=um(e);if(t===``)return null;for(let e of Oh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function jh(e,t){let n=Ah(t);if(n===null)throw Error(`该供应商未支持用 API key 自动查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`该供应商的 apiKey 为空,无法查询额度——请在供应商配置里填入 API key`);if(n.apiKeyPattern?.test(r)===!1)throw Error(`配置里的 apiKey 不是 ${n.vendorLabel} 的 API key 形态——请检查该供应商配置的 apiKey 字段`);return{vendorId:n.vendorId,vendor:new n(r)}}function Mh(e){if(e===void 0)return null;let t=um(e);if(t===``)return null;for(let e of Oh)if(e.credentialSource===`deviceAuth`&&e.apiHosts?.some(e=>e===t))return e;return null}function Nh(e,t){let n=Mh(t);if(n===null)throw Error(`该供应商未支持授权登录查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);return{vendorId:n.vendorId,vendor:new n(r)}}function Ph(e){return e===void 0||eh(e)===null?null:nh}function Fh(e){if(Ph(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:nh.vendorId,vendor:new nh(e)}}function Ih(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of dm(e)){let e=um(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of Oh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=um(t);if(e!==``){for(let t of Oh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of Oh)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>i.has(e))===!0)return e;return null};if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let r=n(e,t);if(r===null){let e=Oh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=Oh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=Ah(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var Lh=20,Rh=2e3,zh=1e4,Bh=3e4;function Vh(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Hh(e){return e instanceof Error?e.message:String(e)}var Uh=class extends Error{constructor(){super(`凭据文件内容异常(非合法 JSON 或形状不符),已拒绝写入以免覆盖现有凭据;请修复或备份后删除该文件`),this.name=`AuthFileCorruptError`}};function Wh(e){let t;try{t=g(e,`utf-8`)}catch{throw new Uh}let n;try{n=JSON.parse(t)}catch{throw new Uh}if(typeof n!=`object`||!n||Array.isArray(n))throw new Uh;let r={};for(let[e,t]of Object.entries(n)){if(typeof t!=`object`||!t||Array.isArray(t))throw new Uh;r[e]=t}return r}function Gh(e){try{let t=JSON.parse(g(e,`utf-8`));if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))typeof r==`object`&&r&&!Array.isArray(r)&&(n[e]=r);return n}catch{return{}}}function Kh(e,t){let n=`${e}.${`${process.pid}.${ae(6).toString(`hex`)}`}.tmp`;try{m(s(e),{recursive:!0}),C(n,`${JSON.stringify(t,null,2)}\n`,{encoding:`utf-8`,mode:384}),v(n,e)}finally{try{y(n,{force:!0})}catch{}}}function qh(e,t){return p(e)?e:t.find(e=>p(e))??null}var Jh=class{#e;#t;#n;#r=null;#i=null;#a=-1;#o=!1;#s=0;constructor(e){this.#e=e.file,this.#t=e.legacyFiles??[],this.#n=e.log,this.#l()}get path(){return this.#e}read(){this.#o&&Date.now()>=this.#s&&this.#l();let e=qh(this.#e,this.#t);if(e===null)return{};try{let t=x(e).mtimeMs;if(this.#r!==null&&this.#i===e&&this.#a===t)return{...this.#r};let n=Gh(e);return this.#r=n,this.#i=e,this.#a=t,{...n}}catch{return{}}}invalidate(){this.#r=null,this.#i=null,this.#a=-1}mutate(e){return this.#d(()=>{let t=e(this.#c());return t===null?null:(Kh(this.#e,t),this.#u(),this.#r=t,this.#i=this.#e,this.#a=x(this.#e).mtimeMs,{...t})})}#c(){let e=qh(this.#e,this.#t);return e===null?{}:Wh(e)}#l(){let e=this.#t.find(e=>p(e));if(e===void 0){this.#o=!1;return}try{let t=this.#d(()=>p(e)?p(this.#e)?(y(e,{force:!0}),this.#n?.(`[auth] 已清理旧凭据文件:${e}(新文件已存在)`),!0):(v(e,this.#e),this.#n?.(`[auth] 凭据文件已迁移:${e} → ${this.#e}`),!0):!0);this.#o=!t,this.#s=t?0:Date.now()+Bh}catch(e){this.#o=!0,this.#s=Date.now()+Bh,this.#n?.(`[auth] 旧凭据文件处理失败(继续只读旧文件,${String(Bh/1e3)}s 后重试):${Hh(e)}`)}}#u(){for(let e of this.#t)if(p(e))try{y(e,{force:!0}),this.#n?.(`[auth] 已清理旧凭据文件:${e}`)}catch{}this.#o=!1}#d(e){let t=`${this.#e}.lock`,n=`${process.pid}.${ae(8).toString(`hex`)}`;m(s(t),{recursive:!0});let r=Date.now()+Rh;for(;;)try{m(t),C(c(t,`owner`),n,`utf-8`);break}catch(e){if(e.code!==`EEXIST`)throw e;try{if(Date.now()-x(t).mtimeMs>zh&&this.#m(t))continue}catch{}if(Date.now()>r)throw Error(`获取凭据文件锁超时:${o(t)}`);Vh(Lh)}try{return e()}finally{this.#p(t,n)}}#f(e){try{return g(c(e,`owner`),`utf-8`)}catch{return null}}#p(e,t){try{if(this.#f(e)!==t)return;y(e,{recursive:!0,force:!0})}catch{}}#m(e){let t=this.#f(e),n=`${e}.stale.${ae(4).toString(`hex`)}`;try{v(e,n)}catch{return!1}let r=this.#f(n);if(t!==null&&r!==null&&t!==r){try{v(n,e)}catch{}return!1}try{y(n,{recursive:!0,force:!0})}catch{}return!0}},Yh=new ve;function Xh(e,t,n){return Yh.run({providerId:e,generation:t},n)}var Zh=3e5,Qh=864e5,$h=15e3,eg=3e4,tg=new class{renewing=new Map;failed=new Map;clear(e){let t=`${e}\0`;for(let e of[...this.renewing.keys()])e.startsWith(t)&&this.renewing.delete(e);for(let e of[...this.failed.keys()])e.startsWith(t)&&this.failed.delete(e)}};function ng(e){let t=`${String(e?.refresh??``)}\0${String(e?.access??``)}`;return ie(`sha256`).update(t).digest(`hex`).slice(0,16)}function rg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.min(e,Qh):Zh}function ig(e,t){if(t.type!==`oauth`)return 0;let n=Number(t.expires);return Number.isFinite(n)&&n>0?Math.max(1,n-e):0}var ag=class{#e;constructor(e){this.#e=e}clear(e){(this.#e.registry??tg).clear(e)}async ensureFresh(e){let t=this.#e.get(e),n=this.#e.refreshOf(e);if(t===void 0||n===void 0)return;let r=this.#n(),i=ig(rg(this.#e.leadOf(e)),t);if(!i||r<i)return;let a=this.#r(),o=`${e}\0${ng(t)}`,s=a.failed.get(o);if(s!==void 0){if(r-s<eg)return;a.failed.delete(o)}let c=a.renewing.get(o);c===void 0&&(c=this.#t(e,t,n,o).finally(()=>a.renewing.delete(o)),a.renewing.set(o,c));let l;await Promise.race([c,new Promise(e=>{l=setTimeout(e,$h)})]),clearTimeout(l)}async#t(e,t,n,r){let i=this.#r(),a=this.#e.generation(e);try{let o=await Xh(e,a,()=>n({...t}));if(typeof o!=`object`||!o||Array.isArray(o)){i.failed.delete(r);return}let s=this.#e.get(e);if(s===void 0||this.#e.generation(e)!==a){i.failed.delete(r),this.#e.log?.(`[auth] 已丢弃过期的续期结果:${e}`);return}if(ng(s)!==ng(t)){i.failed.delete(r),this.#e.log?.(`[auth] 凭据已由供应商续期:${e}`);return}if(!this.#e.save(e,{...t,...o},{generation:a})){i.failed.delete(r),this.#e.log?.(`[auth] 已丢弃过期的续期结果:${e}`);return}i.failed.delete(r),this.#e.log?.(`[auth] 凭据已续期:${e}`)}catch(t){i.failed.set(r,this.#n()),this.#e.log?.(`[auth] 凭据续期失败:${e}(${t instanceof Error?t.message:String(t)})`)}}#n(){return this.#e.now?.()??Date.now()}#r(){return this.#e.registry??tg}},og=class extends Error{status;constructor(e,t){super(t),this.name=`AuthError`,this.status=e}},sg=class extends Error{constructor(e){super(e),this.name=`AuthFailure`}},cg=2e3,lg=6e5;function ug(e){return e instanceof Error?e.message:String(e)}function dg(e){return`auth`in e}function fg(e,t){let n=e.when;if(n!==void 0){let e=typeof n.key==`string`?t[n.key]:void 0;if(e===void 0)return!1;let r=e===n.value;if(n.op===`eq`?!r:r)return!1}return!(typeof e.condition==`function`&&!e.condition(t))}function pg(e,t){let n=[];for(let r of e.prompts??[])typeof r.key!=`string`||r.key===``||r.key in t||fg(r,t)&&n.push(r);return n}function mg(e){return e.map(e=>({type:typeof e.type==`string`?e.type:`text`,key:typeof e.key==`string`?e.key:``,message:typeof e.message==`string`?e.message:``,placeholder:typeof e.placeholder==`string`?e.placeholder:``,options:Array.isArray(e.options)?e.options:[]}))}function hg(e){for(let t of[`accountId`,`email`,`name`,`account`,`uid`]){let n=e[t];if(typeof n==`string`&&n.trim()!==``)return n}return null}function gg(e,t){return t==null||t===``||typeof e.accountId==`string`&&e.accountId!==``?e:{...e,accountId:t}}var _g=class{#e;#t;#n;#r;#i=new Map;#a=new Set;#o=new Map;#s=new Map;constructor(e){this.#e=new Jh({file:e.file,legacyFiles:e.legacyFiles??[],log:e.log}),this.#t=e.now??Date.now,this.#n=e.log,this.#r=new ag({get:e=>this.get(e),generation:e=>this.generation(e),save:(e,t,n)=>this.save(e,t,n),refreshOf:e=>this.#c(e)?.refresh,leadOf:e=>this.#c(e)?.refreshLead,now:e.now,log:e.log,registry:e.registry});for(let t of e.adapters??[])this.register(t)}register(e){let t=this.#s.get(e.id)??[];return this.#s.set(e.id,[...t,e].sort((e,t)=>(t.priority??10)-(e.priority??10))),()=>{let t=this.#s.get(e.id);if(t===void 0)return;let n=t.filter(t=>t!==e);if(n.length===0?this.#s.delete(e.id):this.#s.set(e.id,n),n.length===0){let t=this.#o.get(e.id);t!==void 0&&this.#u(t),this.#o.delete(e.id),this.#r.clear(e.id)}e.dispose?.()}}#c(e){return this.#s.get(e)?.[0]}hasAdapter(e){return this.#c(e)!==void 0}methodsOf(e){return(this.#c(e)?.methods()??[]).map(e=>({type:e.type,label:e.label??``}))}reload(){this.#e.invalidate()}generation(e){return this.#i.get(e)??0}locked(e){return this.#a.has(e)}lock(e){this.#a.add(e)}beginLogin(e){let t=this.generation(e)+1;return this.#i.set(e,t),this.#a.delete(e),t}get(e){let t=this.#e.read()[e];return t===void 0?void 0:{...t}}has(e){return e in this.#e.read()}providers(){return Object.keys(this.#e.read())}save(e,t,n){return n?.generation!==void 0&&n.generation!==this.generation(e)||this.#a.has(e)?!1:(this.#e.mutate(n=>({...n,[e]:{...t}})),!0)}saveFromPlugin(e,t){let n=Yh.getStore(),r=n?.providerId===e?{generation:n.generation}:void 0;return this.save(e,t,r)}remove(e){let t=this.generation(e)+1;return this.#i.set(e,t),this.#a.add(e),this.#e.mutate(t=>{if(!(e in t))return null;let n={...t};return delete n[e],n}),t}status(e){let t=this.get(e),n=t!==void 0&&typeof t.expires==`number`&&Number.isFinite(t.expires)?t.expires:null;return{provider:e,signedIn:t!==void 0,type:t!==void 0&&typeof t.type==`string`?t.type:null,account:t===void 0?null:hg(t),expires:n,expiresInMs:n===null?null:Math.max(0,n-this.#t())}}list(){return[...new Set([...this.#s.keys(),...this.providers()])].sort().map(e=>this.status(e))}view(e){let t=this.#o.get(e);return{provider:e,signedIn:this.has(e),methods:this.methodsOf(e),state:t?.state??`idle`,...t===void 0?{}:{url:t.url,instructions:t.instructions,...t.error===void 0?{}:{error:t.error},...t.accountId===void 0?{}:{accountId:t.accountId},...t.expiresAt===null?{}:{expiresAt:t.expiresAt}}}}async signIn(e,t={}){let n=this.#c(e),r=n?.methods()??[];if(n===void 0||r.length===0)throw new og(400,`${e} 未声明登录方式(auth.methods),无法登录;该供应商可能不需要登录`);if(t.restart!==!0&&this.#o.get(e)?.state===`pending`)return this.view(e);let i=t.method??``,a=t.inputs??{};if(i===``&&r.length>1)return{...this.view(e),needMethod:!0};let o=i===``?r[0]:r.find(e=>(e.label??e.type)===i);if(o===void 0)throw new og(400,`未知登录方式:${i}(可选:${r.map(e=>e.label??`(未命名)`).join(`、`)})`);let s=pg(o,a);if(s.length>0)return{...this.view(e),needInputs:mg(s),inputs:a};let c=(t.key??``).trim();if(o.type===`api`&&c===``)return{...this.view(e),needKey:!0,placeholder:o.placeholder??``,label:o.label??o.type,inputs:a};let l=this.beginLogin(e),u;try{let t={key:c,inputs:a};u=await Xh(e,l,()=>n.authorize(o,t))}catch(t){if(this.#p(e,l),t instanceof sg)return this.#o.set(e,{state:`failed`,url:``,instructions:``,expiresAt:null,attempt:null,error:t.message,generation:l}),this.#n?.(`[auth] ✗ ${e} 登录失败:${t.message}`),this.view(e);throw t instanceof og?t:new og(502,`起登录流程失败:${ug(t)}`)}if(dg(u))return this.save(e,gg(u.auth,u.account),{generation:l})?(this.#o.set(e,{state:`success`,url:``,instructions:``,expiresAt:null,attempt:null,generation:l,...u.account===void 0||u.account===null||u.account===``?{}:{accountId:u.account}}),this.#n?.(`[auth] ✓ ${e} 登录完成${u.account?`(${u.account})`:``}`),this.view(e)):(this.#o.set(e,{state:`failed`,url:``,instructions:``,expiresAt:null,attempt:null,error:`登录结果已过期(已登出或被新的登录流程取代)`,generation:l}),this.view(e));let d={state:`pending`,url:u.url,instructions:u.instructions,expiresAt:u.expiresAt,attempt:u,generation:l};return this.#o.set(e,d),this.#l(e,d),this.#n?.(`[auth] ▶ ${e} 登录已发起(${o.label??o.type}${u.url===``?``:`,等待浏览器完成`})`),this.view(e)}async poll(e){let t=this.#o.get(e);return t===void 0||t.state!==`pending`||t.attempt===null?this.view(e):this.#d(e,t)}#l(e,t){t.deadline=t.expiresAt??this.#t()+lg;let n=()=>{if(this.#o.get(e)!==t||t.state!==`pending`)return;let r=setTimeout(()=>{this.#o.get(e)===t&&t.state===`pending`&&this.#d(e,t).catch(()=>void 0).finally(n)},cg);r.unref?.(),t.timer=r};n()}#u(e){e.timer!==null&&e.timer!==void 0&&clearTimeout(e.timer),e.timer=null}#d(e,t){if(t.polling!==null&&t.polling!==void 0)return t.polling;let n=this.#f(e,t).finally(()=>{t.polling===n&&(t.polling=null)});return t.polling=n,n}async#f(e,t){let n=t.deadline??t.expiresAt;if(n!=null&&this.#t()>n)return this.#u(t),this.#o.delete(e),this.#n?.(`[auth] ✗ ${e} 授权已超时`),{...this.view(e),state:`failed`,error:`授权已超时,请重新发起`};let r=t.attempt;if(r===null)return this.view(e);let i;try{i=await r.poll()}catch(n){let r=ug(n);return this.#o.get(e)===t?(this.#p(e,t.generation),this.#u(t),this.#o.delete(e),this.#n?.(`[auth] ✗ ${e} 登录失败:${r}`),{...this.view(e),state:`failed`,error:r}):this.view(e)}return this.#o.get(e)!==t||i===null?this.view(e):this.save(e,gg(i.auth,i.account),{generation:t.generation})?(t.state=`success`,t.attempt=null,t.error=void 0,this.#u(t),i.account!==void 0&&i.account!==null&&i.account!==``&&(t.accountId=i.account),this.#n?.(`[auth] ✓ ${e} 登录完成${t.accountId?`(${t.accountId})`:``}`),this.view(e)):(t.state=`failed`,t.error=`登录结果已过期(已登出或被新的登录流程取代)`,t.attempt=null,this.#u(t),this.view(e))}signOut(e){let t=this.has(e),n=this.#o.get(e);return n!==void 0&&this.#u(n),this.remove(e),this.#r.clear(e),this.#o.delete(e),this.#c(e)?.dispose?.(),t&&this.#n?.(`[auth] ⏏ ${e} 已退出登录`),this.view(e)}async ensureFresh(e){await this.#r.ensureFresh(e)}#p(e,t){this.generation(e)===t&&this.get(e)===void 0&&this.#a.add(e)}},vg=`https://amr-api.open-design.ai`,yg=`/api/v1/cli/device-authorizations`,bg=`0.1.4`,xg=`ezllm-auth`,Sg=6e5,Cg=3e4;function wg(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Tg(e){return typeof e==`string`?e:null}function Eg(e,t){let n=e.error,r=((typeof n==`string`?n:Tg(wg(n)?.message))??``).replace(/\s+/g,` `).trim();return r===``||r.startsWith(`<`)?t:r.length>160?`${r.slice(0,160)}…`:r}async function Dg(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(Cg)});if(!n.ok){let e=await n.text().then(e=>{let t=e.replace(/\s+/g,` `).trim();return t.startsWith(`<`)?``:t.slice(0,160)}).catch(()=>``);throw Error(`HTTP ${String(n.status)}${e===``?``:`: ${e}`}`)}let r=wg(await n.json());if(r===null)throw Error(`响应不是 JSON 对象`);return r}function Og(e){let t=Tg(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}async function kg(){let e=await Dg(`${vg}${yg}`,{method:`POST`,headers:{accept:`application/json`,"user-agent":xg},body:JSON.stringify({cliVersion:bg,host:T()||`ezllm`,profile:`prod`})}),t=Tg(e.deviceId),n=Tg(e.deviceSecret),r=Tg(e.activationUrl);if(t===null||n===null||r===null)throw Error(`授权接口返回缺少必要字段(${Eg(e,`device authorization`)})`);let i=Tg(e.userCode),a=Og(e.expiresAt)??Date.now()+Sg;return{url:r,instructions:`已发起 Open Design 授权${i===null||i===``?``:`(设备码 ${i})`}:在打开的页面确认 CLI 登录,完成后这里会自动继续。`,expiresAt:a,poll:async()=>{let e;try{e=await Dg(`${vg}${yg}/${encodeURIComponent(t)}/token`,{method:`POST`,headers:{accept:`application/json`,"user-agent":xg},body:JSON.stringify({deviceSecret:n})})}catch(e){let t=e instanceof Error?e.message:String(e);throw/^HTTP 40[134]/u.test(t)?Error(`授权码已失效,请重新发起授权`):e}let r=Tg(e.controlKey);if(r!==null&&r!==``){let t=wg(e.user);return{auth:{type:`api`,key:r},account:t===null?null:Tg(t.email)}}let i=(Tg(e.status)??``).toLowerCase();if([`expired`,`canceled`,`cancelled`,`denied`,`rejected`].includes(i))throw Error(`授权被${i===`expired`?`超时作废`:`拒绝或撤销`},请重新发起`);return null}}}var Ag={id:`opendesign`,priority:50,methods:()=>[{type:`oauth`,label:`登录授权`}],authorize:()=>kg()},jg=null;function Mg(){return jg===null&&(jg=new _g({file:kt(),legacyFiles:[At()],adapters:[Ag],log:e=>D(e)})),jg}function Ng(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function Pg(){let e=e=>{let t=typeof e==`object`&&e?e:{},n=typeof t.apiBase==`string`&&t.apiBase.trim()!==``?t.apiBase:void 0,r=typeof t.apiKey==`string`&&t.apiKey.trim()!==``?t.apiKey:void 0;return{apiBase:n,apiKey:r===void 0?void 0:Ng(r)}};try{let t=El();if(t===null||!Array.isArray(t.providers))return null;let n=new Map;for(let r of t.providers){let t=typeof r==`object`&&r?r.name:void 0;typeof t==`string`&&t!==``&&n.set(t,e(r))}return n}catch{return null}}function Fg(e){return Pg()?.get(e)??null}function Ig(e){let t=Fg(e);if(t===null)return null;let n=Mh(t.apiBase);return n===null?null:n.authKey??e}function Lg(e){let t=Fg(e);return t===null?`key`:Mh(t.apiBase)?.authCredentialField??`key`}var Rg=Ht(`quota.json`);function zg(e){let t=e=>{let t=e=>{let t=J(e);if(t===null)return null;let n=t.used;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=t.cap,i=t.resetAt;return{used:n,cap:typeof r==`number`&&Number.isFinite(r)?r:null,resetAt:typeof i==`number`&&Number.isFinite(i)?i:null,exceeded:t.exceeded===!0}},n=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null},r=e=>{let t=J(e);if(t===null)return null;let r=n(t.cost),i=n(t.requests);if(r===null&&i===null)return null;let a=t.currency;return{cost:r,currency:typeof a==`string`&&a!==``?a:null,requests:i}},i=e=>{if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=J(n);if(e===null)continue;let r=e.label,i=e.value;typeof r==`string`&&r!==``&&typeof i==`string`&&i!==``&&t.push({label:r,value:i})}return t.length>0?t:null},a=e=>{if(!Array.isArray(e))return null;let t=[];for(let r of e){let e=J(r);if(e===null)continue;let i=e.name,a=e.display;if(typeof i!=`string`||i===``||typeof a!=`string`||a===``)continue;let o=e.usedPercent;t.push({name:i,usedPercent:typeof o==`number`&&Number.isFinite(o)?o:0,display:a,amount:n(e.amount),limit:n(e.limit),unit:typeof e.unit==`string`&&e.unit!==``?e.unit:null})}return t.length>0?t:null},o=J(e);if(o===null)return null;let s=o.totalTokens,c=o.totalRuns,l=o.voucherBalance,u=o.balance,d=o.totalCost,f=o.totalCostCurrency;return{fiveHour:t(o.fiveHour),weekly:t(o.weekly),monthly:t(o.monthly),totalTokens:typeof s==`number`&&Number.isFinite(s)?s:null,totalRuns:typeof c==`number`&&Number.isFinite(c)?c:null,voucherBalance:typeof l==`number`&&Number.isFinite(l)?l:null,balance:typeof u==`number`&&Number.isFinite(u)?u:null,totalCost:n(d),totalCostCurrency:typeof f==`string`&&f!==``?f:null,today:r(o.today),yesterday:r(o.yesterday),extraStats:i(o.extraStats),windows:a(o.windows)}},n=J(Rg.get(e));if(n===null)return null;let r=n.fetchText,i=n.authCredential,a=n.authAccount,o=n.vendorId,s=n.fetchedAt,c=n.error;return{fetchText:typeof r==`string`&&r.trim()!==``?r:void 0,authCredential:typeof i==`string`&&i.trim()!==``?i:void 0,authAccount:typeof a==`string`&&a.trim()!==``?a:void 0,vendorId:typeof o==`string`?o:void 0,snapshot:t(n.snapshot)??void 0,fetchedAt:typeof s==`number`&&Number.isFinite(s)?s:void 0,error:typeof c==`string`&&c!==``?c:void 0}}function Bg(e,t){Rg.set(e,t)}function Vg(e){Rg.get(e)!==void 0&&Rg.set(e,void 0)}function Hg(){let e=Rg.getAll(),t={};for(let n of Object.keys(e)){let e=zg(n);e!==null&&(t[n]=e)}return t}function Ug(e,t,n,r){let i=zg(e);Bg(e,{fetchText:i?.fetchText,authCredential:i?.authCredential,authAccount:i?.authAccount,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function Wg(e,t){let n=zg(e);if(n===null){Bg(e,{error:t});return}Bg(e,{...n,error:t})}var Gg=!1;function Kg(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function qg(e){let t=Ig(e);if(t===null)return;let n=Mg(),r=n.get(t),i=Lg(e),a=r?.[i],o=typeof a==`string`&&a.trim()!==``?a:void 0;if(o!==void 0)return o;let s=i===`key`?void 0:r?.key,c=typeof s==`string`&&s.trim()!==``?s:void 0;if(c!==void 0)return c;if(n.locked(t))return;let l=zg(e),u=l?.authCredential;if(u!==void 0){if(r!==void 0)return u;try{let r=l?.authAccount;if(n.save(t,{type:`api`,[i]:u,...r!==void 0&&r.trim()!==``?{accountId:r}:{}})){let t=zg(e);t!==null&&Bg(e,{...t,authCredential:void 0,authAccount:void 0})}}catch{}return u}}function Jg(e){return qg(e)!==void 0}async function Yg(e){try{let t=Fg(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&Ph(t.apiBase)!==null)({vendorId:n,vendor:r}=Fh(t.apiBase));else if(Mh(t.apiBase)!==null){let i=qg(e);if(i===void 0)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);({vendorId:n,vendor:r}=Nh(i,t.apiBase))}else if(Ah(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=jh(t.apiKey,t.apiBase))}else{let i=zg(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=Ih(i,t.apiBase))}let i=await r.fetchQuota();Ug(e,n,i,Date.now())}catch(t){Wg(e,Kg(t))}return zg(e)}async function Xg(){let e=()=>{let e=Pg();return e===null?null:new Set(e.keys())};if(!Gg){Gg=!0;try{let t=Pg(),n=[];for(let[e,r]of t??[]){if(Ah(r.apiBase)!==null||Ph(r.apiBase)!==null){n.push(e);continue}Mh(r.apiBase)!==null&&qg(e)!==void 0&&n.push(e)}for(let e of n)await Yg(e);let r=e();for(let[e,t]of Object.entries(Hg()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){Vg(e);continue}n.includes(e)||await Yg(e)}}catch(e){k(`[quota] 刷新失败:`,Kg(e))}finally{Gg=!1}}}var Zg=new Set;function Qg(e){let t=Ig(e);if(t===null)throw Error(`该供应商未支持授权登录查询额度`);return t}async function $g(e){if(Fg(e)===null)throw Error(`供应商配置不存在(可能已被删除)`);let t=Qg(e);Zg.delete(e);let n;try{n=await Mg().signIn(t,{restart:!0})}catch(e){throw e instanceof og?Error(e.message):e}if(n.needMethod===!0||n.needKey===!0||n.needInputs!==void 0)throw Error(`该供应商的登录需要额外输入,请在「插件」页面完成登录`);return{url:n.url??``,instructions:n.instructions??``,expiresAt:n.expiresAt??null}}async function e_(e){let t=Ig(e);if(t===null)return{status:`idle`};let n=Mg(),r=await n.poll(t);if(r.state===`failed`)return{status:`error`,error:r.error??`授权失败`};if(r.state===`pending`)return{status:`pending`};if(!n.has(t)&&!Jg(e))return{status:`idle`};let i=n.status(t).account??r.accountId??null;return r.state===`success`&&!Zg.has(e)?(Zg.add(e),{status:`authorized`,account:i,entry:await Yg(e)}):{status:`authorized`,account:i,entry:zg(e)}}function t_(e){let t=Ig(e);t!==null&&Mg().signOut(t),Zg.delete(e);let n=zg(e);return n===null?null:(Bg(e,{...n,authCredential:void 0,authAccount:void 0,error:void 0}),zg(e))}function n_(){let e=async e=>{let t=(await _p(e))?.fetchText;return typeof t==`string`?t:null},t=()=>kh().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource,...e.matchMode===void 0?{}:{matchMode:e.matchMode},...e.pathPrefix===void 0?{}:{pathPrefix:e.pathPrefix},...e.credentialSource===`deviceAuth`?{authLabel:`登录授权`}:{}})),n=(e,t)=>{if(t===null)return null;let n=Ig(e);if(n===null)return t;let r=Mg().status(n);return{...t,authCredential:void 0,authSignedIn:r.signedIn,authAccount:r.account??t.authAccount}},r=()=>{let e={};for(let[t,r]of Object.entries(Hg())){let i=n(t,r);i!==null&&(e[t]=i)}return e},i=new j;return i.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:r()})),i.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),i.put(`/:provider`,async t=>{let r=t.req.param(`provider`),i=Fg(r)?.apiBase;if(Ph(i)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(Ah(i)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);if(Mh(i)!==null)return t.json({ok:!1,error:`该供应商的额度需先「登录授权」,无需粘贴凭据`},400);let a=await e(t);if(a===null)return t.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let o=zg(r);Bg(r,{fetchText:a,vendorId:o?.vendorId,snapshot:o?.snapshot,fetchedAt:o?.fetchedAt,error:void 0});let s=await Yg(r);return t.json({ok:!0,entry:n(r,s)})}),i.delete(`/:provider`,e=>(Vg(e.req.param(`provider`)),e.json({ok:!0}))),i.post(`/:provider/refresh`,async e=>{let t=e.req.param(`provider`),r=await Yg(t);return e.json({ok:!0,entry:n(t,r)})}),i.post(`/:provider/auth`,async e=>{let t=e.req.param(`provider`);try{let n=await $g(t);return e.json({ok:!0,auth:n})}catch(t){let n=t instanceof Error?t.message:String(t);return e.json({ok:!1,error:n},400)}}),i.get(`/:provider/auth`,async e=>{let t=e.req.param(`provider`),r=await e_(t);return e.json({ok:!0,auth:r.entry===void 0?r:{...r,entry:n(t,r.entry)}})}),i.delete(`/:provider/auth`,e=>{let t=e.req.param(`provider`),r=t_(t);return e.json({ok:!0,entry:n(t,r)})}),i}function r_(){let e=new j;return e.get(`/`,e=>e.json({ok:!0,providers:Mg().list()})),e}function i_(e){return e===`0.0.0.0`||e===`::`}function a_(e=ee()){let t=[];for(let n of Object.values(e))for(let e of n??[])e.internal||e.family!==`IPv4`||t.includes(e.address)||t.push(e.address);return t}function o_(e,t){let n=new j;return n.get(`/`,n=>n.json({listenPort:fp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&i_(t.hostname)?{lanAddresses:a_()}:{},masterKey:Fl()})),n}var s_=864e5,c_=3e5,l_=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,u_=new Map;try{let e=g(Et(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;u_.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function d_(){let e=e=>({model:e.model,client:e.client,sessionId:e.sessionId,noSession:e.noSession===`1`||void 0,startDate:e.startDate||e.date,endDate:e.endDate||e.date,status:e.status,pathGroup:e.pathGroup,keyword:e.keyword}),t=e=>{let t=u_.get(e);if(!t)return null;let n=t.value.error===void 0?s_:c_;return Date.now()-t.at>=n?(u_.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of u_)e[t]={...n,_ts:r};C(Et(),JSON.stringify(e))}catch(e){k(`保存 IP 缓存失败:`,e.message)}},r=async e=>{let r=t(e);if(r)return r;let i=await(await fetch(l_.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return u_.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return u_.set(e,{value:a,at:Date.now()}),n(),a},i=new j;return i.onError(wp),i.get(`/dates`,e=>{let t=uf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=df();return e.json({clients:t})}),i.get(`/ipinfo`,async e=>{let t=e.req.query(`ip`)||``;if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return e.json({error:`invalid ip`},400);try{let n=await r(t);return e.json({ip:t,...n})}catch(e){throw new Cp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Jd(t);return n||=(await Of(),Jd(t)??hu(Number(t))),n?e.json({...n,meta:{...n.meta,tps:Zd(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Tp(async t=>{let n=t.req.query(),r=cf({...e(n),sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize}),i=(n.keyword??``).trim();return i.length>=2&&r.total===0&&(r=hf({...e(n),keyword:i,sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize})),t.json({...r,items:r.items.map(e=>({...e,user_agent:nu(e.headers),tps:Zd(e)}))})})),i.get(`/sessions`,Tp(t=>{let n=t.req.query(),r=pf({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Tp(async t=>{await Af();let n=du().length;n>0&&O(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=_f(e(r));return D(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var f_=3e4,p_=9e5,m_=5242880,h_=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],g_=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function __(e){let t=e.toLowerCase();return t===``||t.startsWith(`text/`)||t.startsWith(`application/json`)||t.endsWith(`+json`)||t.startsWith(`application/xml`)||t.endsWith(`+xml`)||t.startsWith(`application/javascript`)||t.startsWith(`application/x-www-form-urlencoded`)||t.startsWith(`application/x-ndjson`)||t.startsWith(`application/graphql`)}function v_(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(g_.includes(n.toLowerCase())||(t[n]=r));return t}function y_(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?f_:Math.min(Math.floor(e),p_)}function b_(e){if(typeof e!=`string`||e.trim()===``)throw new Cp(400,`缺少 url(要转发的目标地址)`);let t=e.trim(),n=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)?t:`https://${t}`,r;try{r=new URL(n)}catch{throw new Cp(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new Cp(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function x_(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function S_(e){let t=e.body;if(t===null)return{text:``,truncated:!1};let n=t.getReader(),r=[],i=0,a=!1;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(t===void 0)continue;let o=m_-i;if(t.byteLength>=o){r.push(t.subarray(0,o)),i+=o,a=!0;break}r.push(t),i+=t.byteLength}}finally{await n.cancel().catch(()=>void 0)}let o=new Uint8Array(i),s=0;for(let e of r)o.set(e,s),s+=e.byteLength;return{text:new TextDecoder(`utf-8`).decode(o),truncated:a}}function C_(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function w_(e){let{url:t,method:n,headers:r,body:i,timeoutMs:a}=e,o=i!==void 0&&n!==`GET`&&n!==`HEAD`,s=Date.now(),c;try{c=await fetch(t,{method:n,headers:r,...o?{body:i}:{},signal:AbortSignal.timeout(a),redirect:`follow`})}catch(e){let n=e instanceof Error?e.message:String(e);throw new Cp(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=__(l),{text:d,truncated:f}=u?await S_(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:C_(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function T_(){let e=new j;return e.onError(wp),e.post(`/`,async e=>{let t=await _p(e);if(t===null)throw new Cp(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!h_.includes(n))throw new Cp(400,`不支持的请求方法:${n}(可用 ${h_.join(` / `)})`);return await w_({url:b_(t.url),method:n,headers:v_(t.headers),body:x_(t.body),timeoutMs:y_(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await w_({url:b_(t.url),method:`GET`,headers:v_(void 0),body:void 0,timeoutMs:y_(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function E_(e){return`http://127.0.0.1:${String(e.port)}`}var D_=`daemon.json`;function O_(e){let t=e=>{let t=e.port??null;return{role:`main`,pid:e.pid??null,status:e.status??`stopped`,port:t,address:t?`http://127.0.0.1:${String(t)}`:null,startedAt:e.startedAt??null,restarts:null}},n=e=>{try{let t=JSON.parse(g(c(e,D_),`utf-8`))?.children;if(typeof t!=`object`||!t)return null;for(let e of Object.values(t)){let t=e;if(t?.pid===process.pid)return typeof t.startedAt==`number`?{pid:t.pid,startedAt:t.startedAt}:null}return null}catch{return null}},r=new j;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:E_(e)})),r.get(`/processes`,r=>{let i=n(e.appDir);return r.json({ok:!0,processes:[t({pid:i?.pid??process.pid,status:`online`,port:e.port,startedAt:i?.startedAt??e.startedAt})]})}),r}var k_=`ezllm-autostart.vbs`,A_=`ezllm-autostart.cmd`,j_=`com.ezllm.autostart`,M_=`ezllm.service`,N_=`autostart.opt-out`,P_=`ezllm-v2`,F_=`Auto-generated by "npx ezllm install" (${P_}). Managed automatically by ezllm. To remove it, run \`npx ezllm uninstall\`.`;function I_(e){return c(e,N_)}function L_(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),k_)}function R_(){return c(w(),`Library`,`LaunchAgents`,`${j_}.plist`)}function z_(){return c(w(),`.config`,`systemd`,`user`,M_)}var B_=3e4;function V_(e,t){return new Promise(n=>{let r=ce(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},B_),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var H_={win32:{itemPath:L_,on:q_,off:X_},darwin:{itemPath:R_,on:J_,off:Z_},linux:{itemPath:z_,on:Y_,off:Q_}};function U_(e){return H_[e]??null}function W_(e,t){return[e,t.entryJs,...t.args??[]]}function G_(e){return c(e,`logs`,`autostart.log`)}async function K_(e,t,n=V_){try{C(e,t,`utf16le`);return}catch(r){if(await n(`powershell`,[`-NoProfile`,`-Command`,`$bytes=[Convert]::FromBase64String('${Buffer.from(t,`utf16le`).toString(`base64`)}');[IO.File]::WriteAllBytes('${e.replace(/'/g,`''`)}', $bytes)`])!==0)throw r}}async function q_(e,t){let n=(e,t)=>{let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 npx ezllm install`)},r=(e,t)=>{let r=G_(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${F_}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${W_(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
85
85
|
`)},i=e=>[`' ${F_}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
|
|
86
86
|
`),a=L_(),o=c(t.appDir,A_);return C(o,r(e,t),`utf-8`),await K_(a,`\uFEFF${i(o)}`),a}async function J_(e,t){let n=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`),r=(e,t)=>{let r=G_(t.appDir),i=Object.entries(t.env).map(([e,t])=>` <string>${n(e)}</string>\n <string>${n(t)}</string>`).join(`
|
|
87
87
|
`),a=W_(e,t).map(e=>` <string>${n(e)}</string>`).join(`
|
|
@@ -94,7 +94,7 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
94
94
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
95
95
|
`))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=yv(t.toml,t.ptr),i=bv(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};function xv(e,t=0){let n=e.indexOf(`
|
|
96
96
|
`,t);return e.charCodeAt(n-1)===13&&n--,n}function Sv(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}if(t<32&&t!==9||t===127)throw new Z(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function Cv(e,t,n){let r;for(;;){for(;(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;Sv(e)}}function wv(e,t,n){let r=e.p;if(!n){r=xv(e.s,r),e.p=r<0?e.s.length:r;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)Sv(e);else if(r===n||r===t)return}throw new Z(`cannot find end of structure`,{toml:e.s,ptr:r})}var Tv=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Ev=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Dv=/^[+-]?0[0-9_]/;function Ov(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)throw new Z(`control characters are not allowed in strings`,{toml:e.s,ptr:e.p});else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r))return a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),c||(o+=e.s.slice(s,e.p)),e.p+=a?3:1,o;else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1){if(n===120||n===117||n===85){let t=0,r=n===120?2:n===117?4:8;for(let n=0;n<r;n++,e.p++){let n=e.s.charCodeAt(e.p+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new Z(`invalid non-hex character in unicode escape`,{toml:e.s,ptr:e.p+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new Z(`invalid unicode escape`,{toml:e.s,ptr:e.p});o+=String.fromCodePoint(t),s=e.p+1,c=0}else if(n===32||n===9)c=2;else{if(n===98)o+=`\b`;else if(n===116)o+=` `;else if(n===110)o+=`
|
|
97
|
-
`;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new Z(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new Z(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new Z(`unfinished string`,{toml:e.s,ptr:t})}function kv(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Sv({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Av(e,t,n){let r=e.p,i={toml:e.s,ptr:r};wv(e,44,n);let a=kv(e,r,e.p);if(!a)throw new Z(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=Tv.test(a);if(o||Ev.test(a)){if(Dv.test(a))throw new Z(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new Z(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new Z(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new vv(a);if(!s.isValid())throw new Z(`invalid value`,i);return s}function jv(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new Z(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?Fv(e,n):Pv(e,n);return e.d++,t}if(i===34||i===39)return Ov(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new Z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new Z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return Av(e,n,t)}var Mv=/^[a-zA-Z0-9-_]+[ \t]*$/;function Nv(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new Z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new Z(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=Ov(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=xv(c);if(l>-1)throw new Z(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new Z(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new Z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!Mv.test(t))throw new Z(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,Cv(e,!0,!0),i}function Pv(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Cv(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Nv(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new Z(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new Z(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=jv(e,125,t);if(r.add(o[a]=u),Cv(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new Z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Z(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function Fv(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Cv(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(jv(e,93,t)),Cv(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new Z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Z(`unfinished array encountered`,{toml:e.s,ptr:e.p})}function Iv(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function Lv(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Cv(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Nv(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new Z(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=Iv(n,i,a,t?2:1);if(!l)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=Iv(Nv(r),s,c,0);if(!t)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=jv(r,void 0,n)}if(Cv(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new Z(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Cv(r)}return i}var Rv=`ellm-proxy`,zv=c(w(),`.codex`,`config.toml`),Bv=`# >>> ellm-proxy codex switch >>>`,Vv=`# <<< ellm-proxy codex switch <<<`;function Hv(e){return p(e)?g(e,`utf-8`):null}function Uv(){return RegExp(`${Bv}[\\s\\S]*?${Vv}\\n?`)}function Wv(e,t,n=(e,t)=>
|
|
97
|
+
`;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new Z(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new Z(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new Z(`unfinished string`,{toml:e.s,ptr:t})}function kv(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Sv({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Av(e,t,n){let r=e.p,i={toml:e.s,ptr:r};wv(e,44,n);let a=kv(e,r,e.p);if(!a)throw new Z(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=Tv.test(a);if(o||Ev.test(a)){if(Dv.test(a))throw new Z(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new Z(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new Z(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new vv(a);if(!s.isValid())throw new Z(`invalid value`,i);return s}function jv(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new Z(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?Fv(e,n):Pv(e,n);return e.d++,t}if(i===34||i===39)return Ov(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new Z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new Z(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return Av(e,n,t)}var Mv=/^[a-zA-Z0-9-_]+[ \t]*$/;function Nv(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new Z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new Z(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=Ov(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=xv(c);if(l>-1)throw new Z(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new Z(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new Z(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!Mv.test(t))throw new Z(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,Cv(e,!0,!0),i}function Pv(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Cv(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Nv(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new Z(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new Z(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=jv(e,125,t);if(r.add(o[a]=u),Cv(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new Z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Z(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function Fv(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Cv(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(jv(e,93,t)),Cv(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new Z(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Z(`unfinished array encountered`,{toml:e.s,ptr:e.p})}function Iv(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function Lv(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Cv(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Nv(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new Z(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=Iv(n,i,a,t?2:1);if(!l)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=Iv(Nv(r),s,c,0);if(!t)throw new Z(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=jv(r,void 0,n)}if(Cv(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new Z(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Cv(r)}return i}var Rv=`ellm-proxy`,zv=c(w(),`.codex`,`config.toml`),Bv=`# >>> ellm-proxy codex switch >>>`,Vv=`# <<< ellm-proxy codex switch <<<`;function Hv(e){return p(e)?g(e,`utf-8`):null}function Uv(){return RegExp(`${Bv}[\\s\\S]*?${Vv}\\n?`)}function Wv(e,t,n=(e,t)=>se(e,t,{stdio:`ignore`}),r=process.platform,i=c(w(),`.zshrc`)){let a=e=>e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),o=(e,t,n)=>{let r=[Bv,`export ${e}="${a(t)}"`,Vv,``].join(`
|
|
98
98
|
`),i=Hv(n)??``,o=Uv(),c=o.test(i)?i.replace(o,r):i&&!i.endsWith(`
|
|
99
99
|
`)?`${i}\n${r}`:i+r;m(s(n),{recursive:!0}),C(n,c,`utf-8`)};if(r===`win32`)n(`setx`,[e,t]);else if(r!==`darwin`)return!1;else o(e,t,i);return process.env[e]=t,!0}function Gv(e,t=c(w(),`.zshrc`),n=process.platform){if(n!==`darwin`)return!1;let r=Hv(t),i=r?.match(Uv());return!r||!i||!i[0].includes(`export ${e}=`)?!1:(C(t,r.replace(Uv(),``),`utf-8`),!0)}function Kv(e){try{return Lv(e)?.model_provider===Rv}catch{return!1}}function qv(e,t){let n;try{n=Lv(e)}catch(e){throw Error(`编辑后的 config.toml 不是合法 TOML,已保留原文件: ${e.message}`)}if(t&&n?.model_provider!==Rv)throw Error(`编辑后的 config.toml 顶层 model_provider 不是 "${Rv}",已保留原文件`)}function Jv(){let e=Hv(zv);return e?Kv(e):!1}function Yv(e){let t=(()=>{let e=Rv.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^\\s*\\[model_providers\\.(?:"|')?(?:${e}|ezllm)(?:"|')?\\]\\s*$`)})(),n=e.split(`
|
|
100
100
|
`),r=[],i=!1;for(let e of n){if(t.test(e)){i=!0;continue}i&&/^\s*\[/.test(e)&&(i=!1),i||r.push(e)}return r.join(`
|
|
@@ -224,6 +224,6 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
224
224
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
225
225
|
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){l(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,a=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(i(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(t.sep,`newline`)){let e=c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:a,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!i(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){l(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||i(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));u(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
226
226
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
227
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),fb=E((e=>{var t=ib(),n=Vy(),r=Hy(),i=fy(),a=Q(),o=ub(),s=db();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),pb=E((e=>{var t=ib(),n=Vy(),r=zy(),i=Hy(),a=iy(),o=Q(),s=hy(),c=$(),l=_y(),u=yy();cb();var d=lb(),f=ub(),p=db(),m=fb(),h=Qv();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),mb=`DEEPSEEK_API_KEY`,hb=1,gb=`ezllm`,_b=()=>process.env.DSH_HOME||c(w(),`.dsh`),vb=()=>c(_b(),`settings.yaml`),yb=()=>c(_b(),`.credentials.yaml`);function bb(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function xb(e,t){let n=(0,pb.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function Sb(e){return`${e}/v1`}function Cb(e){let t=bb(vb());if(!t)return!1;try{return dv(xb(t,vb()).toJS()?.[`llm-deepseek`]?.baseURL,Sb(e))}catch{return!1}}function wb(e){let t=Sb(e.gatewayBase);m(_b(),{recursive:!0});let n=vb(),r=bb(n),i=xb(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);lv(n),i.setIn([`llm-deepseek`,`baseURL`],t),Eb(n,i);let o=yb(),s=e.masterKey||gb,c=bb(o);if(lv(o),c===null){let e=xb(``,o);e.set(`version`,hb),e.setIn([`refs`,mb],s),Eb(o,e);return}let l=xb(c,o),u=l.toJS();if(!(0,pb.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==hb)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(hb)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(mb,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,mb],s)}Eb(o,l)}function Tb(e,t){let n=vb(),r=yb(),i=!1;if(uv(n))i=!0;else{let t=bb(n);if(t){let r=xb(t,n);if(dv(r.toJS()?.[`llm-deepseek`]?.baseURL,Sb(e))){r.deleteIn([`llm-deepseek`,`baseURL`]);let e=r.toJS()?.[`llm-deepseek`];(!e||typeof e!=`object`||Object.keys(e).length===0)&&r.deleteIn([`llm-deepseek`]),Eb(n,r),i=!0}}}if(uv(r))i=!0;else{let e=bb(r);if(e){let n=xb(e,r),a=n.toJS(),o=e=>e===t||e===gb;a?.version===hb&&o(a?.refs?.[mb])?(n.deleteIn([`refs`,mb]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),Eb(r,n),i=!0):a?.version===void 0&&o(a?.[mb])&&(n.deleteIn([mb]),Eb(r,n),i=!0)}}return i}function Eb(e,t){let n=t.toString(),r=(0,pb.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);m(s(e),{recursive:!0}),C(e,n,`utf-8`)}async function Db(e){let t;try{t=(await e.req.json())?.enabled}catch{return e.json({ok:!1,error:`请求体不是合法 JSON`},400)}return typeof t==`boolean`?t:e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400)}function Ob(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new j;return n.get(`/`,t=>{let n=E_(e);return t.json({ok:!0,claudeCode:mv(n),codex:Jv(),dsh:Cb(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Db(n);if(r instanceof Response)return r;let i=E_(e);if(r){let e=t(Tt());return e?(hv({gatewayBase:i,token:e}),n.json({ok:!0,claudeCode:!0,file:`~/.claude/settings.json`,note:`已备份原文件为 settings.json.ellm-bak,重启 Claude Code 会话后生效`})):n.json({ok:!1,error:`配置未设置 masterKey,Claude Code 代理无法鉴权。请先在配置文件中设置 masterKey: ${Tt()}`},400)}let a=gv(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Db(n);if(r instanceof Response)return r;let i=E_(e);if(r){let e=t(Tt()),r=Xv({gatewayBase:i,apiKey:e||void 0});return n.json({ok:!0,codex:!0,file:`~/.codex/config.toml`,note:e?r?`已备份原文件为 config.toml.ellm-bak;已自动写入用户环境变量 ELLM_PROXY_API_KEY(Windows 写注册表 / macOS 写 ~/.zshrc,对之后新开的终端与 Codex 会话生效)`:`已备份原文件为 config.toml.ellm-bak;当前平台不支持自动写入,请手动设置环境变量 ELLM_PROXY_API_KEY=${e}`:`已备份原文件为 config.toml.ellm-bak;请设置环境变量 ELLM_PROXY_API_KEY(网关未配 masterKey 时取值任意)`})}let a=Zv();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Db(n);if(r instanceof Response)return r;let i=E_(e),a=t(Tt());if(r)return wb({gatewayBase:i,masterKey:a}),n.json({ok:!0,dsh:!0,file:`~/.dsh/settings.yaml`,note:a?`已写入 settings.yaml(llm-deepseek.baseURL)与 .credentials.yaml(refs.DEEPSEEK_API_KEY),原文件备份为 *.ellm-bak。注意:进程环境里已设 DEEPSEEK_API_KEY 时其优先级更高,需自行改用网关 masterKey;模型请在 dsh 内选择与网关部署名一致的模型`:`已写入 settings.yaml 与 .credentials.yaml(网关未配 masterKey,密钥为占位值即可放行),原文件备份为 *.ellm-bak。模型请在 dsh 内选择与网关部署名一致的模型`});let o=Tb(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var kb=[`/api/*(管理台与全部接口)`,`POST|GET /api/fetch(通用 HTTP 转发)`,`GET /api/service/status|processes`,`GET /api/service/autostart`,`GET /api/service/update`,`POST /api/service/update/check|apply`,`GET|POST /api/service/managed`,`PUT|DELETE /api/service/managed/:name`,`POST /api/service/managed/:name/start|stop|restart`,`GET /api/service/plugins`,`POST /api/service/plugins/restart`,`GET /api/harness`,`POST /api/harness/claude-code|codex|dsh`,`GET /api/latency/history`,`POST /api/latency/run`].join(`, `);function Ab(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,bp),e.route(`/api/setup`,Dp()),e.use(`/api/*`,Sp),e.route(`/api/config`,Np({runtime:n})),e.route(`/api/test`,zp(n)),e.route(`/api/latency`,am(n)),e.route(`/api/usage`,om()),e.route(`/api/quota`,n_()),e.route(`/api/provider-auth`,r_()),e.route(`/api/logs`,d_()),e.route(`/api/status`,o_(n,i)),e.route(`/api/fetch`,T_()),r&&(e.route(`/api/service`,O_(r)),e.route(`/api/service`,iv(r)),e.route(`/api/service/managed`,ov(r)),e.route(`/api/service/plugins`,cv(r)),e.route(`/api/harness`,Ob(r)))}var jb=(e,t=Mb)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},Mb={aac:`audio/aac`,avi:`video/x-msvideo`,avif:`image/avif`,av1:`video/av1`,bin:`application/octet-stream`,bmp:`image/bmp`,css:`text/css; charset=utf-8`,csv:`text/csv; charset=utf-8`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gif:`image/gif`,gz:`application/gzip`,htm:`text/html; charset=utf-8`,html:`text/html; charset=utf-8`,ico:`image/x-icon`,ics:`text/calendar; charset=utf-8`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript; charset=utf-8`,json:`application/json`,jsonld:`application/ld+json`,map:`application/json`,mid:`audio/x-midi`,midi:`audio/x-midi`,mjs:`text/javascript; charset=utf-8`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,pdf:`application/pdf`,png:`image/png`,rtf:`application/rtf`,svg:`image/svg+xml; charset=utf-8`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain; charset=utf-8`,wasm:`application/wasm`,webm:`video/webm`,weba:`audio/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml; charset=utf-8`,xml:`application/xml; charset=utf-8`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,gltf:`model/gltf+json`,glb:`model/gltf-binary`},Nb=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,Pb={br:`.br`,zstd:`.zst`,gzip:`.gz`},Fb=Object.keys(Pb),Ib=(()=>{let[e,t]=ye.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Lb=e=>Ib?i.toWeb(e):new ReadableStream({start(t){e.on(`data`,e=>{t.enqueue(e)}),e.on(`error`,e=>{t.error(e)}),e.on(`end`,()=>{t.close()})},cancel(){e.destroy()}}),Rb=e=>{let t;try{t=Se(e)}catch{}return t},zb=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Bb=e=>zb(e,decodeURI),Vb=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!xe(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(r,i)=>{if(r.finalized)return i();let a;if(n)a=n;else try{if(a=Bb(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=Ce(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=Rb(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=Ce(o,t),s=Rb(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=jb(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||Nb.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of Fb){if(!e.has(t))continue;let n=Rb(o+Pb[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=Pb[t];break}}}let l,u=s.size,d=r.req.header(`range`)||``;if(r.req.method==`HEAD`||r.req.method==`OPTIONS`)r.header(`Content-Length`,u.toString()),r.status(200),l=r.body(null);else if(!d)r.header(`Content-Length`,u.toString()),l=r.body(Lb(be(o)),200);else{r.header(`Accept-Ranges`,`bytes`),r.header(`Date`,s.birthtime.toUTCString());let e=d.replace(/bytes=/,``).split(`-`,2),t=parseInt(e[0],10)||0,n=parseInt(e[1],10)||u-1;u<n-t+1&&(n=u-1);let i=n-t+1,a=be(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(Lb(a),206)}return await e.onFound?.(o,r),l}},Hb=s(ne(import.meta.url));function Ub(e,t){let n=t??[c(Hb,`web-ui`),l(Hb,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(Hb,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(Hb,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await le(c(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await Vb({root:n})(e,t);return r instanceof Response&&r.status===200&&e.req.path.startsWith(`/assets/`)&&r.headers.set(`Cache-Control`,`public, max-age=31536000, immutable`),r}))}function Wb(e,t,n){let r=new j;return r.use(`/v1/*`,gp()),Ab(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),Ub(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${kb})`},404)),r.onError(wp),r}var Gb=6e4;function Kb(e){let t=()=>{let e=El()?.latencyTest;return typeof e==`object`&&e?e:{}},n=(e,t,n)=>{if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r};return{name:`latencyAutoTest`,everyMs:Gb,run:async()=>{try{if(nm(e)===0)return;let r=t();if(!n(r,Jp()??void 0,Date.now()))return;D(`[latency] 自动测试触发`),await tm(e)}catch(e){k(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var qb=6e5,Jb=3e4;function Yb(){return{name:`quotaRefresh`,everyMs:qb,firstDelayMs:Jb,run:async()=>{try{await Xg()}catch(e){k(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var Xb=6e4,Zb=3e4,Qb=20,$b=3e4,ex=1024,tx=/^[^\u0000-\u001f\u007f]{1,24}$/u,nx=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),rx=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
227
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),fb=E((e=>{var t=ib(),n=Vy(),r=Hy(),i=fy(),a=Q(),o=ub(),s=db();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),pb=E((e=>{var t=ib(),n=Vy(),r=zy(),i=Hy(),a=iy(),o=Q(),s=hy(),c=$(),l=_y(),u=yy();cb();var d=lb(),f=ub(),p=db(),m=fb(),h=Qv();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),mb=`DEEPSEEK_API_KEY`,hb=1,gb=`ezllm`,_b=()=>process.env.DSH_HOME||c(w(),`.dsh`),vb=()=>c(_b(),`settings.yaml`),yb=()=>c(_b(),`.credentials.yaml`);function bb(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function xb(e,t){let n=(0,pb.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function Sb(e){return`${e}/v1`}function Cb(e){let t=bb(vb());if(!t)return!1;try{return dv(xb(t,vb()).toJS()?.[`llm-deepseek`]?.baseURL,Sb(e))}catch{return!1}}function wb(e){let t=Sb(e.gatewayBase);m(_b(),{recursive:!0});let n=vb(),r=bb(n),i=xb(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);lv(n),i.setIn([`llm-deepseek`,`baseURL`],t),Eb(n,i);let o=yb(),s=e.masterKey||gb,c=bb(o);if(lv(o),c===null){let e=xb(``,o);e.set(`version`,hb),e.setIn([`refs`,mb],s),Eb(o,e);return}let l=xb(c,o),u=l.toJS();if(!(0,pb.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==hb)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(hb)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(mb,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,mb],s)}Eb(o,l)}function Tb(e,t){let n=vb(),r=yb(),i=!1;if(uv(n))i=!0;else{let t=bb(n);if(t){let r=xb(t,n);if(dv(r.toJS()?.[`llm-deepseek`]?.baseURL,Sb(e))){r.deleteIn([`llm-deepseek`,`baseURL`]);let e=r.toJS()?.[`llm-deepseek`];(!e||typeof e!=`object`||Object.keys(e).length===0)&&r.deleteIn([`llm-deepseek`]),Eb(n,r),i=!0}}}if(uv(r))i=!0;else{let e=bb(r);if(e){let n=xb(e,r),a=n.toJS(),o=e=>e===t||e===gb;a?.version===hb&&o(a?.refs?.[mb])?(n.deleteIn([`refs`,mb]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),Eb(r,n),i=!0):a?.version===void 0&&o(a?.[mb])&&(n.deleteIn([mb]),Eb(r,n),i=!0)}}return i}function Eb(e,t){let n=t.toString(),r=(0,pb.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);m(s(e),{recursive:!0}),C(e,n,`utf-8`)}async function Db(e){let t;try{t=(await e.req.json())?.enabled}catch{return e.json({ok:!1,error:`请求体不是合法 JSON`},400)}return typeof t==`boolean`?t:e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400)}function Ob(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new j;return n.get(`/`,t=>{let n=E_(e);return t.json({ok:!0,claudeCode:mv(n),codex:Jv(),dsh:Cb(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Db(n);if(r instanceof Response)return r;let i=E_(e);if(r){let e=t(Tt());return e?(hv({gatewayBase:i,token:e}),n.json({ok:!0,claudeCode:!0,file:`~/.claude/settings.json`,note:`已备份原文件为 settings.json.ellm-bak,重启 Claude Code 会话后生效`})):n.json({ok:!1,error:`配置未设置 masterKey,Claude Code 代理无法鉴权。请先在配置文件中设置 masterKey: ${Tt()}`},400)}let a=gv(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Db(n);if(r instanceof Response)return r;let i=E_(e);if(r){let e=t(Tt()),r=Xv({gatewayBase:i,apiKey:e||void 0});return n.json({ok:!0,codex:!0,file:`~/.codex/config.toml`,note:e?r?`已备份原文件为 config.toml.ellm-bak;已自动写入用户环境变量 ELLM_PROXY_API_KEY(Windows 写注册表 / macOS 写 ~/.zshrc,对之后新开的终端与 Codex 会话生效)`:`已备份原文件为 config.toml.ellm-bak;当前平台不支持自动写入,请手动设置环境变量 ELLM_PROXY_API_KEY=${e}`:`已备份原文件为 config.toml.ellm-bak;请设置环境变量 ELLM_PROXY_API_KEY(网关未配 masterKey 时取值任意)`})}let a=Zv();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Db(n);if(r instanceof Response)return r;let i=E_(e),a=t(Tt());if(r)return wb({gatewayBase:i,masterKey:a}),n.json({ok:!0,dsh:!0,file:`~/.dsh/settings.yaml`,note:a?`已写入 settings.yaml(llm-deepseek.baseURL)与 .credentials.yaml(refs.DEEPSEEK_API_KEY),原文件备份为 *.ellm-bak。注意:进程环境里已设 DEEPSEEK_API_KEY 时其优先级更高,需自行改用网关 masterKey;模型请在 dsh 内选择与网关部署名一致的模型`:`已写入 settings.yaml 与 .credentials.yaml(网关未配 masterKey,密钥为占位值即可放行),原文件备份为 *.ellm-bak。模型请在 dsh 内选择与网关部署名一致的模型`});let o=Tb(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var kb=[`/api/*(管理台与全部接口)`,`POST|GET /api/fetch(通用 HTTP 转发)`,`GET /api/service/status|processes`,`GET /api/service/autostart`,`GET /api/service/update`,`POST /api/service/update/check|apply`,`GET|POST /api/service/managed`,`PUT|DELETE /api/service/managed/:name`,`POST /api/service/managed/:name/start|stop|restart`,`GET /api/service/plugins`,`POST /api/service/plugins/restart`,`GET /api/harness`,`POST /api/harness/claude-code|codex|dsh`,`GET /api/latency/history`,`POST /api/latency/run`].join(`, `);function Ab(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,bp),e.route(`/api/setup`,Dp()),e.use(`/api/*`,Sp),e.route(`/api/config`,Np({runtime:n})),e.route(`/api/test`,zp(n)),e.route(`/api/latency`,am(n)),e.route(`/api/usage`,om()),e.route(`/api/quota`,n_()),e.route(`/api/provider-auth`,r_()),e.route(`/api/logs`,d_()),e.route(`/api/status`,o_(n,i)),e.route(`/api/fetch`,T_()),r&&(e.route(`/api/service`,O_(r)),e.route(`/api/service`,iv(r)),e.route(`/api/service/managed`,ov(r)),e.route(`/api/service/plugins`,cv(r)),e.route(`/api/harness`,Ob(r)))}var jb=(e,t=Mb)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},Mb={aac:`audio/aac`,avi:`video/x-msvideo`,avif:`image/avif`,av1:`video/av1`,bin:`application/octet-stream`,bmp:`image/bmp`,css:`text/css; charset=utf-8`,csv:`text/csv; charset=utf-8`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gif:`image/gif`,gz:`application/gzip`,htm:`text/html; charset=utf-8`,html:`text/html; charset=utf-8`,ico:`image/x-icon`,ics:`text/calendar; charset=utf-8`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript; charset=utf-8`,json:`application/json`,jsonld:`application/ld+json`,map:`application/json`,mid:`audio/x-midi`,midi:`audio/x-midi`,mjs:`text/javascript; charset=utf-8`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,pdf:`application/pdf`,png:`image/png`,rtf:`application/rtf`,svg:`image/svg+xml; charset=utf-8`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain; charset=utf-8`,wasm:`application/wasm`,webm:`video/webm`,weba:`audio/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml; charset=utf-8`,xml:`application/xml; charset=utf-8`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,gltf:`model/gltf+json`,glb:`model/gltf-binary`},Nb=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,Pb={br:`.br`,zstd:`.zst`,gzip:`.gz`},Fb=Object.keys(Pb),Ib=(()=>{let[e,t]=ye.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Lb=e=>Ib?i.toWeb(e):new ReadableStream({start(t){e.on(`data`,e=>{t.enqueue(e)}),e.on(`error`,e=>{t.error(e)}),e.on(`end`,()=>{t.close()})},cancel(){e.destroy()}}),Rb=e=>{let t;try{t=Se(e)}catch{}return t},zb=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Bb=e=>zb(e,decodeURI),Vb=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!xe(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(r,i)=>{if(r.finalized)return i();let a;if(n)a=n;else try{if(a=Bb(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=Ce(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=Rb(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=Ce(o,t),s=Rb(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=jb(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||Nb.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of Fb){if(!e.has(t))continue;let n=Rb(o+Pb[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=Pb[t];break}}}let l,u=s.size,d=r.req.header(`range`)||``;if(r.req.method==`HEAD`||r.req.method==`OPTIONS`)r.header(`Content-Length`,u.toString()),r.status(200),l=r.body(null);else if(!d)r.header(`Content-Length`,u.toString()),l=r.body(Lb(be(o)),200);else{r.header(`Accept-Ranges`,`bytes`),r.header(`Date`,s.birthtime.toUTCString());let e=d.replace(/bytes=/,``).split(`-`,2),t=parseInt(e[0],10)||0,n=parseInt(e[1],10)||u-1;u<n-t+1&&(n=u-1);let i=n-t+1,a=be(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(Lb(a),206)}return await e.onFound?.(o,r),l}},Hb=s(ne(import.meta.url));function Ub(e,t){let n=t??[c(Hb,`web-ui`),l(Hb,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(Hb,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(Hb,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await de(c(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await Vb({root:n})(e,t);return r instanceof Response&&r.status===200&&e.req.path.startsWith(`/assets/`)&&r.headers.set(`Cache-Control`,`public, max-age=31536000, immutable`),r}))}function Wb(e,t,n){let r=new j;return r.use(`/v1/*`,gp()),Ab(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),Ub(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${kb})`},404)),r.onError(wp),r}var Gb=6e4;function Kb(e){let t=()=>{let e=El()?.latencyTest;return typeof e==`object`&&e?e:{}},n=(e,t,n)=>{if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r};return{name:`latencyAutoTest`,everyMs:Gb,run:async()=>{try{if(nm(e)===0)return;let r=t();if(!n(r,Jp()??void 0,Date.now()))return;D(`[latency] 自动测试触发`),await tm(e)}catch(e){k(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var qb=6e5,Jb=3e4;function Yb(){return{name:`quotaRefresh`,everyMs:qb,firstDelayMs:Jb,run:async()=>{try{await Xg()}catch(e){k(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var Xb=6e4,Zb=3e4,Qb=20,$b=3e4,ex=1024,tx=/^[^\u0000-\u001f\u007f]{1,24}$/u,nx=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),rx=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
228
228
|
`);async function ix(e){let t=async(e,t)=>{let n=(e,t)=>{let n=Fp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0);return e.provider===`anthropic`?{url:`${n}/messages`,payload:{model:e.modelName,system:rx,messages:[{role:`user`,content:t}],max_tokens:ex}}:e.provider===`openai-responses`?{url:`${n}/responses`,payload:{model:e.modelName,instructions:rx,input:t,max_output_tokens:ex}}:{url:`${n}/chat/completions`,payload:{model:e.modelName,messages:[{role:`system`,content:rx},{role:`user`,content:t}],max_tokens:ex}}},r=(e,t)=>{if(typeof t!=`object`||!t)return``;let n=t;if(e===`anthropic`){let e=n.content;return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``}if(e===`openai-responses`){if(typeof n.output_text==`string`)return n.output_text;let e=n.output;return Array.isArray(e)?e.map(e=>{if(typeof e!=`object`||!e)return``;let t=e.content;return Array.isArray(t)?t.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``}).join(``):``}let r=n.choices;if(!Array.isArray(r)||r.length===0)return``;let i=r[0].message;if(typeof i!=`object`||!i)return``;let a=i.content;return typeof a==`string`?a:Array.isArray(a)?a.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``},{url:i,payload:a}=n(e,t),o={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Ip(e.apiKey,e.provider):{}},s=await fetch(i,{method:`POST`,headers:o,body:JSON.stringify(a),signal:AbortSignal.timeout($b)});if(!s.ok){let e=await s.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(s.status)}${e?`: ${e}`:``}`)}let c=await s.json().catch(()=>null);return r(e.provider,c)},n=e=>{let t=e.current.expanded.deployments,n=t.names;if(n.length===0)return null;let r=cf({status:`2xx`,pageSize:30}).items;for(let e of r){let n=typeof e.model==`string`?e.model:``;if(n===``)continue;let r=t.byName.get(n);if(r!==void 0)return{provider:r.provider,modelName:r.modelName,apiKey:r.apiKey,apiBase:r.apiBase,autoV1:r.autoV1,headers:r.headers}}let i=t.byName.get(n[0]);return i===void 0?null:{provider:i.provider,modelName:i.modelName,apiKey:i.apiKey,apiBase:i.apiBase,autoV1:i.autoV1,headers:i.headers}},r=(e,t)=>{let n=new Map,r=e.replace(/```[a-zA-Z]*/g,``).trim(),i=r.indexOf(`[`),a=r.lastIndexOf(`]`);if(i===-1||a<=i)return n;let o;try{o=JSON.parse(r.slice(i,a+1))}catch{return n}if(!Array.isArray(o))return n;for(let e of o){if(typeof e!=`object`||!e)continue;let r=e,i=Number(r.i),a=r.name;if(!Number.isInteger(i)||i<1||i>t||typeof a!=`string`)continue;let o=a.trim();tx.test(o)&&(nx.has(o.toLowerCase())||n.set(i,o))}return n},i=qf(Qb);if(i.length===0)return{resolved:0,fallback:0,failed:0};let a=n(e);if(a===null)return O(`[client-name] 无可用部署,${String(i.length)} 个待识别 UA 顺延到下一轮`),{resolved:0,fallback:0,failed:i.length};let o=i.map((e,t)=>`${String(t+1)}) ${e}`).join(`
|
|
229
|
-
`),s=``,c=null;try{s=await t(a,o)}catch(e){c=e instanceof Error?e.message:String(e)}let l=new Map;if(c===null)for(let[e,t]of r(s,i.length)){let n=i[e-1];n!==void 0&&l.set(n,t)}let u=Jf(l,`llm`),d=i.filter(e=>!l.has(e)),f=Yf(d),p=new Map;for(let e of f){let t=ap(e);t!==``&&p.set(e,t)}let m=Jf(p,Ff);return c!==null&&O(`[client-name] 识别请求失败(${String(d.length)} 个 UA 顺延重试): ${c}`),(u>0||m>0)&&D(`[client-name] 客户端短名: 模型定名 ${String(u)} 个 / 回落 ${String(m)} 个(模型 ${a.modelName})`),{resolved:u,fallback:m,failed:d.length-m}}function ax(e){return{name:`clientNameResolve`,everyMs:Xb,firstDelayMs:Zb,run:async()=>{try{await ix(e)}catch(e){k(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var ox=`--log-backfill`;function sx(e=process.argv){return e.includes(ox)}async function cx(){D(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),bd();let e=sp({onProgress:e=>D(`[log-backfill] ${e}`)});D(`[log-backfill] 入站头:${String(e.days)} 天 / 扫描 ${String(e.scanned)} 行,回填 ${String(e.filled)} 行,跳过(详情无入站头)${String(e.skipped)} 行,登记 UA ${String(e.uas)} 个,补写 client ${String(e.clientsAssigned)} 行`);let t=up({onProgress:e=>D(`[log-backfill] ${e}`)});D(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),D(`[log-backfill] 完成`)}function lx(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??
|
|
229
|
+
`),s=``,c=null;try{s=await t(a,o)}catch(e){c=e instanceof Error?e.message:String(e)}let l=new Map;if(c===null)for(let[e,t]of r(s,i.length)){let n=i[e-1];n!==void 0&&l.set(n,t)}let u=Jf(l,`llm`),d=i.filter(e=>!l.has(e)),f=Yf(d),p=new Map;for(let e of f){let t=ap(e);t!==``&&p.set(e,t)}let m=Jf(p,Ff);return c!==null&&O(`[client-name] 识别请求失败(${String(d.length)} 个 UA 顺延重试): ${c}`),(u>0||m>0)&&D(`[client-name] 客户端短名: 模型定名 ${String(u)} 个 / 回落 ${String(m)} 个(模型 ${a.modelName})`),{resolved:u,fallback:m,failed:d.length-m}}function ax(e){return{name:`clientNameResolve`,everyMs:Xb,firstDelayMs:Zb,run:async()=>{try{await ix(e)}catch(e){k(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var ox=`--log-backfill`;function sx(e=process.argv){return e.includes(ox)}async function cx(){D(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),bd();let e=sp({onProgress:e=>D(`[log-backfill] ${e}`)});D(`[log-backfill] 入站头:${String(e.days)} 天 / 扫描 ${String(e.scanned)} 行,回填 ${String(e.filled)} 行,跳过(详情无入站头)${String(e.skipped)} 行,登记 UA ${String(e.uas)} 个,补写 client ${String(e.clientsAssigned)} 行`);let t=up({onProgress:e=>D(`[log-backfill] ${e}`)});D(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),D(`[log-backfill] 完成`)}function lx(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??ce,r,i;try{return m(Dt(),{recursive:!0}),r=h(c(Dt(),`out-backfill.log`),`a`),i=h(c(Dt(),`err-backfill.log`),`a`),n(process.execPath,[...e.execArgv??process.execArgv,t,ox],{detached:!0,stdio:[`ignore`,r,i],env:{...process.env,ELLM_APP_DIR:Ct()}}).unref(),{started:!0,reason:``}}catch(e){return{started:!1,reason:e instanceof Error?e.message:String(e)}}finally{r!==void 0&&d(r),i!==void 0&&d(i)}}function ux(e={}){let t=lx(e);return t.started||k(`[log-backfill] 存量补齐子进程未拉起:${t.reason}`),t}sx()&&(await cx(),process.exit(0));var dx=Dl();dx===null&&(k(`[ezllm] 缺少配置文件 ${Tt()}(参考 ezllm.config.example.json)`),process.exit(1));var fx=dx;bd(),Wp();var px=new mu({maxBytes:Jl().maxBytes}),mx=Df({spool:px,getConfig:()=>Jl()}),hx=pu();hx>0&&D(`[ezllm] spool 启动清理:回收中断残留 ${String(hx)} 个中转文件`),await kf(),ux();var gx=new np({spool:px}),_x=()=>{let e=fx;try{e=El()??fx}catch{e=fx}return e.providers.flatMap(e=>e.models.map(e=>e.modelName))},vx=await pp(fx,{authorize(e){let t=Fl();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=Fl();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),hp(e,{knownModelNames:_x})}},{traceSink:gx}),yx={port:0,startedAt:Date.now(),appDir:Ct()},bx=Ul(),xx=Wb(vx,yx,bx),Sx=Wt({jobs:[mx,Nf({getRetention:()=>ql()}),Kb(vx),Yb(),ax(vx)]}),Cx=await Ex(xx,fp(vx),bx.hostname);yx.port=Cx;var wx=!1;function Tx(e,t=0){wx||(wx=!0,Sx.stop(),D(`[ezllm] ${e},服务退出`),Promise.race([gx.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}Mp(()=>Tx(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>Tx(`收到 ${e}`));Dx(Cx,bx);async function Ex(e,t,n){let r=Date.now()+1e4;for(;;)try{return await new Promise((r,i)=>{let a=ut({fetch:e.fetch,port:t,hostname:n,overrideGlobalObjects:!1});a.once(`error`,e=>i(e)),a.once(`listening`,()=>r(a.address()?.port??t))})}catch(e){let n=e.code??String(e);if(n===`EADDRINUSE`&&Date.now()<r){await new Promise(e=>setTimeout(e,300));continue}k(`错误:服务监听 ${String(t)} 失败(${n})${n===`EADDRINUSE`?`,端口被占用(可在配置文件修改 port)`:``}`),process.exit(1)}}function Dx(e,t){let n=i_(t.hostname)?`localhost`:t.hostname,r=i_(t.hostname)?`全部网卡`:t.hostname,i=t.source===`credentials`?`未设置任何有效凭据(主密钥为空且未启用管理台登录),强制仅本机(设置页开关已忽略)`:t.hostname===`127.0.0.1`?`设置页「允许局域网访问」已关闭`:`设置页「允许局域网访问」开启(缺省)`;if(D(`========================================`),D(` EZLLM 服务(网关 + 管理台,单进程)`),D(` 网关端点: http://${n}:${String(e)}/v1/*`),D(` 管理台: http://${n}:${String(e)}/(管理 API 与界面同端口,登录后使用)`),D(` 监听地址: ${r}:${String(e)}(${i})`),i_(t.hostname))for(let t of a_())D(` 局域网访问: http://${t}:${String(e)}`);D(` 模型数量: ${String(vx.current.expanded.deployments.names.length)}`),Vl().completed||D(` ⚠ 首次启动:请打开 http://${n}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),D(`========================================`)}export{};
|