ezllm 0.0.45 → 0.0.47
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/README.md +5 -5
- package/dist/cli.js +24 -23
- package/dist/daemon.js +14 -6
- package/dist/plugin-host.js +3 -3
- package/dist/server.js +75 -75
- package/dist/web-ui/assets/DashboardView-CNsnnzad.css +1 -0
- package/dist/web-ui/assets/DashboardView-CqupMCmm.js +2 -0
- package/dist/web-ui/assets/LayoutView-CyOrx1rA.js +1 -0
- package/dist/web-ui/assets/LayoutView-cQeiOjLU.css +1 -0
- package/dist/web-ui/assets/LoginView-YolyK2Q0.js +1 -0
- package/dist/web-ui/assets/{LogsView-CXFJ_22b.css → LogsView-DPmB8dy8.css} +1 -1
- package/dist/web-ui/assets/LogsView-E64a6PIt.js +5 -0
- package/dist/web-ui/assets/ManagedServicesView-DVCADa1y.css +1 -0
- package/dist/web-ui/assets/ManagedServicesView-mk_mSWzE.js +6 -0
- package/dist/web-ui/assets/PluginsView-DTJeufic.js +2 -0
- package/dist/web-ui/assets/PluginsView-DzHAW2gO.css +1 -0
- package/dist/web-ui/assets/ProvidersView-BrirhwQN.js +14 -0
- package/dist/web-ui/assets/ProvidersView-BwX8Y3kP.css +1 -0
- package/dist/web-ui/assets/SettingsView-BGMZbskz.css +1 -0
- package/dist/web-ui/assets/SettingsView-p3uvWhGh.js +1 -0
- package/dist/web-ui/assets/SetupView-6BYv_B5n.css +1 -0
- package/dist/web-ui/assets/SetupView-CGQibXHs.js +1 -0
- package/dist/web-ui/assets/config-Dzo6AFZx.js +1 -0
- package/dist/web-ui/assets/{format-CPPf8IfM.js → format-Deb1hfjO.js} +1 -1
- package/dist/web-ui/assets/{index-s_h6GEbv.css → index-DodsqGDu.css} +1 -1
- package/dist/web-ui/assets/index-wQG3qUgW.js +49 -0
- package/dist/web-ui/assets/message-C8pR37GK.js +2 -0
- package/dist/web-ui/assets/navVisibility-CPbwxq3d.js +1 -0
- package/dist/web-ui/assets/pluginProviders-DeHPKGnd.js +1 -0
- package/dist/web-ui/assets/providers-Dbg0NkwB.js +1 -0
- package/dist/web-ui/assets/router-JpU_7F6L.js +6 -0
- package/dist/web-ui/assets/{useCopyToast-BeWZ6lSF.js → useCopyToast-GaJ4QVNE.js} +1 -1
- package/dist/web-ui/assets/useManagerApi-DEPhOKWy.js +1 -0
- package/dist/web-ui/assets/{useQuickRangeFilter-DQQ8QAr5.js → useQuickRangeFilter-DeKORPZt.js} +1 -1
- package/dist/web-ui/assets/useToast-DVCDN-da.js +1 -0
- package/dist/web-ui/index.html +4 -4
- package/ezllm.config.example.json +0 -1
- package/package.json +2 -1
- package/dist/web-ui/assets/DashboardView-CkTFY0Da.js +0 -1
- package/dist/web-ui/assets/LayoutView-CcXUd-b0.js +0 -1
- package/dist/web-ui/assets/LayoutView-D84C9Iqp.css +0 -1
- package/dist/web-ui/assets/LoginView-Dq7gaxB9.js +0 -1
- package/dist/web-ui/assets/LogsView-CO6GNtfl.js +0 -5
- package/dist/web-ui/assets/ManagedServicesView-CNLHAVAL.js +0 -6
- package/dist/web-ui/assets/ManagedServicesView-D29NyvP6.css +0 -1
- package/dist/web-ui/assets/PluginsView-B2H4xfag.css +0 -1
- package/dist/web-ui/assets/PluginsView-Dljy9HZq.js +0 -2
- package/dist/web-ui/assets/ProvidersView-CD3QYu3i.js +0 -14
- package/dist/web-ui/assets/ProvidersView-Cwe2Q81Y.css +0 -1
- package/dist/web-ui/assets/ServiceStatusView-BgHmV09I.js +0 -2
- package/dist/web-ui/assets/ServiceStatusView-DmUKbS8w.css +0 -1
- package/dist/web-ui/assets/SettingsView-BLQl0mEB.js +0 -1
- package/dist/web-ui/assets/SettingsView-NXkxZUgr.css +0 -1
- package/dist/web-ui/assets/SetupView-BzZqIZpo.js +0 -1
- package/dist/web-ui/assets/SetupView-CSBKlfcJ.css +0 -1
- package/dist/web-ui/assets/config-CLbcTOt9.js +0 -1
- package/dist/web-ui/assets/index-yak1S-7W.js +0 -49
- package/dist/web-ui/assets/message-K5WVknE-.js +0 -2
- package/dist/web-ui/assets/pluginProviders-CB38zjhC.js +0 -1
- package/dist/web-ui/assets/providers-BuzQNH1W.js +0 -1
- package/dist/web-ui/assets/router-tvNif7bs.js +0 -6
- package/dist/web-ui/assets/updateNote-CttDt8SZ.js +0 -1
- package/dist/web-ui/assets/useManagerApi-Wm9Nz3_p.js +0 -1
- package/dist/web-ui/assets/useToast-D_jja27E.js +0 -1
package/dist/server.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
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,networkInterfaces as T,platform as E}from"node:os";import{fileURLToPath as ee,pathToFileURL as te}from"node:url";import{createHash as ne,randomBytes as re,randomUUID as ie}from"node:crypto";import{Readable as ae}from"node:stream";import{mkdir as oe,readFile as se,rename as ce,writeFile as le}from"node:fs/promises";import{DatabaseSync as ue}from"node:sqlite";import{brotliCompressSync as de,brotliDecompressSync as fe,constants as pe}from"node:zlib";import{execFileSync as me,spawn as he}from"node:child_process";import{versions as ge}from"process";import{createReadStream as _e,existsSync as ve,statSync as ye}from"fs";import{join as be}from"path";var D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),xe=e(import.meta.url),Se=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Ce=e=>e instanceof Se?e:new Se(e.message,{cause:e}),we=global.Request,Te=class extends we{constructor(e,t){typeof e==`object`&&ke in e&&(e=e[ke]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Ee=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)},De=Symbol(`wrapBodyStream`),Oe=(e,t,n,r,a)=>{let o={method:e,headers:n,signal:a.signal};if(e===`TRACE`){o.method=`GET`;let e=new Te(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[De]){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 Te(t,o)},ke=Symbol(`getRequestCache`),Ae=Symbol(`requestCache`),je=Symbol(`incomingKey`),Me=Symbol(`urlKey`),Ne=Symbol(`headersKey`),Pe=Symbol(`abortControllerKey`),Fe={get method(){return this[je].method||`GET`},get url(){return this[Me]},get headers(){return this[Ne]||=Ee(this[je])},[Symbol(`getAbortController`)](){return this[ke](),this[Pe]},[ke](){return this[Pe]||=new AbortController,this[Ae]||=Oe(this.method,this[Me],this.headers,this[je],this[Pe])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Fe,e,{get(){return this[ke]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Fe,e,{value:function(){return this[ke]()[e]()}})}),Object.defineProperty(Fe,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[Ae]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Fe,Te.prototype);var Ie=(e,t)=>{let r=Object.create(Fe);r[je]=e;let i=e.url||``;if(i[0]!==`/`&&(i.startsWith(`http://`)||i.startsWith(`https://`))){if(e instanceof n)throw new Se(`Absolute URL for :path is not allowed in HTTP/2`);try{r[Me]=new URL(i).href}catch(e){throw new Se(`Invalid absolute URL`,{cause:e})}return r}let a=(e instanceof n?e.authority:e.headers.host)||t;if(!a)throw new Se(`Missing host header`);let o;if(e instanceof n){if(o=e.scheme,o!==`http`&&o!==`https`)throw new Se(`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 Se(`Invalid host header`);return r[Me]=s.href,r},Le=Symbol(`responseCache`),Re=Symbol(`getResponseCache`),ze=Symbol(`cache`),Be=global.Response,Ve=class e{#e;#t;[Re](){return delete this[ze],this[Le]||=new Be(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Le];if(e){this.#t=e,this[Re]();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[ze]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[ze];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Re]().headers}get status(){return this[ze]?.[0]??this[Re]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Ve.prototype,e,{get(){return this[Re]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Ve.prototype,e,{value:function(){return this[Re]()[e]()}})}),Object.defineProperty(Ve.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[Le]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Ve,Be),Object.setPrototypeOf(Ve.prototype,Be.prototype);async function He(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Ue(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 We(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return Ue(e.getReader(),t)}var Ge=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},Ke=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=a);var qe=Symbol(`outgoingEnded`),Je=Symbol(`incomingDraining`),Ye=500,Xe=67108864,Ze=e=>{let t=e;if(e.destroyed||t[Je])return;if(t[Je]=!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,Ye);s.unref?.();let c=e=>{i+=e.length,i>Xe&&o()};e.on(`data`,c),e.on(`end`,a),e.on(`error`,a),e.resume()},Qe=()=>new Response(null,{status:400}),$e=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),et=(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))},tt=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},nt=async(e,t)=>{let[n,r,i]=e[ze],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=Ge(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Ge(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())):(tt(t),await We(r,t)?.catch(e=>et(e,t))),t[qe]?.()},rt=e=>typeof e.then==`function`,it=async(e,t,n={})=>{if(rt(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($e)}if(ze in e)return nt(e,t);let r=Ge(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 He(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&&tt(t),await Ue(n,t,o))}else r[Ke]||(t.writeHead(e.status,r),t.end());t[qe]?.()},at=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Te&&(Object.defineProperty(global,"Request",{value:Te}),Object.defineProperty(global,"Response",{value:Ve})),async(i,a)=>{let o,s;try{s=Ie(i,t.hostname);let c=!r||i.method===`GET`||i.method===`HEAD`;if(c||(i[De]=!0,i.on(`end`,()=>{c=!0}),i instanceof n&&(a[qe]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{Ze(i)})})}),a.on(`finish`,()=>{c||Ze(i)})),a.on(`close`,()=>{s[Pe]&&(i.errored?s[Pe].abort(i.errored.toString()):a.writableFinished||s[Pe].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{Ze(i)})})}),o=e(s,{incoming:i,outgoing:a}),ze in o)return nt(o,a)}catch(e){if(o)return et(e,a);if(t.errorHandler){if(o=await t.errorHandler(s?e:Ce(e)),!o)return}else o=s?$e(e):Qe()}try{return await it(o,a,t)}catch(e){return et(e,a)}}},ot=e=>{let n=e.fetch,r=at(n,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||t)(e.serverOptions||{},r)},st=(e,t)=>{let n=ot(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function O(e,...t){console.log(e,...t)}function k(e,...t){console.warn(e,...t)}function A(e,...t){console.error(e,...t)}function ct(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function lt(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 ct(i.slice(n.length));if(i===t){let t=r[e+1]??``;return t.startsWith(`-`)?void 0:ct(t)}}}function ut(e,t){return lt(e)??ct(process.env[t])}var dt=65535;function ft(e){let t=ct(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0&&n<=dt?n:void 0}var pt=(()=>{let e=ut(`app-dir`,`ELLM_APP_DIR`),t=e===void 0?void 0:l(u(),e),n=lt(`port`),r=ft(n??ct(process.env.ELLM_PORT));n!==void 0&&r===void 0&&k(`--port=${n} 无效(需为 1-65535 的整数),已忽略:本次不生效、也不会写入配置文件。`);let i=ut(`node-mirror`,`ELLM_NODE_MIRROR`),a=ut(`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}})(),mt=s(ee(import.meta.url)),ht=`runtime.json`,gt;function _t(e){try{let t=g(c(e,ht),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function vt(){let e=_t(bt())?.source;return typeof e==`string`&&e!==``?e:void 0}function yt(){return c(w(),`.ezllm`)}function bt(){return gt===void 0&&(gt=pt.appDir??yt()),gt}function xt(){return l(bt(),`data`)}function St(){return l(bt(),`ezllm.config.json`)}function Ct(){return l(xt(),`ipinfo.json`)}function wt(){return l(bt(),`logs`)}function Tt(){return l(xt(),`updater.json`)}var Et=[`hook.cjs`,`hook.mjs`,`hook.js`];function Dt(){return Et.map(e=>c(bt(),e))}var Ot=`ezllm`;function kt(e=bt()){return l(e,`node`,`node_modules`,Ot)}var At=[`app`,`dist`];function jt(e){return e.find(e=>p(e))}function Mt(e){try{let t=g(c(e,`package.json`),`utf-8`).replace(/^\uFEFF/,``);return JSON.parse(t)}catch{return null}}function Nt(e,t){let n=mt;for(let r=0;r<t;r++){if(Mt(n)?.name===e)return n;n=s(n)}return null}var Pt=Nt(`ezllm`,5)??l(mt,`..`),Ft=Nt(`ellm`,6);function It(){return Mt(Pt)?.name===`ezllm`}function Lt(){let e=Mt(Pt);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function Rt(){let e=xt();p(e)||m(e,{recursive:!0})}function zt(e){let t=bt();return jt([c(kt(),`dist`,e),...At.map(n=>l(t,n,e)),c(Pt,`dist`,e),...Ft?[c(Ft,`app`,`cli`,`dist`,e)]:[]])??c(Pt,`dist`,e)}function Bt(){return zt(`daemon.js`)}function Vt(e,t){let n=`${e}.${`${process.pid}.${re(6).toString(`hex`)}`}.tmp`;try{C(n,JSON.stringify(t,null,2)+`
|
|
3
|
-
`,`utf-8`),v(n,e)}finally{try{y(n,{force:!0})}catch{}}}function Ht(e){Rt();let t=l(xt(),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 A(`[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=>{A(`[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(Tt(),`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??O,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))})}},j=()=>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=j();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=j();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=j();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:j()},this.#t={ALL:j()},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]=j();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=j();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Kn=j(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=j(),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,j()]),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),j())])}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=j(),Qn=0,$n=class e{#e=[];#t=j();#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=j(),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)}},M=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 N(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
|
-
- `)}`),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(!
|
|
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)+`
|
|
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
|
+
- `)}`),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(`
|
|
6
6
|
`),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===Sr?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===Sr&&e.charCodeAt(r+1)===xr?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===Sr){C(e,0,e.length-1),g=!0;return}if(b(e)){s.push(e),c=e.length;return}h=!0}}function b(e){let t=e.charCodeAt(0);return t===58&&!!n||t===100&&Or(e,`data`)||t===101&&Or(e,`event`)||t===105&&Or(e,`id`)||t===114&&Or(e,`retry`)}function x(){t!==void 0&&(c+d.length<=t||(m=!0,s.length=0,c=0,u=void 0,d=``,f=0,p=void 0,h=!1,g=!1,r?.(new br(`Buffered data exceeded max buffer size of ${t} characters`,{type:`max-buffer-size-exceeded`}))))}function S(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
|
|
7
7
|
`,t);for(;n!==-1;){if(t===n){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0,t=n+1,n=e.indexOf(`
|
|
8
8
|
`,t);continue}let r=e.charCodeAt(t);if(Er(e,t,r)){let r=e.charCodeAt(t+5)===Cr?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===xr){u!==void 0&&a?.(u),i?.({id:u,event:p,data:o}),u=void 0,d=``,p=void 0,t=n+2,n=e.indexOf(`
|
|
9
9
|
`,t);continue}d=f===0?o:`${d}\n${o}`,f++}else Dr(e,t,r)?p=e.slice(e.charCodeAt(t+6)===Cr?t+7:t+6,n)||void 0:C(e,t,n);t=n+1,n=e.indexOf(`
|
|
10
10
|
`,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
|
|
11
|
-
`,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;C(e,t,i),t=i+1,e.charCodeAt(t-1)===Sr&&e.charCodeAt(t)===xr&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(Er(e,t,i)){let n=e.charCodeAt(t+5)===Cr?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(Dr(e,t,i)){p=e.slice(e.charCodeAt(t+6)===Cr?t+7:t+6,r)||void 0;return}if(i===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let n=e.slice(e.charCodeAt(t+3)===Cr?t+4:t+3,r);n.includes(`\0`)||(u=n);return}if(i===58){if(n){let i=e.slice(t,r);n(i.slice(e.charCodeAt(t+1)===Cr?2:1))}return}let a=e.slice(t,r),o=a.indexOf(`:`);if(o===-1){w(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===Cr?2:1;w(s,a.slice(o+c),a)}function w(e,t,n){switch(e){case`event`:p=t||void 0;break;case`data`:d=f===0?t:`${d}\n${t}`,f++;break;case`id`:t.includes(`\0`)||(u=t);break;case`retry`:/^\d+$/.test(t)?o?.(parseInt(t,10)):r?.(new br(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new br(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function
|
|
11
|
+
`,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;C(e,t,i),t=i+1,e.charCodeAt(t-1)===Sr&&e.charCodeAt(t)===xr&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(Er(e,t,i)){let n=e.charCodeAt(t+5)===Cr?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(Dr(e,t,i)){p=e.slice(e.charCodeAt(t+6)===Cr?t+7:t+6,r)||void 0;return}if(i===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let n=e.slice(e.charCodeAt(t+3)===Cr?t+4:t+3,r);n.includes(`\0`)||(u=n);return}if(i===58){if(n){let i=e.slice(t,r);n(i.slice(e.charCodeAt(t+1)===Cr?2:1))}return}let a=e.slice(t,r),o=a.indexOf(`:`);if(o===-1){w(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===Cr?2:1;w(s,a.slice(o+c),a)}function w(e,t,n){switch(e){case`event`:p=t||void 0;break;case`data`:d=f===0?t:`${d}\n${t}`,f++;break;case`id`:t.includes(`\0`)||(u=t);break;case`retry`:/^\d+$/.test(t)?o?.(parseInt(t,10)):r?.(new br(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new br(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function ee(e={}){if(e.consume&&s.length>0){let e=s.join(``);C(e,0,e.length)}l=!0,u=void 0,d=``,f=0,p=void 0,s.length=0,c=0,m=!1,h=!1,g=!1}return{feed:_,reset:ee}}function Er(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Dr(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}function Or(e,t){let n=1;for(;n<e.length&&n<t.length;){if(e.charCodeAt(n)!==t.charCodeAt(n))return!1;n++}return e.length<=t.length||e.charCodeAt(t.length)===58}var kr=`[DONE]`,Ar=``,jr=class{parser;collected=[];sawFirstChunk=!1;constructor(){this.parser=Tr({onEvent:e=>{e.data!==``&&this.collected.push({event:e.event||null,data:e.data})}})}push(e){let t=e;return this.sawFirstChunk||(this.sawFirstChunk=!0,t.startsWith(Ar)&&(t=t.slice(1))),this.parser.feed(t),this.take()}flush(){return this.parser.feed(`
|
|
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 ae({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=ae.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 F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I(e){return F(e)?e:{}}function L(e){return Array.isArray(e)?e:[]}function R(e){return typeof e==`string`?e:null}function z(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 B(){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=I(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=R(e)??``;return ei.has(t)?t:ni(t)}function ii(e){let t=R(e.stop_reason),n=R(I(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=R(e.refusal);if(t!==null&&t!==``)return t;let n=R(I(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=F(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function li(e){if(!F(e))return!1;let t=e.type===`error`?e.error:void 0;return F(t)&&typeof t.type==`string`&&typeof t.message==`string`}function ui(e,t){if(F(t)){let e=t.error;if(F(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(F(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=I(e);if(t.type===`message_start`){let e=I(t.message).usage;return F(e)?e:null}if(t.type===`message_delta`){let e=t.usage;return F(e)?e:null}return null}function pi(e){if(typeof e!=`object`||!e||Array.isArray(e))return String(e);let t=I(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 P(pi(t),{status:ci(t)});let n=I(L(e.choices)[0]),r=I(n.delta),i=[];if(!this.#c){this.#c=!0;let t=e.id;this.#p=typeof t==`string`&&t!==``?t:B(),i.push(this.#m(R(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 L(r.thinking_blocks)){let t=R(I(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 L(r.tool_calls).entries()){let n=I(t),r=I(n.function),a=typeof n.index==`number`?n.index:e,o=R(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:R(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=I(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(I(n)))yield e;for(let e of t.flush())yield e}var gi=4096;function _i(e){return e.map(e=>{if(!F(e))return I(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(!F(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(I(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(!F(e.metadata))return;let t=I(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function bi(e){let t=e.output_config;if(!F(t))return;let n=t.effort;if(typeof n==`string`&&n!==``&&![`high`,`medium`,`low`,`xhigh`,`max`].includes(n))throw new P(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function xi(e){let t=I(e),n=_i(L(t.messages)),r=L(t.tools).map(I),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(I):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=R(t);return`reasoning_content`in e?{reasoningContent:R(e.reasoning_content),content:n}:`reasoning`in e?{reasoningContent:R(e.reasoning),content:n}:typeof t==`string`?Ti(t):{reasoningContent:null,content:n}}function Di(e){let t=I(e),n=t.arguments,r;if(n==null){let e=t.parameters;r=F(e)?JSON.stringify(e):``}else r=F(n)?JSON.stringify(n):String(n);return{arguments:r,name:R(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?B():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=I(r.function),i=e.name,a=JSON.parse(typeof e.arguments==`string`?e.arguments:``);if(i!==`multi_tool_use.parallel`)continue;let o=I(a),s=(Array.isArray(o.tool_uses)?o.tool_uses:[]).map((e,t)=>{let n=I(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(I(e)))):[]}function Ni(e){if(typeof e!=`string`||e===``)return{};try{return I(JSON.parse(e))}catch{return{}}}function Pi(e){let t=[];for(let n of e.thinkingBlocks){let e=I(n);e.type===`thinking`?t.push({type:`thinking`,thinking:R(e.thinking)??``,signature:R(e.signature)}):e.type===`redacted_thinking`&&t.push({type:`redacted_thinking`,data:R(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=I(n),r=I(e.function);t.push({type:`tool_use`,id:R(e.id)??``,name:R(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=I(e),n=t.error;if(n!=null){let e=I(n);throw new P(typeof e.message==`string`?e.message:JSON.stringify(n),{status:ci(n)})}let r=L(t.choices);if(r.length===0)throw Error(`upstream returned a response with no 'choices'. Raw keys: ${Object.keys(t).join(`, `)}`);let i=I(r[0]),a=I(i.message),o=Mi(a),{reasoningContent:s,content:c}=Ei(a),l=L(a.thinking_blocks),u=ai(a),d=R(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(I(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(`, `)}]`:F(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=I(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=I(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=I(e);if(t.type!==`tool_use`)continue;let r=n[i];i+=1,r!==void 0&&(t.caller=r)}}function Vi(e){let t=I(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new P(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=I(Ii({id:B(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:R(t.stop_reason),message:r}],usage:Ci(I(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=R(e.type)??``,n=``,r=null,i=``,a=null,o=null,s=null,c=null;if(t===`content_block_delta`){let t=I(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=>I(e.delta)).filter(e=>typeof e.thinking==`string`).map(e=>e.thinking).join(``),signature:n}])}}else if(t===`content_block_start`){let t=I(e.content_block);if(this.contentBlocks.length=0,this.currentContentBlockType=R(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=R(t.name)??``;r={id:R(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=>I(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=R(I(e.delta).stop_reason)??``,`usage`in e&&(a=Ci(this.#e(e.usage)));else if(t===`message_start`){let t=I(e.message);c=R(t.model),`usage`in t&&(a=Ci(this.#e(t.usage)))}else if(t===`error`){let t=I(e.error);throw new P(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,...I(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(I(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 L(t)){let t=I(e);if(t.type!==`text`)continue;let r=R(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=>F(e)?n.get(e)??e:e);return e.every((e,n)=>e===t[n])?t:e}if(!F(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(F(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)&&F(r))for(let e of Object.values(r))F(e)&&t.push(e);else if($i.has(n)&&Array.isArray(r))for(let e of r)F(e)&&t.push(e);else Qi.has(n)&&F(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(F(e))return e;if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return F(t)?t:null}catch{return null}}function ca(e,t){if(typeof e==`string`)return e===``?null:e;let n=[];for(let r of L(e)){let e=I(r);if(e.type!==`text`)continue;let i=R(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=I(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 L(e)){let e=I(r);if(e.type===`text`)t.push({type:`text`,text:R(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:R(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:L(e).map(e=>R(I(e).text)??``).join(``)}function pa(e){let t=I(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`?R(t.url):null}function ma(e){return e.map(e=>e.type===`thinking`?R(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
16
|
-
`)}function ha(e){if(typeof e==`string`)return[{role:`assistant`,content:e}];let t=[],n=[],r=[];for(let i of L(e)){let e=I(i);e.type===`text`?t.push(R(e.text)??``):e.type===`tool_use`?n.push({id:R(e.id)??``,type:`function`,function:{name:R(e.name)??``,arguments:JSON.stringify(e.input??{})}}):e.type===`thinking`?r.push({type:`thinking`,thinking:R(e.thinking)??``,signature:R(e.signature)??``}):e.type===`redacted_thinking`&&r.push({type:`redacted_thinking`,data:R(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=I(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(I(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`,L(d).map(ba),L(d).length>0);let f=xa(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function ya(e){let t=I(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=I(e),n=t.input_schema,r=sa(n);if(r===null&&n!=null)throw new P(`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=I(e),r=R(n.type)??``;if(r===`disabled`)return null;if(r===`adaptive`)return R(I(n.output_config).effort)??R(I(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=I(e),r=Zi([...la(n.system),...ua(L(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(F(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 F(t)&&F(t.error)?t:{error:{message:Ea(e,t),type:Ta(e),param:null,code:String(e)}}}function Oa(){return`chatcmpl-${B()}`}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[R(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=I(I(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=I(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(F(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=R(e.inference_geo);l!==null&&(c.inference_geo=l);let u=R(e.speed);if(u!==null&&(c.speed=u),t.fromStreamBuilder!==!0){let t=R(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(F(t)){let e=t.error;if(F(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(F(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(F(t)){let e=t.error;if(F(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(!F(e))throw new P(`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=I(e),n=I(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new P(`Unsupported tool type: ${String(r)}`,{status:400});let i=R(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;F(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=I(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 P(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function Za(e){if(!F(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 F(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:R(I(e).url)??``,n=typeof e==`string`?null:R(I(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 P(`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=I(n);if(t.type===`text`)e.push({type:`text`,text:R(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(R(e.tool_call_id)??B()),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=I(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 L(r)){let n=I(e),r=Qa(n);if(n.type===`text`){let e=$a(R(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=I(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(I(e));if(i!==null)for(let e of i){let n=I(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(R(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=I(e);if(r.type!==`function`)continue;let i=I(r.function),a=R(i.name)??``,o=Ya(R(r.id)??B());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(I(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 L(e)){let e=I(n);if(e.type!==`text`)continue;let r=$a(R(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]:L(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(F(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=I(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=I(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,...F(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 P(`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(I(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:R(I(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 P(`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=R(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`:L(i).length>0&&(r.tools=qa(L(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=R(i);e!==null&&lo(e)&&(r.metadata={user_id:e});break}case`metadata`:F(i)&&i.user_id!==null&&i.user_id!==void 0&&(r.metadata={user_id:i.user_id});break;case`cache_control`:F(i)&&(r.cache_control=i)}}return r.messages=t,r.tools===void 0&&So(e)&&(r.tools=[Ja]),r}function So(e){return L(e.messages).some(e=>`tool_calls`in I(e))}function Co(e){let t=I(e),n=L(t.messages),r=0;for(;r<n.length&&I(n[r]).role===`system`;)r+=1;let i=n.slice(0,r).map(e=>I(e)),a=xo(t,ao(Zi(n.slice(r).map(e=>I(e))))),o=oo(i);if(o.length>0&&(a.system=o),a.max_tokens===void 0){let e=I(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=I(a),o=R(e.type)??``;if(o===`text`)t+=R(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};F(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=I(e),n=t.error;if(n!=null)throw new P(R(I(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(L(r))}],usage:Ma(I(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(R(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 P(R(I(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=I(e.message),n=R(t.model);n!==null&&(this.#n=n);let r=t.usage;return F(r)&&(this.#r=Na(this.#r,r)),[]}#p(e){let t=I(e.content_block),n=R(t.type)??``;if(this.#c=n,this.#u=``,this.#d=``,n===`text`){let e=R(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 F(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=I(e.delta),n=R(t.type)??``;if(n===`text_delta`){let e=R(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`thinking_delta`){let e=R(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=R(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=R(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;F(t)&&(this.#r=Na(this.#r,t));let n=Aa(I(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(I(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 F(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 F(t)?t:null}errorEnvelope(e,t){return Da(e,t)}};function Ao(e){let t=e;if(F(t.usage))return t.usage;let n=t.response;return F(n)&&F(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:L(e).flatMap(e=>{if(typeof e==`string`)return[e];let t=I(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:z(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(z(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=z(e.input);t=n===``?``:JSON.stringify({content:n})}return[{role:`assistant`,content:null,tool_calls:[{id:z(e.call_id??e.id),type:`function`,function:{name:z(e.name),arguments:String(t??``)},index:0}]}]}function Lo(e){let t=z(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=I(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(F(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=>I(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(z(e.type))}function Bo(e){return z(e.type)===`function_call`||z(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 L(e)){let e=I(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}]:L(e),r=typeof t==`string`?[{type:`text`,text:t}]:L(t);return[...n,...r]}function Uo(e){return z(e.role)===``?`user`:z(e.role)}function Wo(e){return Ko(e.content)??qo(e.summary)}function Go(e,t){let n=e.flatMap(e=>{let n=I(e);if(t.has(z(n.type)))return[];let r=n.text;return typeof r==`string`&&r.trim()!==``?[r.trim()]:[]});return n.length>0?n.join(`
|
|
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=
|
|
18
|
-
`):null,a=t.flatMap(e=>L(e.thinking_blocks));return{...e,...i===null?{}:{reasoning_content:i},...a.length>0?{thinking_blocks:[...a,...L(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=I(e),n=I(t.function);if(F(t.function)&&z(n.name)!==``)return t;let r=z(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=z(t.name);return e===``?`required`:{type:`function`,function:{name:e}}}if(r===`custom`){let e=I(t.custom),n=z(t.name)===``?z(e.name):z(t.name);return n===``?`required`:{type:`function`,function:{name:n}}}return e}function ts(e){let t=[],n=null,r=L(e);for(let e=0;e<r.length;e++){let i=I(r[e]),a=z(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 P(`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:z(i.name),description:z(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=I(I(e).format);return z(t.type)===`json_schema`?{type:`json_schema`,json_schema:{name:t.name??`response_schema`,schema:t.schema??{},strict:t.strict??!1}}:z(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=I(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 L(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=I(e.message),n=Array.isArray(t.tool_calls)?t.tool_calls.map(e=>ki(I(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=R(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=I(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=F(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=F(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=I(t);throw new P(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(I(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:L(e).map(e=>typeof e==`string`?e:R(I(e).text)??``).join(``)}function fs(e){if(!F(e))return null;let t=Jr(e.prompt_tokens)??0,n=Jr(e.completion_tokens)??0,r=Jr(e.total_tokens)??t+n,i=I(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=I(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=I(e.function);return{type:`function_call`,id:t,call_id:R(e.id)??`call_${B()}`,name:R(n.name)??``,arguments:R(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=I(L(e.choices)[0]),r=I(n.message),i=R(n.finish_reason),a=ds(r.content),o=L(r.tool_calls),s=R(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${B()}`,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_${B()}`,status:ls(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(ps(I(e),`fc_${B()}`));return ms(t,ls(i),c,fs(e.usage),i)}function gs(e){let t=I(e),n=R(t.model);return hs(cs(t),{id:`resp_${B()}`,created:Xr(),...n===null?{}:{model:n}})}function _s(e){let t=e.error;if(t)throw new P(typeof t!=`object`||!t||Array.isArray(t)?String(t):typeof I(t).message==`string`?I(t).message:JSON.stringify(t),{status:ci(t)});let n={choices:(Array.isArray(e.choices)?e.choices:[]).map(e=>{let t=I(e),n=t.finish_reason,r=I(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={...I(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_${B()}`;#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=R(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())}F(e.usage)&&(this.#l=e.usage);let r=I(L(e.choices)[0]),i=I(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=R(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 L(i.tool_calls))n.push(...this.#_(I(e)));let c=R(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_${B()}`),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=I(e.function),r=this.#s.get(t),i=[];if(r===void 0){let a=R(e.id)??`call_${B()}`;r={itemId:`fc_${a}`,outputIndex:this.#o,callId:a,name:R(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=R(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_${B()}`,created:Xr(),...F(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(!F(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(!F(t))return;let n={...t};for(let e of Es)e in n||(n[e]=null);let r=n.input_tokens_details;F(r)&&(n.input_tokens_details=ks(r,Ds));let i=n.output_tokens_details;F(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(!F(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(!F(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(F(t)&&t.code===null)return{...e,error:{...t,code:`unknown_error`}};let n=e.response;if(F(n)){let t=n.error;if(F(t)&&t.code===null)return{...e,response:{...n,error:{...t,code:`unknown_error`}}}}return null}function Is(e){if(!F(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(!F(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 N(t)?t:null}function Ks(e){let t=e.type===`error`?e.error:void 0;return N(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(N(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 P(`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 P(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=>N(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function yc(e,t){let n=e=>N(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 N(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(!N(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(!N(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 P(`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(!N(t))return t;let n=t.choices;if(!Array.isArray(n)||n.length===0)return t;let r=!1,i=n.map(t=>{if(!N(t))return t;let n=t.delta;if(!N(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||!N(e.body))return e;let t=e.body.stream_options;if(N(t)&&t.include_usage===!0)return e;let n={...N(t)?t:{},include_usage:!0};return{...e,body:{...e.body,stream_options:n}}}}),r=()=>({upstreamRequest:e=>{if(!N(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(!N(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(!N(e))return null;let t=ar(e.prompt_tokens),n=ar(e.completion_tokens);if(t===null&&n===null)return null;let r=N(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(!N(e))return null;let t=ar(e.input_tokens),n=ar(e.output_tokens);if(t===null&&n===null)return null;let r=N(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 N(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(N(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(!N(e))return null;let n=e[t];return typeof n==`string`&&Hc.test(n)?n:null};if(N(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(!N(e))return null;let n=e.metadata;return N(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(`
|
|
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(`
|
|
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
|
+
`):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
|
+
`):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;k(`[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){k(`[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 M,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?.()??ie(),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):k(`[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 M;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)k(`[ezllm] ${t}`)}var wl=`重启服务(CLI 会重新生成默认配置)`,Tl=class extends Error{constructor(e,t=St(),n=wl){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function El(){let e=St();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&&(A(`[ezllm] ${e.message}`),process.exit(1)),e}}function Ol(e){Vt(St(),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(){let{config:e,broken:t}=Il(),n=Ll(e);return n===void 0?t?{required:!0,configBroken:!0,username:``,password:``}:{required:!1,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function zl(){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 Bl(e){return(e=>Pl(e)!==``||Ll(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?jl:Ml,source:`config`}:{hostname:Ml,source:`credentials`}}function Vl(){try{return Bl(El())}catch{return Bl(null)}}function Hl(e,t){return Bl(e).hostname!==Bl(t).hostname||e?.port!==t.port}function Ul(){return El()?.logs}function Wl(e){return typeof e==`number`&&Number.isFinite(e)}function Gl(){let e=Ul(),t=(e,t)=>Wl(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function Kl(){let e=Ul(),t=(e,t)=>Wl(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 ql=`__blob`,Jl=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Yl=1e3,Xl=134217728;function Zl(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function Ql(e){return e instanceof Error?e.message:String(e)}var $l=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function eu(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 tu(){return c(xt(),`spool`)}var nu=/^(\d+)\.jsonl$/,ru=`.tmp`,iu=268435456;function au(){return new Promise(e=>setImmediate(e))}function ou(e){return c(tu(),`${String(e)}.jsonl`)}function su(e){return ou(e)+ru}function cu(){Rt(),m(tu(),{recursive:!0})}function lu(){try{return _(tu()).map(e=>nu.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function uu(e){let t;try{t=g(ou(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function du(){let e=0;try{for(let t of _(tu()))if(t.endsWith(ru))try{S(c(tu(),t)),e++}catch{}}catch{return 0}return e}var fu=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:iu}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of _(tu()))if(nu.test(t))try{e+=x(c(tu(),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 lu()}readRecord(e){return uu(e)}deleteFile(e){try{let t=x(ou(e)).size;S(ou(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){cu();let t=su(e.id);C(t,e.line,`utf-8`),v(t,ou(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await oe(tu(),{recursive:!0});let t=su(e.id);await le(t,e.line,`utf-8`),await ce(t,ou(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){A(`[spool] 写入失败:`,Ql(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>au()).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)&&k(`[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,au()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){A(`[spool] 崩溃前写入失败:`,Ql(e))}}}};function pu(e){let t=uu(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 mu(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function hu(e){return e.map(mu)}function gu(e){return{text:e,values:[]}}function _u(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 V=Object.assign(_u,{raw:gu}),vu=Symbol(`ezllm-db:table`);function yu(e){return e[vu]}function bu(e){return`"${e.replaceAll(`"`,`""`)}"`}function xu(e){return e.map(e=>bu(e)).join(`, `)}function Su(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 H(){return Su(`text`)}function U(){return Su(`integer`)}function Cu(){return Su(`blob`)}function wu(e){return{on(...t){return{name:e,columns:t}}}}function Tu(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,[vu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Eu(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=[bu(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=xu(t.columns);return`CREATE INDEX IF NOT EXISTS ${bu(t.name)} ON ${bu(e)} (${n})`},r=yu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${bu(e)})`);let o=[...i,...a].join(`,
|
|
22
|
-
`),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${
|
|
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(`,
|
|
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
|
|
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
|
|
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 fe(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 pe(e,{params:{[he.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=pe(Buffer.from(e,`utf-8`),{params:{[he.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 me(Buffer.from(e)).toString(`utf-8`)}function Ud(e){if(e.length>0&&e[0]===2)return me(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,
|
|
29
29
|
SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN 0 ELSE output_tokens END) AS tps_output_tokens,
|
|
30
|
-
SUM(CASE WHEN stream = 1 AND ttft IS NOT NULL THEN 1 ELSE 0 END) AS ttft_calls`);function
|
|
30
|
+
SUM(CASE WHEN stream = 1 AND ttft IS NOT NULL THEN 1 ELSE 0 END) AS ttft_calls`);function Xd(e,t){return e>0&&t>0?Math.round(e*1e3/t*10)/10:null}function Zd(e){if(e==null)return null;let t=e=>typeof e==`number`&&Number.isFinite(e)?e:null,n=t(e.output_tokens),r=t(e.duration);if(n===null||n<=0||r===null)return null;let i=e.stream===!0||e.stream===1,a=t(e.ttft),o=i?a===null?null:r-a:r;return o===null?null:Xd(n,o)}function Qd(e,t,n){let r=(e,t)=>e>=400||t!=null&&t!==``;if(!t)return!0;if(String(t)===`err`)return r(e,n);let i=/^([1-5])xx$/i.exec(String(t));if(i&&i[1]){let t=Number(i[1])*100;return e>=t&&e<t+100}return!/^\d+$/.test(String(t))||e===Number(t)}function $d(e,t){if(!t)return!0;let n=Xl.some(t=>RegExp(`^`+t.replace(/%/g,`.*`)+`$`).test(e||``));return t===`model`?n:!n}function ef(e){let t=[];if(e.startDate&&t.push(W.gte(G.date,e.startDate)),e.endDate&&t.push(W.lte(G.date,e.endDate)),e.model&&t.push(W.like(G.model,`%${e.model}%`)),e.sessionId){let n=e.sessionId.trim();n&&t.push(W.and(W.gte(G.session_id,n),W.lt(G.session_id,`${n}\uffff`)))}return e.noSession&&t.push(W.or(W.isNull(G.session_id),W.eq(G.session_id,``))),e.client&&t.push(W.eq(G.client,e.client)),t.length===0?null:W.and(...t)}function tf(e){let t=[],n=ef(e);if(n!==null&&t.push(n),e.pathGroup){let n=W.or(...Xl.map(e=>W.like(G.path,e)));e.pathGroup===`model`?t.push(n):e.pathGroup===`other`&&t.push(W.or(W.isNull(G.path),W.not(n)))}if(e.status){if(String(e.status)===`err`)t.push(W.or(W.gte(G.status,400),W.and(W.isNotNull(G.error),W.ne(G.error,``))));else{let n=/^([1-5])xx$/i.exec(String(e.status));if(n&&n[1]){let e=Number(n[1]);t.push(W.and(W.gte(G.status,e*100),W.lt(G.status,(e+1)*100)))}else/^\d+$/.test(String(e.status))&&t.push(W.eq(G.status,Number(e.status)))}}if(e.keyword){let n=`%${e.keyword}%`;t.push(W.or(W.like(G.model,n),W.like(G.method,n),W.like(G.path,n),W.like(G.preview,n),W.like(G.error,n),W.like(G.time,n)))}return t.length===0?null:W.and(...t)}function nf(e,t){return t===null?e:e.where(t)}function rf(e){return{p:Math.max(parseInt(String(e.page))||1,1),ps:Math.min(Math.max(parseInt(String(e.pageSize))||50,1),500)}}function af(e){return e===`model`||e===`status`||e===`stream`?e:`time`}var of={model:G.model,status:G.status,stream:G.stream,time:G.time},sf=[`id`,`time`,`method`,`path`,`model`,`status`,`stream`,`error`,`preview`,`input_tokens`,`output_tokens`,`cache_read_tokens`,`cache_creation_tokens`,`ip`,`session_id`,`duration`,`ttft`,`headers`,`client`];function cf(e){let t=e=>{let t=of[af(e.sort)];return e.order===`asc`?W.asc(t):W.desc(t)},{p:n,ps:r}=rf(e),i=tf(e),a=q(),o=nf(a.select(G).columns({c:W.count()}),i).get();return{total:o?Number(o.c):0,page:n,pageSize:r,items:nf(a.select(G).columns(sf),i).orderBy(t(e)).limit(r).offset((n-1)*r).all().map(e=>({...e}))}}function lf(e={}){let t=[W.and(W.isNotNull(G.model),W.ne(G.model,``)),W.eq(G.status,200),W.or(...Xl.map(e=>W.like(G.path,e)))];e.startDate&&t.push(W.gte(G.date,e.startDate)),e.endDate&&t.push(W.lte(G.date,e.endDate)),e.model&&t.push(W.eq(G.model,e.model));let n=W.and(...t),r=q().all(B`
|
|
31
31
|
SELECT model,
|
|
32
32
|
COUNT(*) AS calls,
|
|
33
33
|
SUM(input_tokens) AS input_tokens,
|
|
@@ -35,12 +35,12 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
35
35
|
SUM(cache_read_tokens) AS cache_read_tokens,
|
|
36
36
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
37
37
|
AVG(duration) AS avg_duration,
|
|
38
|
-
${
|
|
38
|
+
${Yd}
|
|
39
39
|
FROM logs
|
|
40
40
|
WHERE ${n}
|
|
41
41
|
GROUP BY model
|
|
42
42
|
ORDER BY calls DESC
|
|
43
|
-
`),i=0,a=0,o=0,s=0,c=r.map(e=>{let t=Number(e.input_tokens),n=Number(e.output_tokens),r=Number(e.cache_read_tokens),c=Number(e.ttft_calls??0),l=e.avg_ttft==null?null:Math.round(Number(e.avg_ttft)),u=Number(e.tps_output_tokens??0),d=Number(e.tps_window_ms??0);return i+=u,a+=d,l!==null&&c>0&&(o+=l*c,s+=c),{model:e.model||`unknown`,calls:Number(e.calls),input_tokens:t,output_tokens:n,total_tokens:t+n,cache_read_tokens:r,cache_creation_tokens:Number(e.cache_creation_tokens),cache_rate:t>0?Math.round(r/t*1e3)/10:null,avg_duration:e.avg_duration==null?null:Math.round(Number(e.avg_duration)),avg_ttft:l,tps:
|
|
43
|
+
`),i=0,a=0,o=0,s=0,c=r.map(e=>{let t=Number(e.input_tokens),n=Number(e.output_tokens),r=Number(e.cache_read_tokens),c=Number(e.ttft_calls??0),l=e.avg_ttft==null?null:Math.round(Number(e.avg_ttft)),u=Number(e.tps_output_tokens??0),d=Number(e.tps_window_ms??0);return i+=u,a+=d,l!==null&&c>0&&(o+=l*c,s+=c),{model:e.model||`unknown`,calls:Number(e.calls),input_tokens:t,output_tokens:n,total_tokens:t+n,cache_read_tokens:r,cache_creation_tokens:Number(e.cache_creation_tokens),cache_rate:t>0?Math.round(r/t*1e3)/10:null,avg_duration:e.avg_duration==null?null:Math.round(Number(e.avg_duration)),avg_ttft:l,tps:Xd(u,d)}}),l=c.reduce((e,t)=>e+t.input_tokens,0),u=c.reduce((e,t)=>e+t.output_tokens,0),d=c.reduce((e,t)=>e+t.cache_read_tokens,0);return{total:{calls:c.reduce((e,t)=>e+t.calls,0),input_tokens:l,output_tokens:u,total_tokens:l+u,cache_read_tokens:d,cache_creation_tokens:c.reduce((e,t)=>e+t.cache_creation_tokens,0),cache_rate:l>0?Math.round(d/l*1e3)/10:null,avg_duration:(()=>{let e=c.filter(e=>e.avg_duration!=null);if(!e.length)return null;let t=e.reduce((e,t)=>e+(t.avg_duration??0)*t.calls,0),n=e.reduce((e,t)=>e+t.calls,0);return n>0?Math.round(t/n):null})(),avg_ttft:s>0?Math.round(o/s):null,tps:Xd(i,a)},models:c}}function uf(){return q().select(G).columns([`date`]).groupBy(G.date).orderBy(W.desc(G.date)).all().map(e=>e.date)}function df(){return q().select(G).columns([`client`]).where(W.and(W.isNotNull(G.client),W.ne(G.client,``))).groupBy(G.client).orderBy(W.asc(G.client)).all().map(e=>e.client)}var ff=B.raw(`
|
|
44
44
|
COUNT(*) AS calls,
|
|
45
45
|
MIN(time) AS first_time,
|
|
46
46
|
MAX(time) AS last_time,
|
|
@@ -51,74 +51,74 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
51
51
|
SUM(output_tokens) AS output_tokens,
|
|
52
52
|
SUM(cache_read_tokens) AS cache_read_tokens,
|
|
53
53
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
54
|
-
SUM(duration) AS duration`);function
|
|
55
|
-
SELECT session_id, ${
|
|
54
|
+
SUM(duration) AS duration`);function pf(e){let t=e=>({session_id:e.session_id==null?``:String(e.session_id),calls:Number(e.calls??0),first_time:String(e.first_time??``),last_time:String(e.last_time??``),models:e.models==null?null:String(e.models),clients:e.clients==null?null:String(e.clients),errors:Number(e.errors??0),input_tokens:Number(e.input_tokens??0),output_tokens:Number(e.output_tokens??0),cache_read_tokens:Number(e.cache_read_tokens??0),cache_creation_tokens:Number(e.cache_creation_tokens??0),duration:Number(e.duration??0),avg_ttft:e.avg_ttft==null?null:Math.round(Number(e.avg_ttft)),tps:Xd(Number(e.tps_output_tokens??0),Number(e.tps_window_ms??0))}),{p:n,ps:r}=rf(e),i=tf(e),a=W.and(W.isNotNull(G.session_id),W.ne(G.session_id,``)),o=W.or(W.isNull(G.session_id),W.eq(G.session_id,``)),s=i===null?a:W.and(i,a),c=i===null?o:W.and(i,o),l=q(),u=l.all(B`
|
|
55
|
+
SELECT session_id, ${ff}, ${Yd}
|
|
56
56
|
FROM logs
|
|
57
57
|
WHERE ${s}
|
|
58
58
|
GROUP BY session_id
|
|
59
59
|
ORDER BY last_time DESC
|
|
60
60
|
LIMIT ${r} OFFSET ${(n-1)*r}
|
|
61
|
-
`).map(t),d=l.get(
|
|
62
|
-
SELECT ${
|
|
61
|
+
`).map(t),d=l.get(B`
|
|
62
|
+
SELECT ${ff}, ${Yd}
|
|
63
63
|
FROM logs
|
|
64
64
|
WHERE ${c}
|
|
65
|
-
`),f=d&&Number(d.calls??0)>0?t(d):null,p=l.get(
|
|
65
|
+
`),f=d&&Number(d.calls??0)>0?t(d):null,p=l.get(B`
|
|
66
66
|
SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${s}
|
|
67
|
-
`),m=l.get(
|
|
68
|
-
SELECT COUNT(*) AS c FROM logs WHERE ${i??
|
|
69
|
-
`);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var
|
|
67
|
+
`),m=l.get(B`
|
|
68
|
+
SELECT COUNT(*) AS c FROM logs WHERE ${i??W.and()}
|
|
69
|
+
`);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var mf=[`id`,`time`,`date`,`model`,`status`,`stream`,`error`,`preview`];function hf(e,t=Zl,n=Ql){let{p:r,ps:i}=rf(e),a=String(e.keyword??``).toLowerCase(),o=Math.max(0,Math.floor(t));if(!a)return{total:0,page:r,pageSize:i,items:[],truncated:!1,scanLimit:o};let s=nf(q().select(G).columns(mf),ef(e)).orderBy(W.desc(G.time)).limit(o+1).all(),c=s.length>o,l=s.slice(0,o),u=new Map;for(let e of l){let t=String(e.date),n=u.get(t);n===void 0?u.set(t,[Number(e.id)]):n.push(Number(e.id))}let d=new Map,f=new Map;for(let[e,t]of u){let n=Bd.openIfExists(e);if(n!==null){f.set(e,n);for(let e=0;e<t.length;e+=400){let r=t.slice(e,e+400),i=n.select(ud).columns([`log_id`,`detail`]).where(W.in(ud.log_id,r)).all();for(let e of i)d.set(Number(e.log_id),e.detail)}}}let p=[],m=new Map,h=0,g=!1;for(let e of l){let t=d.get(Number(e.id));if(!t||t.length===0)continue;if(h>=n){g=!0;break}let r=String(e.date),i;try{let e=Ud(t).toString(`utf-8`);h+=Buffer.byteLength(e),i=JSON.parse(e)}catch{continue}let a=m.get(r);if(a===void 0){let e=new Set;Kd(i,e),m.set(r,e)}else Kd(i,a);p.push({r:e,date:r,raw:i})}let _=c||g,v=new Map;for(let[e,t]of m){let n=f.get(e);n!==void 0&&v.set(e,qd(t,n))}let y=[];for(let{r:t,date:n,raw:r}of p){let i=Gd(r,v.get(n)??new Map);JSON.stringify(i).toLowerCase().includes(a)&&(!e.model||String(i.model??``).includes(e.model))&&(!e.status||Qd(Number(i.status??0),e.status,i.error))&&$d(i.path,e.pathGroup)&&y.push({time:t.time,method:i.method||null,path:i.path||null,model:i.model||``,status:i.status,stream:!!i.stream,error:i.error||null,preview:t.preview,id:t.id})}let b=af(e.sort),x=e.order===`asc`?1:-1;return y.sort((e,t)=>{let n=e[b]??``,r=t[b]??``;return n>r?x:n<r?-x:0}),{total:y.length,page:r,pageSize:i,items:y.slice((r-1)*i,(r-1)*i+i),truncated:_,scanLimit:o}}function gf(e){let t=Bd.open(e),n=new Set,r=0,i=0,a=t.select(ud).columns([`detail`]).all();for(let e of a){r++;try{Kd(JSON.parse(Ud(e.detail).toString(`utf-8`)),n)}catch{i++}}if(i>0)return O(`[logs] 详情库 ${e} 有 ${String(i)} 条详情解析失败,跳过本次 blob 回收(避免误删仍被引用的内容)`),{scanned:r,blobsDeleted:0,skipped:!0};let o=t.select(dd).columns([`hash`]).all().map(e=>e.hash).filter(e=>!n.has(e));if(o.length===0)return{scanned:r,blobsDeleted:0,skipped:!1};let s=0;return t.transaction(()=>{for(let e=0;e<o.length;e+=400){let n=t.delete(dd).where(W.in(dd.hash,o.slice(e,e+400))).run();s+=Number(n.changes)}}),{scanned:r,blobsDeleted:s,skipped:!1}}function _f(e){let t=q(),n=tf(e),r=nf(t.select(G).columns({c:W.count()}),n).get(),i=r?Number(r.c):0,a;if(i>0)a=nf(t.select(G).columns([`id`]),n).all().map(e=>Number(e.id));else if(e.keyword){a=[];let t=!1;for(let n=1;;n++){let r=hf({...e,page:n,pageSize:500,sort:`time`,order:`desc`});if(a.push(...r.items.map(e=>Number(e.id))),t||=r.truncated,r.items.length===0||a.length>=r.total)break}t&&O(`[logs] 详情扫描达到上限,仅清理最近扫描窗口内的命中条目(更早的命中未参与匹配)`)}else return 0;if(a.length===0)return 0;let o=new Map;for(let e=0;e<a.length;e+=400){let n=t.select(G).columns([`id`,`date`]).where(W.in(G.id,a.slice(e,e+400))).all();for(let e of n){let t=o.get(e.date);t===void 0?o.set(e.date,[Number(e.id)]):t.push(Number(e.id))}}for(let[e,t]of o){let n=Bd.open(e);n.transaction(()=>{for(let e=0;e<t.length;e+=400)n.delete(ud).where(W.in(ud.log_id,t.slice(e,e+400))).run()})}Sd(()=>{for(let e=0;e<a.length;e+=400)t.delete(G).where(W.in(G.id,a.slice(e,e+400))).run()});for(let e of o.keys())try{gf(e)}catch(t){O(`[logs] 详情库 ${e} 的 blob 回收失败:`,eu(t))}return a.length}function vf(e,t){let n=e=>$l(new Date(Date.now()-e*86400*1e3).toISOString());if(e<=0&&t<=0)return{detailsDeleted:0,rowsDeleted:0};let r=0;if(e>0){let t=n(e);for(let e of Bd.listDetailDates())e<t&&Bd.deleteDetailDb(e)&&r++}let i=0;if(t>0){let e=n(t),r=Sd(()=>q().delete(G).where(W.lt(G.date,e)).run());i=Number(r.changes)}return{detailsDeleted:r,rowsDeleted:i}}var yf={syncIntervalMs:5e3,payloadQuality:9},bf=2e3,xf=1e3,Sf=1e3;function Cf(e){return q().select(G).columns([`id`]).where(W.eq(G.id,e)).get()!==void 0}var wf=class{#e;#t;#n=null;#r=!1;#i=0;constructor(e){this.#e=e.spool,this.#t=e.getConfig}runScheduledRound(){this.#r||this.#n!==null||(this.#r=!0,this.syncOnce().then(e=>{(e.inserted>0||e.poisoned>0)&&D(`[ezllm] spool 入库: 详情 ${String(e.inserted)} 条`)}).catch(e=>{k(`[ezllm] spool 入库失败:`,eu(e))}).finally(()=>{this.#r=!1}))}async syncOnce(e={}){let t=e.budgetMs??bf,n=Date.now()+t,r={inserted:0,poisoned:0,anchorFilled:0,filesDone:[]},i=this.#t(),a=this.#e.listIds();for(let e of a){if(Date.now()>=n)break;let t=this.#e.readRecord(e);if(t.kind!==`missing`){if(t.kind===`corrupt`){O(`[spool] 丢弃不可解析的记录 ${String(e)}.jsonl`),this.#e.deleteFile(e),r.poisoned++;continue}try{let n=Ad(t.entry,e,i.payloadQuality),a=Cf(e);Vd([n]),a||r.anchorFilled++,r.inserted++}catch(t){k(`[spool] 记录 ${String(e)} 入库失败:`,eu(t));continue}this.#e.deleteFile(e),r.filesDone.push(e),await su()}}return r}async syncNow(){if(this.#n!==null){await this.#n;return}if(!this.#r&&!(Date.now()-this.#i<Sf)){this.#i=Date.now(),this.#n=this.syncOnce({budgetMs:500});try{await this.#n}finally{this.#n=null}}}async recover(){if(this.#n!==null){await this.#n;return}let e=this.syncOnce({budgetMs:3e4});this.#n=e;try{let t=await e;t.inserted>0&&D(`[ezllm] spool 启动恢复:补录 ${String(t.inserted)} 条日志详情`)}catch(e){k(`[ezllm] spool 启动恢复失败:`,eu(e))}finally{this.#n=null}}async drain(e=6e4){let t={inserted:0,poisoned:0,anchorFilled:0,filesDone:[]},n=Date.now()+e;for(;;){let e=await this.syncOnce({budgetMs:Math.min(5e3,Math.max(0,n-Date.now()))});if(t.inserted+=e.inserted,t.poisoned+=e.poisoned,t.anchorFilled+=e.anchorFilled,t.filesDone.push(...e.filesDone),this.#e.listIds().length===0||Date.now()>=n)break}return t}},Tf=null;function Ef(e){return Tf===null&&(Tf=e===void 0?new wf({spool:new mu,getConfig:()=>yf}):new wf(e)),Tf}function Df(e){let t=Ef(e);return{name:`spoolSync`,everyMs:()=>e.getConfig().syncIntervalMs,firstDelayMs:xf,run:()=>{t.runScheduledRound()}}}async function Of(){await Ef().syncNow()}async function kf(){await Ef().recover()}async function Af(e=6e4){return Ef().drain(e)}var jf=216e5,Mf=3e4;function Nf(e){return{name:`logPrune`,everyMs:jf,firstDelayMs:Mf,run:()=>{try{let{detailDays:t,rowDays:n}=e.getRetention(),r=vf(t,n);(r.detailsDeleted>0||r.rowsDeleted>0)&&D(`[ezllm] 日志清理: 详情库 -${String(r.detailsDeleted)} 天, 摘要 -${String(r.rowsDeleted)} 条 (详情${t>0?` ${String(t)}天`:`永久`}, 摘要${n>0?` ${String(n)}天`:`永久`})`)}catch(e){k(`[ezllm] 日志清理失败:`,eu(e))}}}}var Pf=3,Ff=`fallback`;function If(){return new Date().toISOString()}function Lf(e){return q().select(K).columns([`client`]).where(W.eq(K.ua,e)).get()}function Rf(e){if(e.length===0)return 0;let t=If(),n=q(),r=0;return Sd(()=>{for(let i of e){let e=n.insert(K).values({ua:i,client:null,source:null,attempts:0,created_at:t,updated_at:t}).orIgnore().run();r+=Number(e.changes)}}),r}function zf(){return q().select(K).columns([`ua`,`client`]).where(W.isNotNull(K.client)).all().filter(e=>e.client!==null&&e.client!==``)}function Bf(e,t){if(e===``||t===``)return 0;let n=q().run(B`
|
|
70
70
|
UPDATE logs SET client = ${t}
|
|
71
|
-
WHERE client IS NULL AND ${
|
|
72
|
-
`);return Number(n.changes)}function
|
|
71
|
+
WHERE client IS NULL AND ${B.raw(tu)} = ${e}
|
|
72
|
+
`);return Number(n.changes)}function Vf(e){return q().select(K).columns([`ua`]).where(W.and(W.isNull(K.client),W.lt(K.attempts,Pf))).orderBy(W.asc(K.created_at)).limit(e).all().map(e=>e.ua)}function Hf(e,t){if(e.size===0)return 0;let n=If(),r=q(),i=0;return Sd(()=>{for(let[a,o]of e){let e=r.update(K).set({client:o,source:t,updated_at:n}).where(W.eq(K.ua,a)).run();i+=Number(e.changes)}}),i}function Uf(e){if(e.length===0)return[];let t=q(),n=t.select(K).columns([`ua`,`attempts`,`client`]).where(W.in(K.ua,[...e])).all(),r=[],i=If();return Sd(()=>{for(let e of n){if(e.client!==null)continue;let n=e.attempts+1;t.update(K).set({attempts:n,updated_at:i}).where(W.eq(K.ua,e.ua)).run(),n>=Pf&&r.push(e.ua)}}),r}var Wf=new Map,Gf=new Set;function Kf(e){let t=e.trim();if(t===``)return null;if(Wf.has(t))return Wf.get(t)??null;let n=Lf(t);return n===void 0?(Wf.set(t,null),Gf.add(t),null):(Wf.set(t,n.client),n.client)}function qf(e){return(()=>{if(Gf.size===0)return 0;let e=Rf([...Gf]);return Gf.clear(),e})(),Vf(e)}function Jf(e,t){if(e.size===0)return 0;let n=Hf(e,t);for(let[t,n]of e)Bf(t,n),Wf.set(t,n),Gf.delete(t);return n}function Yf(e){return Uf(e)}var Xf=100,Zf=67108864,Qf=new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`x-goog-api-key`,`cookie`,`set-cookie`]),$f=new Set([`key`,`apikey`,`accesskey`,`accesstoken`,`token`,`authtoken`,`sig`,`signature`,`secret`,`password`]);function ep(e){let t=e=>e===null?null:e.split(`
|
|
73
73
|
|
|
74
|
-
`).filter(e=>e.trim()!==``),n=e=>`***redacted(${String(e)})***`,r=e=>e.toLowerCase().replace(/[-_]/g,``),i=e=>{if(e===null)return null;try{return JSON.parse(e)}catch{return e}},a=e=>{if(!e)return e;let t=!1,r={};for(let[i,a]of Object.entries(e))
|
|
74
|
+
`).filter(e=>e.trim()!==``),n=e=>`***redacted(${String(e)})***`,r=e=>e.toLowerCase().replace(/[-_]/g,``),i=e=>{if(e===null)return null;try{return JSON.parse(e)}catch{return e}},a=e=>{if(!e)return e;let t=!1,r={};for(let[i,a]of Object.entries(e))Qf.has(i.toLowerCase())?(r[i]=n(a.length),t=!0):r[i]=a;return t?r:e},o=e=>{let t;try{t=new URL(e)}catch{return e}let i=!1;for(let[e,a]of Array.from(t.searchParams.entries()))$f.has(r(e))&&(t.searchParams.set(e,n(a.length)),i=!0);return i?t.toString():e},s=e.streaming,c=e.upstream,l=e.inbound.bodyText!==null||c.url!==null||c.responseText!==null||e.client.body!==void 0||e.client.streamText!==null,u=a(e.inbound.headers);return{time:e.time,method:e.http.method||void 0,path:e.http.path||void 0,model:e.route?.name||void 0,status:e.status,stream:s,error:e.error?.message??null,response:l?{_capture:!0,inbound_request:{url:o(e.http.url),headers:u,body:e.inbound.body??null},upstream_request:c.url?{url:o(c.url),headers:a(c.requestHeaders),body:i(c.requestBody)}:null,upstream_response_text:s?null:c.responseText,upstream_stream_frames:s?t(c.responseText):null,client_response:s?void 0:e.client.body,client_stream_frames:s?t(e.client.streamText):null,truncated:e.truncated}:null,input_tokens:e.usage?.inputTokens??0,output_tokens:e.usage?.outputTokens??0,cache_read_tokens:e.usage?.cacheReadInputTokens??0,cache_creation_tokens:e.usage?.cacheCreationInputTokens??0,ip:e.http.clientIp||null,session_id:e.http.sessionId||null,duration:e.durationMs,ttft:e.upstream.firstTokenMs,headers:u===null?null:JSON.stringify(u),client:Kf(e.http.userAgent)}}function tp(e,t){let n=ep(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:Dd();e.write(i,n),Md(i,n);let a=Zd({output_tokens:n.output_tokens,duration:n.duration,stream:n.stream,ttft:n.ttft});D(`[ezllm] ${t.requestId} ${t.route?.name??t.http.path} -> ${String(t.status)} ${String(t.durationMs)}ms streaming=${String(t.streaming)}`+(n.ttft==null?``:` ttft=${String(n.ttft)}ms`)+(a===null?``:` tps=${String(a)}`)+(t.error===null?``:` error=${t.error.stage}: ${t.error.message}`))}var np=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new mu,this.#t=e.queueCapacity??Xf,this.#n=e.queueMaxBytes??Zf}#o(){let e=this.#r.shift();return this.#i-=rp(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await su();try{tp(this.#e,this.#o())}catch(e){k(`[ezllm] trace 落盘失败:`,eu(e))}}}finally{this.#a=!1}}}write(e){for(;this.#r.length>=this.#t||this.#i>=this.#n&&this.#r.length>0;)this.#o(),O(`[ezllm] trace 队列已满(${String(this.#t)} 条 / ${String(Math.round(this.#n/1024/1024))}MB),丢弃最旧一条`);this.#r.push(e),this.#i+=rp(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await su();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{tp(this.#e,this.#o())}catch(e){k(`[ezllm] trace 崩溃前落盘失败:`,eu(e))}this.#e.flushSync()}};function rp(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}var ip=48;function ap(e){let t=e.trim();if(t===``)return``;let n=t.split(/\s+/)[0]??t;return n.length>ip?n.slice(0,ip):n}var op=500;function sp(e={}){let t=e=>{let t=e.headers;if(typeof t==`string`&&t!==``)return t;let n=e.response;if(typeof n!=`object`||!n)return null;let r=n.inbound_request;if(typeof r!=`object`||!r)return null;let i=r.headers;return typeof i!=`object`||!i||Array.isArray(i)||Object.entries(i).length===0?null:JSON.stringify(i)},n=(e,t)=>{let n=e.get(B`SELECT detail FROM log_details WHERE log_id = ${t}`);if(n===void 0)return null;try{return JSON.parse(Ud(n.detail).toString(`utf-8`))}catch{return null}},r=q(),i={days:0,scanned:0,filled:0,skipped:0,uas:0,clientsAssigned:0},a=Bd.listDetailDates();for(let o of a){let a=r.all(B`SELECT id FROM logs WHERE date = ${o} AND headers IS NULL`).map(e=>Number(e.id));if(a.length===0)continue;i.days++;let s=Bd.openIfExists(o);if(s===null){i.skipped+=a.length,e.onProgress?.(`${o}: 详情库不存在,跳过 ${String(a.length)} 行`);continue}let c=new Set,l=[],u=()=>{if(l.length===0)return;let e=l;l=[],Sd(()=>{for(let t of e)r.run(B`UPDATE logs SET headers = ${t.headers} WHERE id = ${t.id} AND headers IS NULL`)})};for(let e of a){i.scanned++;let r=n(s,e),a=r===null?null:t(r);if(a===null){i.skipped++;continue}l.push({id:e,headers:a}),i.filled++;let o=nu(a);o!==``&&c.add(o),l.length>=op&&u()}u(),c.size>0&&(i.uas+=Rf([...c])),e.onProgress?.(`${o}: 扫描 ${String(a.length)} 行,回填 ${String(i.filled)} 行(累计)`)}if(a.length>0){let e=r.select(G).columns({n:W.count()}).where(W.and(W.isNull(G.headers),W.not(W.in(G.date,a)))).get();i.skipped+=Number(e?.n??0)}for(let e of zf())i.clientsAssigned+=Bf(e.ua,e.client);return i}var cp=2e3,lp=500;function up(e={}){let t=e=>{let t;try{t=JSON.parse(e)}catch{return``}if(typeof t!=`object`||!t||Array.isArray(t))return``;try{let e=new Headers;for(let[n,r]of Object.entries(t))typeof r==`string`&&e.set(n,r);return Wc(e)}catch{return``}},n=(e,t)=>{t.length!==0&&Sd(()=>{for(let n of t)e.run(B`
|
|
75
75
|
UPDATE logs SET session_id = ${n.sessionId}
|
|
76
76
|
WHERE id = ${n.id} AND (session_id IS NULL OR session_id = '')
|
|
77
|
-
`)})},r=
|
|
77
|
+
`)})},r=q(),i={scanned:0,filled:0},a=0;for(;;){let o=r.all(B`
|
|
78
78
|
SELECT id, headers FROM logs
|
|
79
79
|
WHERE id > ${a}
|
|
80
80
|
AND (session_id IS NULL OR session_id = '')
|
|
81
81
|
AND headers IS NOT NULL
|
|
82
82
|
ORDER BY id
|
|
83
|
-
LIMIT ${
|
|
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>=sp&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function lp(e){let t=()=>{for(let e of Dt())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}:(k(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)},r=t();if(r===null)return;let i;try{i=await import(te(r).href)}catch(e){A(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${r}`),A(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),A(`[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),O(`[ezllm] 已加载用户钩子:${r}(onModelRequest)`))}function up(e){return pt.port??e.port}async function dp(e,t,n={}){let r=new Sl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Td())}});t.register(r),await lp(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)} 个已停用)`:``;O(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new M},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 fp=64;function pp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>fp;){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 mp=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 hp(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var gp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,_p=new M;function vp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}_p.post(`/login`,async e=>{let t=Rl();if(t.configBroken)return e.json({error:gp},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await hp(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:vp(t)})});async function yp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Rl();if(!n.required)return await t();if(n.configBroken)return e.json({error:gp},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==vp(n))return e.json({error:`token 无效或已过期`},401);await t()}var bp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function xp(e,t){return e instanceof bp?(e.status>=500&&A(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(A(`[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 Sp(e){return async t=>{try{return await e(t)}catch(e){throw new bp(500,e.message)}}}var Cp=8,wp=6;function Tp(){let e=()=>{let e=El();if(e===null)throw new bp(500,`配置文件不存在`);return e},t=new M;return t.onError(xp),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=zl(),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:Rl().required,version:Lt(),buildSource:vt()})}),t.post(`/master-key`,async t=>{if(zl().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await hp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r;if(n.mode===`generate`)r=re(32).toString(`base64url`);else if(n.mode===`custom`){if(r=(n.masterKey??``).trim(),r.length<Cp)return t.json({error:`主密钥至少 ${String(Cp)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return Ol(a),t.json({masterKey:r,...Hl(i,a)?{restartHint:Nl}:{}})}),t.post(`/finish`,async t=>{if(zl().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await hp(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);let i=(n.masterKey??``).trim();if(i!==``&&i.length<Cp)return t.json({error:`主密钥至少 ${String(Cp)} 位`},400);if(r===`server`&&i===``&&Fl()===``)return t.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);let a=(n.username??``).trim(),o=n.password??``,s=a!==``||o!==``;if(s){if(a===``||o===``)return t.json({error:`用户名和密码需同时提供`},400);if(o.length<wp)return t.json({error:`密码至少 ${String(wp)} 位`},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`,...s?{"web-ui":{...c[`web-ui`],"login-account":{username:a,password:o}}}:{}};return Ol(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...Hl(c,l)?{restartHint:Nl}:{}})}),t}function Ep(e){let t=new M;return t.onError(xp),t.get(`/`,Sp(e=>{let t=El();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Sp(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{Al(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=El()}catch{r=null}return Ol(n),e.runtime.rebuild(kl(n)),t.json({message:`配置已保存并生效`,...Hl(r,n)?{restartHint:Nl}:{}})})),t}var Dp=`直接回复我 ok,不要思考不要解释`;function Op(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function kp(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Ap(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 jp(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=Ap(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 Mp(e){let t=new M;t.onError(xp);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)),`${Op(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:kp(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`,Sp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Sp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Sp(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:Dp}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:Dp,stream:!0}:{model:e,messages:[{role:`user`,content:Dp}],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`,...kp(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Op(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 jp(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=up(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 A(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}return c({response:f,read:await jp(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 Np=Tu(`latency_probes`,{id:U().primaryKey({autoIncrement:!0}),model:H().notNull(),time:U().notNull(),latency_ms:U().notNull(),ok:U().notNull(),error:H()},[wu(`idx_latency_probes_model_time`).on(`model`,`time`),wu(`idx_latency_probes_time`).on(`time`)]),Pp=2592e6,Fp=null;function Ip(){let e=Fp;if(e!==null)return e;let t=sd(`latency`);return t.createTables([Np]),Fp=t,t}function Lp(){return Ip().native}function Rp(e){if(e.length!==0)try{Ip().insert(Np).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){A(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function zp(){let e=Date.now()-Pp;return Ip().select(Np).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(G.gt(Np.time,e)).orderBy(G.asc(Np.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 Bp(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=Ip().select(Np).columns([`time`,`latency_ms`,`ok`]).where(G.and(G.eq(Np.model,e),G.gt(Np.time,a),G.lte(Np.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 Vp(){let e=Ip().select(Np).columns({t:G.max(Np.time)}).get();return e?.t==null?null:Number(e.t)}function Hp(e){try{let t=Date.now()-e;Ip().delete(Np).where(G.lte(Np.time,t)).run()}catch(e){A(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Up=3e4,Wp=4,Gp=!1;function Kp(){return Gp}function qp(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function Jp(e){let t=async e=>{let t=Op((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?kp(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Dp}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Dp,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Dp}],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(Up)});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 jp(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(Wp,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(Gp)return!1;Gp=!0;try{let t=await n(qp(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));Rp(t),Hp(Pp);let r=t.filter(e=>e.ok).length;return O(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(r)}),数据已入库 latency.db`),!0}catch(e){return A(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Gp=!1}}function Yp(e){return qp(e).length}var Xp=[{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 Zp(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 Xp){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 Qp(e){let t=new M;return t.get(`/history`,t=>{let n=zp(),r=Date.now();return t.json({running:Kp(),lastRunAt:Vp(),models:Zp(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=Bp(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>Kp()?t.json({ok:!1,error:`测试进行中,请稍候`},409):Yp(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(Jp(e),t.json({ok:!0,running:!0}))),t}function $p(){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(xt())/1024/1024*10)/10,n=new M;return n.onError(xp),n.get(`/`,Sp(e=>{let n=e.req.query(),r=sf({startDate:n.startDate,endDate:n.endDate,model:n.model});return e.json({...r,logStorageMB:t()})})),n}function Y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function em(e){return typeof e==`string`?e:null}function tm(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function nm(e,t){let n=tm(e,t);return n===void 0?void 0:e[n]}function rm(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 im(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function am(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=Y(r);if(i===null)return null;let a={},o=Y(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=tm(n.headers,`cookie`);if(e===void 0)continue;let r=im(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(tm(e.headers,`cookie`)!==void 0)return e;let n=im(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 om(e){return e.some(e=>tm(e.headers,`cookie`)!==void 0)}var sm=0xe8d4a51000,cm=3e4;async function lm(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(cm)});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=Y(await r.json());if(i===null)throw Error(`响应不是 JSON 对象`);return i}function um(e){return e===null||e<=0?null:Math.round(e<sm?e*1e3:e)}function dm(e){return Math.round(e*100)/100}function fm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function pm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function mm(e,t){let n=Y(e);if(n===null)return null;let r=X(n[t.used])??0,i=X(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:um(X(n[t.resetAt])),exceeded:a}}var hm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await lm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await lm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},gm=`https://api.commandcode.ai`,_m=`/alpha/billing/credits`,vm=`/alpha/usage/summary`,ym=`/alpha/billing/subscriptions`,bm={"individual-pro-v1":80,"individual-goat":70},xm=/^user_[A-Za-z0-9_-]+$/,Sm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function Cm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:fm(t)}]}function wm(e){let t=em(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Tm=class extends hm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=xm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!xm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(gm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(vm),this.get(_m),this.get(ym).catch(()=>null)]),r=Y(t.windowLimits),i=Y(t.credits),a=n===null?null:Y(n.data),o=a===null?null:em(a.planId),s=o===null?null:bm[o]??null,c=i===null?null:X(i.monthlyCredits),l=s===null||c===null?null:{used:dm(Math.max(0,s-c)),cap:s,resetAt:a===null?null:wm(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:mm(r.fiveHour,Sm),weekly:r===null?null:mm(r.weekly,Sm),monthly:l,totalTokens:X(e.totalTokens),totalRuns:X(e.totalCount),voucherBalance:null,balance:null,extraStats:Cm(l,c)}}},Em=`https://api.deepseek.com`,Dm=`/user/balance`,Om=`余额不足,无法调用 API`;function km(e){let t=X(e);if(t!==null)return t;let n=em(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Am(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function jm(e){let t=[];if(!Array.isArray(e))return t;let n=new Set;for(let r of e){let e=Y(r);if(e===null)continue;let i=em(e.currency);if(i===null||i.trim()===``)continue;let a=i.trim();if(n.has(a))continue;let o=km(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:km(e.granted_balance),toppedUp:km(e.topped_up_balance)}))}return t}function Mm(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 Nm=class extends hm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(Em,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Dm),t=Mm(jm(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=Am(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${fm(dm(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${fm(dm(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:Om}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:dm(t.total),extraStats:r.length===0?null:r}}},Pm=[`127.0.0.1`,`localhost`,`[::1]`],Fm=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function Im(e){let t;try{t=new URL(e)}catch{return null}if(!Pm.some(e=>e===t.hostname.toLowerCase()))return null;let n=Fm.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 Lm(e){let t=[];if(!Array.isArray(e))return t;for(let n of e){let e=Y(n);if(e===null)continue;let r=em(e.name),i=em(e.display);r!==null&&r.trim()!==``&&i!==null&&i.trim()!==``&&t.push({name:r,usedPercent:X(e.used)??0,display:i,amount:X(e.amount),limit:X(e.limit),unit:em(e.unit)})}return t}var Rm=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=Pm;#e;#t;constructor(e){let t=Im(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await lm(`${this.#e}/p/${encodeURIComponent(this.#t)}/usage`,{method:`GET`,headers:{accept:`application/json`}}),t=em(e.error);if(t!==null&&t.trim()!==``)throw Error(t);let n=em(e.plan);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:null,windows:Lm(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},zm=`/api/user/self`,Bm=`/api/user/subscription/current_cycle`,Vm={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Hm(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=Y(e);if(n!==null&&n.key===t)return n}return null}function Um(e){return e===null||X(e.total_count)===null?null:mm(e,Vm)}function Wm(e){let t=Y(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=Y(e),n=t===null?null:X(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function Gm(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Km=class extends hm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=am(e),n=Gm(t,zm),r=Gm(t,Bm);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>nm(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(zm),this.get(Bm).catch(()=>null)]),n=Um(Hm(e,`credit_5h_limit`)),r=Um(Hm(e,`credit_7d_limit`)),i=Um(Hm(e,`credit_30d_limit`));if(i===null&&t!==null){let e=X(t.plan_points),n=X(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:um(X(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:Wm(e),balance:null}}},qm=`GetAgentPlanAFPUsage`,Jm=`GetAgentPlanUsageDetails`,Ym=`console.volcengine.com`,Xm=`2024-01-01`,Zm=`cn-beijing`,Qm={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function $m(e){return e.find(e=>e.url.includes(qm))}function eh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Zm}/${Xm}`:t}function th(e){return e.find(e=>im(e.url)===Ym)}var nh=class extends hm{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=am(e),n=$m(t)??th(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!om(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==Ym)throw Error(`非方舟控制台域`);r=e.origin,i=eh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=rm(nm(n.headers,`cookie`),`csrfToken`)??nm(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}/${qm}`,this.#t=`${i}/${Jm}`}envelope(e){let t=Y(e.ResponseMetadata),n=t===null?null:Y(t.Error);if(n!==null){let e=em(n.Code)??`Unknown`,t=em(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=Y((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=mm(e.AFPFiveHour,Qm),n=mm(e.AFPWeekly,Qm),r=mm(e.AFPMonthly,Qm);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=Y(e.AFPMonthly),a=i===null?null:X(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=Y((await this.post(this.#t,{Filter:{StartTime:pm(new Date(n)),EndTime:pm(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=Y(t);return n===null||n.Unit!==`Tokens`?e:e+(X(n.Usage)??0)},0):null}catch{return null}}},rh=`/api/biz/account/query-customer-account-report`,ih=`/api/finance/expenseBill/expenseBillListByDay`,ah=200,oh=`bigmodel_token_production`;function sh(e){let t=rm(nm(e.headers,`cookie`),oh);if(t!==null&&t.trim()!==``)return t.trim();let n=nm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var ch=class extends hm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=am(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=sh(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=X(e.code);if(t!==200){let n=em(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=pm(e).slice(0,7),n=pm(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(ih,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(ah)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=X(l)??o.length,o=o.concat(c);for(let e of c){let t=Y(e);if(t===null)continue;let a=X(t.originalAmount),o=em(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(rh),this.#e()]),n=Y(e.data),r=(n===null?null:X(n.availableBalance))??(n===null?null:X(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=X(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:lh(n)}}};function lh(e){let t=e=>`${fm(e)} 元`,n=[],r=X(e.rechargeAmount);r!==null&&n.push({label:`累计充值`,value:t(r)});let i=X(e.giveAmount);i!==null&&n.push({label:`赠送金额`,value:t(i)});let a=X(e.creditBalance);return a===null?e.creditStatus===`NOT_OPEN`&&n.push({label:`信用余额`,value:`未开通`}):n.push({label:`信用余额`,value:t(a)}),n}var uh=[Tm,Nm,Km,nh,ch,Rm];function dh(){return uh}function fh(e){if(e===void 0)return null;let t=im(e);if(t===``)return null;for(let e of uh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function ph(e,t){let n=fh(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){return e===void 0||Im(e)===null?null:Rm}function hh(e){if(mh(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:Rm.vendorId,vendor:new Rm(e)}}function gh(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of am(e)){let e=im(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of uh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=im(t);if(e!==``){for(let t of uh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of uh)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=uh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=uh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=fh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var _h=Ht(`quota.json`);function vh(e){let t=e=>{let t=e=>{let t=Y(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=Y(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=Y(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=Y(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=Y(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=Y(_h.get(e));if(n===null)return null;let r=n.fetchText,i=n.vendorId,a=n.fetchedAt,o=n.error;return{fetchText:typeof r==`string`&&r.trim()!==``?r:void 0,vendorId:typeof i==`string`?i:void 0,snapshot:t(n.snapshot)??void 0,fetchedAt:typeof a==`number`&&Number.isFinite(a)?a:void 0,error:typeof o==`string`&&o!==``?o:void 0}}function yh(e,t){_h.set(e,t)}function bh(e){_h.get(e)!==void 0&&_h.set(e,void 0)}function xh(){let e=_h.getAll(),t={};for(let n of Object.keys(e)){let e=vh(n);e!==null&&(t[n]=e)}return t}function Sh(e,t,n,r){yh(e,{fetchText:vh(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function Ch(e,t){let n=vh(e);if(n===null){yh(e,{error:t});return}yh(e,{...n,error:t})}var wh=!1;function Th(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function Eh(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function Dh(){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:Eh(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 Oh(e){return Dh()?.get(e)??null}async function kh(e){try{let t=Oh(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&mh(t.apiBase)!==null)({vendorId:n,vendor:r}=hh(t.apiBase));else if(fh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=ph(t.apiKey,t.apiBase))}else{let i=vh(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=gh(i,t.apiBase))}let i=await r.fetchQuota();Sh(e,n,i,Date.now())}catch(t){Ch(e,Th(t))}return vh(e)}async function Ah(){let e=()=>{let e=Dh();return e===null?null:new Set(e.keys())};if(!wh){wh=!0;try{let t=Dh(),n=[];for(let[e,r]of t??[])(fh(r.apiBase)!==null||mh(r.apiBase)!==null)&&n.push(e);for(let e of n)await kh(e);let r=e();for(let[e,t]of Object.entries(xh()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){bh(e);continue}n.includes(e)||await kh(e)}}catch(e){A(`[quota] 刷新失败:`,Th(e))}finally{wh=!1}}}function jh(){let e=async e=>{let t=(await hp(e))?.fetchText;return typeof t==`string`?t:null},t=()=>dh().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}})),n=new M;return n.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:xh()})),n.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),n.put(`/:provider`,async t=>{let n=t.req.param(`provider`),r=Oh(n)?.apiBase;if(mh(r)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(fh(r)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);let i=await e(t);if(i===null)return t.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let a=vh(n);yh(n,{fetchText:i,vendorId:a?.vendorId,snapshot:a?.snapshot,fetchedAt:a?.fetchedAt,error:void 0});let o=await kh(n);return t.json({ok:!0,entry:o})}),n.delete(`/:provider`,e=>(bh(e.req.param(`provider`)),e.json({ok:!0}))),n.post(`/:provider/refresh`,async e=>{let t=await kh(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),n}function Mh(e){return e===`0.0.0.0`||e===`::`}function Nh(e=T()){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 Ph(e,t){let n=new M;return n.get(`/`,n=>n.json({listenPort:up(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&Mh(t.hostname)?{lanAddresses:Nh()}:{},masterKey:Fl()})),n}var Fh=864e5,Ih=3e5,Lh=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,Rh=new Map;try{let e=g(Ct(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;Rh.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function zh(){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=Rh.get(e);if(!t)return null;let n=t.value.error===void 0?Fh:Ih;return Date.now()-t.at>=n?(Rh.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of Rh)e[t]={...n,_ts:r};C(Ct(),JSON.stringify(e))}catch(e){A(`保存 IP 缓存失败:`,e.message)}},r=async e=>{let r=t(e);if(r)return r;let i=await(await fetch(Lh.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return Rh.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return Rh.set(e,{value:a,at:Date.now()}),n(),a},i=new M;return i.onError(xp),i.get(`/dates`,e=>{let t=cf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=lf();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 bp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Kd(t);return n||=(await Ef(),Kd(t)??pu(Number(t))),n?e.json({...n,meta:{...n.meta,tps:Yd(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Sp(async t=>{let n=t.req.query(),r=of({...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=pf({...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:eu(e.headers),tps:Yd(e)}))})})),i.get(`/sessions`,Sp(t=>{let n=t.req.query(),r=df({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Sp(async t=>{await Of();let n=lu().length;n>0&&k(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=hf(e(r));return O(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var Bh=3e4,Vh=12e4,Hh=5242880,Uh=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],Wh=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function Gh(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 Kh(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(Wh.includes(n.toLowerCase())||(t[n]=r));return t}function qh(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?Bh:Math.min(Math.floor(e),Vh)}function Jh(e){if(typeof e!=`string`||e.trim()===``)throw new bp(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 bp(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new bp(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function Yh(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function Xh(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=Hh-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 Zh(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function Qh(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 bp(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=Gh(l),{text:d,truncated:f}=u?await Xh(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:Zh(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function $h(){let e=new M;return e.onError(xp),e.post(`/`,async e=>{let t=await hp(e);if(t===null)throw new bp(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!Uh.includes(n))throw new bp(400,`不支持的请求方法:${n}(可用 ${Uh.join(` / `)})`);return await Qh({url:Jh(t.url),method:n,headers:Kh(t.headers),body:Yh(t.body),timeoutMs:qh(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await Qh({url:Jh(t.url),method:`GET`,headers:Kh(void 0),body:void 0,timeoutMs:qh(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function eg(e){return`http://127.0.0.1:${String(e.port)}`}var tg=`daemon.json`;function ng(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,tg),`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 M;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:eg(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 rg=`ezllm-autostart.vbs`,ig=`ezllm-autostart.cmd`,ag=`com.ezllm.autostart`,og=`ezllm.service`,sg=`autostart.opt-out`,cg=`ezllm-v2`,lg=`Auto-generated by "npx ezllm install" (${cg}). Disable in the ezllm admin UI (Settings → startup) or by running \`npx ezllm uninstall\`.`,ug=`ELLM_`,dg=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]),fg=new Set([`ELLM_PORT`,`ELLM_NODE_MIRROR`,`ELLM_NODE_BIN`]);function pg(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(fg.has(n)||(n.startsWith(ug)||dg.has(n))&&(t[n]=r));return t}function mg(e){return c(e,sg)}function hg(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),rg)}function gg(){return c(w(),`Library`,`LaunchAgents`,`${ag}.plist`)}function _g(){return c(w(),`.config`,`systemd`,`user`,og)}var vg=3e4;function yg(e,t){return new Promise(n=>{let r=he(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},vg),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var bg={win32:{itemPath:hg,on:Eg,off:kg},darwin:{itemPath:gg,on:Dg,off:Ag},linux:{itemPath:_g,on:Og,off:jg}};function xg(e){return bg[e]??null}function Sg(e){let t=xg(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function Cg(e,t){return[e,t.entryJs,...t.args??[]]}function wg(e){return c(e,`logs`,`autostart.log`)}async function Tg(e,t,n=yg){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 Eg(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=wg(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${lg}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${Cg(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
85
|
-
`)},i=e=>[`' ${
|
|
86
|
-
`),a=
|
|
87
|
-
`),a=
|
|
88
|
-
`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<!-- ${
|
|
89
|
-
`)},i=
|
|
90
|
-
`),r=
|
|
91
|
-
`)},r=
|
|
92
|
-
`,`utf-8`)}function
|
|
93
|
-
`,`utf-8`),!0)}var
|
|
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
|
|
85
|
+
`)},i=e=>[`' ${F_}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
|
|
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
|
+
`),a=W_(e,t).map(e=>` <string>${n(e)}</string>`).join(`
|
|
88
|
+
`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<!-- ${P_}: launch daemon -->`,`<plist version="1.0">`,`<dict>`,` <key>Label</key><string>${n(j_)}</string>`,` <key>ProgramArguments</key>`,` <array>`,a,` </array>`,` <key>EnvironmentVariables</key>`,` <dict>`,i,` </dict>`,` <key>RunAtLoad</key><true/>`,` <key>StandardOutPath</key><string>${n(r)}</string>`,` <key>StandardErrorPath</key><string>${n(r)}</string>`,`</dict>`,`</plist>`,``].join(`
|
|
89
|
+
`)},i=R_();C(i,r(e,t),`utf-8`),await V_(`launchctl`,[`unload`,i]);let a=await V_(`launchctl`,[`load`,i]);if(a!==0)throw Error(`launchctl load 失败(退出码 ${String(a)})。请手动执行: launchctl load "${i}"`);return i}async function Y_(e,t){let n=(e,t)=>{let n=Object.entries(t.env).map(([e,t])=>`Environment="${e}=${t.replace(/"/g,`\\"`)}"`).join(`
|
|
90
|
+
`),r=W_(e,t).map(e=>`"${e.replace(/"/g,`\\"`)}"`).join(` `);return[`[Unit]`,`Description=ezllm autostart (${P_}, launch daemon)`,`After=default.target`,``,`[Service]`,`Type=simple`,`ExecStart=${r}`,n,`Restart=on-failure`,`RestartSec=3`,``,`[Install]`,`WantedBy=default.target`,``].join(`
|
|
91
|
+
`)},r=z_();m(s(r),{recursive:!0}),C(r,n(e,t),`utf-8`);let i=await V_(`systemctl`,[`--user`,`daemon-reload`]);if(i!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(i)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${r}`);let a=await V_(`systemctl`,[`--user`,`enable`,M_]);if(a!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(a)})。请手动执行: systemctl --user enable ${M_}`);return r}async function X_(e){let t=L_(),n=p(t);return y(t,{force:!0}),y(c(e,A_),{force:!0}),n}async function Z_(){let e=R_();return p(e)?(await V_(`launchctl`,[`unload`,e]),y(e,{force:!0}),!0):!1}async function Q_(){let e=z_();return p(e)?(await V_(`systemctl`,[`--user`,`disable`,M_]),y(e,{force:!0}),await V_(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function $_(e,t){if(e.includes(t))return!0;let n=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`);return e.includes(n)?!0:e.includes(t.replace(/"/g,`\\"`))}function ev(e,t){let n=()=>U_(te())?.itemPath()??null,r=e=>{let t=g(e);return t.length>=2&&t[0]===255&&t[1]===254?t.toString(`utf16le`).slice(1):t.toString(`utf-8`)},i=n(),a=!1;if(i&&p(i))try{let e=r(i);if(a=e.includes(P_),a&&t!==void 0){let n=[t.nodePath,t.entryJs,...t.args??[]];if(te()===`win32`){let r=c(t.appDir,A_),i=p(r)?g(r,`utf-8`):``;a=e.includes(r)&&i.includes(P_)&&n.every(e=>$_(i,e))}else a=n.every(t=>$_(e,t))}}catch{}return{platform:te(),enabled:a,itemPath:i,optOut:p(I_(e))}}var tv=`当前为源码运行模式,更新功能不可用(仅通过 npx ezllm install 装配的实例支持)`,nv=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 npx ezllm update`,rv=9e5;function iv(e){let t=()=>{if(!Rt())return!1;if(p(c(Pt(),`dist`,`cli.js`)))return!0;let e=s(Lt);return o(e)===`node_modules`||o(s(e))===`node_modules`},n=()=>t()?Ap()?null:nv:tv,r=new j;return r.get(`/autostart`,t=>t.json({ok:!0,...ev(e.appDir)})),r.get(`/update`,e=>{let n=Ut(),r=n.pending??null,i=r!==null&&Date.now()-r.startedAt<rv;return e.json({ok:!0,enabled:!0,lastCheck:n.lastCheck??null,lastApply:n.lastApply??null,pendingUpdate:i&&r?r.toVersion:null,supported:t()&&Ap(),updating:i})}),r.post(`/update/check`,async e=>{let t=n();if(t)return e.json({ok:!1,error:t},400);let r=await jp(`update.check`);return e.json({ok:!0,...r})}),r.post(`/update/apply`,async e=>{let t=n();if(t)return e.json({ok:!1,error:t},400);let r=await jp(`update.apply`);return e.json({ok:!0,fromVersion:r.currentVersion,toVersion:r.latestVersion,hasUpdate:r.hasUpdate,updated:r.updated,...r.updated?{restarting:!0}:{},note:r.updated?`已开始更新 ${r.currentVersion} → ${r.latestVersion},服务将在安装完成后自动重启`:`已是最新版本 ${r.currentVersion}`})}),r}var av=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function ov(e){let t=(e,t)=>{let n={};return t===null?typeof e.name==`string`&&(n.name=e.name):n.name=t,typeof e.exec==`string`&&(n.exec=e.exec),typeof e.cwd==`string`&&(n.cwd=e.cwd),typeof e.autostart==`boolean`&&(n.autostart=e.autostart),typeof e.start==`boolean`&&(n.start=e.start),Array.isArray(e.args)&&(n.args=e.args.map(e=>String(e))),n},n=()=>Ap()?null:Response.json({ok:!1,error:av},{status:400}),r=new j;return r.onError(wp),r.get(`/`,async e=>{let t=n();if(t)return t;let r=await jp(`svc.list`);return e.json({ok:!0,...r})}),r.post(`/`,async e=>{let r=n();if(r)return r;let i=await _p(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await jp(`svc.create`,t(i,null));return e.json({ok:!0,...a})}),r.put(`/:name`,async e=>{let r=n();if(r)return r;let i=await _p(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await jp(`svc.update`,t(i,e.req.param(`name`)));return e.json({ok:!0,...a})}),r.delete(`/:name`,async e=>{let t=n();if(t)return t;let r=await jp(`svc.remove`,{name:e.req.param(`name`)});return e.json({ok:!0,...r})}),r.post(`/:name/start`,async e=>{let t=n();if(t)return t;let r=await jp(`child.start`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r.post(`/:name/stop`,async e=>{let t=n();if(t)return t;let r=await jp(`child.stop`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r.post(`/:name/restart`,async e=>{let t=n();if(t)return t;let r=await jp(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r}var sv=`服务未由 ezllm 主进程托管(源码运行模式),插件服务不可用;请用 ezllm 启动服务`;function cv(e){let t=()=>Ap()?null:Response.json({ok:!1,error:sv},{status:400}),n=new j;return n.onError(wp),n.get(`/`,async e=>{let n=t();if(n)return n;let r=await jp(`plugin.status`);return e.json({ok:!0,available:!0,...r})}),n.post(`/restart`,async e=>{let n=t();if(n)return n;let r=await jp(`plugin.restart`);return e.json({ok:!0,available:!0,...r})}),n}function lv(e){let t=`${e}.ellm-bak`;return!p(t)&&(p(e)&&f(e,t),!0)}function uv(e){let t=`${e}.ellm-bak`;return p(t)?(f(t,e),y(t,{force:!0}),!0):!1}function dv(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var fv=c(w(),`.claude`,`settings.json`);function pv(){if(!p(fv))return null;try{return JSON.parse(g(fv,`utf-8`))}catch(e){throw Error(`${fv} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function mv(e){let t=pv();return t?dv(t?.env?.ANTHROPIC_BASE_URL,e):!1}function hv(e){m(s(fv),{recursive:!0});let t=pv()??{};lv(fv),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,C(fv,JSON.stringify(t,null,2)+`
|
|
92
|
+
`,`utf-8`)}function gv(e){if(uv(fv))return!0;let t=pv();return!t||!dv(t?.env?.ANTHROPIC_BASE_URL,e)?!1:(delete t.env.ANTHROPIC_BASE_URL,delete t.env.ANTHROPIC_AUTH_TOKEN,t.env&&Object.keys(t.env).length===0&&delete t.env,C(fv,JSON.stringify(t,null,2)+`
|
|
93
|
+
`,`utf-8`),!0)}var _v=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,vv=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(_v);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};function yv(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function bv(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
94
94
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
95
|
-
`))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
96
|
-
`,t);return e.charCodeAt(n-1)===13&&n--,n}function
|
|
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
|
|
98
|
-
`),i=
|
|
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
|
|
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
|
+
`,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)=>_e(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
|
+
`),i=Hv(n)??``,o=Uv(),c=o.test(i)?i.replace(o,r):i&&!i.endsWith(`
|
|
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(`
|
|
101
101
|
`).replace(/\n{3,}$/,`
|
|
102
102
|
|
|
103
|
-
`)}function
|
|
104
|
-
`),n=`model_provider = "${
|
|
103
|
+
`)}function Xv(e){let t=e=>{let t=e.split(`
|
|
104
|
+
`),n=`model_provider = "${Rv}"`,r=!1,i=t.map(e=>!r&&/^\s*model_provider\s*=/.test(e)&&!e.trim().startsWith(`#`)?(r=!0,n):e);if(r)return i.join(`
|
|
105
105
|
`);let a=i.findIndex(e=>/^\s*\[/.test(e));return a===-1?[...i,n].join(`
|
|
106
106
|
`):(i.splice(a,0,n,``),i.join(`
|
|
107
|
-
`))};m(s(
|
|
107
|
+
`))};m(s(zv),{recursive:!0});let n=Hv(zv);if(n!==null)try{Lv(n)}catch(e){throw Error(`${zv} 不是合法 TOML,拒绝修改(请先手工修复): ${e.message}`)}let r=n??``;lv(zv),r=Yv(r),r=t(r);let i=[`[model_providers.${Rv}]`,`name = "ezllm gateway"`,`base_url = "${e.gatewayBase}/v1"`,`wire_api = "chat"`,`env_key = "ELLM_PROXY_API_KEY"`].join(`
|
|
108
108
|
`);return r=r.replace(/\s*$/,``)+`
|
|
109
109
|
|
|
110
110
|
`+i+`
|
|
111
|
-
`,
|
|
111
|
+
`,qv(r,!0),C(zv,r,`utf-8`),e.apiKey?Wv(`ELLM_PROXY_API_KEY`,e.apiKey):!1}function Zv(){let e=uv(zv),t=Gv(`ELLM_PROXY_API_KEY`);if(delete process.env.ELLM_PROXY_API_KEY,e)return!0;let n=Hv(zv);if(!n||!Kv(n))return t;let r=Yv(n);return r=r.split(`
|
|
112
112
|
`).filter(e=>!/^\s*model_provider\s*=\s*["']?ellm-proxy["']?\s*$/.test(e)).join(`
|
|
113
|
-
`),
|
|
114
|
-
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),
|
|
113
|
+
`),qv(r,!1),C(zv,r,`utf-8`),!0}var Q=E((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),Qv=E((e=>{var t=Q(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),$v=E((e=>{var t=Q(),n=Qv(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
114
|
+
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),ey=E((e=>{var t=Q(),n=Qv();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),ty=E((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),ny=E((e=>{var t=Q();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),ry=E((e=>{var t=ty(),n=Q(),r=ny();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),iy=E((e=>{var t=ey(),n=Qv(),r=Q(),i=ry(),a=ny(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),$=E((e=>{var t=Q(),n=ry(),r=ny(),i=e=>!e||typeof e!=`function`&&typeof e!=`object`,a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ay=E((e=>{var t=iy(),n=Q(),r=$(),i=`tag:yaml.org,2002:`;function a(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function o(e,o,s){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=s.schema[n.MAP].createNode?.(s.schema,null,s);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:c,onAnchor:l,onTagObj:u,schema:d,sourceObjects:f}=s,p;if(c&&e&&typeof e==`object`){if(p=f.get(e),p)return p.anchor??(p.anchor=l(e)),new t.Alias(p.anchor);p={anchor:null,node:null},f.set(e,p)}o?.startsWith(`!!`)&&(o=i+o.slice(2));let m=a(e,o,d.tags);if(!m){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return p&&(p.node=t),t}m=e instanceof Map?d[n.MAP]:Symbol.iterator in Object(e)?d[n.SEQ]:d[n.MAP]}u&&(u(m),delete s.onTagObj);let h=m?.createNode?m.createNode(s.schema,e,s):typeof m?.nodeClass?.from==`function`?m.nodeClass.from(s.schema,e,s):new r.Scalar(e);return o?h.tag=o:m.default||(h.tag=m.tag),p&&(p.node=h),h}e.createNode=o})),oy=E((e=>{var t=ay(),n=Q(),r=ry();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),sy=E((e=>{var t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
115
115
|
`)?n(r,t):r.includes(`
|
|
116
116
|
`)?`
|
|
117
|
-
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),
|
|
117
|
+
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),cy=E((e=>{var t=`flow`,n=`block`,r=`quoted`;function i(e,t,i=`flow`,{indentAtStart:o,lineWidth:s=80,minContentWidth:c=20,onFold:l,onOverflow:u}={}){if(!s||s<0)return e;s<c&&(c=0);let d=Math.max(1+c,1+s-t.length);if(e.length<=d)return e;let f=[],p={},m=s-t.length;typeof o==`number`&&(o>s-Math.max(2,c)?f.push(0):m=s-o);let h,g,_=!1,v=-1,y=-1,b=-1;i===n&&(v=a(e,v,t.length),v!==-1&&(m=v+d));for(let o;o=e[v+=1];){if(i===r&&o===`\\`){switch(y=v,e[v+1]){case`x`:v+=3;break;case`u`:v+=5;break;case`U`:v+=9;break;default:v+=1}b=v}if(o===`
|
|
118
118
|
`)i===n&&(v=a(e,v,t.length)),m=v+t.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
|
|
119
119
|
`&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
|
|
120
120
|
`&&t!==` `&&(h=v)}if(v>=m){if(h)f.push(h),m=h+d,h=void 0;else if(i===r){for(;g===` `||g===` `;)g=o,o=e[v+=1],_=!0;let t=v>b+1?v-2:y-1;if(p[t])return e;f.push(t),p[t]=!0,m=t+d,h=void 0}else _=!0}}g=o}if(_&&u&&u(),f.length===0)return e;l&&l();let x=e.slice(0,f[0]);for(let n=0;n<f.length;++n){let a=f[n],o=f[n+1]||e.length;a===0?x=`\n${t}${e.slice(0,o)}`:(i===r&&p[a]&&(x+=`${e[a]}\\`),x+=`\n${t}${e.slice(a+1,o)}`)}return x}function a(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
121
|
-
`);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i})),
|
|
121
|
+
`);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i})),ly=E((e=>{var t=$(),n=cy(),r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),i=e=>/^(%|---|\.\.\.)/m.test(e);function a(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
|
|
122
122
|
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function o(e,t){let a=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return a;let{implicitKey:o}=t,s=t.options.doubleQuotedMinMultiLineLength,c=t.indent||(i(e)?` `:``),l=``,u=0;for(let e=0,t=a[e];t;t=a[++e])if(t===` `&&a[e+1]===`\\`&&a[e+2]===`n`&&(l+=a.slice(u,e)+`\\ `,e+=1,u=e,t=`\\`),t===`\\`)switch(a[e+1]){case`u`:{l+=a.slice(u,e);let t=a.substr(e+2,4);switch(t){case`0000`:l+=`\\0`;break;case`0007`:l+=`\\a`;break;case`000b`:l+=`\\v`;break;case`001b`:l+=`\\e`;break;case`0085`:l+=`\\N`;break;case`00a0`:l+=`\\_`;break;case`2028`:l+=`\\L`;break;case`2029`:l+=`\\P`;break;default:t.substr(0,2)===`00`?l+=`\\x`+t.substr(2):l+=a.substr(e,6)}e+=5,u=e+1}break;case`n`:if(o||a[e+2]===`"`||a.length<s)e+=1;else{for(l+=a.slice(u,e)+`
|
|
123
123
|
|
|
124
124
|
`;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
|
|
@@ -132,33 +132,33 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
|
|
|
132
132
|
`&&e!==` `&&e!==` `)break}let b=s.substring(y),x=b.indexOf(`
|
|
133
133
|
`);x===-1?v=`-`:s===b||x!==b.length-1?(v=`+`,f&&f()):v=``,b&&=(s=s.slice(0,-b.length),b[b.length-1]===`
|
|
134
134
|
`&&(b=b.slice(0,-1)),b.replace(l,`$&${g}`));let S=!1,C,w=-1;for(C=0;C<s.length;++C){let e=s[C];if(e===` `)S=!0;else if(e===`
|
|
135
|
-
`)w=C;else break}let T=s.substring(0,w<C?w+1:C);T&&=(s=s.substring(T.length),T.replace(/\n+/g,`$&${g}`));let
|
|
136
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${g}`),i=!1,a=r(u,!0);p!==`folded`&&o!==t.Scalar.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let c=n.foldFlowLines(`${T}${e}${b}`,g,n.FOLD_BLOCK,a);if(!i)return`>${
|
|
135
|
+
`)w=C;else break}let T=s.substring(0,w<C?w+1:C);T&&=(s=s.substring(T.length),T.replace(/\n+/g,`$&${g}`));let ee=(S?g?`2`:`1`:``)+v;if(e&&(ee+=` `+m(e.replace(/ ?[\r\n]+/g,` `)),d&&d()),!_){let e=s.replace(/\n+/g,`
|
|
136
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${g}`),i=!1,a=r(u,!0);p!==`folded`&&o!==t.Scalar.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let c=n.foldFlowLines(`${T}${e}${b}`,g,n.FOLD_BLOCK,a);if(!i)return`>${ee}\n${g}${c}`}return s=s.replace(/\n+/g,`$&${g}`),`|${ee}\n${g}${T}${s}${b}`}function d(e,a,o,s){let{type:l,value:d}=e,{actualString:f,implicitKey:p,indent:m,indentStep:h,inFlow:g}=a;if(p&&d.includes(`
|
|
137
137
|
`)||g&&/[[\]{},]/.test(d))return c(d,a);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return p||g||!d.includes(`
|
|
138
138
|
`)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
|
|
139
|
-
`))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),
|
|
140
|
-
`:``,S){let e=p(S);
|
|
141
|
-
`&&C&&(
|
|
139
|
+
`))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),uy=E((e=>{var t=ey(),n=Q(),r=sy(),i=ly();function a(e,t){let n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function o(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function s(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function c(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let c,l=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>c=e});c??=o(t.doc.schema.tags,l);let u=s(l,c,t);u.length>0&&(t.indentAtStart=(t.indentAtStart??0)+u.length+1);let d=typeof c.stringify==`function`?c.stringify(l,t,r,a):n.isScalar(l)?i.stringifyString(l,t,r,a):l.toString(t,r,a);return u?n.isScalar(l)||d[0]===`{`||d[0]===`[`?`${u} ${d}`:`${u}\n${t.indent}${d}`:d}e.createStringifyContext=a,e.stringify=c})),dy=E((e=>{var t=Q(),n=$(),r=uy(),i=sy();function a({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),ee=` `;if(g||x||S){if(ee=x?`
|
|
140
|
+
`:``,S){let e=p(S);ee+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?ee===`
|
|
141
|
+
`&&C&&(ee=`
|
|
142
142
|
|
|
143
|
-
`):
|
|
144
|
-
`),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(
|
|
145
|
-
`)&&(
|
|
143
|
+
`):ee+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
|
|
144
|
+
`),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(ee=`\n${o.indent}`)}}else(T===``||T[0]===`
|
|
145
|
+
`)&&(ee=``);return b+=ee+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),fy=E((e=>{var t=we(`process`);function n(e,...t){e===`debug`&&console.log(...t)}function r(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=n,e.warn=r})),py=E((e=>{var t=Q(),n=$(),r=`<<`,i={identify:e=>e===r||typeof e==`symbol`&&e.description===r,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(r)),{addToJSMap:o}),stringify:()=>r},a=(e,r)=>(i.identify(r)||t.isScalar(r)&&(!r.type||r.type===n.Scalar.PLAIN)&&i.identify(r.value))&&e?.doc.schema.tags.some(e=>e.tag===i.tag&&e.default);function o(e,n,r){let i=c(e,r);if(t.isSeq(i))for(let t of i.items)s(e,n,t);else if(Array.isArray(i))for(let t of i)s(e,n,t);else s(e,n,i)}function s(e,n,r){let i=c(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function c(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=o,e.isMergeKey=a,e.merge=i})),my=E((e=>{var t=fy(),n=py(),r=uy(),i=Q(),a=ny();function o(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=s(r,n,e),c=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:c,writable:!0,enumerable:!0,configurable:!0}):t[i]=c}}return t}function s(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=o})),hy=E((e=>{var t=ay(),n=dy(),r=my(),i=Q();function a(e,n,r){return new o(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var o=class e{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return i.isNode(n)&&(n=n.clone(t)),i.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=o,e.createPair=a})),gy=E((e=>{var t=Q(),n=uy(),r=sy();function i(e,t,n){return(t.inFlow??e.flow?o:a)(e,t,n)}function a({comment:e,items:i},a,{blockItemPrefix:o,flowChars:c,itemIndent:l,onChompKeep:u,onComment:d}){let{indent:f,options:{commentString:p}}=a,m=Object.assign({},a,{indent:l,type:null}),h=!1,g=[];for(let e=0;e<i.length;++e){let c=i[e],u=null;if(t.isNode(c))!h&&c.spaceBefore&&g.push(``),s(a,g,c.commentBefore,h),c.comment&&(u=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(!h&&e.spaceBefore&&g.push(``),s(a,g,e.commentBefore,h))}h=!1;let d=n.stringify(c,m,()=>u=null,()=>h=!0);u&&(d+=r.lineComment(d,l,p(u))),h&&u&&(h=!1),g.push(o+d)}let _;if(g.length===0)_=c.start+c.end;else{_=g[0];for(let e=1;e<g.length;++e){let t=g[e];_+=t?`\n${f}${t}`:`
|
|
146
146
|
`}}return e?(_+=`
|
|
147
147
|
`+r.indentComment(p(e),f),d&&d()):h&&u&&u(),_}function o({items:e},i,{flowChars:a,itemIndent:o}){let{indent:c,indentStep:l,flowCollectionPadding:u,options:{commentString:d}}=i;o+=l;let f=Object.assign({},i,{indent:o,inFlow:!0,type:null}),p=!1,m=0,h=[];for(let a=0;a<e.length;++a){let c=e[a],l=null;if(t.isNode(c))c.spaceBefore&&h.push(``),s(i,h,c.commentBefore,!1),c.comment&&(l=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(e.spaceBefore&&h.push(``),s(i,h,e.commentBefore,!1),e.comment&&(p=!0));let n=t.isNode(c.value)?c.value:null;n?(n.comment&&(l=n.comment),n.commentBefore&&(p=!0)):c.value==null&&e?.comment&&(l=e.comment)}l&&(p=!0);let u=n.stringify(c,f,()=>l=null);p||=h.length>m||u.includes(`
|
|
148
148
|
`),a<e.length-1?u+=`,`:i.options.trailingComma&&(i.options.lineWidth>0&&(p||=h.reduce((e,t)=>e+t.length+2,2)+(u.length+2)>i.options.lineWidth),p&&(u+=`,`)),l&&(u+=r.lineComment(u,o,d(l))),h.push(u),m=h.length}let{start:g,end:_}=a;if(h.length===0)return g+_;if(!p){let e=h.reduce((e,t)=>e+t.length+2,2);p=i.options.lineWidth>0&&e>i.options.lineWidth}if(p){let e=g;for(let t of h)e+=t?`\n${l}${c}${t}`:`
|
|
149
|
-
`;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),
|
|
150
|
-
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),gv=D((e=>{var t=Q(),n=tv(),r=$(),i=av();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}var s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),_v=D((e=>{var t=Q(),n=H_(),r=rv(),i=av(),a=gv(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;var s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),vv=D((e=>{var t=$();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),yv=D((e=>{var t=$(),n=uv(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),bv=D((e=>{var t=uv(),n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}var a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),xv=D((e=>{var t=Q(),n=tv(),r=rv(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;var a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Sv=D((e=>{var t=uv();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),Cv=D((e=>{var t=iv(),n=cv(),r=ov(),i=sv(),a=hv(),o=vv(),s=yv(),c=bv(),l=$_(),u=_v(),d=gv(),f=xv(),p=Sv();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),wv=D((e=>{var t=iv(),n=cv(),r=ov(),i=sv(),a=lv(),o=dv(),s=fv(),c=pv(),l=mv(),u=hv(),d=$_(),f=_v(),p=gv(),m=Cv(),h=xv(),g=Sv(),_=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),Tv=D((e=>{var t=Q(),n=iv(),r=ov(),i=sv(),a=wv(),o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),Ev=D((e=>{var t=Q(),n=X_(),r=q_();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
|
|
149
|
+
`;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),_y=E((e=>{var t=gy(),n=my(),r=oy(),i=Q(),a=hy(),o=$();function s(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}e.YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),s=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)s(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))s(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=s(this.items,n.key),c=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(c){let e=this.items.findIndex(e=>c(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=s(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=s(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!s(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}},e.findPair=s})),vy=E((e=>{var t=Q(),n=_y();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),yy=E((e=>{var t=ay(),n=gy(),r=oy(),i=Q(),a=$(),o=ny(),s=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=c(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=c(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=c(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=c(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function c(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=s})),by=E((e=>{var t=Q(),n=yy();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),xy=E((e=>{var t=ly();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),Sy=E((e=>{var t=$(),n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),Cy=E((e=>{var t=$(),n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),wy=E((e=>{function t({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=t})),Ty=E((e=>{var t=$(),n=wy(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Ey=E((e=>{var t=wy(),n=e=>typeof e==`bigint`||Number.isInteger(e),r=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function i(e,r,i){let{value:a}=e;return n(a)&&a>=0?i+a.toString(r):t.stringifyNumber(e)}e.int={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)},e.intOct={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>i(e,8,`0o`)}})),Dy=E((e=>{var t=vy(),n=Sy(),r=by(),i=xy(),a=Cy(),o=Ty(),s=Ey();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),Oy=E((e=>{var t=$(),n=vy(),r=by();function i(e){return typeof e==`bigint`||Number.isInteger(e)}var a=({value:e})=>JSON.stringify(e),o=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:a},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:a},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:a},{identify:i,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>i(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:a}];e.schema=[n.map,r.seq].concat(o,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),ky=E((e=>{var t=we(`buffer`),n=$(),r=ly();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
|
|
150
|
+
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),Ay=E((e=>{var t=Q(),n=hy(),r=$(),i=yy();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}var s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),jy=E((e=>{var t=Q(),n=ny(),r=_y(),i=yy(),a=Ay(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;var s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),My=E((e=>{var t=$();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),Ny=E((e=>{var t=$(),n=wy(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Py=E((e=>{var t=wy(),n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}var a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),Fy=E((e=>{var t=Q(),n=hy(),r=_y(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;var a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Iy=E((e=>{var t=wy();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),Ly=E((e=>{var t=vy(),n=Sy(),r=by(),i=xy(),a=ky(),o=My(),s=Ny(),c=Py(),l=py(),u=jy(),d=Ay(),f=Fy(),p=Iy();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Ry=E((e=>{var t=vy(),n=Sy(),r=by(),i=xy(),a=Cy(),o=Ty(),s=Ey(),c=Dy(),l=Oy(),u=ky(),d=py(),f=jy(),p=Ay(),m=Ly(),h=Fy(),g=Iy(),_=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),zy=E((e=>{var t=Q(),n=vy(),r=by(),i=xy(),a=Ry(),o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),By=E((e=>{var t=Q(),n=uy(),r=sy();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
|
|
151
151
|
`)?(a.push(`...`),a.push(r.indentComment(t,``))):a.push(`... ${t}`)}else a.push(`...`)}else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,``)),t&&((!l||u)&&a[a.length-1]!==``&&a.push(``),a.push(r.indentComment(c(t),``)))}return a.join(`
|
|
152
152
|
`)+`
|
|
153
|
-
`}e.stringifyDocument=i})),
|
|
154
|
-
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),
|
|
155
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),
|
|
153
|
+
`}e.stringifyDocument=i})),Vy=E((e=>{var t=iy(),n=oy(),r=Q(),i=hy(),a=ny(),o=zy(),s=By(),c=ey(),l=ty(),u=ay(),d=$v(),f=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let t=Object.create(e.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=r.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){p(this.contents)&&this.contents.add(e)}addIn(e,t){p(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return p(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):p(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):p(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):p(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function p(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),Hy=E((e=>{var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},r=class extends t{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
|
|
154
|
+
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),Uy=E((e=>{function t(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=t})),Wy=E((e=>{function t(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
|
|
155
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),Gy=E((e=>{var t=Wy();function n(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=n})),Ky=E((e=>{var t=Q();function n(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=n})),qy=E((e=>{var t=hy(),n=_y(),r=Uy(),i=Wy(),a=Gy(),o=Ky(),s=`All mapping items must start at the same column`;function c({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
|
|
156
156
|
`+y.comment:p.comment=y.comment);continue}(y.newlineAfterProp||i.containsNewline(g))&&d(g??f[f.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else y.found?.indent!==u.indent&&d(m,`BAD_INDENT`,s);l.atKey=!0;let x=y.end,S=g?e(l,g,y,d):c(l,x,f,null,y,d);l.schema.compat&&a.flowIndentCheck(u.indent,g,d),l.atKey=!1,o.mapIncludes(l,p.items,S)&&d(x,`DUPLICATE_KEY`,`Map keys must be unique`);let C=r.resolveProps(_??[],{indicator:`map-value-ind`,next:v,offset:S.range[2],onError:d,parentIndent:u.indent,startOnNewline:!g||g.type===`block-scalar`});if(m=C.end,C.found){b&&(v?.type===`block-map`&&!C.hasNewline&&d(m,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),l.options.strict&&y.start<C.found.offset-1024&&d(S.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let r=v?e(l,v,C,d):c(l,m,_,null,C,d);l.schema.compat&&a.flowIndentCheck(u.indent,v,d),m=r.range[2];let i=new t.Pair(S,r);l.options.keepSourceTokens&&(i.srcToken=n),p.items.push(i)}else{b&&d(S.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),C.comment&&(S.comment?S.comment+=`
|
|
157
|
-
`+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),
|
|
157
|
+
`+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),Jy=E((e=>{var t=yy(),n=Uy(),r=Gy();function i({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=i})),Yy=E((e=>{function t(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=t})),Xy=E((e=>{var t=Q(),n=hy(),r=_y(),i=yy(),a=Yy(),o=Uy(),s=Wy(),c=Ky(),l=`Block collections are not allowed within flow collections`,u=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function d({composeNode:e,composeEmptyNode:d},f,p,m,h){let g=p.start.source===`{`,_=g?`flow map`:`flow sequence`,v=new((h?.nodeClass)??(g?r.YAMLMap:i.YAMLSeq))(f.schema);v.flow=!0;let y=f.atRoot;y&&(f.atRoot=!1),f.atKey&&=!1;let b=p.offset+p.start.source.length;for(let i=0;i<p.items.length;++i){let a=p.items[i],{start:h,key:y,sep:x,value:S}=a,C=o.resolveProps(h,{flow:_,indicator:`explicit-key-ind`,next:y??x?.[0],offset:b,onError:m,parentIndent:p.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!x&&!S){i===0&&C.comma?m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`):i<p.items.length-1&&m(C.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${_}`),C.comment&&(v.comment?v.comment+=`
|
|
158
158
|
`+C.comment:v.comment=C.comment),b=C.end;continue}!g&&f.options.strict&&s.containsNewline(y)&&m(y,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(i===0)C.comma&&m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`);else if(C.comma||m(C.start,`MISSING_CHAR`,`Missing , between ${_} items`),C.comment){let e=``;loop:for(let t of h)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let n=v.items[v.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+=`
|
|
159
159
|
`+e:n.comment=e,C.comment=C.comment.substring(e.length+1)}}if(!g&&!x&&!C.found){let t=S?e(f,S,C,m):d(f,C.end,x,null,C,m);v.items.push(t),b=t.range[2],u(S)&&m(t.range,`BLOCK_IN_FLOW`,l)}else{f.atKey=!0;let t=C.end,i=y?e(f,y,C,m):d(f,t,h,null,C,m);u(y)&&m(i.range,`BLOCK_IN_FLOW`,l),f.atKey=!1;let s=o.resolveProps(x??[],{flow:_,indicator:`map-value-ind`,next:S,offset:i.range[2],onError:m,parentIndent:p.indent,startOnNewline:!1});if(s.found){if(!g&&!C.found&&f.options.strict){if(x)for(let e of x){if(e===s.found)break;if(e.type===`newline`){m(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}C.start<s.found.offset-1024&&m(s.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else S&&(`source`in S&&S.source?.[0]===`:`?m(S,`MISSING_CHAR`,`Missing space after : in ${_}`):m(s.start,`MISSING_CHAR`,`Missing , or : between ${_} items`));let w=S?e(f,S,s,m):s.found?d(f,s.end,x,null,s,m):null;w?u(S)&&m(w.range,`BLOCK_IN_FLOW`,l):s.comment&&(i.comment?i.comment+=`
|
|
160
160
|
`+s.comment:i.comment=s.comment);let T=new n.Pair(i,w);if(f.options.keepSourceTokens&&(T.srcToken=a),g){let e=v;c.mapIncludes(f,e.items,i)&&m(t,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(T)}else{let e=new r.YAMLMap(f.schema);e.flow=!0,e.items.push(T);let t=(w??i).range;e.range=[i.range[0],t[1],t[2]],v.items.push(e)}b=w?w.range[2]:s.end}}let x=g?`}`:`]`,[S,...C]=p.end,w=b;if(S?.source===x)w=S.offset+S.source.length;else{let e=_[0].toUpperCase()+_.substring(1),t=y?`${e} must end with a ${x}`:`${e} in block collection must be sufficiently indented and end with a ${x}`;m(b,y?`MISSING_CHAR`:`BAD_INDENT`,t),S&&S.source.length!==1&&C.unshift(S)}if(C.length>0){let e=a.resolveEnd(C,w,f.options.strict,m);e.comment&&(v.comment?v.comment+=`
|
|
161
|
-
`+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),
|
|
161
|
+
`+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),Zy=E((e=>{var t=Q(),n=$(),r=_y(),i=yy(),a=qy(),o=Jy(),s=Xy();function c(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function l(e,a,o,s,l){let u=s.tag,d=u?a.directives.tagName(u.source,e=>l(u,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&u?e.offset>u.offset?e:u:e??u;n&&(!t||t.offset<n.offset)&&l(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let f=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!u||!d||d===`!`||d===r.YAMLMap.tagName&&f===`map`||d===i.YAMLSeq.tagName&&f===`seq`)return c(e,a,o,l,d);let p=a.schema.tags.find(e=>e.tag===d&&e.collection===f);if(!p){let t=a.schema.knownTags[d];if(t?.collection===f)a.schema.tags.push(Object.assign({},t,{default:!1})),p=t;else return t?l(u,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${f} collection, but expects ${t.collection??`scalar`}`,!0):l(u,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${d}`,!0),c(e,a,o,l,d)}let m=c(e,a,o,l,d,p),h=p.resolve?.(m,e=>l(u,`TAG_RESOLVE_FAILED`,e),a.options)??m,g=t.isNode(h)?h:new n.Scalar(h);return g.range=m.range,g.tag=d,p?.format&&(g.format=p.format),g}e.composeCollection=l})),Qy=E((e=>{var t=$();function n(e,n,a){let o=n.offset,s=r(n,e.options.strict,a);if(!s)return{value:``,type:null,comment:``,range:[o,o,o]};let c=s.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,l=n.source?i(n.source):[],u=l.length;for(let e=l.length-1;e>=0;--e){let t=l[e][1];if(t===``||t===`\r`)u=e;else break}if(u===0){let e=s.chomp===`+`&&l.length>0?`
|
|
162
162
|
`.repeat(Math.max(1,l.length-1)):``,t=o+s.length;return n.source&&(t+=n.source.length),{value:e,type:c,comment:s.comment,range:[o,t,t]}}let d=n.indent+s.indent,f=n.offset+s.length,p=0;for(let t=0;t<u;++t){let[n,r]=l[t];if(r===``||r===`\r`)s.indent===0&&n.length>d&&(d=n.length);else{n.length<d&&a(f+n.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),s.indent===0&&(d=n.length),p=t,d===0&&!e.atRoot&&a(f,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}f+=n.length+r.length+1}for(let e=l.length-1;e>=u;--e)l[e][0].length>d&&(u=e+1);let m=``,h=``,g=!1;for(let e=0;e<p;++e)m+=l[e][0].slice(d)+`
|
|
163
163
|
`;for(let e=p;e<u;++e){let[n,r]=l[e];f+=n.length+r.length+1;let i=r[r.length-1]===`\r`;if(i&&(r=r.slice(0,-1)),r&&n.length<d){let e=`Block scalar lines must not be less indented than their ${s.indent?`explicit indentation indicator`:`first line`}`;a(f-r.length-(i?2:1),`BAD_INDENT`,e),n=``}c===t.Scalar.BLOCK_LITERAL?(m+=h+n.slice(d)+r,h=`
|
|
164
164
|
`):n.length>d||r[0]===` `?(h===` `?h=`
|
|
@@ -173,7 +173,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
173
173
|
`+l[e][0].slice(d);m[m.length-1]!==`
|
|
174
174
|
`&&(m+=`
|
|
175
175
|
`);break;default:m+=`
|
|
176
|
-
`}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n}))
|
|
176
|
+
`}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),$y=E((e=>{var t=$(),n=Yy();function r(e,r,o){let{offset:c,type:l,source:u,end:d}=e,f,p,m=(e,t,n)=>o(c+e,t,n);switch(l){case`scalar`:f=t.Scalar.PLAIN,p=i(u,m);break;case`single-quoted-scalar`:f=t.Scalar.QUOTE_SINGLE,p=a(u,m);break;case`double-quoted-scalar`:f=t.Scalar.QUOTE_DOUBLE,p=s(u,m);break;default:return o(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${l}`),{value:``,type:null,comment:``,range:[c,c+u.length,c+u.length]}}let h=c+u.length,g=n.resolveEnd(d,h,r,o);return{value:p,type:f,comment:g.comment,range:[c,h,g.offset]}}function i(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),o(e)}function a(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),o(e.slice(1,-1)).replace(/''/g,`'`)}function o(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
177
177
|
`,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
178
178
|
`,`sy`)}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],a=` `,o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)r[1]===``?a===`
|
|
179
179
|
`?i+=a:a=`
|
|
@@ -188,10 +188,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
188
188
|
`);)r===`
|
|
189
189
|
`&&(n+=`
|
|
190
190
|
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var l={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
|
|
191
|
-
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),
|
|
191
|
+
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),eb=E((e=>{var t=Q(),n=$(),r=Qy(),i=$y();function a(e,a,c,l){let{value:u,type:d,comment:f,range:p}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,l):i.resolveFlowScalar(a,e.options.strict,l),m=c?e.directives.tagName(c.source,e=>l(c,`TAG_RESOLVE_FAILED`,e)):null,h;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:m?o(e.schema,u,m,c,l):a.type===`scalar`?s(e,u,a,l):e.schema[t.SCALAR];let g;try{let r=h.resolve(u,e=>l(c??a,`TAG_RESOLVE_FAILED`,e),e.options);g=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);l(c??a,`TAG_RESOLVE_FAILED`,t),g=new n.Scalar(u)}return g.range=p,g.source=u,d&&(g.type=d),m&&(g.tag=m),h.format&&(g.format=h.format),f&&(g.comment=f),g}function o(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function s({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=a})),tb=E((e=>{function t(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=t})),nb=E((e=>{var t=iy(),n=Q(),r=Zy(),i=eb(),a=Yy(),o=tb(),s={composeNode:c,composeEmptyNode:l};function c(e,t,a,o){let c=e.atKey,{spaceBefore:d,comment:f,anchor:p,tag:m}=a,h,g=!0;switch(t.type){case`alias`:h=u(e,t,o),(p||m)&&o(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:h=i.composeScalar(e,t,m,o),p&&(h.anchor=p.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{h=r.composeCollection(s,e,t,a,o),p&&(h.anchor=p.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),g=!1}return h??=l(e,t.offset,void 0,null,a,o),p&&h.anchor===``&&o(p,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(h)||typeof h.value!=`string`||h.tag&&h.tag!==`tag:yaml.org,2002:str`)&&o(m??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),d&&(h.spaceBefore=!0),f&&(t.type===`scalar`&&t.source===``?h.comment=f:h.commentBefore=f),e.options.keepSourceTokens&&g&&(h.srcToken=t),h}function l(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function u({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=l,e.composeNode=c})),rb=E((e=>{var t=Vy(),n=nb(),r=Yy(),i=Uy();function a(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=a})),ib=E((e=>{var t=we(`process`),n=$v(),r=Vy(),i=Hy(),a=Q(),o=rb(),s=Yy();function c(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function l(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
|
|
192
192
|
|
|
193
193
|
`:`
|
|
194
|
-
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),
|
|
194
|
+
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),ab=E((e=>{var t=Qy(),n=$y(),r=Hy(),i=ly();function a(e,i=!0,a){if(e){let o=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,o);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,o)}}return null}function o(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:`newline`,offset:-1,indent:r,source:`
|
|
195
195
|
`}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
|
|
196
196
|
`),t=c.substring(0,e),n=c.substring(e+1)+`
|
|
197
197
|
`,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
|
|
@@ -199,9 +199,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
199
199
|
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
200
200
|
`;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];l(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
|
|
201
201
|
`});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function l(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function u(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
|
|
202
|
-
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),
|
|
202
|
+
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),ob=E((e=>{var t=e=>`type`in e?n(e):r(e);function n(e){switch(e.type){case`block-scalar`:{let t=``;for(let r of e.props)t+=n(r);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=r(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=r(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=r(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function r({start:e,key:t,sep:r,value:i}){let a=``;for(let t of e)a+=t.source;if(t&&(a+=n(t)),r)for(let e of r)a+=e.source;return i&&(a+=n(i)),a}e.stringify=t})),sb=E((e=>{var t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function i(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),a(Object.freeze([]),e,t)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},i.parentCollection=(e,t)=>{let n=i.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],a=n?.[r];if(a&&`items`in a)return a;throw Error(`Parent collection not found`)};function a(e,n,i){let o=i(n,e);if(typeof o==`symbol`)return o;for(let s of[`key`,`value`]){let c=n[s];if(c&&`items`in c){for(let n=0;n<c.items.length;++n){let o=a(Object.freeze(e.concat([[s,n]])),c.items[n],i);if(typeof o==`number`)n=o-1;else if(o===t)return t;else o===r&&(c.items.splice(n,1),--n)}typeof o==`function`&&s===`key`&&(o=o(n,e))}}return typeof o==`function`?o(n,e):o}e.visit=i})),cb=E((e=>{var t=ab(),n=ob(),r=sb(),i=``,a=``,o=``,s=``,c=e=>!!e&&`items`in e,l=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);function u(e){switch(e){case i:return`<BOM>`;case a:return`<DOC>`;case o:return`<FLOW_END>`;case s:return`<SCALAR>`;default:return JSON.stringify(e)}}function d(e){switch(e){case i:return`byte-order-mark`;case a:return`doc-mode`;case o:return`flow-error-end`;case s:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
|
|
203
203
|
`:case`\r
|
|
204
|
-
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=a,e.FLOW_END=o,e.SCALAR=s,e.isCollection=c,e.isScalar=l,e.prettyToken=u,e.tokenType=d})),
|
|
204
|
+
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=a,e.FLOW_END=o,e.SCALAR=s,e.isCollection=c,e.isScalar=l,e.prettyToken=u,e.tokenType=d})),lb=E((e=>{var t=cb();function n(e){switch(e){case void 0:case` `:case`
|
|
205
205
|
`:case`\r`:case` `:return!0;default:return!1}}var r=new Set(`0123456789ABCDEFabcdef`),i=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=new Set(`,[]{}`),o=new Set(` ,[]{}
|
|
206
206
|
\r `),s=e=>!e||o.has(e);e.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
|
|
207
207
|
`||t===`\r`&&this.buffer[e+1]===`
|
|
@@ -220,10 +220,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
220
220
|
`,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
|
|
221
221
|
`){let e=this.continueScalar(i+1);if(e===-1)break;i=Math.max(i,e-2)}}else{if(e&&a.has(o))break;r=i}return!o&&!this.atEnd?this.setNext(`plain-scalar`):(yield t.SCALAR,yield*this.pushToIndex(r+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(s),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,r=this.charAt(1);if(n(r)||t&&a.has(r)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!n(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(i.has(t))t=this.buffer[++e];else if(t===`%`&&r.has(this.buffer[e+1])&&r.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
222
222
|
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
223
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),
|
|
223
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),ub=E((e=>{e.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}})),db=E((e=>{var t=we(`process`),n=cb(),r=lb();function i(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function o(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function s(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function c(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function l(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function u(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!i(t.start,`explicit-key-ind`)&&!i(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,o(t.value)?t.value.end?l(t.value.end,t.sep):t.value.end=t.sep:l(t.start,t.sep),delete t.sep)}e.Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&u(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&a(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:a(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=c(s(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
|
|
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())}}}})),Qv=D((e=>{var t=Wv(),n=Dv(),r=Ov(),i=Q_(),a=Q(),o=Xv(),s=Zv();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})),$v=D((e=>{var t=Wv(),n=Dv(),r=Tv(),i=Ov(),a=W_(),o=Q(),s=tv(),c=$(),l=rv(),u=av();Jv();var d=Yv(),f=Xv(),p=Zv(),m=Qv(),h=R_();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}))(),ey=`DEEPSEEK_API_KEY`,ty=1,ny=`ezllm`,ry=()=>process.env.DSH_HOME||c(w(),`.dsh`),iy=()=>c(ry(),`settings.yaml`),ay=()=>c(ry(),`.credentials.yaml`);function oy(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function sy(e,t){let n=(0,$v.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function cy(e){return`${e}/v1`}function ly(e){let t=oy(iy());if(!t)return!1;try{return Zg(sy(t,iy()).toJS()?.[`llm-deepseek`]?.baseURL,cy(e))}catch{return!1}}function uy(e){let t=cy(e.gatewayBase);m(ry(),{recursive:!0});let n=iy(),r=oy(n),i=sy(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);Yg(n),i.setIn([`llm-deepseek`,`baseURL`],t),fy(n,i);let o=ay(),s=e.masterKey||ny,c=oy(o);if(Yg(o),c===null){let e=sy(``,o);e.set(`version`,ty),e.setIn([`refs`,ey],s),fy(o,e);return}let l=sy(c,o),u=l.toJS();if(!(0,$v.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==ty)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(ty)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(ey,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,ey],s)}fy(o,l)}function dy(e,t){let n=iy(),r=ay(),i=!1;if(Xg(n))i=!0;else{let t=oy(n);if(t){let r=sy(t,n);if(Zg(r.toJS()?.[`llm-deepseek`]?.baseURL,cy(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`]),fy(n,r),i=!0}}}if(Xg(r))i=!0;else{let e=oy(r);if(e){let n=sy(e,r),a=n.toJS(),o=e=>e===t||e===ny;a?.version===ty&&o(a?.refs?.[ey])?(n.deleteIn([`refs`,ey]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),fy(r,n),i=!0):a?.version===void 0&&o(a?.[ey])&&(n.deleteIn([ey]),fy(r,n),i=!0)}}return i}function fy(e,t){let n=t.toString(),r=(0,$v.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`)}function py(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new M;return n.get(`/`,t=>{let n=eg(e);return t.json({ok:!0,claudeCode:e_(n),codex:P_(),dsh:ly(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Bg(n);if(r instanceof Response)return r;let i=eg(e);if(r){let e=t(St());return e?(t_({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: ${St()}`},400)}let a=n_(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Bg(n);if(r instanceof Response)return r;let i=eg(e);if(r){let e=t(St()),r=I_({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=L_();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Bg(n);if(r instanceof Response)return r;let i=eg(e),a=t(St());if(r)return uy({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=dy(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var my=[`/api/*(管理台与全部接口)`,`POST|GET /api/fetch(通用 HTTP 转发)`,`GET /api/service/status|processes`,`GET|POST /api/service/autostart`,`GET /api/service/update`,`POST /api/service/update/enabled|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/enabled`,`POST /api/service/plugins/restart`,`POST /api/service/plugins/auto-update`,`GET /api/harness`,`POST /api/harness/claude-code|codex|dsh`,`GET /api/latency/history`,`POST /api/latency/run`].join(`, `);function hy(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,_p),e.route(`/api/setup`,Tp()),e.use(`/api/*`,yp),e.route(`/api/config`,Ep({runtime:n})),e.route(`/api/test`,Mp(n)),e.route(`/api/latency`,Qp(n)),e.route(`/api/usage`,$p()),e.route(`/api/quota`,jh()),e.route(`/api/logs`,zh()),e.route(`/api/status`,Ph(n,i)),e.route(`/api/fetch`,$h()),r&&(e.route(`/api/service`,ng(r)),e.route(`/api/service`,Wg(r)),e.route(`/api/service/managed`,Kg(r)),e.route(`/api/service/plugins`,Jg(r)),e.route(`/api/harness`,py(r)))}var gy=(e,t=_y)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},_y={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`},vy=/^\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,yy={br:`.br`,zstd:`.zst`,gzip:`.gz`},by=Object.keys(yy),xy=(()=>{let[e,t]=ge.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Sy=e=>xy?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()}}),Cy=e=>{let t;try{t=ye(e)}catch{}return t},wy=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Ty=e=>wy(e,decodeURI),Ey=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!ve(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=Ty(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=be(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=Cy(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=be(o,t),s=Cy(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=gy(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||vy.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of by){if(!e.has(t))continue;let n=Cy(o+yy[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=yy[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(Sy(_e(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=_e(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(Sy(a),206)}return await e.onFound?.(o,r),l}},Dy=s(ee(import.meta.url));function Oy(e,t){let n=t??[c(Dy,`web-ui`),l(Dy,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(Dy,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(Dy,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await se(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 Ey({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 ky(e,t,n){let r=new M;return r.use(`/v1/*`,mp()),hy(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),Oy(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${my})`},404)),r.onError(xp),r}var Ay=6e4;function jy(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:Ay,run:async()=>{try{if(Yp(e)===0)return;let r=t();if(!n(r,Vp()??void 0,Date.now()))return;O(`[latency] 自动测试触发`),await Jp(e)}catch(e){A(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var My=6e5,Ny=3e4;function Py(){return{name:`quotaRefresh`,everyMs:My,firstDelayMs:Ny,run:async()=>{try{await Ah()}catch(e){A(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var Fy=6e4,Iy=3e4,Ly=20,Ry=3e4,zy=1024,By=/^[^\u0000-\u001f\u007f]{1,24}$/u,Vy=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),Hy=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
228
|
-
`);async function
|
|
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=
|
|
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(`
|
|
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??ve,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{};
|