ezllm 0.0.49 → 0.0.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/cli.js +22 -23
  2. package/dist/daemon.js +14 -15
  3. package/dist/plugin-host.js +3 -3
  4. package/dist/server.js +59 -58
  5. package/dist/web-ui/assets/{DashboardView-CNsnnzad.css → DashboardView-CrDoH6I9.css} +1 -1
  6. package/dist/web-ui/assets/{DashboardView--YRv0pdB.js → DashboardView-bM9PqDiJ.js} +2 -2
  7. package/dist/web-ui/assets/LayoutView-C_LbQR7r.css +1 -0
  8. package/dist/web-ui/assets/LayoutView-CnpMPvtX.js +1 -0
  9. package/dist/web-ui/assets/{LoginView-DyiYIltJ.js → LoginView-CAMVAyqQ.js} +1 -1
  10. package/dist/web-ui/assets/{LogsView-BlO9eUXV.js → LogsView-HFN9O54e.js} +1 -1
  11. package/dist/web-ui/assets/{ManagedServicesView-DalOm5fB.js → ManagedServicesView-BUUPqj4x.js} +1 -1
  12. package/dist/web-ui/assets/{PluginsView-CMjFrpCT.js → PluginsView-a2QVnO1e.js} +1 -1
  13. package/dist/web-ui/assets/ProvidersView-B9lw6njY.css +1 -0
  14. package/dist/web-ui/assets/{ProvidersView-PlwErhJU.js → ProvidersView-BKyDkKE1.js} +9 -9
  15. package/dist/web-ui/assets/{SettingsView-Dl-dHm8U.js → SettingsView-CNcoc3UN.js} +1 -1
  16. package/dist/web-ui/assets/{SetupView-BblW5D0m.js → SetupView-CWmlLn1Y.js} +1 -1
  17. package/dist/web-ui/assets/{config-DRb_7Qvh.js → config-xKRJvzmN.js} +1 -1
  18. package/dist/web-ui/assets/{index-BviWrBv1.js → index-BPFg2Vwy.js} +1 -1
  19. package/dist/web-ui/assets/{message-BgUNwRuF.js → message-BCzerIAw.js} +1 -1
  20. package/dist/web-ui/assets/{pluginProviders-CMNUPYaO.js → pluginProviders-D3aFIsze.js} +1 -1
  21. package/dist/web-ui/assets/{providers-fXKPM_nK.js → providers-A7mAhs_N.js} +1 -1
  22. package/dist/web-ui/assets/{router-Cpy-sU_q.js → router-B4JKSClW.js} +2 -2
  23. package/dist/web-ui/assets/{useCopyToast-DreqvPDI.js → useCopyToast-DtJhxffK.js} +1 -1
  24. package/dist/web-ui/assets/useManagerApi-Dfa7oUgw.js +1 -0
  25. package/dist/web-ui/assets/{useQuickRangeFilter-D2Epk9Kj.js → useQuickRangeFilter-BrncYqWD.js} +1 -1
  26. package/dist/web-ui/assets/useToast-C4AY3_4n.js +1 -0
  27. package/dist/web-ui/index.html +3 -3
  28. package/package.json +1 -1
  29. package/dist/web-ui/assets/LayoutView-3OpEgcEH.js +0 -1
  30. package/dist/web-ui/assets/LayoutView-cQeiOjLU.css +0 -1
  31. package/dist/web-ui/assets/ProvidersView-DZs-NofB.css +0 -1
  32. package/dist/web-ui/assets/useManagerApi-DBsdJZgc.js +0 -1
  33. package/dist/web-ui/assets/useToast-BpZaUS2s.js +0 -1
package/dist/server.js CHANGED
@@ -16,19 +16,20 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
16
16
  `)}function ha(e){if(typeof e==`string`)return[{role:`assistant`,content:e}];let t=[],n=[],r=[];for(let i of I(e)){let e=F(i);e.type===`text`?t.push(L(e.text)??``):e.type===`tool_use`?n.push({id:L(e.id)??``,type:`function`,function:{name:L(e.name)??``,arguments:JSON.stringify(e.input??{})}}):e.type===`thinking`?r.push({type:`thinking`,thinking:L(e.thinking)??``,signature:L(e.signature)??``}):e.type===`redacted_thinking`&&r.push({type:`redacted_thinking`,data:L(e.data)??``})}let i=ma(r);return[{role:`assistant`,content:t.length>0?t.join(``):null,...n.length>0?{tool_calls:n}:{},...r.length>0?{thinking_blocks:r}:{},...i===``?{}:{reasoning_content:i}}]}var ga=64;function _a(e){if(typeof e!=`string`)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=F(t).session_id;if(typeof n!=`string`)return null;let r=n.slice(0,ga);return r===``?null:r}function va(e,t){let n=new Set([`max_tokens`,`temperature`,`top_p`,`stop_sequences`,`stream`,`metadata`,`tool_choice`,`tools`,`thinking`,`reasoning_effort`,`system`,`context_management`,`output_config`]);t.topK!==`preserve`&&n.add(`top_k`);let r=Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=(e,t,n)=>{n&&(r[e]=t)},a=e.max_tokens;i(`max_tokens`,a,typeof a==`number`);let o=e.temperature;i(`temperature`,o,typeof o==`number`);let s=e.top_p;i(`top_p`,s,typeof s==`number`);let c=e.stop_sequences;i(`stop`,c,Array.isArray(c)&&c.length>0),i(`stream`,!0,e.stream===!0);let l=_a(F(e.metadata).user_id);i(`prompt_cache_key`,l,l!==null);let u=ya(e.tool_choice);i(`tool_choice`,u,u!==null);let d=e.tools;i(`tools`,I(d).map(ba),I(d).length>0);let f=xa(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function ya(e){let t=F(e);return t.type===`auto`?`auto`:t.type===`any`?`required`:t.type===`none`?`none`:t.type===`tool`&&typeof t.name==`string`?{type:`function`,function:{name:t.name}}:null}function ba(e){let t=F(e),n=t.input_schema,r=sa(n);if(r===null&&n!=null)throw new N(`Invalid type for tools[${String(t.name??``)}].input_schema: expected an object, but got ${typeof n} instead.`,{status:400});return{type:`function`,function:{name:t.name??``,description:t.description,parameters:oa(r!==null&&Object.keys(r).length>0?r:{type:`object`,properties:{}})}}}function xa(e,t=void 0){let n=F(e),r=L(n.type)??``;if(r===`disabled`)return null;if(r===`adaptive`)return L(F(n.output_config).effort)??L(F(t).effort)??null;if(r!==`enabled`)return null;let i=n.budget_tokens;return typeof i==`number`?i<=1024?`low`:i<=2048?`medium`:`high`:`medium`}function Sa(e,t){let n=F(e),r=Zi([...la(n.system),...ua(I(n.messages))]),i=va(n,t);if(i.messages=r,i.reasoning_effort===`none`){let e={...i};delete e.reasoning_effort,i=e}return i}var Ca=class{inbound=`anthropic`;upstream=`openai`;translateRequest(e,t){return Sa(e,t)}translateResponse(e){return Ii(e)}bridgeFrames(e){return hi(e)}usageFromFrame(e){return fi(e)}errorEnvelope(e,t){return di(e,t)}},wa={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`};function Ta(e){let t=wa[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function Ea(e,t){if(typeof t==`string`&&t!==``)return t;if(P(t)){let e=t.message;if(typeof e==`string`&&e!==``)return e;let n=JSON.stringify(t);if(n!==void 0&&n!==``)return n}return`upstream error (HTTP ${e})`}function Da(e,t){return P(t)&&P(t.error)?t:{error:{message:Ea(e,t),type:Ta(e),param:null,code:String(e)}}}function Oa(){return`chatcmpl-${z()}`}var ka={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,content_filtered:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`};function Aa(e){return ka[L(e)??``]??`stop`}function ja(e,t){let n=e.iterations,r=null;if(Array.isArray(n)&&n.length>0){let e=n.map(e=>{let t=F(F(e).output_tokens_details).thinking_tokens;return typeof t==`number`&&Number.isFinite(t)?t:null});r=e.every(e=>e!==null)?e.reduce((e,t)=>e+(t??0),0):null}if(r===null){let t=F(e.output_tokens_details).thinking_tokens;typeof t==`number`&&Number.isFinite(t)&&(r=t)}if(r===null)return{reasoning_tokens:0,text_tokens:t};let i=Math.min(Math.max(0,r),t);return{reasoning_tokens:i,text_tokens:t-i}}function Ma(e,t={}){let n=Yr(e.input_tokens),r=Yr(e.output_tokens),i=Yr(e.cache_creation_input_tokens),a=Yr(e.cache_read_input_tokens),o=n+i+a,s={cached_tokens:a,text_tokens:n,cache_write_tokens:i,cache_creation_tokens:i};if(P(e.cache_creation)){let t=e.cache_creation,n={};for(let e of[`ephemeral_5m_input_tokens`,`ephemeral_1h_input_tokens`]){let r=t[e];typeof r==`number`&&(n[e]=Yr(r))}s.cache_creation_token_details=n}let c={completion_tokens:r,prompt_tokens:o,total_tokens:o+r,completion_tokens_details:ja(e,r),prompt_tokens_details:s,cache_creation_input_tokens:i,cache_read_input_tokens:a},l=L(e.inference_geo);l!==null&&(c.inference_geo=l);let u=L(e.speed);if(u!==null&&(c.speed=u),t.fromStreamBuilder!==!0){let t=L(e.service_tier);t!==null&&(c.service_tier=t)}return c}function Na(e,t){return{...e??{},...t}}function Pa(e){return/claude-[a-z]+-(?:4[-._](?:[6-9]|[1-9]\d)(?!\d)|[5-9](?!\d)(?:[-._]\d{1,2}(?!\d))?)/.test(e)}function Fa(e){return/claude-[a-z]+-4[-._]6(?!\d)/.test(e)}function Ia(e){let t=e.toLowerCase();return![`fable`,`opus-4-7`,`opus_4_7`,`opus-4.7`,`opus_4.7`,`opus-4-8`,`opus_4_8`,`opus-4.8`,`opus_4.8`].some(e=>t.includes(e))}function La(e,t){if(typeof t==`string`&&t!==``)return t;if(P(t)){let e=t.error;if(P(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(P(n)&&typeof n.message==`string`&&n.message!==``)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return`upstream error (HTTP ${e})`}function Ra(e,t){if(P(t)){let e=t.error;if(P(e)&&t.type!==`error`&&typeof e.message==`string`)return t}return{error:{message:La(e,t),type:Ta(e),param:null,code:String(e)}}}var za={low:1024,medium:2048,high:4096,xhigh:8192,max:16384,minimal:1024},Ba={low:`low`,minimal:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`},Va=4096,Ha=1024,Ua=`[System: Empty message content sanitised to satisfy protocol]`,Wa=new Set([`type`,`properties`,`additionalProperties`,`required`,`$defs`,`strict`]);function Ga(e,t){if(e==null)return{type:`object`,properties:{}};if(!P(e))throw new N(`Invalid input_schema for tool "${t}": expected an object, got ${typeof e}`,{status:400});let n={};for(let[t,r]of Object.entries(e))Wa.has(t)&&(n[t]=r);return n.type!==`object`&&(n.type=`object`),n.properties===void 0&&(n.properties={}),n}function Ka(e){let t=F(e),n=F(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new N(`Unsupported tool type: ${String(r)}`,{status:400});let i=L(n.name)??``,a={name:i,input_schema:Ga(n.parameters,i),type:`custom`},o=n.description;o!=null&&(a.description=o);let s=t.eager_input_streaming??n.eager_input_streaming;typeof s==`boolean`&&(a.eager_input_streaming=s);let c=t.cache_control??n.cache_control;P(c)&&(a.cache_control=c);let l=t.defer_loading??n.defer_loading;typeof l==`boolean`&&(a.defer_loading=l);let u=t.allowed_callers??n.allowed_callers;Array.isArray(u)&&(a.allowed_callers=u);let d=t.input_examples??n.input_examples;return Array.isArray(d)&&(a.input_examples=d),a}function qa(e){return e.map(e=>{let t=F(e);return t.input_schema===void 0?Ka(e):t})}var Ja={name:`dummy_tool`,input_schema:{type:`object`,properties:{}},type:`custom`,description:`This is a dummy tool call`};function Ya(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)||`tool_use_id`}function Xa(e,t){if(typeof e!=`string`||e.trim()===``)return{};try{return JSON.parse(e)}catch(e){throw new N(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function Za(e){if(!P(e))return!1;let t=e.type,n=t===`thinking`?e.signature:t===`redacted_thinking`?e.data:void 0;if(typeof n==`string`&&n.startsWith(`litellm_encrypted_reasoning:`))return!0;if(t!==`thinking`)return!1;let r=e.signature;return!(typeof r==`string`&&r.length>0)}function Qa(e){if(!(`index`in e))return e;let{index:t,...n}=e;return n}function $a(e){let t=e.cache_control;return P(t)?t:void 0}function eo(e,t){return e===``?null:t===void 0?{type:`text`,text:e}:{type:`text`,text:e,cache_control:t}}function to(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 no(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=to(t.image_url),r=$a(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=$a(e);return i!==void 0&&(r.cache_control=i),r}function ro(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=t===`assistant`&&(n.some(e=>io(F(e)))||ao(e.tool_calls)),i=!1,a=n.flatMap(e=>{let t=F(e);if(t.type!==`text`)return[e];let n=t.text;return typeof n==`string`&&n.trim()!==``?[e]:(i=!0,r?[]:[{...t,text:Ua}])});return i?{...e,content:a}:e}function io(e){let t=e.type;return t===`thinking`?!Za(e):t===`redacted_thinking`||t===`server_tool_use`||typeof t==`string`&&t.endsWith(`_tool_result`)}function ao(e){return Array.isArray(e)&&e.some(e=>F(e).type===`function`)}function oo(e){let t=[];for(let n of e){let e=n.role;if(e===`tool`||e===`function`){t.push(no(n));continue}let r=n.content;if(typeof r==`string`){let e=eo(r,void 0);e!==null&&t.push(e);continue}for(let e of I(r)){let n=F(e),r=$a(n);if(n.type===`text`){let e=eo(L(n.text)??``,r);e!==null&&t.push(e)}else if(n.type===`image_url`){let e=to(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 so(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(Qa(F(e)));if(i!==null)for(let e of i){let n=F(e),r=n.type;if(r===`thinking`)Za(n)||t.push(Qa(n));else if(r===`redacted_thinking`)t.push(Qa(n));else if(r===`text`){let e=eo(L(n.text)??``,$a(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=eo(e,$a(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=$a(r);c!==void 0&&(s.cache_control=c),t.push(s)}}return t.length>0?{role:`assistant`,content:t}:null}function co(e){let t=e.map(e=>ro(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=oo(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=so(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 lo(e){let t=[];for(let n of e){let e=n.content;if(typeof e==`string`){let r=eo(e,$a(n));r!==null&&t.push(r);continue}for(let n of I(e)){let e=F(n);if(e.type!==`text`)continue;let r=eo(L(e.text)??``,$a(e));r!==null&&t.push(r)}}return t}var uo=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,fo=/^\+?[\d\s()-]{7,}$/;function po(e){return!uo.test(e)&&!fo.test(e)}function mo(e){return typeof e!=`number`||!Number.isFinite(e)?null:Number.isInteger(e)?e:Math.max(1,Math.round(e))}function ho(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 go(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 _o(e,t){let n=Pa(e)&&!Fa(e);return t>=8192&&n?`xhigh`:t>=4096?`high`:t>=2048?`medium`:`low`}function vo(e,t){if(!Pa(e)||Fa(e))return;let n=F(t.thinking);if(n.type!==`enabled`)return;let r=n.budget_tokens,i=_o(e,typeof r==`number`?r:0);t.thinking={type:`adaptive`};let a=t.output_config;t.output_config={effort:i,...P(a)?a:{}}}function yo(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 bo(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 xo(e,t,n,r){if(F(n).type===`adaptive`&&!Pa(r)){let n=e.max_completion_tokens??e.max_tokens,r=yo({type:`enabled`,budget_tokens:za.medium??2048},n);r!==null&&(t.thinking=r);return}t.thinking=n,vo(r,t)}function So(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=bo(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 Co=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 wo(e,t){let n=L(e.model)??``,r={};for(let[t,i]of Object.entries(e)){if(!Co.has(t)){r[t]=i;continue}switch(t){case`model`:r.model=i;break;case`max_tokens`:case`max_completion_tokens`:{let e=mo(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=go(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=ho(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`:xo(e,r,i,n);break;case`reasoning_effort`:So(r,i,n);break;case`user`:{let e=L(i);e!==null&&po(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&&To(e)&&(r.tools=[Ja]),r}function To(e){return I(e.messages).some(e=>`tool_calls`in F(e))}function Eo(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=wo(t,co(Zi(n.slice(r).map(e=>F(e))))),o=lo(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 Do(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 Oo(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:Do(I(r))}],usage:Ma(F(t.usage))}}var ko=class{#e;#t;#n=null;#r=null;#i=!1;#a=!1;#o=!1;#s=!1;#c=null;#l=-1;#u=``;#d=-1;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=``,(n===`thinking`||n===`redacted_thinking`)&&(this.#d+=1),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,index:this.#d}];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[];let n=[{type:`thinking`,thinking:e,index:this.#d}];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:``,signature:e,index:this.#d}];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*Ao(e){let t=new ko;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 jo=class{inbound=`openai`;upstream=`anthropic`;translateRequest(e){return Eo(e)}translateResponse(e){return Oo(e)}bridgeFrames(e){return Ao(e)}usageFromFrame(e){let t=e.usage;return P(t)?t:null}errorEnvelope(e,t){return Ra(e,t)}},Mo=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 No(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 Po=new Set([`text`,`image_url`,`input_audio`,`audio_url`,`document`,`guarded_text`,`grounding_source`,`query`,`video_url`,`file`,`thinking`,`redacted_thinking`]),Fo=new Set([`encrypted_content`,`redacted_thinking`]),Io=new Set;function Lo(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:Ro(R(t.type)),text:n};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]})}function Ro(e){if(e.startsWith(`input_`)){let t=e.slice(6);return t===`audio`?`input_audio`:Po.has(t)?t:`text`}return e===`tool_result`||e===`output_text`?`text`:Po.has(e)?e:`text`}function zo(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 Bo(e){let t=R(e.call_id);return t===``?[]:[{role:`tool`,content:Vo(e.output),tool_call_id:t}]}function Vo(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 Ho(e){return[`function_call_output`,`custom_tool_call_output`,`web_search_call`,`computer_call_output`,`tool_result`].includes(R(e.type))}function Uo(e){return R(e.type)===`function_call`||R(e.type)===`custom_tool_call`}function Wo(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(Uo(e)){let t=zo(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(Ho(e)){n.push(...Bo(e));continue}if(e.type===`reasoning`){n.push(...Qo(e));continue}let r=e.content;if(r==null)continue;let i=Ko(e),a=i,o=Lo(r),s=n[n.length-1];i===`assistant`&&s?.role===`assistant`&&Array.isArray(s.tool_calls)?n[n.length-1]={...s,content:Go(s.content,o)}:n.push({role:a,content:o})}return ns(n)}function Go(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 Ko(e){return R(e.role)===``?`user`:R(e.role)}function qo(e){return Yo(e.content)??Xo(e.summary)}function Jo(e,t){let n=e.flatMap(e=>{let n=F(e);if(t.has(R(n.type)))return[];let r=n.text;return typeof r==`string`&&r.trim()!==``?[r.trim()]:[]});return n.length>0?n.join(`
17
17
  `):null}function Yo(e){return typeof e==`string`&&e.trim()!==``?e:Array.isArray(e)?Jo(e,Fo):null}function Xo(e){return Array.isArray(e)?Jo(e,Io):null}function Zo(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 Qo(e){let t=qo(e),n=Zo(e);return t===null&&n===null?[]:[{role:`assistant`,content:null,...t===null?{}:{reasoning_content:t},...n===null?{}:{thinking_blocks:n}}]}function $o(e){return typeof e==`string`&&e!==``}function es(e){return e.role===`assistant`&&e.content===null&&I(e.tool_calls).length===0&&($o(e.reasoning_content)||I(e.thinking_blocks).length>0)}function ts(e,t){let n=t.map(e=>e.reasoning_content).filter($o),r=e.reasoning_content,i=n.length>0?[...n,...$o(r)?[r]:[]].join(`
18
18
  `):null,a=t.flatMap(e=>I(e.thinking_blocks));return{...e,...i===null?{}:{reasoning_content:i},...a.length>0?{thinking_blocks:[...a,...I(e.thinking_blocks)]}:{}}}function ns(e){let t=[],n=[];for(let r of e){if(es(r)){n.push(r);continue}if(n.length>0){if(r.role===`assistant`){t.push(ts(r,n)),n=[];continue}t.push(...n),n=[]}t.push(r)}return t.push(...n),t}function rs(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 is(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 as(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 os(e){let t=e,{tools:n,webSearchOptions:r}=is(t.tools??[]),i=as(t.text),a=F(t.reasoning).effort,o=typeof a==`string`?a:null,s={messages:Wo(t.input,t.instructions),model:t.model??null,tool_choice:rs(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 ss={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 cs(e,t=()=>{}){let n=ss[e];return n===void 0?(t(e),`stop`):n}function ls(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:cs(o),message:a}}function us(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 ds(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=>ls(F(e)))};return e.usage!=null&&(r.usage=us(e.usage)),r}function fs(e){return e===`length`||e===`max_tokens`||e===`content_filter`?`incomplete`:`completed`}function ps(e){return e===`content_filter`?`content_filter`:`max_output_tokens`}function ms(e){return typeof e==`string`?e:I(e).map(e=>typeof e==`string`?e:L(F(e).text)??``).join(``)}function hs(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 gs(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 _s(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:ps(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 vs(e,t){let n=F(I(e.choices)[0]),r=F(n.message),i=L(n.finish_reason),a=ms(r.content),o=I(r.tool_calls),s=L(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${z()}`,status:fs(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:fs(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(gs(F(e),`fc_${z()}`));return _s(t,fs(i),c,hs(e.usage),i)}function ys(e){let t=F(e),n=L(t.model);return vs(ds(t),{id:`resp_${z()}`,created:Xr(),...n===null?{}:{model:n}})}function bs(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?cs(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 xs=10;function Ss(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function Cs(e){if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var ws=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=_s(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=fs(this.#c);return e.push(this.#S({type:`response.completed`,response:_s(this.#m(),t,this.#x(),hs(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=Cs(n.arguments);if(o!==``){r.args+=o;for(let e=0;e<o.length;e+=xs)i.push(this.#S({type:`response.function_call_arguments.delta`,item_id:r.itemId,output_index:r.outputIndex,delta:o.slice(e,e+xs)}))}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:fs(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=Ss(e.response)),t}},Ts=class{inbound=`openai-responses`;upstream=`openai`;translateRequest(e){return os(e)}translateResponse(e){return ys(e)}async*bridgeFrames(e,t,n){let r=new ws({id:`resp_${z()}`,created:Xr(),...P(n)?{requestEcho:n}:{}});for await(let t of e)for(let e of r.translateFrame(bs(t)))yield e;for(let e of r.flush())yield e}usageFromFrame(e){return No(e)}errorEnvelope(e,t){return Da(e,t)}};function Es(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 Ds(e){let t=e;return{...t,input:Es(t.input)}}var Os=[`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`],ks=[`input_tokens_details`,`output_tokens_details`,`cost`],As={audio_tokens:null,cached_tokens:0,cached_tokens_details:null,image_tokens:null,text_tokens:null,video_tokens:null},js={audio_tokens:null,reasoning_tokens:null,text_tokens:null};function Ms(e,t){let n={...e};for(let[e,r]of Object.entries(t))e in n||(n[e]=r);return n}function Ns(e){let t=e.usage;if(!P(t))return;let n={...t};for(let e of ks)e in n||(n[e]=null);let r=n.input_tokens_details;P(r)&&(n.input_tokens_details=Ms(r,As));let i=n.output_tokens_details;P(i)&&(n.output_tokens_details=Ms(i,js)),e.usage=n}function Ps(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 Fs(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 Is(e){for(let t of Os)t in e||(e[t]=null);return Ps(e),Fs(e),Ns(e),e}function Ls(e){return Is({...e})}function Rs(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 zs(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 Bs(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(zs);e.some((e,t)=>e!==i[t])&&(n.tools=e,r=!0)}return r?{...e,response:n}:e}var Vs=class{inbound=`openai-responses`;upstream=`openai-responses`;translateRequest(e){return Ds(e)}translateResponse(e){return Ls(e)}async*bridgeFrames(e){for await(let t of e){let e=t;yield Bs(Rs(e)??e)}}usageFromFrame(e){return No(e)}errorEnvelope(e,t){return Da(e,t)}},Hs={anthropicToAnthropic:new Ui,anthropicToChatCompletions:new Ca,chatCompletionsToAnthropic:new jo,chatCompletionsToChatCompletions:new Mo,responsesToResponses:new Vs,responsesToChatCompletions:new Ts},Us=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(Hs[e],t??{},e)}};function Ws(){return new Us}var Gs={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`},Ks={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`},qs=new Set([204,205,304]);function Js(e){let t;try{t=JSON.parse(e)}catch{return null}return M(t)?t:null}function Ys(e){let t=e.type===`error`?e.error:void 0;return M(t)&&typeof t.type==`string`&&typeof t.message==`string`}function Xs(e){let t=Js(e);if(t===null)return e;if(Ys(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 Zs(e,t,n,r){let i=t===``||qs.has(e)?null:t;return new Response(i,{status:e,headers:{"content-type":n,...r}})}function Qs(e,t,n,r){let i=e=>Gs[e]??`api_error`,a=Js(t),o;if(a!==null&&Ys(a))o={...a},n!==void 0&&a.request_id===void 0&&(o.request_id=n);else{let r={type:`error`,error:{type:i(e),message:Xs(t)}};n!==void 0&&(r.request_id=n),o=r}return Zs(e,JSON.stringify(o),`application/json`,r)}function $s(e,t,n){let r={error:{message:Xs(t),type:(e=>{let t=Ks[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t})(e),param:null,code:String(e)}};return Zs(e,JSON.stringify(r),`application/json`,n)}function ec(e,t,n,r,i){return e===`anthropic`?Qs(t,n,r,i):$s(t,n,i)}function tc(e,t,n,r){return e===`anthropic`?Qs(t,n,r):$s(t,n)}var nc={openai:`chat/completions`,anthropic:`messages`,"openai-responses":`responses`},rc={openai:`https://api.openai.com`,anthropic:`https://api.anthropic.com`,"openai-responses":`https://api.openai.com`};function ic(e){let t=e.provider,n=(e.apiBase??rc[t]).replace(/\/+$/,``),r=nc[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 ac=class{id;created;model;usage=null;#e=new Map;get hasChoices(){return this.#e.size>0}push(e){typeof e.id==`string`&&(this.id??=e.id),typeof e.created==`number`&&(this.created??=e.created),typeof e.model==`string`&&(this.model??=e.model),M(e.usage)&&(this.usage=e.usage);let t=e.choices;if(Array.isArray(t))for(let e of t){if(!M(e))continue;let t=typeof e.index==`number`?e.index:0,n=this.#t(t),r=M(e.delta)?e.delta:null;r!==null&&this.#n(n,r);let i=e.finish_reason;typeof i==`string`&&i!==``&&(n.finishReason=i),e.logprobs!==null&&e.logprobs!==void 0&&(n.logprobs=e.logprobs)}}finish(){let e={object:`chat.completion`,choices:[...this.#e.entries()].sort(([e],[t])=>e-t).map(([e,t])=>{let n={role:t.role??`assistant`,content:this.#r(t)};t.reasoning!==``&&(n.reasoning_content=t.reasoning),t.refusal!==``&&(n.refusal=t.refusal);let r=[...t.toolCalls.entries()].sort(([e],[t])=>e-t).filter(([,e])=>e.name!==``||e.arguments!==``);return r.length>0&&(n.tool_calls=r.map(([,e])=>({id:e.id,type:e.type===``?`function`:e.type,function:{name:e.name,arguments:e.arguments}}))),t.functionCall!==null&&(t.functionCall.name!==``||t.functionCall.arguments!==``)&&(n.function_call=t.functionCall),{index:e,message:n,logprobs:t.logprobs??null,finish_reason:t.finishReason}})};return this.id!==void 0&&(e.id=this.id),this.created!==void 0&&(e.created=this.created),this.model!==void 0&&(e.model=this.model),this.usage!==null&&(e.usage=this.usage),e}#t(e){let t=this.#e.get(e);return t===void 0&&(t={role:void 0,content:null,reasoning:``,refusal:``,toolCalls:new Map,functionCall:null,finishReason:null,logprobs:null},this.#e.set(e,t)),t}#n(e,t){typeof t.role==`string`&&e.role===void 0&&(e.role=t.role),typeof t.content==`string`&&(e.content=(e.content??``)+t.content),typeof t.reasoning_content==`string`&&(e.reasoning+=t.reasoning_content),typeof t.refusal==`string`&&(e.refusal+=t.refusal);let n=t.tool_calls;if(Array.isArray(n))for(let t of n){if(!M(t))continue;let n=typeof t.index==`number`?t.index:0,r=e.toolCalls.get(n);r===void 0&&(r={id:``,type:``,name:``,arguments:``},e.toolCalls.set(n,r)),typeof t.id==`string`&&t.id!==``&&(r.id=t.id),typeof t.type==`string`&&t.type!==``&&(r.type=t.type);let i=t.function;M(i)&&(typeof i.name==`string`&&i.name!==``&&(r.name=i.name),typeof i.arguments==`string`&&(r.arguments+=i.arguments))}let r=t.function_call;M(r)&&(e.functionCall??={name:``,arguments:``},typeof r.name==`string`&&r.name!==``&&(e.functionCall.name=r.name),typeof r.arguments==`string`&&(e.functionCall.arguments+=r.arguments))}#r(e){if(e.content!==null)return e.content;let t=[...e.toolCalls.values()].some(e=>e.name!==``||e.arguments!==``),n=e.functionCall!==null&&(e.functionCall.name!==``||e.functionCall.arguments!==``);return t||n?null:``}};function oc(e){if(M(e)){if(typeof e.message==`string`)return e.message;if(typeof e.msg==`string`)return e.msg}return typeof e==`string`?e:`upstream stream reported an error`}function sc(e){if(!M(e))return null;let t=e.code;return typeof t==`number`?t:typeof t==`string`&&/^\d+$/.test(t)?Number(t):null}async function cc(e){if(e===null)return{ok:!1,message:`upstream streamed response has no body`,code:null};let t=e.getReader(),n=new TextDecoder,r=new ac,i=``,a=null,o=null,s=e=>{if(!e.startsWith(`data:`))return!0;let t=e.slice(5).trim();if(t===``||t===`[DONE]`)return!0;let n;try{n=JSON.parse(t)}catch{return!0}if(!M(n))return!0;let i=n.error;return i==null?(r.push(n),!0):(a=oc(i),o=sc(i),!1)};try{for(;;){let{done:e,value:r}=await t.read();if(e)break;for(r!==void 0&&(i+=n.decode(r,{stream:!0}));;){let e=i.indexOf(`
19
- `);if(e<0)break;let n=i.slice(0,e).replace(/\r$/,``);if(i=i.slice(e+1),!s(n))return await t.cancel().catch(()=>void 0),{ok:!1,message:a??`upstream stream reported an error`,code:o}}}if(i+=n.decode(),i!==``&&s(i.replace(/\r$/,``)),a!==null)return{ok:!1,message:a,code:o}}catch(e){return await t.cancel().catch(()=>void 0),{ok:!1,message:`failed to read upstream stream: ${or(e)}`,code:null}}return t.releaseLock(),r.hasChoices?{ok:!0,body:r.finish()}:{ok:!1,message:`upstream stream contained no completion chunks`,code:null}}var lc=6e5,uc=12e4,dc=65536,fc=4096,pc=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??lc,this.#a=t.timeouts?.idleMs??uc;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 hc(t,dc),r=n.length<=fc?n:n.slice(0,fc),i=sr(e.headers),a=i[`retry-after`],o=a!==void 0&&(e.status===429||e.status===503)?{"retry-after":a}:void 0;return{kind:`error`,status:e.status,response:ec(this.#t,e.status,r,this.#n,o),upstreamText:r,upstreamHeaders:i}}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:tc(this.#t,e,t,this.#n),upstreamText:null,upstreamHeaders:null}}#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 mc(e){e!==null&&e.cancel().catch(()=>{})}async function hc(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 gc=new Set([500,502,503,504,529]);function _c(e){if(e===null)return!1;try{let t=JSON.parse(e);if(M(t)){let e=M(t.error)?t.error:t;if(e.code===11101||e.code===`11101`)return!0}}catch{}return/non-stream chat request is currently not supported/i.test(e)}function vc(e,t,n){return e===400&&_c(t)?{kind:`capability`,status:e,retryAfterMs:null}:e===429?{kind:`rate_limited`,status:e,retryAfterMs:n}:e===504&&t===null?{kind:`fatal`,status:e,retryAfterMs:null}:gc.has(e)?{kind:`transient`,status:e,retryAfterMs:n}:{kind:`fatal`,status:e,retryAfterMs:null}}function yc(e){if(e===null)return null;let t=e[`retry-after`]??e[`Retry-After`];if(t===void 0||t.trim()===``)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function bc(e,t){if(t.attempts>=2||t.rawPassthrough||e.kind===`fatal`)return{kind:`surface`};if(e.kind===`capability`)return t.openAiUpstream&&!t.requestStream?{kind:`retry`,delayMs:0,forceStream:!0}:{kind:`surface`};let n=e.kind===`rate_limited`?e.retryAfterMs??500:300;return n>2e3||t.waitedMs+n>2e3?{kind:`surface`}:{kind:`retry`,delayMs:n,forceStream:!1}}var xc=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`]),Sc=`sk-ant-oat`,Cc=`oauth-2025-04-20`,wc="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 Tc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();xc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function Ec(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 ${Sc}`)){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`],Cc),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(i===void 0)throw new N(wc,{status:401});let s=i.startsWith(Sc),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={...Tc(n),...t.headers??{}};return e===`anthropic`?i(o,t.apiKey):a(o,t.apiKey)}var Dc=/<invoke\s+name=/g,Oc=2;function kc(e,t){let n=Ec(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function Ac(e){return{clientRequest:t=>M(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function jc(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 Mc(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 Nc(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,Dc.lastIndex=0;for(let e=Dc.exec(o);e!==null;e=Dc.exec(o))n+=1;if(t>e&&n>=Oc)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 Pc=()=>{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 Fc(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(Pc()),e===`chatCompletionsToAnthropic`&&i.push(r()),e===`anthropicToChatCompletions`&&t.maxReasoningEffort!==void 0&&i.push(Mc(t.maxReasoningEffort));let a=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&a>0&&i.push(Nc(a)),i}function Ic(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 Lc(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 Rc(e){return M(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?Ic(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?Lc(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 zc=Ws(),Bc=new WeakSet;async function Vc(e,t,n,r,i){let a=(t,n)=>({kind:`error`,status:t,response:tc(e,t,n,i.requestId)}),o;try{o=y()}catch(e){return a(mr(e)??500,or(e))}let s=o.begin(),c=r.stream!==!0&&(n.upstreamStreamOnly===!0||Bc.has(n)),l=c?{...r,stream:!0}:r,u=0,d=await h();if(d.kind===`failure`)return a(d.status,d.message);if(d.kind===`error`)return d;let f=await _(d.transport);if(f.kind===`failure`)return a(f.status,f.message);let p=await v(f.value);if(p.kind===`failure`)return a(p.status,p.message);let m=p.value;return`stream`in m?{kind:`ok`,sse:!0,stream:m.stream,collectUsage:()=>Rc(m.collectUsage())}:{kind:`ok`,sse:!1,body:m.body,usage:Rc(M(m.body)?m.body.usage:void 0)};async function h(){for(let e=1;;e+=1){let t=await g();if(t.kind!==`error`)return t;let a=bc(vc(t.status,t.upstreamText,yc(t.upstreamHeaders)),{attempts:e,waitedMs:u,requestStream:l.stream===!0,rawPassthrough:n.rawPassthrough===!0,openAiUpstream:n.provider===`openai`});if(a.kind===`surface`||i.signal?.aborted===!0)return t;a.forceStream?(c=!0,l={...r,stream:!0},Bc.add(n),console.warn(`[gateway] upstream rejected non-stream for "${n.name}" → retry as stream (attempt ${String(e)})`)):console.warn(`[gateway] upstream ${String(t.status)} for "${n.name}" → retry after ${String(a.delayMs)}ms (attempt ${String(e)})`),a.delayMs>0&&(await new Promise(e=>setTimeout(e,a.delayMs)),u+=a.delayMs),s=o.begin()}}async function g(){let t=await s.request({body:l});return t.kind===`error`?{kind:`failure`,status:t.status,message:t.message}:new pc({url:ic(n),...t.value},{inbound:e,requestId:i.requestId,signal:i.signal,timeouts:i.timeouts,fetchFn:i.fetchFn}).send()}async function _(e){let t=(e.headers[`content-type`]??``).includes(`text/event-stream`);if(c&&t){let t=await cc(e.stream);if(!t.ok)return{kind:`failure`,status:t.code!==null&&t.code>=400&&t.code<=599?t.code:502,message:t.message};let n=JSON.stringify(t.body);return{kind:`ok`,value:{status:e.status,headers:{"content-type":`application/json`},stream:null,text:()=>Promise.resolve(n)}}}if(t)return{kind:`ok`,value:e};try{let t=await e.text();return{kind:`ok`,value:{...e,stream:null,text:()=>Promise.resolve(t)}}}catch(e){return{kind:`failure`,status:mr(e)??502,message:or(e)}}}async function v(e){let t;try{t=await s.response({status:e.status,headers:e.headers,body:e.stream,text:e.text})}catch(t){return mc(e.stream),{kind:`failure`,status:500,message:or(t)}}return t.kind===`error`?(mc(e.stream),{kind:`failure`,status:t.status,message:t.message}):{kind:`ok`,value:t.value}}function y(){let e=n.rawPassthrough===!0,r;if(t===`anthropicToChatCompletions`){let e=``;try{e=new URL(ic(n)).hostname}catch{e=``}r=e!==``&&e!==`openai.com`&&!e.endsWith(`.openai.com`)?`preserve`:`drop`}let a=zc[t]({...e?{translate:!1}:{},...r===void 0?{}:{topK:r}});if(a.intercept(kc(n,i.inboundHeaders)),a.intercept(Ac(n)),!e){t!==`anthropicToAnthropic`&&a.intercept(jc(t,n));for(let e of Fc(t,n))a.intercept(e)}return a}}function Hc(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 Uc(e,t){return Hc(e,t.provider,t.rawPassthrough===!0)!==null}async function Wc(e,t,n){return Kc(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function Gc(e,t,n){return Kc(e,t,n,`openai-responses`)}async function Kc(e,t,n,r){let i=(e,t,n)=>{let r=mr(e)??500;return{kind:`error`,status:r,response:tc(t,r,or(e),n)}};try{return await qc(e,t,n,r)}catch(e){return i(e,r,n.requestId)}}async function qc(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=Hc(r,e.provider,o);if(s===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:tc(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 Vc(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 Jc=[`x-litellm-trace-id`,`x-litellm-session-id`],Yc=new Set(Jc),Xc=/^x-.+-session-id$/,Zc=/^x-.+-conversation-id$/,Qc=[`thread-id`,`conversation_id`],$c=/^codex[-_ /]/i,el=/^[a-zA-Z0-9_-]{8,}$/,tl=/^[a-zA-Z0-9_-]+$/,nl=`_session_`;function rl(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of Jc){let n=t.get(e);if(n!==void 0&&el.test(n))return n}let n=Yc;for(let[e,r]of t)if(!n.has(e)&&(Xc.test(e)||Zc.test(e))&&el.test(r))return r;for(let e of[`x-session-id`,`x-conversation-id`]){let n=t.get(e);if(n!==void 0&&el.test(n))return n}for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&el.test(n))return n}let r=t.get(`user-agent`);if(r!==void 0&&$c.test(r))for(let e of Qc){let n=t.get(e);if(n!==void 0&&el.test(n))return n}return``}function il(e){let t=e=>{let t=(e,t)=>{if(!M(e))return null;let n=e[t];return typeof n==`string`&&tl.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(nl);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 al=10485760;function ol(e){try{return JSON.parse(e)}catch{return e}}function sl(e){for(let t of e.split(`
20
- `)){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 cl=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)}},ll=class{text=null;#e;constructor(e){this.#e=e}add(e){this.text=this.#e.append(this.text,e)}},ul=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)}},dl=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 cl(e.maxBytes??al),this.#t=new ll(this.#e),this.#n=new ll(this.#e),this.#r=new ll(this.#e),this.#i=new ul(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(il(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 fl(e);t.#i.addBody(n),t.clientBody=ol(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=sl(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(`
19
+ `);if(e<0)break;let n=i.slice(0,e).replace(/\r$/,``);if(i=i.slice(e+1),!s(n))return await t.cancel().catch(()=>void 0),{ok:!1,message:a??`upstream stream reported an error`,code:o}}}if(i+=n.decode(),i!==``&&s(i.replace(/\r$/,``)),a!==null)return{ok:!1,message:a,code:o}}catch(e){return await t.cancel().catch(()=>void 0),{ok:!1,message:`failed to read upstream stream: ${or(e)}`,code:null}}return t.releaseLock(),r.hasChoices?{ok:!0,body:r.finish()}:{ok:!1,message:`upstream stream contained no completion chunks`,code:null}}var lc=6e5,uc=12e4,dc=65536,fc=4096,pc=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??lc,this.#a=t.timeouts?.idleMs??uc;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 hc(t,dc),r=n.length<=fc?n:n.slice(0,fc),i=sr(e.headers),a=i[`retry-after`],o=a!==void 0&&(e.status===429||e.status===503)?{"retry-after":a}:void 0;return{kind:`error`,status:e.status,response:ec(this.#t,e.status,r,this.#n,o),upstreamText:r,upstreamHeaders:i}}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:tc(this.#t,e,t,this.#n),upstreamText:null,upstreamHeaders:null}}#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 mc(e){e!==null&&e.cancel().catch(()=>{})}async function hc(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 gc=new Set([500,502,503,504,529]);function _c(e){if(e===null)return!1;try{let t=JSON.parse(e);if(M(t)){let e=M(t.error)?t.error:t;if(e.code===11101||e.code===`11101`)return!0}}catch{}return/non-stream chat request is currently not supported/i.test(e)}function vc(e,t,n){return e===400&&_c(t)?{kind:`capability`,status:e,retryAfterMs:null}:e===429?{kind:`rate_limited`,status:e,retryAfterMs:n}:e===504&&t===null?{kind:`fatal`,status:e,retryAfterMs:null}:gc.has(e)?{kind:`transient`,status:e,retryAfterMs:n}:{kind:`fatal`,status:e,retryAfterMs:null}}function yc(e){if(e===null)return null;let t=e[`retry-after`]??e[`Retry-After`];if(t===void 0||t.trim()===``)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}function bc(e,t){if(t.attempts>=2||t.rawPassthrough||e.kind===`fatal`)return{kind:`surface`};if(e.kind===`capability`)return t.openAiUpstream&&!t.requestStream?{kind:`retry`,delayMs:0,forceStream:!0}:{kind:`surface`};let n=e.kind===`rate_limited`?e.retryAfterMs??500:300;return n>2e3||t.waitedMs+n>2e3?{kind:`surface`}:{kind:`retry`,delayMs:n,forceStream:!1}}var xc=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`]),Sc=`sk-ant-oat`,Cc=`oauth-2025-04-20`,wc="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 Tc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();xc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function Ec(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 ${Sc}`)){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`],Cc),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(i===void 0)throw new N(wc,{status:401});let s=i.startsWith(Sc),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={...Tc(n),...t.headers??{}};return e===`anthropic`?i(o,t.apiKey):a(o,t.apiKey)}var Dc=/<invoke\s+name=/g,Oc=2;function kc(e,t){let n=Ec(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function Ac(e){return{clientRequest:t=>M(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function jc(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 Mc(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 Nc(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,Dc.lastIndex=0;for(let e=Dc.exec(o);e!==null;e=Dc.exec(o))n+=1;if(t>e&&n>=Oc)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 Pc=()=>{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 Fc(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(Pc()),e===`chatCompletionsToAnthropic`&&i.push(r()),e===`anthropicToChatCompletions`&&t.maxReasoningEffort!==void 0&&i.push(Mc(t.maxReasoningEffort));let a=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&a>0&&i.push(Nc(a)),i}function Ic(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 Lc(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 Rc(e){return M(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?Ic(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?Lc(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 zc=Ws(),Bc=new WeakSet;async function Vc(e,t,n,r,i){let a=(t,n)=>({kind:`error`,status:t,response:tc(e,t,n,i.requestId)}),o;try{o=y()}catch(e){return a(mr(e)??500,or(e))}let s=o.begin(),c=r.stream!==!0&&(n.upstreamStreamOnly===!0||Bc.has(n)),l=c?{...r,stream:!0}:r,u=0,d=await h();if(d.kind===`failure`)return a(d.status,d.message);if(d.kind===`error`)return d;let f=await _(d.transport);if(f.kind===`failure`)return a(f.status,f.message);let p=await v(f.value);if(p.kind===`failure`)return a(p.status,p.message);let m=p.value;return`stream`in m?{kind:`ok`,sse:!0,stream:m.stream,collectUsage:()=>Rc(m.collectUsage())}:{kind:`ok`,sse:!1,body:m.body,usage:Rc(M(m.body)?m.body.usage:void 0)};async function h(){for(let e=1;;e+=1){let t=await g();if(t.kind!==`error`)return t;let a=bc(vc(t.status,t.upstreamText,yc(t.upstreamHeaders)),{attempts:e,waitedMs:u,requestStream:l.stream===!0,rawPassthrough:n.rawPassthrough===!0,openAiUpstream:n.provider===`openai`});if(a.kind===`surface`||i.signal?.aborted===!0)return t;a.forceStream?(c=!0,l={...r,stream:!0},Bc.add(n),console.warn(`[gateway] upstream rejected non-stream for "${n.name}" → retry as stream (attempt ${String(e)})`)):console.warn(`[gateway] upstream ${String(t.status)} for "${n.name}" → retry after ${String(a.delayMs)}ms (attempt ${String(e)})`),a.delayMs>0&&(await new Promise(e=>setTimeout(e,a.delayMs)),u+=a.delayMs),s=o.begin()}}async function g(){let t=await s.request({body:l});return t.kind===`error`?{kind:`failure`,status:t.status,message:t.message}:new pc({url:ic(n),...t.value},{inbound:e,requestId:i.requestId,signal:i.signal,timeouts:i.timeouts,fetchFn:i.fetchFn}).send()}async function _(e){let t=(e.headers[`content-type`]??``).includes(`text/event-stream`);if(c&&t){let t=await cc(e.stream);if(!t.ok)return{kind:`failure`,status:t.code!==null&&t.code>=400&&t.code<=599?t.code:502,message:t.message};let n=JSON.stringify(t.body);return{kind:`ok`,value:{status:e.status,headers:{"content-type":`application/json`},stream:null,text:()=>Promise.resolve(n)}}}if(t)return{kind:`ok`,value:e};try{let t=await e.text();return{kind:`ok`,value:{...e,stream:null,text:()=>Promise.resolve(t)}}}catch(e){return{kind:`failure`,status:mr(e)??502,message:or(e)}}}async function v(e){let t;try{t=await s.response({status:e.status,headers:e.headers,body:e.stream,text:e.text})}catch(t){return mc(e.stream),{kind:`failure`,status:500,message:or(t)}}return t.kind===`error`?(mc(e.stream),{kind:`failure`,status:t.status,message:t.message}):{kind:`ok`,value:t.value}}function y(){let e=n.rawPassthrough===!0,r;if(t===`anthropicToChatCompletions`){let e=``;try{e=new URL(ic(n)).hostname}catch{e=``}r=e!==``&&e!==`openai.com`&&!e.endsWith(`.openai.com`)?`preserve`:`drop`}let a=zc[t]({...e?{translate:!1}:{},...r===void 0?{}:{topK:r}});if(a.intercept(kc(n,i.inboundHeaders)),a.intercept(Ac(n)),!e){t!==`anthropicToAnthropic`&&a.intercept(jc(t,n));for(let e of Fc(t,n))a.intercept(e)}return a}}function Hc(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 Uc(e,t){return Hc(e,t.provider,t.rawPassthrough===!0)!==null}async function Wc(e,t,n){return Kc(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function Gc(e,t,n){return Kc(e,t,n,`openai-responses`)}async function Kc(e,t,n,r){let i=(e,t,n)=>{let r=mr(e)??500;return{kind:`error`,status:r,response:tc(t,r,or(e),n)}};try{return await qc(e,t,n,r)}catch(e){return i(e,r,n.requestId)}}async function qc(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=Hc(r,e.provider,o);if(s===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:tc(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 Vc(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 Jc=[`x-litellm-trace-id`,`x-litellm-session-id`],Yc=new Set(Jc),Xc=/^x-.+-session-id$/,Zc=/^x-.+-conversation-id$/,Qc=[`thread-id`,`conversation_id`],$c=/^codex[-_ /]/i,el=/^[a-zA-Z0-9_-]{8,}$/,tl=/^[a-zA-Z0-9_-]+$/,nl=`_session_`;function rl(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of Jc){let n=t.get(e);if(n!==void 0&&el.test(n))return n}let n=Yc;for(let[e,r]of t)if(!n.has(e)&&(Xc.test(e)||Zc.test(e))&&el.test(r))return r;for(let e of[`x-session-id`,`x-conversation-id`]){let n=t.get(e);if(n!==void 0&&el.test(n))return n}for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&el.test(n))return n}let r=t.get(`user-agent`);if(r!==void 0&&$c.test(r))for(let e of Qc){let n=t.get(e);if(n!==void 0&&el.test(n))return n}return``}function il(e){let t=e=>{let t=(e,t)=>{if(!M(e))return null;let n=e[t];return typeof n==`string`&&tl.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(nl);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 al=2;function ol(e){if(!M(e))return null;let t=Array.isArray(e.messages)?e.messages:[],n=sl(e.system)||ll(t,`system`),r=cl(t,`user`,al).map(ul);return r.length===0?null:`fp-${ie(`sha256`).update([ul(n),...r].join(`\0`)).digest(`hex`).slice(0,16)}`}function sl(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return``;let t=[];for(let n of e)M(n)&&typeof n.text==`string`&&t.push(n.text);return t.join(`
20
+ `)}function cl(e,t,n){let r=[];for(let i of e){if(r.length>=n)break;if(!M(i)||i.role!==t)continue;let e=sl(i.content);e!==``&&r.push(e)}return r}function ll(e,t){return cl(e,t,1)[0]??``}function ul(e){return e.replace(/\s+/g,` `).trim()}var dl=10485760;function fl(e){try{return JSON.parse(e)}catch{return e}}function pl(e){for(let t of e.split(`
21
+ `)){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 ml=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)}},hl=class{text=null;#e;constructor(e){this.#e=e}add(e){this.text=this.#e.append(this.text,e)}},gl=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)}},_l=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 ml(e.maxBytes??dl),this.#t=new hl(this.#e),this.#n=new hl(this.#e),this.#r=new hl(this.#e),this.#i=new gl(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(il(this.inboundBody)??ol(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 vl(e);t.#i.addBody(n),t.clientBody=fl(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=pl(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(`
21
22
 
22
- `).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:ol(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 fl(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 pl=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function ml(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var hl=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=!pl.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}},gl=67108864,_l=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??ml({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 vl(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 _l(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:rl(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let d=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??gl,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 yl=3.5,bl=8,xl=24;function Sl(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/yl)),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,bl),i+=t(e.system),i+=t(e.thinking),i+=t(e.output_config),i+=r(e.tools,xl),{input_tokens:n(i)}}var Cl=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}},wl={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function Tl(e){let t=new j,n=e.runner??new hl().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??oe(),o=new dl({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 Cl({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:Tc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,vl(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=>jl(e,`openai`)),t.post(`/v1/messages`,e=>jl(e,`anthropic`)),t.post(`/v1/responses`,e=>kl(e)),t.post(`/v1/messages/count_tokens`,e=>Al(e)),t.post(`/responses`,e=>kl(e)),t.post(`/chat/completions`,e=>jl(e,`openai`)),t.post(`/messages`,e=>jl(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>Al(e)),t.get(`/v1/models`,e=>Dl(e)),t.get(`/models`,e=>Dl(e)),t}async function El(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 Dl(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(ml({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await El(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function Ol(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??ml({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||!Uc(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=ml({requestId:a.requestId,inboundProtocol:t.hookProtocol,requestModel:c??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),a.hookCtx=l;let n=await El(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=Nl(c??``,d)),{body:s,model:c,deployment:d,hookCtx:l})}async function kl(e){let t=e.get(`gctx`),n=await Ol(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return Ml(e,await Gc(i,Pl(r),t.dispatchCtx))}async function Al(e){let t=await Ol(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(Sl(n))}async function jl(e,t){let n=(e,t)=>t===`anthropic`?{...e,inbound_format:`anthropic`}:Pl(e),r=e.get(`gctx`),i=r.runner,a=await Ol(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=Nl(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&&Uc(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 Ml(e,await Wc(u,n(s.request.body,t),d),{runner:i,hookCtx:c})}let d=n(o,t);return Ml(e,await Wc(u,d,r.dispatchCtx))}async function Ml(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:{...wl}}),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 Nl(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function Pl(e){let{inbound_format:t,...n}=e;return n}var Fl=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=ur(e.config),Il(this._expanded.warnings),this.hookRunner=new hl().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=ur(e),Il(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(`/`,Tl({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return lr}};function Il(e){for(let t of e)O(`[ezllm] ${t}`)}var Ll=`重启服务(CLI 会重新生成默认配置)`,Rl=class extends Error{constructor(e,t=Tt(),n=Ll){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function zl(){let e=Tt();if(!p(e))return null;let t;try{t=JSON.parse(g(e,`utf-8`))}catch(t){throw new Rl(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new Rl(`顶层必须是 JSON 对象`,e);return t}function Bl(){try{return zl()}catch(e){throw e instanceof Rl&&(k(`[ezllm] ${e.message}`),process.exit(1)),e}}function Vl(e){Vt(Tt(),e)}function Hl(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function Ul(e){return ur(Hl(e))}var Wl=`0.0.0.0`,Gl=`127.0.0.1`,Kl=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function ql(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function Jl(){return ql(zl())}function Yl(){try{return{config:zl(),broken:!1}}catch(e){if(!(e instanceof Rl))throw e;return{config:null,broken:!0}}}function Xl(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 Zl(e){let t=e?.[`web-ui`]?.[`login-enabled`];return t===!1?!1:t!==void 0||Xl(e)!==void 0}function Ql(e){return Zl(e)?Xl(e):void 0}function $l(){let{config:e,broken:t}=Yl();if(t)return{required:!0,configBroken:!0,username:``,password:``};if(!Zl(e))return{required:!1,configBroken:!1,username:``,password:``};let n=Xl(e);return n===void 0?{required:!0,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function eu(){let{config:e,broken:t}=Yl();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 tu(e){return(e=>ql(e)!==``||Ql(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?Wl:Gl,source:`config`}:{hostname:Gl,source:`credentials`}}function nu(){try{return tu(zl())}catch{return tu(null)}}function ru(e,t){return tu(e).hostname!==tu(t).hostname||e?.port!==t.port}function iu(){return zl()?.logs}function au(e){return typeof e==`number`&&Number.isFinite(e)}function ou(){let e=iu(),t=(e,t)=>au(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function su(){let e=iu(),t=(e,t)=>au(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 cu=`__blob`,lu=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],uu=1e3,du=134217728;function fu(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function pu(e){return e instanceof Error?e.message:String(e)}var mu=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function hu(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 gu(){return c(wt(),`spool`)}var _u=/^(\d+)\.jsonl$/,vu=`.tmp`,yu=268435456;function bu(){return new Promise(e=>setImmediate(e))}function xu(e){return c(gu(),`${String(e)}.jsonl`)}function Su(e){return xu(e)+vu}function Cu(){Bt(),m(gu(),{recursive:!0})}function wu(){try{return _(gu()).map(e=>_u.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function Tu(e){let t;try{t=g(xu(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function Eu(){let e=0;try{for(let t of _(gu()))if(t.endsWith(vu))try{S(c(gu(),t)),e++}catch{}}catch{return 0}return e}var Du=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:yu}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of _(gu()))if(_u.test(t))try{e+=x(c(gu(),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 wu()}readRecord(e){return Tu(e)}deleteFile(e){try{let t=x(xu(e)).size;S(xu(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,xu(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await ue(gu(),{recursive:!0});let t=Su(e.id);await pe(t,e.line,`utf-8`),await fe(t,xu(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){k(`[spool] 写入失败:`,pu(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>bu()).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,bu()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){k(`[spool] 崩溃前写入失败:`,pu(e))}}}};function Ou(e){let t=Tu(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 ku(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function Au(e){return e.map(ku)}function ju(e){return{text:e,values:[]}}function Mu(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(Mu,{raw:ju}),Nu=Symbol(`ezllm-db:table`);function Pu(e){return e[Nu]}function Fu(e){return`"${e.replaceAll(`"`,`""`)}"`}function Iu(e){return e.map(e=>Fu(e)).join(`, `)}function Lu(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 Lu(`text`)}function H(){return Lu(`integer`)}function Ru(){return Lu(`blob`)}function zu(e){return{on(...t){return{name:e,columns:t}}}}function Bu(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,[Nu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Vu(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=[Fu(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=Iu(t.columns);return`CREATE INDEX IF NOT EXISTS ${Fu(t.name)} ON ${Fu(e)} (${n})`},r=Pu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${Fu(e)})`);let o=[...i,...a].join(`,
23
- `),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${Iu(r.tablePrimaryKey)})`);let c=[`CREATE TABLE IF NOT EXISTS ${Fu(r.name)} (\n${s}\n)`];for(let e of r.indexes)c.push(n(r.name,e));return c.map(e=>`${e};`).join(`
23
+ `).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:fl(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 vl(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 yl=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function bl(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var xl=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=!yl.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}},Sl=67108864,Cl=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??bl({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 wl(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 Cl(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:rl(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let d=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??Sl,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 Tl=3.5,El=8,Dl=24;function Ol(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/Tl)),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,El),i+=t(e.system),i+=t(e.thinking),i+=t(e.output_config),i+=r(e.tools,Dl),{input_tokens:n(i)}}var kl=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}},Al={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function jl(e){let t=new j,n=e.runner??new xl().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??oe(),o=new _l({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 kl({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:Tc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,wl(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=>Ll(e,`openai`)),t.post(`/v1/messages`,e=>Ll(e,`anthropic`)),t.post(`/v1/responses`,e=>Fl(e)),t.post(`/v1/messages/count_tokens`,e=>Il(e)),t.post(`/responses`,e=>Fl(e)),t.post(`/chat/completions`,e=>Ll(e,`openai`)),t.post(`/messages`,e=>Ll(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>Il(e)),t.get(`/v1/models`,e=>Nl(e)),t.get(`/models`,e=>Nl(e)),t}async function Ml(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 Nl(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(bl({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await Ml(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function Pl(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??bl({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||!Uc(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=bl({requestId:a.requestId,inboundProtocol:t.hookProtocol,requestModel:c??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),a.hookCtx=l;let n=await Ml(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=zl(c??``,d)),{body:s,model:c,deployment:d,hookCtx:l})}async function Fl(e){let t=e.get(`gctx`),n=await Pl(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return Rl(e,await Gc(i,Bl(r),t.dispatchCtx))}async function Il(e){let t=await Pl(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(Ol(n))}async function Ll(e,t){let n=(e,t)=>t===`anthropic`?{...e,inbound_format:`anthropic`}:Bl(e),r=e.get(`gctx`),i=r.runner,a=await Pl(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=zl(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&&Uc(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 Rl(e,await Wc(u,n(s.request.body,t),d),{runner:i,hookCtx:c})}let d=n(o,t);return Rl(e,await Wc(u,d,r.dispatchCtx))}async function Rl(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:{...Al}}),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 zl(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function Bl(e){let{inbound_format:t,...n}=e;return n}var Vl=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=ur(e.config),Hl(this._expanded.warnings),this.hookRunner=new xl().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=ur(e),Hl(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(`/`,jl({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return lr}};function Hl(e){for(let t of e)O(`[ezllm] ${t}`)}var Ul=`重启服务(CLI 会重新生成默认配置)`,Wl=class extends Error{constructor(e,t=Tt(),n=Ul){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function Gl(){let e=Tt();if(!p(e))return null;let t;try{t=JSON.parse(g(e,`utf-8`))}catch(t){throw new Wl(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new Wl(`顶层必须是 JSON 对象`,e);return t}function Kl(){try{return Gl()}catch(e){throw e instanceof Wl&&(k(`[ezllm] ${e.message}`),process.exit(1)),e}}function ql(e){Vt(Tt(),e)}function Jl(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function Yl(e){return ur(Jl(e))}var Xl=`0.0.0.0`,Zl=`127.0.0.1`,Ql=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function $l(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function eu(){return $l(Gl())}function tu(){try{return{config:Gl(),broken:!1}}catch(e){if(!(e instanceof Wl))throw e;return{config:null,broken:!0}}}function nu(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 ru(e){let t=e?.[`web-ui`]?.[`login-enabled`];return t===!1?!1:t!==void 0||nu(e)!==void 0}function iu(e){return ru(e)?nu(e):void 0}function au(){let{config:e,broken:t}=tu();if(t)return{required:!0,configBroken:!0,username:``,password:``};if(!ru(e))return{required:!1,configBroken:!1,username:``,password:``};let n=nu(e);return n===void 0?{required:!0,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function ou(){let{config:e,broken:t}=tu();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 su(e){return(e=>$l(e)!==``||iu(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?Xl:Zl,source:`config`}:{hostname:Zl,source:`credentials`}}function cu(){try{return su(Gl())}catch{return su(null)}}function lu(e,t){return su(e).hostname!==su(t).hostname||e?.port!==t.port}function uu(){return Gl()?.logs}function du(e){return typeof e==`number`&&Number.isFinite(e)}function fu(){let e=uu(),t=(e,t)=>du(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function pu(){let e=uu(),t=(e,t)=>du(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 mu=`__blob`,hu=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],gu=1e3,_u=134217728;function vu(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function yu(e){return e instanceof Error?e.message:String(e)}var bu=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function xu(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 Su(){return c(wt(),`spool`)}var Cu=/^(\d+)\.jsonl$/,wu=`.tmp`,Tu=268435456;function Eu(){return new Promise(e=>setImmediate(e))}function Du(e){return c(Su(),`${String(e)}.jsonl`)}function Ou(e){return Du(e)+wu}function ku(){Bt(),m(Su(),{recursive:!0})}function Au(){try{return _(Su()).map(e=>Cu.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function ju(e){let t;try{t=g(Du(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function Mu(){let e=0;try{for(let t of _(Su()))if(t.endsWith(wu))try{S(c(Su(),t)),e++}catch{}}catch{return 0}return e}var Nu=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:Tu}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of _(Su()))if(Cu.test(t))try{e+=x(c(Su(),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 Au()}readRecord(e){return ju(e)}deleteFile(e){try{let t=x(Du(e)).size;S(Du(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){ku();let t=Ou(e.id);C(t,e.line,`utf-8`),v(t,Du(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await ue(Su(),{recursive:!0});let t=Ou(e.id);await pe(t,e.line,`utf-8`),await fe(t,Du(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){k(`[spool] 写入失败:`,yu(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>Eu()).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,Eu()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){k(`[spool] 崩溃前写入失败:`,yu(e))}}}};function Pu(e){let t=ju(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 Fu(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function Iu(e){return e.map(Fu)}function Lu(e){return{text:e,values:[]}}function Ru(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(Ru,{raw:Lu}),zu=Symbol(`ezllm-db:table`);function Bu(e){return e[zu]}function Vu(e){return`"${e.replaceAll(`"`,`""`)}"`}function Hu(e){return e.map(e=>Vu(e)).join(`, `)}function Uu(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 Uu(`text`)}function H(){return Uu(`integer`)}function Wu(){return Uu(`blob`)}function Gu(e){return{on(...t){return{name:e,columns:t}}}}function Ku(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,[zu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function qu(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=[Vu(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=Hu(t.columns);return`CREATE INDEX IF NOT EXISTS ${Vu(t.name)} ON ${Vu(e)} (${n})`},r=Bu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${Vu(e)})`);let o=[...i,...a].join(`,
24
+ `),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${Hu(r.tablePrimaryKey)})`);let c=[`CREATE TABLE IF NOT EXISTS ${Vu(r.name)} (\n${s}\n)`];for(let e of r.indexes)c.push(n(r.name,e));return c.map(e=>`${e};`).join(`
24
25
  `)}).join(`
25
- `)}function Hu(e){return`${Fu(e.meta.table)}.${Fu(e.meta.name)}`}function U(e,t){return{kind:`condition`,text:e,values:t}}function Uu(e,t){return U(`${Hu(e)} = ?`,[t])}function Wu(e,t){return U(`${Hu(e)} <> ?`,[t])}function Gu(e,t){return U(`${Hu(e)} > ?`,[t])}function Ku(e,t){return U(`${Hu(e)} >= ?`,[t])}function qu(e,t){return U(`${Hu(e)} < ?`,[t])}function Ju(e,t){return U(`${Hu(e)} <= ?`,[t])}function Yu(e,t){return U(`${Hu(e)} LIKE ?`,[t])}function Xu(e,t){if(t.length===0)return U(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return U(`${Hu(e)} IN (${n})`,t)}function Zu(e){return U(`${Hu(e)} IS NULL`,[])}function Qu(e){return U(`${Hu(e)} IS NOT NULL`,[])}function $u(e,t,n){return e.length===0?U(n,[]):U(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function ed(...e){return $u(e,`AND`,`1 = 1`)}function td(...e){return $u(e,`OR`,`1 = 0`)}function nd(e){return U(`NOT (${e.text})`,e.values)}function rd(e,t){return{kind:`sort`,text:`${Hu(e)} ${t}`,values:[]}}function id(e){return rd(e,`ASC`)}function ad(e){return rd(e,`DESC`)}function od(e){return{kind:`aggregation`,text:e,values:[]}}function sd(e,t){return od(`${e}(${Hu(t)})`)}function cd(e){return sd(`SUM`,e)}function ld(e){return sd(`MIN`,e)}function ud(e){return sd(`MAX`,e)}function dd(e){return e?sd(`COUNT`,e):od(`COUNT(*)`)}var W={eq:Uu,ne:Wu,gt:Gu,gte:Ku,lt:qu,lte:Ju,like:Yu,in:Xu,isNull:Zu,isNotNull:Qu,and:ed,or:td,not:nd,asc:id,desc:ad,sum:cd,count:dd,min:ld,max:ud},fd=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return Pu(this.table).name}get tableColumns(){return Pu(this.table).columns}get quotedTable(){return Fu(this.tableName)}},pd=class extends fd{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=ed(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},md=class extends pd{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 hd(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var gd=class extends fd{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(ku(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${Iu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=hd(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},_d=class extends pd{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=Iu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${Fu(e)}`).join(`, `);break;default:e=Iu(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=>Hu(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())}},vd=class extends md{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(ku(r)),`${Fu(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},yd=class extends md{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},bd=new Map,xd=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(...Au(t))}}getPrepared(e,t){return e.get(...Au(t))}allPrepared(e,t){return e.all(...Au(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(Vu(e))}insert(e){return new gd(this,e)}select(e){return new _d(this,e)}update(e){return new vd(this,e)}delete(e){return new yd(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(),bd.get(this.name)===this&&bd.delete(this.name))}};function Sd(e){let t=bd.get(e);if(t!==void 0)return t;Bt();let n=new me(c(wt(),`${e}.db`));try{n.exec(`PRAGMA busy_timeout = 5000`),n.exec(`PRAGMA journal_mode = WAL`),n.exec(`PRAGMA journal_size_limit = 67108864`)}catch(e){throw n.close(),e}let r=new xd(e,n);return bd.set(e,r),r}var G=Bu(`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()},[zu(`idx_logs_date`).on(`date`),zu(`idx_logs_time`).on(`time`),zu(`idx_logs_model`).on(`model`),zu(`idx_logs_session`).on(`session_id`),zu(`idx_logs_client`).on(`client`)]),Cd=Bu(`log_details`,{log_id:H().primaryKey(),detail:Ru().notNull()}),wd=Bu(`log_blobs`,{hash:V().primaryKey(),content:Ru().notNull()}),Td=Bu(`log_id_alloc`,{next_id:H().notNull()}),K=Bu(`client_names`,{ua:V().primaryKey(),client:V(),source:V(),attempts:H().notNull().default(0),created_at:V().notNull(),updated_at:V().notNull()}),Ed=[G,Td,K],Dd=[Cd,wd],Od=[[`headers`,`TEXT`],[`client`,`TEXT`],[`ttft`,`INTEGER`]],kd=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${mu})`];function Ad(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 Od)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function jd(e){for(let t of kd)e.exec(t)}var Md=null;function Nd(){return Pd().native}function Pd(){if(Md!==null)return Md;let e=Sd(`logs`);return Ad(e),e.createTables(Ed),jd(e),Md=e,e}function q(){return Pd()}function Fd(e){return q().transaction(e)}var Id=1e3,Ld=!1,Rd=0,zd=0;function Bd(){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(Td).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(Td).values({next_id:r}).run()};if(Rd>=zd){let e=q();Fd(()=>{Ld||=(n(e),!0);let r=e.select(Td).columns([`next_id`]).limit(1).get();Rd=Number(r.next_id),zd=Rd+Id,e.update(Td).set({next_id:zd}).allRows().run(),t(e,zd-1)})}return Rd++}function Vd(e){return he(e,{params:{[_e.BROTLI_PARAM_QUALITY]:9}})}function Hd(e){if(!e)return`-`;if(typeof e==`string`){let t=e.split(`
26
- `).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 Ud(e,t,n=9){let r=(e,t=9)=>{let n=he(Buffer.from(e,`utf-8`),{params:{[_e.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])},i=e=>ie(`sha256`).update(e,`utf-8`).digest(`hex`),a=(e,t)=>{if(typeof e==`string`){if(e.length<8192)return e;let n=i(e);return t.has(n)||t.set(n,e),{[cu]: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:fu(o),preview:Hd(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function Wd(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 Gd(e,t){let n=t.time||new Date().toISOString(),r=fu(n),i=q();return Fd(()=>{i.insert(G).values({id:e,time:n,date:r,preview:Hd(t.response),...Wd(t)}).run()}),e}var Kd=4,qd=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,Jd=/^\d{6}$/;function Yd(){return c(wt(),`details`)}function Xd(e){return c(Yd(),e.slice(0,7).replace(/-/g,``))}function Zd(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function Qd(e){return c(Xd(e),`logs-${e.replace(/-/g,``)}.db`)}var $d=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(Xd(e),{recursive:!0});else if(!p(Qd(e)))return null;let r=Sd(Zd(e));return r.createTables(Dd),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>Kd;){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=_(Yd())}catch{return[]}let t=[];for(let n of e){if(!Jd.test(n))continue;let e;try{e=_(c(Yd(),n))}catch{continue}for(let n of e){let e=qd.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=Qd(e),n=!1;p(t)&&(y(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])y(t+e,{force:!0});try{b(Xd(e))}catch{}return n}};function ef(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){Fd(()=>{for(let e of r)n.insert(G).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...Wd(e.entry)}).orIgnore().run()});let t=$d.open(e);t.transaction(()=>{for(let e of r){t.insert(Cd).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(wd).values({hash:n,content:Vd(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function tf(e){return ge(Buffer.from(e)).toString(`utf-8`)}function nf(e){if(e.length>0&&e[0]===2)return ge(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function rf(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[cu];return typeof n==`string`?n:null}function af(e,t){if(Array.isArray(e))return e.map(e=>af(e,t));if(typeof e==`object`&&e){let n=e,r=rf(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]=af(r,t);return i}return e}function of(e,t){if(Array.isArray(e)){for(let n of e)of(n,t);return}if(typeof e==`object`&&e){let n=e,r=rf(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))of(e,t)}}function sf(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(wd).columns([`hash`,`content`]).where(W.in(wd.hash,i)).all();for(let e of a)n.set(e.hash,tf(e.content))}return n}function cf(e){let t=q().select(G).where(W.eq(G.id,Number(e))).get();if(t===void 0)return null;let n=$d.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(Cd).columns([`detail`]).where(W.eq(Cd.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(nf(i.detail).toString(`utf-8`)),t=new Set;of(e,t),r=af(e,sf(t,n))}catch(e){k(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,pu(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 lf=B.raw(`AVG(CASE WHEN stream = 1 THEN ttft END) AS avg_ttft,
26
+ `)}function Ju(e){return`${Vu(e.meta.table)}.${Vu(e.meta.name)}`}function U(e,t){return{kind:`condition`,text:e,values:t}}function Yu(e,t){return U(`${Ju(e)} = ?`,[t])}function Xu(e,t){return U(`${Ju(e)} <> ?`,[t])}function Zu(e,t){return U(`${Ju(e)} > ?`,[t])}function Qu(e,t){return U(`${Ju(e)} >= ?`,[t])}function $u(e,t){return U(`${Ju(e)} < ?`,[t])}function ed(e,t){return U(`${Ju(e)} <= ?`,[t])}function td(e,t){return U(`${Ju(e)} LIKE ?`,[t])}function nd(e,t){if(t.length===0)return U(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return U(`${Ju(e)} IN (${n})`,t)}function rd(e){return U(`${Ju(e)} IS NULL`,[])}function id(e){return U(`${Ju(e)} IS NOT NULL`,[])}function ad(e,t,n){return e.length===0?U(n,[]):U(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function od(...e){return ad(e,`AND`,`1 = 1`)}function sd(...e){return ad(e,`OR`,`1 = 0`)}function cd(e){return U(`NOT (${e.text})`,e.values)}function ld(e,t){return{kind:`sort`,text:`${Ju(e)} ${t}`,values:[]}}function ud(e){return ld(e,`ASC`)}function dd(e){return ld(e,`DESC`)}function fd(e){return{kind:`aggregation`,text:e,values:[]}}function pd(e,t){return fd(`${e}(${Ju(t)})`)}function md(e){return pd(`SUM`,e)}function hd(e){return pd(`MIN`,e)}function gd(e){return pd(`MAX`,e)}function _d(e){return e?pd(`COUNT`,e):fd(`COUNT(*)`)}var W={eq:Yu,ne:Xu,gt:Zu,gte:Qu,lt:$u,lte:ed,like:td,in:nd,isNull:rd,isNotNull:id,and:od,or:sd,not:cd,asc:ud,desc:dd,sum:md,count:_d,min:hd,max:gd},vd=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return Bu(this.table).name}get tableColumns(){return Bu(this.table).columns}get quotedTable(){return Vu(this.tableName)}},yd=class extends vd{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=od(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},bd=class extends yd{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 xd(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var Sd=class extends vd{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(Fu(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${Hu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=xd(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},Cd=class extends yd{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=Hu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${Vu(e)}`).join(`, `);break;default:e=Hu(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=>Ju(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())}},wd=class extends bd{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(Fu(r)),`${Vu(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},Td=class extends bd{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},Ed=new Map,Dd=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(...Iu(t))}}getPrepared(e,t){return e.get(...Iu(t))}allPrepared(e,t){return e.all(...Iu(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(qu(e))}insert(e){return new Sd(this,e)}select(e){return new Cd(this,e)}update(e){return new wd(this,e)}delete(e){return new Td(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(),Ed.get(this.name)===this&&Ed.delete(this.name))}};function Od(e){let t=Ed.get(e);if(t!==void 0)return t;Bt();let n=new me(c(wt(),`${e}.db`));try{n.exec(`PRAGMA busy_timeout = 5000`),n.exec(`PRAGMA journal_mode = WAL`),n.exec(`PRAGMA journal_size_limit = 67108864`)}catch(e){throw n.close(),e}let r=new Dd(e,n);return Ed.set(e,r),r}var G=Ku(`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()},[Gu(`idx_logs_date`).on(`date`),Gu(`idx_logs_time`).on(`time`),Gu(`idx_logs_model`).on(`model`),Gu(`idx_logs_session`).on(`session_id`),Gu(`idx_logs_client`).on(`client`)]),kd=Ku(`log_details`,{log_id:H().primaryKey(),detail:Wu().notNull()}),Ad=Ku(`log_blobs`,{hash:V().primaryKey(),content:Wu().notNull()}),jd=Ku(`log_id_alloc`,{next_id:H().notNull()}),K=Ku(`client_names`,{ua:V().primaryKey(),client:V(),source:V(),attempts:H().notNull().default(0),created_at:V().notNull(),updated_at:V().notNull()}),Md=[G,jd,K],Nd=[kd,Ad],Pd=[[`headers`,`TEXT`],[`client`,`TEXT`],[`ttft`,`INTEGER`]],Fd=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${bu})`];function Id(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 Pd)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function Ld(e){for(let t of Fd)e.exec(t)}var Rd=null;function zd(){return Bd().native}function Bd(){if(Rd!==null)return Rd;let e=Od(`logs`);return Id(e),e.createTables(Md),Ld(e),Rd=e,e}function q(){return Bd()}function Vd(e){return q().transaction(e)}var Hd=1e3,Ud=!1,Wd=0,Gd=0;function Kd(){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(jd).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(jd).values({next_id:r}).run()};if(Wd>=Gd){let e=q();Vd(()=>{Ud||=(n(e),!0);let r=e.select(jd).columns([`next_id`]).limit(1).get();Wd=Number(r.next_id),Gd=Wd+Hd,e.update(jd).set({next_id:Gd}).allRows().run(),t(e,Gd-1)})}return Wd++}function qd(e){return he(e,{params:{[_e.BROTLI_PARAM_QUALITY]:9}})}function Jd(e){if(!e)return`-`;if(typeof e==`string`){let t=e.split(`
27
+ `).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 Yd(e,t,n=9){let r=(e,t=9)=>{let n=he(Buffer.from(e,`utf-8`),{params:{[_e.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])},i=e=>ie(`sha256`).update(e,`utf-8`).digest(`hex`),a=(e,t)=>{if(typeof e==`string`){if(e.length<8192)return e;let n=i(e);return t.has(n)||t.set(n,e),{[mu]: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:vu(o),preview:Jd(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function Xd(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 Zd(e,t){let n=t.time||new Date().toISOString(),r=vu(n),i=q();return Vd(()=>{i.insert(G).values({id:e,time:n,date:r,preview:Jd(t.response),...Xd(t)}).run()}),e}var Qd=4,$d=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,ef=/^\d{6}$/;function tf(){return c(wt(),`details`)}function nf(e){return c(tf(),e.slice(0,7).replace(/-/g,``))}function rf(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function af(e){return c(nf(e),`logs-${e.replace(/-/g,``)}.db`)}var of=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(nf(e),{recursive:!0});else if(!p(af(e)))return null;let r=Od(rf(e));return r.createTables(Nd),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>Qd;){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=_(tf())}catch{return[]}let t=[];for(let n of e){if(!ef.test(n))continue;let e;try{e=_(c(tf(),n))}catch{continue}for(let n of e){let e=$d.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=af(e),n=!1;p(t)&&(y(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])y(t+e,{force:!0});try{b(nf(e))}catch{}return n}};function sf(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){Vd(()=>{for(let e of r)n.insert(G).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...Xd(e.entry)}).orIgnore().run()});let t=of.open(e);t.transaction(()=>{for(let e of r){t.insert(kd).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(Ad).values({hash:n,content:qd(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function cf(e){return ge(Buffer.from(e)).toString(`utf-8`)}function lf(e){if(e.length>0&&e[0]===2)return ge(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function uf(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[mu];return typeof n==`string`?n:null}function df(e,t){if(Array.isArray(e))return e.map(e=>df(e,t));if(typeof e==`object`&&e){let n=e,r=uf(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]=df(r,t);return i}return e}function ff(e,t){if(Array.isArray(e)){for(let n of e)ff(n,t);return}if(typeof e==`object`&&e){let n=e,r=uf(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))ff(e,t)}}function pf(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(Ad).columns([`hash`,`content`]).where(W.in(Ad.hash,i)).all();for(let e of a)n.set(e.hash,cf(e.content))}return n}function mf(e){let t=q().select(G).where(W.eq(G.id,Number(e))).get();if(t===void 0)return null;let n=of.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(kd).columns([`detail`]).where(W.eq(kd.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(lf(i.detail).toString(`utf-8`)),t=new Set;ff(e,t),r=df(e,pf(t,n))}catch(e){k(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,yu(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 hf=B.raw(`AVG(CASE WHEN stream = 1 THEN ttft END) AS avg_ttft,
27
28
  SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN NULL
28
29
  WHEN stream = 1 THEN duration - ttft
29
30
  ELSE duration END) AS tps_window_ms,
30
31
  SUM(CASE WHEN stream = 1 AND ttft IS NULL THEN 0 ELSE output_tokens END) AS tps_output_tokens,
31
- SUM(CASE WHEN stream = 1 AND ttft IS NOT NULL THEN 1 ELSE 0 END) AS ttft_calls`);function uf(e,t){return e>0&&t>0?Math.round(e*1e3/t*10)/10:null}function df(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:uf(n,o)}function ff(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 pf(e,t){if(!t)return!0;let n=lu.some(t=>RegExp(`^`+t.replace(/%/g,`.*`)+`$`).test(e||``));return t===`model`?n:!n}function mf(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 hf(e){let t=[],n=mf(e);if(n!==null&&t.push(n),e.pathGroup){let n=W.or(...lu.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 gf(e,t){return t===null?e:e.where(t)}function _f(e){return{p:Math.max(parseInt(String(e.page))||1,1),ps:Math.min(Math.max(parseInt(String(e.pageSize))||50,1),500)}}function vf(e){return e===`model`||e===`status`||e===`stream`?e:`time`}var yf={model:G.model,status:G.status,stream:G.stream,time:G.time},bf=[`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 xf(e){let t=e=>{let t=yf[vf(e.sort)];return e.order===`asc`?W.asc(t):W.desc(t)},{p:n,ps:r}=_f(e),i=hf(e),a=q(),o=gf(a.select(G).columns({c:W.count()}),i).get();return{total:o?Number(o.c):0,page:n,pageSize:r,items:gf(a.select(G).columns(bf),i).orderBy(t(e)).limit(r).offset((n-1)*r).all().map(e=>({...e}))}}function Sf(e={}){let t=[W.and(W.isNotNull(G.model),W.ne(G.model,``)),W.eq(G.status,200),W.or(...lu.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`
32
+ SUM(CASE WHEN stream = 1 AND ttft IS NOT NULL THEN 1 ELSE 0 END) AS ttft_calls`);function gf(e,t){return e>0&&t>0?Math.round(e*1e3/t*10)/10:null}function _f(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:gf(n,o)}function vf(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 yf(e,t){if(!t)return!0;let n=hu.some(t=>RegExp(`^`+t.replace(/%/g,`.*`)+`$`).test(e||``));return t===`model`?n:!n}function bf(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 xf(e){let t=[],n=bf(e);if(n!==null&&t.push(n),e.pathGroup){let n=W.or(...hu.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 Sf(e,t){return t===null?e:e.where(t)}function Cf(e){return{p:Math.max(parseInt(String(e.page))||1,1),ps:Math.min(Math.max(parseInt(String(e.pageSize))||50,1),500)}}function wf(e){return e===`model`||e===`status`||e===`stream`?e:`time`}var Tf={model:G.model,status:G.status,stream:G.stream,time:G.time},Ef=[`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 Df(e){let t=e=>{let t=Tf[wf(e.sort)];return e.order===`asc`?W.asc(t):W.desc(t)},{p:n,ps:r}=Cf(e),i=xf(e),a=q(),o=Sf(a.select(G).columns({c:W.count()}),i).get();return{total:o?Number(o.c):0,page:n,pageSize:r,items:Sf(a.select(G).columns(Ef),i).orderBy(t(e)).limit(r).offset((n-1)*r).all().map(e=>({...e}))}}function Of(e={}){let t=[W.and(W.isNotNull(G.model),W.ne(G.model,``)),W.eq(G.status,200),W.or(...hu.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`
32
33
  SELECT model,
33
34
  COUNT(*) AS calls,
34
35
  SUM(input_tokens) AS input_tokens,
@@ -36,12 +37,12 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
36
37
  SUM(cache_read_tokens) AS cache_read_tokens,
37
38
  SUM(cache_creation_tokens) AS cache_creation_tokens,
38
39
  AVG(duration) AS avg_duration,
39
- ${lf}
40
+ ${hf}
40
41
  FROM logs
41
42
  WHERE ${n}
42
43
  GROUP BY model
43
44
  ORDER BY calls DESC
44
- `),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:uf(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:uf(i,a)},models:c}}function Cf(){return q().select(G).columns([`date`]).groupBy(G.date).orderBy(W.desc(G.date)).all().map(e=>e.date)}function wf(){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 Tf=B.raw(`
45
+ `),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:gf(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:gf(i,a)},models:c}}function kf(){return q().select(G).columns([`date`]).groupBy(G.date).orderBy(W.desc(G.date)).all().map(e=>e.date)}function Af(){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 jf=B.raw(`
45
46
  COUNT(*) AS calls,
46
47
  MIN(time) AS first_time,
47
48
  MAX(time) AS last_time,
@@ -52,27 +53,27 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
52
53
  SUM(output_tokens) AS output_tokens,
53
54
  SUM(cache_read_tokens) AS cache_read_tokens,
54
55
  SUM(cache_creation_tokens) AS cache_creation_tokens,
55
- SUM(duration) AS duration`);function Ef(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:uf(Number(e.tps_output_tokens??0),Number(e.tps_window_ms??0))}),{p:n,ps:r}=_f(e),i=hf(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`
56
- SELECT session_id, ${Tf}, ${lf}
56
+ SUM(duration) AS duration`);function Mf(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:gf(Number(e.tps_output_tokens??0),Number(e.tps_window_ms??0))}),{p:n,ps:r}=Cf(e),i=xf(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`
57
+ SELECT session_id, ${jf}, ${hf}
57
58
  FROM logs
58
59
  WHERE ${s}
59
60
  GROUP BY session_id
60
61
  ORDER BY last_time DESC
61
62
  LIMIT ${r} OFFSET ${(n-1)*r}
62
63
  `).map(t),d=l.get(B`
63
- SELECT ${Tf}, ${lf}
64
+ SELECT ${jf}, ${hf}
64
65
  FROM logs
65
66
  WHERE ${c}
66
67
  `),f=d&&Number(d.calls??0)>0?t(d):null,p=l.get(B`
67
68
  SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${s}
68
69
  `),m=l.get(B`
69
70
  SELECT COUNT(*) AS c FROM logs WHERE ${i??W.and()}
70
- `);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var Df=[`id`,`time`,`date`,`model`,`status`,`stream`,`error`,`preview`];function Of(e,t=uu,n=du){let{p:r,ps:i}=_f(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=gf(q().select(G).columns(Df),mf(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=$d.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(Cd).columns([`log_id`,`detail`]).where(W.in(Cd.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=nf(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;of(i,e),m.set(r,e)}else of(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,sf(t,n))}let y=[];for(let{r:t,date:n,raw:r}of p){let i=af(r,v.get(n)??new Map);JSON.stringify(i).toLowerCase().includes(a)&&(!e.model||String(i.model??``).includes(e.model))&&(!e.status||ff(Number(i.status??0),e.status,i.error))&&pf(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=vf(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 kf(e){let t=$d.open(e),n=new Set,r=0,i=0,a=t.select(Cd).columns([`detail`]).all();for(let e of a){r++;try{of(JSON.parse(nf(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(wd).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(wd).where(W.in(wd.hash,o.slice(e,e+400))).run();s+=Number(n.changes)}}),{scanned:r,blobsDeleted:s,skipped:!1}}function Af(e){let t=q(),n=hf(e),r=gf(t.select(G).columns({c:W.count()}),n).get(),i=r?Number(r.c):0,a;if(i>0)a=gf(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=Of({...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=$d.open(e);n.transaction(()=>{for(let e=0;e<t.length;e+=400)n.delete(Cd).where(W.in(Cd.log_id,t.slice(e,e+400))).run()})}Fd(()=>{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{kf(e)}catch(t){O(`[logs] 详情库 ${e} 的 blob 回收失败:`,pu(t))}return a.length}function jf(e,t){let n=e=>fu(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 $d.listDetailDates())e<t&&$d.deleteDetailDb(e)&&r++}let i=0;if(t>0){let e=n(t),r=Fd(()=>q().delete(G).where(W.lt(G.date,e)).run());i=Number(r.changes)}return{detailsDeleted:r,rowsDeleted:i}}var Mf={syncIntervalMs:5e3,payloadQuality:9},Nf=2e3,Pf=1e3,Ff=1e3;function If(e){return q().select(G).columns([`id`]).where(W.eq(G.id,e)).get()!==void 0}var Lf=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 入库失败:`,pu(e))}).finally(()=>{this.#r=!1}))}async syncOnce(e={}){let t=e.budgetMs??Nf,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=Ud(t.entry,e,i.payloadQuality),a=If(e);ef([n]),a||r.anchorFilled++,r.inserted++}catch(t){k(`[spool] 记录 ${String(e)} 入库失败:`,pu(t));continue}this.#e.deleteFile(e),r.filesDone.push(e),await bu()}}return r}async syncNow(){if(this.#n!==null){await this.#n;return}if(!this.#r&&!(Date.now()-this.#i<Ff)){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 启动恢复失败:`,pu(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}},Rf=null;function zf(e){return Rf===null&&(Rf=e===void 0?new Lf({spool:new Du,getConfig:()=>Mf}):new Lf(e)),Rf}function Bf(e){let t=zf(e);return{name:`spoolSync`,everyMs:()=>e.getConfig().syncIntervalMs,firstDelayMs:Pf,run:()=>{t.runScheduledRound()}}}async function Vf(){await zf().syncNow()}async function Hf(){await zf().recover()}async function Uf(e=6e4){return zf().drain(e)}var Wf=216e5,Gf=3e4;function Kf(e){return{name:`logPrune`,everyMs:Wf,firstDelayMs:Gf,run:()=>{try{let{detailDays:t,rowDays:n}=e.getRetention(),r=jf(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] 日志清理失败:`,pu(e))}}}}var qf=3,Jf=`fallback`;function Yf(){return new Date().toISOString()}function Xf(e){return q().select(K).columns([`client`]).where(W.eq(K.ua,e)).get()}function Zf(e){if(e.length===0)return 0;let t=Yf(),n=q(),r=0;return Fd(()=>{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 Qf(){return q().select(K).columns([`ua`,`client`]).where(W.isNotNull(K.client)).all().filter(e=>e.client!==null&&e.client!==``)}function $f(e,t){if(e===``||t===``)return 0;let n=q().run(B`
71
+ `);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var Nf=[`id`,`time`,`date`,`model`,`status`,`stream`,`error`,`preview`];function Pf(e,t=gu,n=_u){let{p:r,ps:i}=Cf(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=Sf(q().select(G).columns(Nf),bf(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=of.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(kd).columns([`log_id`,`detail`]).where(W.in(kd.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=lf(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;ff(i,e),m.set(r,e)}else ff(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,pf(t,n))}let y=[];for(let{r:t,date:n,raw:r}of p){let i=df(r,v.get(n)??new Map);JSON.stringify(i).toLowerCase().includes(a)&&(!e.model||String(i.model??``).includes(e.model))&&(!e.status||vf(Number(i.status??0),e.status,i.error))&&yf(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=wf(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 Ff(e){let t=of.open(e),n=new Set,r=0,i=0,a=t.select(kd).columns([`detail`]).all();for(let e of a){r++;try{ff(JSON.parse(lf(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(Ad).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(Ad).where(W.in(Ad.hash,o.slice(e,e+400))).run();s+=Number(n.changes)}}),{scanned:r,blobsDeleted:s,skipped:!1}}function If(e){let t=q(),n=xf(e),r=Sf(t.select(G).columns({c:W.count()}),n).get(),i=r?Number(r.c):0,a;if(i>0)a=Sf(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=Pf({...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=of.open(e);n.transaction(()=>{for(let e=0;e<t.length;e+=400)n.delete(kd).where(W.in(kd.log_id,t.slice(e,e+400))).run()})}Vd(()=>{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{Ff(e)}catch(t){O(`[logs] 详情库 ${e} 的 blob 回收失败:`,yu(t))}return a.length}function Lf(e,t){let n=e=>vu(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 of.listDetailDates())e<t&&of.deleteDetailDb(e)&&r++}let i=0;if(t>0){let e=n(t),r=Vd(()=>q().delete(G).where(W.lt(G.date,e)).run());i=Number(r.changes)}return{detailsDeleted:r,rowsDeleted:i}}var Rf={syncIntervalMs:5e3,payloadQuality:9},zf=2e3,Bf=1e3,Vf=1e3;function Hf(e){return q().select(G).columns([`id`]).where(W.eq(G.id,e)).get()!==void 0}var Uf=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 入库失败:`,yu(e))}).finally(()=>{this.#r=!1}))}async syncOnce(e={}){let t=e.budgetMs??zf,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=Yd(t.entry,e,i.payloadQuality),a=Hf(e);sf([n]),a||r.anchorFilled++,r.inserted++}catch(t){k(`[spool] 记录 ${String(e)} 入库失败:`,yu(t));continue}this.#e.deleteFile(e),r.filesDone.push(e),await Eu()}}return r}async syncNow(){if(this.#n!==null){await this.#n;return}if(!this.#r&&!(Date.now()-this.#i<Vf)){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 启动恢复失败:`,yu(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}},Wf=null;function Gf(e){return Wf===null&&(Wf=e===void 0?new Uf({spool:new Nu,getConfig:()=>Rf}):new Uf(e)),Wf}function Kf(e){let t=Gf(e);return{name:`spoolSync`,everyMs:()=>e.getConfig().syncIntervalMs,firstDelayMs:Bf,run:()=>{t.runScheduledRound()}}}async function qf(){await Gf().syncNow()}async function Jf(){await Gf().recover()}async function Yf(e=6e4){return Gf().drain(e)}var Xf=216e5,Zf=3e4;function Qf(e){return{name:`logPrune`,everyMs:Xf,firstDelayMs:Zf,run:()=>{try{let{detailDays:t,rowDays:n}=e.getRetention(),r=Lf(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] 日志清理失败:`,yu(e))}}}}var $f=3,ep=`fallback`;function tp(){return new Date().toISOString()}function np(e){return q().select(K).columns([`client`]).where(W.eq(K.ua,e)).get()}function rp(e){if(e.length===0)return 0;let t=tp(),n=q(),r=0;return Vd(()=>{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 ip(){return q().select(K).columns([`ua`,`client`]).where(W.isNotNull(K.client)).all().filter(e=>e.client!==null&&e.client!==``)}function ap(e,t){if(e===``||t===``)return 0;let n=q().run(B`
71
72
  UPDATE logs SET client = ${t}
72
- WHERE client IS NULL AND ${B.raw(mu)} = ${e}
73
- `);return Number(n.changes)}function ep(e){return q().select(K).columns([`ua`]).where(W.and(W.isNull(K.client),W.lt(K.attempts,qf))).orderBy(W.asc(K.created_at)).limit(e).all().map(e=>e.ua)}function tp(e,t){if(e.size===0)return 0;let n=Yf(),r=q(),i=0;return Fd(()=>{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 np(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=Yf();return Fd(()=>{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>=qf&&r.push(e.ua)}}),r}var rp=new Map,ip=new Set;function ap(e){let t=e.trim();if(t===``)return null;if(rp.has(t))return rp.get(t)??null;let n=Xf(t);return n===void 0?(rp.set(t,null),ip.add(t),null):(rp.set(t,n.client),n.client)}function op(e){return(()=>{if(ip.size===0)return 0;let e=Zf([...ip]);return ip.clear(),e})(),ep(e)}function sp(e,t){if(e.size===0)return 0;let n=tp(e,t);for(let[t,n]of e)$f(t,n),rp.set(t,n),ip.delete(t);return n}function cp(e){return np(e)}var lp=100,up=67108864,dp=new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`x-goog-api-key`,`cookie`,`set-cookie`]),fp=new Set([`key`,`apikey`,`accesskey`,`accesstoken`,`token`,`authtoken`,`sig`,`signature`,`secret`,`password`]);function pp(e){let t=e=>e===null?null:e.split(`
73
+ WHERE client IS NULL AND ${B.raw(bu)} = ${e}
74
+ `);return Number(n.changes)}function op(e){return q().select(K).columns([`ua`]).where(W.and(W.isNull(K.client),W.lt(K.attempts,$f))).orderBy(W.asc(K.created_at)).limit(e).all().map(e=>e.ua)}function sp(e,t){if(e.size===0)return 0;let n=tp(),r=q(),i=0;return Vd(()=>{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 cp(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=tp();return Vd(()=>{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>=$f&&r.push(e.ua)}}),r}var lp=new Map,up=new Set;function dp(e){let t=e.trim();if(t===``)return null;if(lp.has(t))return lp.get(t)??null;let n=np(t);return n===void 0?(lp.set(t,null),up.add(t),null):(lp.set(t,n.client),n.client)}function fp(e){return(()=>{if(up.size===0)return 0;let e=rp([...up]);return up.clear(),e})(),op(e)}function pp(e,t){if(e.size===0)return 0;let n=sp(e,t);for(let[t,n]of e)ap(t,n),lp.set(t,n),up.delete(t);return n}function mp(e){return cp(e)}var hp=100,gp=67108864,_p=new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`x-goog-api-key`,`cookie`,`set-cookie`]),vp=new Set([`key`,`apikey`,`accesskey`,`accesstoken`,`token`,`authtoken`,`sig`,`signature`,`secret`,`password`]);function yp(e){let t=e=>e===null?null:e.split(`
74
75
 
75
- `).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))dp.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()))fp.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:ap(e.http.userAgent)}}function mp(e,t){let n=pp(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:Bd();e.write(i,n),Gd(i,n);let a=df({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 hp=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new Du,this.#t=e.queueCapacity??lp,this.#n=e.queueMaxBytes??up}#o(){let e=this.#r.shift();return this.#i-=gp(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await bu();try{mp(this.#e,this.#o())}catch(e){k(`[ezllm] trace 落盘失败:`,pu(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+=gp(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await bu();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{mp(this.#e,this.#o())}catch(e){k(`[ezllm] trace 崩溃前落盘失败:`,pu(e))}this.#e.flushSync()}};function gp(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}var _p=48;function vp(e){let t=e.trim();if(t===``)return``;let n=t.split(/\s+/)[0]??t;return n.length>_p?n.slice(0,_p):n}var yp=500;function bp(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(nf(n.detail).toString(`utf-8`))}catch{return null}},r=q(),i={days:0,scanned:0,filled:0,skipped:0,uas:0,clientsAssigned:0},a=$d.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=$d.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=[],Fd(()=>{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=hu(a);o!==``&&c.add(o),l.length>=yp&&u()}u(),c.size>0&&(i.uas+=Zf([...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 Qf())i.clientsAssigned+=$f(e.ua,e.client);return i}var xp=2e3,Sp=500;function Cp(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 rl(e)}catch{return``}},n=(e,t)=>{t.length!==0&&Fd(()=>{for(let n of t)e.run(B`
76
+ `).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))_p.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()))vp.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:dp(e.http.userAgent)}}function bp(e,t){let n=yp(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:Kd();e.write(i,n),Zd(i,n);let a=_f({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 xp=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new Nu,this.#t=e.queueCapacity??hp,this.#n=e.queueMaxBytes??gp}#o(){let e=this.#r.shift();return this.#i-=Sp(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await Eu();try{bp(this.#e,this.#o())}catch(e){k(`[ezllm] trace 落盘失败:`,yu(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+=Sp(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await Eu();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{bp(this.#e,this.#o())}catch(e){k(`[ezllm] trace 崩溃前落盘失败:`,yu(e))}this.#e.flushSync()}};function Sp(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}var Cp=48;function wp(e){let t=e.trim();if(t===``)return``;let n=t.split(/\s+/)[0]??t;return n.length>Cp?n.slice(0,Cp):n}var Tp=500;function Ep(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(lf(n.detail).toString(`utf-8`))}catch{return null}},r=q(),i={days:0,scanned:0,filled:0,skipped:0,uas:0,clientsAssigned:0},a=of.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=of.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=[],Vd(()=>{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=xu(a);o!==``&&c.add(o),l.length>=Tp&&u()}u(),c.size>0&&(i.uas+=rp([...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 ip())i.clientsAssigned+=ap(e.ua,e.client);return i}var Dp=2e3,Op=500;function kp(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 rl(e)}catch{return``}},n=(e,t)=>{t.length!==0&&Vd(()=>{for(let n of t)e.run(B`
76
77
  UPDATE logs SET session_id = ${n.sessionId}
77
78
  WHERE id = ${n.id} AND (session_id IS NULL OR session_id = '')
78
79
  `)})},r=q(),i={scanned:0,filled:0},a=0;for(;;){let o=r.all(B`
@@ -81,45 +82,45 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
81
82
  AND (session_id IS NULL OR session_id = '')
82
83
  AND headers IS NOT NULL
83
84
  ORDER BY id
84
- LIMIT ${xp}
85
- `);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 wp(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 Tp(e){return gt.port??e.port}async function Ep(e,t,n={}){let r=new Fl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Bd())}});t.register(r),await wp(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 Dp=64;function Op(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>Dp;){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 kp=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 Ap(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var jp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,Mp=`已启用管理台登录但未设置账号密码,请修改配置文件补充凭据或关闭登录开关`,Np=new j;function Pp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}Np.post(`/login`,async e=>{let t=$l();if(t.configBroken)return e.json({error:jp},503);if(t.required&&(t.username===``||t.password===``))return e.json({error:Mp},503);if(!t.required)return e.json({error:`当前未启用管理台登录,管理台免登录访问(如需启用请在设置中打开登录开关)`},400);let n=await Ap(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:Pp(t)})});async function Fp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=$l();if(!n.required)return await t();if(n.configBroken)return e.json({error:jp},401);if(n.username===``||n.password===``)return e.json({error:Mp},503);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==Pp(n))return e.json({error:`token 无效或已过期`},401);await t()}var Ip=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function Lp(e,t){return e instanceof Ip?(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 Rp(e){return async t=>{try{return await e(t)}catch(e){throw new Ip(500,e.message)}}}var zp=8;function Bp(){let e=()=>{let e=zl();if(e===null)throw new Ip(500,`配置文件不存在`);return e},t=new j;return t.onError(Lp),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=eu(),n=!1;try{n=Jl()!==``}catch(e){if(!(e instanceof Rl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:$l().required,version:zt(),buildSource:xt()})}),t.post(`/master-key`,async t=>{if(eu().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await Ap(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<zp)return t.json({error:`主密钥至少 ${String(zp)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return Vl(a),t.json({masterKey:r,...ru(i,a)?{restartHint:Kl}:{}})}),t.post(`/finish`,async t=>{if(eu().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await Ap(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<zp)return t.json({error:`主密钥至少 ${String(zp)} 位`},400);if(r===`server`&&i===``&&Jl()===``)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 Vl(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...ru(c,l)?{restartHint:Kl}:{}})}),t}var Vp=new Map,Hp=1;function Up(){return typeof process.send==`function`}function Wp(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=Hp++;return new Promise((i,a)=>{let o=setTimeout(()=>{Vp.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);Vp.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function Gp(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=Vp.get(t.id);n&&(Vp.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}function Kp(e){let t=new j;return t.onError(Lp),t.get(`/`,Rp(e=>{let t=zl();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Rp(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{Ul(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let a=null;try{a=zl()}catch{a=null}if(Vl(n),e.runtime.rebuild(Hl(n)),Up())try{await Wp(`plugin.sync`)}catch(e){O(`[ezllm] 插件服务同步失败(配置已保存,重启主进程后会按配置恢复):${e instanceof Error?e.message:String(e)}`)}return t.json({message:`配置已保存并生效`,...ru(a,n)?{restartHint:Kl}:{}})})),t}var qp=`直接回复我 ok,不要思考不要解释`;function Jp(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function Yp(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Xp(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 Zp(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=Xp(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 Qp(e){let t=new j;t.onError(Lp);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)),`${Jp(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:Yp(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`,Rp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Rp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Rp(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:qp}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:qp,stream:!0}:{model:e,messages:[{role:`user`,content:qp}],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`,...Yp(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Jp(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 Zp(u,l),url:o,headers:i,payload:s})}function p(e){let t=zl();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=Jl(),i=Tp(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 Zp(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 $p=Bu(`latency_probes`,{id:H().primaryKey({autoIncrement:!0}),model:V().notNull(),time:H().notNull(),latency_ms:H().notNull(),ok:H().notNull(),error:V()},[zu(`idx_latency_probes_model_time`).on(`model`,`time`),zu(`idx_latency_probes_time`).on(`time`)]),em=2592e6,tm=null;function nm(){let e=tm;if(e!==null)return e;let t=Sd(`latency`);return t.createTables([$p]),tm=t,t}function rm(){return nm().native}function im(e){if(e.length!==0)try{nm().insert($p).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 am(){let e=Date.now()-em;return nm().select($p).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(W.gt($p.time,e)).orderBy(W.asc($p.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 om(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=nm().select($p).columns([`time`,`latency_ms`,`ok`]).where(W.and(W.eq($p.model,e),W.gt($p.time,a),W.lte($p.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 sm(){let e=nm().select($p).columns({t:W.max($p.time)}).get();return e?.t==null?null:Number(e.t)}function cm(e){try{let t=Date.now()-e;nm().delete($p).where(W.lte($p.time,t)).run()}catch(e){k(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var lm=3e4,um=4,dm=!1;function fm(){return dm}function pm(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function mm(e){let t=async e=>{let t=Jp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Yp(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:qp}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:qp,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:qp}],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(lm)});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 Zp(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(um,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(dm)return!1;dm=!0;try{let t=await n(pm(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));im(t),cm(em);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{dm=!1}}function hm(e){return pm(e).length}var gm=[{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 _m(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 gm){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 vm(e){let t=new j;return t.get(`/history`,t=>{let n=am(),r=Date.now();return t.json({running:fm(),lastRunAt:sm(),models:_m(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=om(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>fm()?t.json({ok:!1,error:`测试进行中,请稍候`},409):hm(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(mm(e),t.json({ok:!0,running:!0}))),t}function ym(){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(Lp),n.get(`/`,Rp(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 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 bm(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function xm(e,t){let n=bm(e,t);return n===void 0?void 0:e[n]}function Sm(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 Cm(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function wm(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=bm(n.headers,`cookie`);if(e===void 0)continue;let r=Cm(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(bm(e.headers,`cookie`)!==void 0)return e;let n=Cm(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 Tm(e){return e.some(e=>bm(e.headers,`cookie`)!==void 0)}var Em=0xe8d4a51000,Dm=3e4;async function Om(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(Dm)});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 km(e){return e===null||e<=0?null:Math.round(e<Em?e*1e3:e)}function Am(e){return Math.round(e*100)/100}function jm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function Mm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function Nm(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:km(Y(n[t.resetAt])),exceeded:a}}var Pm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await Om(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await Om(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},Fm=`https://api.commandcode.ai`,Im=`/alpha/billing/credits`,Lm=`/alpha/usage/summary`,Rm=`/alpha/billing/subscriptions`,zm={"individual-pro-v1":80,"individual-goat":70},Bm=/^user_[A-Za-z0-9_-]+$/,Vm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function Hm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:jm(t)}]}function Um(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Wm=class extends Pm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=Bm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!Bm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(Fm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(Lm),this.get(Im),this.get(Rm).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:zm[o]??null,c=i===null?null:Y(i.monthlyCredits),l=s===null||c===null?null:{used:Am(Math.max(0,s-c)),cap:s,resetAt:a===null?null:Um(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:Nm(r.fiveHour,Vm),weekly:r===null?null:Nm(r.weekly,Vm),monthly:l,totalTokens:Y(e.totalTokens),totalRuns:Y(e.totalCount),voucherBalance:null,balance:null,extraStats:Hm(l,c)}}},Gm=`https://api.deepseek.com`,Km=`/user/balance`,qm=`余额不足,无法调用 API`;function Jm(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 Ym(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function Xm(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=Jm(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:Jm(e.granted_balance),toppedUp:Jm(e.topped_up_balance)}))}return t}function Zm(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 Qm=class extends Pm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(Gm,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Km),t=Zm(Xm(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=Ym(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${jm(Am(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${jm(Am(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:qm}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:Am(t.total),extraStats:r.length===0?null:r}}},$m=`https://amr-api.open-design.ai`,eh=`ezllm-quota`,th=86400,nh=691200;function rh(e){return{accept:`application/json`,"user-agent":eh,authorization:`Bearer ${e}`}}function ih(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}function ah(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 oh(e){let t=ih(e);if(t!==null)return t;let n=ah(e);return n===null?null:km(n)}function sh(e){let t=J(e);if(t===null)return null;let n=ah(t.usedCredits),r=ah(t.limitCredits);return n===null||r===null?null:{used:n,cap:r,resetAt:oh(t.resetsAt),exceeded:n>=r}}function ch(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=sh(e);if(n===null)continue;let r=ah(J(e)?.durationSeconds)??0;r>0&&r<th?t.fiveHour??=n:r>=th&&r<nh?t.weekly??=n:r>=nh&&(t.monthly??=n)}return t}function lh(e){if(e===null||e.trim()===``)return null;let t=e.trim();return`Design Plan ${t[0].toUpperCase()}${t.slice(1)}`}var uh=class extends Pm{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($m,rh(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=ch(i),o=ah(n.balanceUsd)??ah(r?.balanceUsd??null),s=X(r?.membershipTier??null)??X(e.personalMembershipTier??null),c=[],l=lh(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}}},dh=[`127.0.0.1`,`localhost`,`[::1]`],fh=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function ph(e){let t;try{t=new URL(e)}catch{return null}if(!dh.some(e=>e===t.hostname.toLowerCase()))return null;let n=fh.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 mh(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 hh=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=dh;#e;#t;constructor(e){let t=ph(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await Om(`${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:mh(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},gh=`/api/user/self`,_h=`/api/user/subscription/current_cycle`,vh={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function yh(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 bh(e){return e===null||Y(e.total_count)===null?null:Nm(e,vh)}function xh(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 Sh(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Ch=class extends Pm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=wm(e),n=Sh(t,gh),r=Sh(t,_h);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>xm(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(gh),this.get(_h).catch(()=>null)]),n=bh(yh(e,`credit_5h_limit`)),r=bh(yh(e,`credit_7d_limit`)),i=bh(yh(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:km(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:xh(e),balance:null}}},wh=`GetAgentPlanAFPUsage`,Th=`GetAgentPlanUsageDetails`,Eh=`console.volcengine.com`,Dh=`2024-01-01`,Oh=`cn-beijing`,kh={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function Ah(e){return e.find(e=>e.url.includes(wh))}function jh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Oh}/${Dh}`:t}function Mh(e){return e.find(e=>Cm(e.url)===Eh)}var Nh=class extends Pm{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=wm(e),n=Ah(t)??Mh(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!Tm(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==Eh)throw Error(`非方舟控制台域`);r=e.origin,i=jh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=Sm(xm(n.headers,`cookie`),`csrfToken`)??xm(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}/${wh}`,this.#t=`${i}/${Th}`}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=Nm(e.AFPFiveHour,kh),n=Nm(e.AFPWeekly,kh),r=Nm(e.AFPMonthly,kh);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:Mm(new Date(n)),EndTime:Mm(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}}},Ph=`/api/biz/account/query-customer-account-report`,Fh=`/api/finance/expenseBill/expenseBillListByDay`,Ih=200,Lh=`bigmodel_token_production`;function Rh(e){let t=Sm(xm(e.headers,`cookie`),Lh);if(t!==null&&t.trim()!==``)return t.trim();let n=xm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var zh=class extends Pm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=wm(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=Rh(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=Mm(e).slice(0,7),n=Mm(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(Fh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(Ih)}`),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(Ph),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:Bh(n)}}};function Bh(e){let t=e=>`${jm(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 Vh=[Wm,Qm,uh,Ch,Nh,zh,hh];function Hh(){return Vh}function Uh(e){if(e===void 0)return null;let t=Cm(e);if(t===``)return null;for(let e of Vh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function Wh(e,t){let n=Uh(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 Gh(e){if(e===void 0)return null;let t=Cm(e);if(t===``)return null;for(let e of Vh)if(e.credentialSource===`deviceAuth`&&e.apiHosts?.some(e=>e===t))return e;return null}function Kh(e,t){let n=Gh(t);if(n===null)throw Error(`该供应商未支持授权登录查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);return{vendorId:n.vendorId,vendor:new n(r)}}function qh(e){return e===void 0||ph(e)===null?null:hh}function Jh(e){if(qh(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:hh.vendorId,vendor:new hh(e)}}function Yh(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of wm(e)){let e=Cm(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of Vh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=Cm(t);if(e!==``){for(let t of Vh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of Vh)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=Vh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=Vh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=Uh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var Xh=20,Zh=2e3,Qh=1e4,$h=3e4;function eg(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function tg(e){return e instanceof Error?e.message:String(e)}var ng=class extends Error{constructor(){super(`凭据文件内容异常(非合法 JSON 或形状不符),已拒绝写入以免覆盖现有凭据;请修复或备份后删除该文件`),this.name=`AuthFileCorruptError`}};function rg(e){let t;try{t=g(e,`utf-8`)}catch{throw new ng}let n;try{n=JSON.parse(t)}catch{throw new ng}if(typeof n!=`object`||!n||Array.isArray(n))throw new ng;let r={};for(let[e,t]of Object.entries(n)){if(typeof t!=`object`||!t||Array.isArray(t))throw new ng;r[e]=t}return r}function ig(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 ag(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 og(e,t){return p(e)?e:t.find(e=>p(e))??null}var sg=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=og(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=ig(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:(ag(this.#e,t),this.#u(),this.#r=t,this.#i=this.#e,this.#a=x(this.#e).mtimeMs,{...t})})}#c(){let e=og(this.#e,this.#t);return e===null?{}:rg(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()+$h}catch(e){this.#o=!0,this.#s=Date.now()+$h,this.#n?.(`[auth] 旧凭据文件处理失败(继续只读旧文件,${String($h/1e3)}s 后重试):${tg(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()+Zh;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>Qh&&this.#m(t))continue}catch{}if(Date.now()>r)throw Error(`获取凭据文件锁超时:${o(t)}`);eg(Xh)}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}},cg=new ve;function lg(e,t,n){return cg.run({providerId:e,generation:t},n)}var ug=3e5,dg=864e5,fg=15e3,pg=3e4,mg=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 hg(e){let t=`${String(e?.refresh??``)}\0${String(e?.access??``)}`;return ie(`sha256`).update(t).digest(`hex`).slice(0,16)}function gg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.min(e,dg):ug}function _g(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 vg=class{#e;constructor(e){this.#e=e}clear(e){(this.#e.registry??mg).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=_g(gg(this.#e.leadOf(e)),t);if(!i||r<i)return;let a=this.#r(),o=`${e}\0${hg(t)}`,s=a.failed.get(o);if(s!==void 0){if(r-s<pg)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,fg)})]),clearTimeout(l)}async#t(e,t,n,r){let i=this.#r(),a=this.#e.generation(e);try{let o=await lg(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(hg(s)!==hg(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??mg}},yg=class extends Error{status;constructor(e,t){super(t),this.name=`AuthError`,this.status=e}},bg=class extends Error{constructor(e){super(e),this.name=`AuthFailure`}},xg=2e3,Sg=6e5;function Cg(e){return e instanceof Error?e.message:String(e)}function wg(e){return`auth`in e}function Tg(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 Eg(e,t){let n=[];for(let r of e.prompts??[])typeof r.key!=`string`||r.key===``||r.key in t||Tg(r,t)&&n.push(r);return n}function Dg(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 Og(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 kg(e,t){return t==null||t===``||typeof e.accountId==`string`&&e.accountId!==``?e:{...e,accountId:t}}var Ag=class{#e;#t;#n;#r;#i=new Map;#a=new Set;#o=new Map;#s=new Map;constructor(e){this.#e=new sg({file:e.file,legacyFiles:e.legacyFiles??[],log:e.log}),this.#t=e.now??Date.now,this.#n=e.log,this.#r=new vg({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=cg.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:Og(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 yg(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 yg(400,`未知登录方式:${i}(可选:${r.map(e=>e.label??`(未命名)`).join(`、`)})`);let s=Eg(o,a);if(s.length>0)return{...this.view(e),needInputs:Dg(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 lg(e,l,()=>n.authorize(o,t))}catch(t){if(this.#p(e,l),t instanceof bg)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 yg?t:new yg(502,`起登录流程失败:${Cg(t)}`)}if(wg(u))return this.save(e,kg(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()+Sg;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)},xg);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=Cg(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,kg(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)}},jg=`https://amr-api.open-design.ai`,Mg=`/api/v1/cli/device-authorizations`,Ng=`0.1.4`,Pg=`ezllm-auth`,Fg=6e5,Ig=3e4;function Lg(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Rg(e){return typeof e==`string`?e:null}function zg(e,t){let n=e.error,r=((typeof n==`string`?n:Rg(Lg(n)?.message))??``).replace(/\s+/g,` `).trim();return r===``||r.startsWith(`<`)?t:r.length>160?`${r.slice(0,160)}…`:r}async function Bg(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(Ig)});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=Lg(await n.json());if(r===null)throw Error(`响应不是 JSON 对象`);return r}function Vg(e){let t=Rg(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}async function Hg(){let e=await Bg(`${jg}${Mg}`,{method:`POST`,headers:{accept:`application/json`,"user-agent":Pg},body:JSON.stringify({cliVersion:Ng,host:T()||`ezllm`,profile:`prod`})}),t=Rg(e.deviceId),n=Rg(e.deviceSecret),r=Rg(e.activationUrl);if(t===null||n===null||r===null)throw Error(`授权接口返回缺少必要字段(${zg(e,`device authorization`)})`);let i=Rg(e.userCode),a=Vg(e.expiresAt)??Date.now()+Fg;return{url:r,instructions:`已发起 Open Design 授权${i===null||i===``?``:`(设备码 ${i})`}:在打开的页面确认 CLI 登录,完成后这里会自动继续。`,expiresAt:a,poll:async()=>{let e;try{e=await Bg(`${jg}${Mg}/${encodeURIComponent(t)}/token`,{method:`POST`,headers:{accept:`application/json`,"user-agent":Pg},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=Rg(e.controlKey);if(r!==null&&r!==``){let t=Lg(e.user);return{auth:{type:`api`,key:r},account:t===null?null:Rg(t.email)}}let i=(Rg(e.status)??``).toLowerCase();if([`expired`,`canceled`,`cancelled`,`denied`,`rejected`].includes(i))throw Error(`授权被${i===`expired`?`超时作废`:`拒绝或撤销`},请重新发起`);return null}}}var Ug={id:`opendesign`,priority:50,methods:()=>[{type:`oauth`,label:`登录授权`}],authorize:()=>Hg()},Wg=null;function Gg(){return Wg===null&&(Wg=new Ag({file:kt(),legacyFiles:[At()],adapters:[Ug],log:e=>D(e)})),Wg}function Kg(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function qg(){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:Kg(r)}};try{let t=zl();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 Jg(e){return qg()?.get(e)??null}function Yg(e){let t=Jg(e);if(t===null)return null;let n=Gh(t.apiBase);return n===null?null:n.authKey??e}function Xg(e){let t=Jg(e);return t===null?`key`:Gh(t.apiBase)?.authCredentialField??`key`}var Zg=Ht(`quota.json`);function Qg(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(Zg.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 $g(e,t){Zg.set(e,t)}function e_(e){Zg.get(e)!==void 0&&Zg.set(e,void 0)}function t_(){let e=Zg.getAll(),t={};for(let n of Object.keys(e)){let e=Qg(n);e!==null&&(t[n]=e)}return t}function n_(e,t,n,r){let i=Qg(e);$g(e,{fetchText:i?.fetchText,authCredential:i?.authCredential,authAccount:i?.authAccount,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function r_(e,t){let n=Qg(e);if(n===null){$g(e,{error:t});return}$g(e,{...n,error:t})}var i_=!1;function a_(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function o_(e){let t=Yg(e);if(t===null)return;let n=Gg(),r=n.get(t),i=Xg(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=Qg(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=Qg(e);t!==null&&$g(e,{...t,authCredential:void 0,authAccount:void 0})}}catch{}return u}}function s_(e){return o_(e)!==void 0}async function c_(e){try{let t=Jg(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&qh(t.apiBase)!==null)({vendorId:n,vendor:r}=Jh(t.apiBase));else if(Gh(t.apiBase)!==null){let i=o_(e);if(i===void 0)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);({vendorId:n,vendor:r}=Kh(i,t.apiBase))}else if(Uh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=Wh(t.apiKey,t.apiBase))}else{let i=Qg(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=Yh(i,t.apiBase))}let i=await r.fetchQuota();n_(e,n,i,Date.now())}catch(t){r_(e,a_(t))}return Qg(e)}async function l_(){let e=()=>{let e=qg();return e===null?null:new Set(e.keys())};if(!i_){i_=!0;try{let t=qg(),n=[];for(let[e,r]of t??[]){if(Uh(r.apiBase)!==null||qh(r.apiBase)!==null){n.push(e);continue}Gh(r.apiBase)!==null&&o_(e)!==void 0&&n.push(e)}for(let e of n)await c_(e);let r=e();for(let[e,t]of Object.entries(t_()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){e_(e);continue}n.includes(e)||await c_(e)}}catch(e){k(`[quota] 刷新失败:`,a_(e))}finally{i_=!1}}}var u_=new Set;function d_(e){let t=Yg(e);if(t===null)throw Error(`该供应商未支持授权登录查询额度`);return t}async function f_(e){if(Jg(e)===null)throw Error(`供应商配置不存在(可能已被删除)`);let t=d_(e);u_.delete(e);let n;try{n=await Gg().signIn(t,{restart:!0})}catch(e){throw e instanceof yg?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 p_(e){let t=Yg(e);if(t===null)return{status:`idle`};let n=Gg(),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)&&!s_(e))return{status:`idle`};let i=n.status(t).account??r.accountId??null;return r.state===`success`&&!u_.has(e)?(u_.add(e),{status:`authorized`,account:i,entry:await c_(e)}):{status:`authorized`,account:i,entry:Qg(e)}}function m_(e){let t=Yg(e);t!==null&&Gg().signOut(t),u_.delete(e);let n=Qg(e);return n===null?null:($g(e,{...n,authCredential:void 0,authAccount:void 0,error:void 0}),Qg(e))}function h_(){let e=async e=>{let t=(await Ap(e))?.fetchText;return typeof t==`string`?t:null},t=()=>Hh().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=Yg(e);if(n===null)return t;let r=Gg().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(t_())){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=Jg(r)?.apiBase;if(qh(i)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(Uh(i)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);if(Gh(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=Qg(r);$g(r,{fetchText:a,vendorId:o?.vendorId,snapshot:o?.snapshot,fetchedAt:o?.fetchedAt,error:void 0});let s=await c_(r);return t.json({ok:!0,entry:n(r,s)})}),i.delete(`/:provider`,e=>(e_(e.req.param(`provider`)),e.json({ok:!0}))),i.post(`/:provider/refresh`,async e=>{let t=e.req.param(`provider`),r=await c_(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 f_(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 p_(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=m_(t);return e.json({ok:!0,entry:n(t,r)})}),i}function g_(){let e=new j;return e.get(`/`,e=>e.json({ok:!0,providers:Gg().list()})),e}function __(e){return e===`0.0.0.0`||e===`::`}function v_(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 y_(e,t){let n=new j;return n.get(`/`,n=>n.json({listenPort:Tp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&__(t.hostname)?{lanAddresses:v_()}:{},masterKey:Jl()})),n}var b_=864e5,x_=3e5,S_=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,C_=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;C_.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function w_(){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=C_.get(e);if(!t)return null;let n=t.value.error===void 0?b_:x_;return Date.now()-t.at>=n?(C_.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of C_)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(S_.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return C_.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return C_.set(e,{value:a,at:Date.now()}),n(),a},i=new j;return i.onError(Lp),i.get(`/dates`,e=>{let t=Cf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=wf();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 Ip(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=cf(t);return n||=(await Vf(),cf(t)??Ou(Number(t))),n?e.json({...n,meta:{...n.meta,tps:df(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Rp(async t=>{let n=t.req.query(),r=xf({...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=Of({...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:hu(e.headers),tps:df(e)}))})})),i.get(`/sessions`,Rp(t=>{let n=t.req.query(),r=Ef({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Rp(async t=>{await Uf();let n=wu().length;n>0&&O(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=Af(e(r));return D(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var T_=3e4,E_=9e5,D_=5242880,O_=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],k_=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function A_(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 j_(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(k_.includes(n.toLowerCase())||(t[n]=r));return t}function M_(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?T_:Math.min(Math.floor(e),E_)}function N_(e){if(typeof e!=`string`||e.trim()===``)throw new Ip(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 Ip(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new Ip(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function P_(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function F_(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=D_-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 I_(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function L_(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 Ip(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=A_(l),{text:d,truncated:f}=u?await F_(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:I_(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function R_(){let e=new j;return e.onError(Lp),e.post(`/`,async e=>{let t=await Ap(e);if(t===null)throw new Ip(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!O_.includes(n))throw new Ip(400,`不支持的请求方法:${n}(可用 ${O_.join(` / `)})`);return await L_({url:N_(t.url),method:n,headers:j_(t.headers),body:P_(t.body),timeoutMs:M_(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await L_({url:N_(t.url),method:`GET`,headers:j_(void 0),body:void 0,timeoutMs:M_(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function z_(e){return`http://127.0.0.1:${String(e.port)}`}var B_=`daemon.json`;function V_(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,B_),`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:z_(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 H_=`ezllm-autostart.vbs`,U_=`ezllm-autostart.cmd`,W_=`com.ezllm.autostart`,G_=`ezllm.service`,K_=`autostart.opt-out`,q_=`ezllm-v2`,J_=`Auto-generated by "npx ezllm install" (${q_}). Managed automatically by ezllm. To remove it, run \`npx ezllm uninstall\`.`;function Y_(e){return c(e,K_)}function X_(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),H_)}function Z_(){return c(w(),`Library`,`LaunchAgents`,`${W_}.plist`)}function Q_(){return c(w(),`.config`,`systemd`,`user`,G_)}var $_=3e4;function ev(e,t){return new Promise(n=>{let r=ce(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},$_),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var tv={win32:{itemPath:X_,on:ov,off:lv},darwin:{itemPath:Z_,on:sv,off:uv},linux:{itemPath:Q_,on:cv,off:dv}};function nv(e){return tv[e]??null}function rv(e,t){return[e,t.entryJs,...t.args??[]]}function iv(e){return c(e,`logs`,`autostart.log`)}async function av(e,t,n=ev){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 ov(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=iv(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${J_}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${rv(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
86
- `)},i=e=>[`' ${J_}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
87
- `),a=X_(),o=c(t.appDir,U_);return C(o,r(e,t),`utf-8`),await av(a,`\uFEFF${i(o)}`),a}async function sv(e,t){let n=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),r=(e,t)=>{let r=iv(t.appDir),i=Object.entries(t.env).map(([e,t])=>` <string>${n(e)}</string>\n <string>${n(t)}</string>`).join(`
88
- `),a=rv(e,t).map(e=>` <string>${n(e)}</string>`).join(`
89
- `);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">`,`<!-- ${q_}: launch daemon -->`,`<plist version="1.0">`,`<dict>`,` <key>Label</key><string>${n(W_)}</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(`
90
- `)},i=Z_();C(i,r(e,t),`utf-8`),await ev(`launchctl`,[`unload`,i]);let a=await ev(`launchctl`,[`load`,i]);if(a!==0)throw Error(`launchctl load 失败(退出码 ${String(a)})。请手动执行: launchctl load "${i}"`);return i}async function cv(e,t){let n=(e,t)=>{let n=Object.entries(t.env).map(([e,t])=>`Environment="${e}=${t.replace(/"/g,`\\"`)}"`).join(`
91
- `),r=rv(e,t).map(e=>`"${e.replace(/"/g,`\\"`)}"`).join(` `);return[`[Unit]`,`Description=ezllm autostart (${q_}, launch daemon)`,`After=default.target`,``,`[Service]`,`Type=simple`,`ExecStart=${r}`,n,`Restart=on-failure`,`RestartSec=3`,``,`[Install]`,`WantedBy=default.target`,``].join(`
92
- `)},r=Q_();m(s(r),{recursive:!0}),C(r,n(e,t),`utf-8`);let i=await ev(`systemctl`,[`--user`,`daemon-reload`]);if(i!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(i)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${r}`);let a=await ev(`systemctl`,[`--user`,`enable`,G_]);if(a!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(a)})。请手动执行: systemctl --user enable ${G_}`);return r}async function lv(e){let t=X_(),n=p(t);return y(t,{force:!0}),y(c(e,U_),{force:!0}),n}async function uv(){let e=Z_();return p(e)?(await ev(`launchctl`,[`unload`,e]),y(e,{force:!0}),!0):!1}async function dv(){let e=Q_();return p(e)?(await ev(`systemctl`,[`--user`,`disable`,G_]),y(e,{force:!0}),await ev(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function fv(e,t){if(e.includes(t))return!0;let n=t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);return e.includes(n)?!0:e.includes(t.replace(/"/g,`\\"`))}function pv(e,t){let n=()=>nv(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(q_),a&&t!==void 0){let n=[t.nodePath,t.entryJs,...t.args??[]];if(te()===`win32`){let r=c(t.appDir,U_),i=p(r)?g(r,`utf-8`):``;a=e.includes(r)&&i.includes(q_)&&n.every(e=>fv(i,e))}else a=n.every(t=>fv(e,t))}}catch{}return{platform:te(),enabled:a,itemPath:i,optOut:p(Y_(e))}}var mv=`当前为源码运行模式,更新功能不可用(仅通过 npx ezllm install 装配的实例支持)`,hv=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 npx ezllm update`,gv=9e5;function _v(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()?Up()?null:hv:mv,r=new j;return r.get(`/autostart`,t=>t.json({ok:!0,...pv(e.appDir)})),r.get(`/update`,e=>{let n=Ut(),r=n.pending??null,i=r!==null&&Date.now()-r.startedAt<gv;return e.json({ok:!0,enabled:!0,lastCheck:n.lastCheck??null,lastApply:n.lastApply??null,pendingUpdate:i&&r?r.toVersion:null,supported:t()&&Up(),updating:i})}),r.post(`/update/check`,async e=>{let t=n();if(t)return e.json({ok:!1,error:t},400);let r=await Wp(`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 Wp(`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 vv=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function yv(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=()=>Up()?null:Response.json({ok:!1,error:vv},{status:400}),r=new j;return r.onError(Lp),r.get(`/`,async e=>{let t=n();if(t)return t;let r=await Wp(`svc.list`);return e.json({ok:!0,...r})}),r.post(`/`,async e=>{let r=n();if(r)return r;let i=await Ap(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Wp(`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 Ap(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Wp(`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 Wp(`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 Wp(`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 Wp(`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 Wp(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r}var bv=`服务未由 ezllm 主进程托管(源码运行模式),插件服务不可用;请用 ezllm 启动服务`;function xv(e){let t=()=>Up()?null:Response.json({ok:!1,error:bv},{status:400}),n=new j;return n.onError(Lp),n.get(`/`,async e=>{let n=t();if(n)return n;let r=await Wp(`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 Wp(`plugin.restart`);return e.json({ok:!0,available:!0,...r})}),n}function Sv(e){let t=`${e}.ellm-bak`;return!p(t)&&(p(e)&&f(e,t),!0)}function Cv(e){let t=`${e}.ellm-bak`;return p(t)?(f(t,e),y(t,{force:!0}),!0):!1}function wv(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var Tv=c(w(),`.claude`,`settings.json`);function Ev(){if(!p(Tv))return null;try{return JSON.parse(g(Tv,`utf-8`))}catch(e){throw Error(`${Tv} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function Dv(e){let t=Ev();return t?wv(t?.env?.ANTHROPIC_BASE_URL,e):!1}function Ov(e){m(s(Tv),{recursive:!0});let t=Ev()??{};Sv(Tv),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,C(Tv,JSON.stringify(t,null,2)+`
93
- `,`utf-8`)}function kv(e){if(Cv(Tv))return!0;let t=Ev();return!t||!wv(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(Tv,JSON.stringify(t,null,2)+`
94
- `,`utf-8`),!0)}var Av=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,jv=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(Av);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 Mv(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Nv(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+=`
85
+ LIMIT ${Dp}
86
+ `);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>=Op&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function Ap(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 jp(e){return gt.port??e.port}async function Mp(e,t,n={}){let r=new Vl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Kd())}});t.register(r),await Ap(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 Np=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>Np;){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 Fp=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 Ip(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var Lp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,Rp=`已启用管理台登录但未设置账号密码,请修改配置文件补充凭据或关闭登录开关`,zp=new j;function Bp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}zp.post(`/login`,async e=>{let t=au();if(t.configBroken)return e.json({error:Lp},503);if(t.required&&(t.username===``||t.password===``))return e.json({error:Rp},503);if(!t.required)return e.json({error:`当前未启用管理台登录,管理台免登录访问(如需启用请在设置中打开登录开关)`},400);let n=await Ip(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:Bp(t)})});async function Vp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=au();if(!n.required)return await t();if(n.configBroken)return e.json({error:Lp},401);if(n.username===``||n.password===``)return e.json({error:Rp},503);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==Bp(n))return e.json({error:`token 无效或已过期`},401);await t()}var Hp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function Up(e,t){return e instanceof Hp?(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 Wp(e){return async t=>{try{return await e(t)}catch(e){throw new Hp(500,e.message)}}}var Gp=8;function Kp(){let e=()=>{let e=Gl();if(e===null)throw new Hp(500,`配置文件不存在`);return e},t=new j;return t.onError(Up),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=ou(),n=!1;try{n=eu()!==``}catch(e){if(!(e instanceof Wl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:au().required,version:zt(),buildSource:xt()})}),t.post(`/master-key`,async t=>{if(ou().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await Ip(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<Gp)return t.json({error:`主密钥至少 ${String(Gp)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return ql(a),t.json({masterKey:r,...lu(i,a)?{restartHint:Ql}:{}})}),t.post(`/finish`,async t=>{if(ou().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await Ip(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<Gp)return t.json({error:`主密钥至少 ${String(Gp)} 位`},400);if(r===`server`&&i===``&&eu()===``)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 ql(l),t.json({message:s?`初始化完成,请使用新账号登录`:`初始化完成`,...lu(c,l)?{restartHint:Ql}:{}})}),t}var qp=new Map,Jp=1;function Yp(){return typeof process.send==`function`}function Xp(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=Jp++;return new Promise((i,a)=>{let o=setTimeout(()=>{qp.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);qp.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function Zp(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=qp.get(t.id);n&&(qp.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}function Qp(e){let t=new j;return t.onError(Up),t.get(`/`,Wp(e=>{let t=Gl();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Wp(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{Yl(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let a=null;try{a=Gl()}catch{a=null}if(ql(n),e.runtime.rebuild(Jl(n)),Yp())try{await Xp(`plugin.sync`)}catch(e){O(`[ezllm] 插件服务同步失败(配置已保存,重启主进程后会按配置恢复):${e instanceof Error?e.message:String(e)}`)}return t.json({message:`配置已保存并生效`,...lu(a,n)?{restartHint:Ql}:{}})})),t}var $p=`直接回复我 ok,不要思考不要解释`;function em(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function tm(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function nm(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 rm(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=nm(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 im(e){let t=new j;t.onError(Up);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)),`${em(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:tm(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`,Wp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Wp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Wp(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:$p}],max_tokens:16,stream:!0}:t===`openai-responses`?{model:e,input:$p,stream:!0}:{model:e,messages:[{role:`user`,content:$p}],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`,...tm(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${em(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 rm(u,l),url:o,headers:i,payload:s})}function p(e){let t=Gl();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=eu(),i=jp(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 rm(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 am=Ku(`latency_probes`,{id:H().primaryKey({autoIncrement:!0}),model:V().notNull(),time:H().notNull(),latency_ms:H().notNull(),ok:H().notNull(),error:V()},[Gu(`idx_latency_probes_model_time`).on(`model`,`time`),Gu(`idx_latency_probes_time`).on(`time`)]),om=2592e6,sm=null;function cm(){let e=sm;if(e!==null)return e;let t=Od(`latency`);return t.createTables([am]),sm=t,t}function lm(){return cm().native}function um(e){if(e.length!==0)try{cm().insert(am).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 dm(){let e=Date.now()-om;return cm().select(am).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(W.gt(am.time,e)).orderBy(W.asc(am.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 fm(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=cm().select(am).columns([`time`,`latency_ms`,`ok`]).where(W.and(W.eq(am.model,e),W.gt(am.time,a),W.lte(am.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 pm(){let e=cm().select(am).columns({t:W.max(am.time)}).get();return e?.t==null?null:Number(e.t)}function mm(e){try{let t=Date.now()-e;cm().delete(am).where(W.lte(am.time,t)).run()}catch(e){k(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var hm=3e4,gm=4,_m=!1;function vm(){return _m}function ym(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function bm(e){let t=async e=>{let t=em((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?tm(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:$p}],max_tokens:1,stream:!0}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:$p,max_output_tokens:16,stream:!0}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:$p}],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(hm)});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 rm(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(gm,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(_m)return!1;_m=!0;try{let t=await n(ym(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));um(t),mm(om);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{_m=!1}}function xm(e){return ym(e).length}var Sm=[{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 Cm(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 Sm){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 wm(e){let t=new j;return t.get(`/history`,t=>{let n=dm(),r=Date.now();return t.json({running:vm(),lastRunAt:pm(),models:Cm(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=fm(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>vm()?t.json({ok:!1,error:`测试进行中,请稍候`},409):xm(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(bm(e),t.json({ok:!0,running:!0}))),t}function Tm(){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(Up),n.get(`/`,Wp(e=>{let n=e.req.query(),r=Of({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 Em(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function Dm(e,t){let n=Em(e,t);return n===void 0?void 0:e[n]}function Om(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 km(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=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=Em(n.headers,`cookie`);if(e===void 0)continue;let r=km(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(Em(e.headers,`cookie`)!==void 0)return e;let n=km(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 jm(e){return e.some(e=>Em(e.headers,`cookie`)!==void 0)}var Mm=0xe8d4a51000,Nm=3e4;async function Pm(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(Nm)});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 Fm(e){return e===null||e<=0?null:Math.round(e<Mm?e*1e3:e)}function Im(e){return Math.round(e*100)/100}function Lm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function Rm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function zm(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:Fm(Y(n[t.resetAt])),exceeded:a}}var Bm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await Pm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await Pm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},Vm=`https://api.commandcode.ai`,Hm=`/alpha/billing/credits`,Um=`/alpha/usage/summary`,Wm=`/alpha/billing/subscriptions`,Gm={"individual-pro-v1":80,"individual-goat":70},Km=/^user_[A-Za-z0-9_-]+$/,qm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function Jm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:Lm(t)}]}function Ym(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Xm=class extends Bm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=Km;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!Km.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(Vm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(Um),this.get(Hm),this.get(Wm).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:Gm[o]??null,c=i===null?null:Y(i.monthlyCredits),l=s===null||c===null?null:{used:Im(Math.max(0,s-c)),cap:s,resetAt:a===null?null:Ym(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:zm(r.fiveHour,qm),weekly:r===null?null:zm(r.weekly,qm),monthly:l,totalTokens:Y(e.totalTokens),totalRuns:Y(e.totalCount),voucherBalance:null,balance:null,extraStats:Jm(l,c)}}},Zm=`https://api.deepseek.com`,Qm=`/user/balance`,$m=`余额不足,无法调用 API`;function eh(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 th(e){return e===`CNY`?`元`:e===`USD`?`美元`:e}function nh(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=eh(e.total_balance);o!==null&&(n.add(a),t.push({currency:a,total:o,granted:eh(e.granted_balance),toppedUp:eh(e.topped_up_balance)}))}return t}function rh(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 ih=class extends Bm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static apiHosts=[`api.deepseek.com`];static credentialSource=`apiKey`;constructor(e){super(Zm,{authorization:`Bearer ${e}`,accept:`application/json`})}async fetchQuota(){let e=await this.get(Qm),t=rh(nh(e.balance_infos));if(t===null)throw Error(`上游未返回余额数据(响应缺少 balance_infos,或各行的 total_balance 不可解析)`);let n=th(t.currency),r=[];return t.toppedUp!==null&&r.push({label:`充值余额`,value:`${Lm(Im(t.toppedUp))} ${n}`}),t.granted!==null&&r.push({label:`赠送余额`,value:`${Lm(Im(t.granted))} ${n}`}),e.is_available===!1&&r.push({label:`账户状态`,value:$m}),{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:Im(t.total),extraStats:r.length===0?null:r}}},ah=`https://amr-api.open-design.ai`,oh=`ezllm-quota`,sh=86400,ch=691200;function lh(e){return{accept:`application/json`,"user-agent":oh,authorization:`Bearer ${e}`}}function uh(e){let t=X(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}function dh(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 fh(e){let t=uh(e);if(t!==null)return t;let n=dh(e);return n===null?null:Fm(n)}function ph(e){let t=J(e);if(t===null)return null;let n=dh(t.usedCredits),r=dh(t.limitCredits);return n===null||r===null?null:{used:n,cap:r,resetAt:fh(t.resetsAt),exceeded:n>=r}}function mh(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=ph(e);if(n===null)continue;let r=dh(J(e)?.durationSeconds)??0;r>0&&r<sh?t.fiveHour??=n:r>=sh&&r<ch?t.weekly??=n:r>=ch&&(t.monthly??=n)}return t}function hh(e){if(e===null||e.trim()===``)return null;let t=e.trim();return`Design Plan ${t[0].toUpperCase()}${t.slice(1)}`}var gh=class extends Bm{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(ah,lh(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=mh(i),o=dh(n.balanceUsd)??dh(r?.balanceUsd??null),s=X(r?.membershipTier??null)??X(e.personalMembershipTier??null),c=[],l=hh(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}}},_h=[`127.0.0.1`,`localhost`,`[::1]`],vh=/^\/p\/([^/]+)(?:\/v1)?\/?$/;function yh(e){let t;try{t=new URL(e)}catch{return null}if(!_h.some(e=>e===t.hostname.toLowerCase()))return null;let n=vh.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 bh(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 xh=class{static vendorId=`pluginHost`;static vendorLabel=`插件(OpenCode 插件宿主)`;static credentialSource=`pluginHost`;static matchMode=`loopbackPath`;static pathPrefix=`/p/`;static apiHosts=_h;#e;#t;constructor(e){let t=yh(e);if(t===null)throw Error(`不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径):${e}`);this.#e=t.origin,this.#t=t.providerId}async fetchQuota(){let e=await Pm(`${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:bh(e.windows),...n!==null&&n.trim()!==``?{extraStats:[{label:`套餐`,value:n}]}:{}}}},Sh=`/api/user/self`,Ch=`/api/user/subscription/current_cycle`,wh={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Th(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 Eh(e){return e===null||Y(e.total_count)===null?null:zm(e,wh)}function Dh(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 Oh(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var kh=class extends Bm{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=Oh(t,Sh),r=Oh(t,Ch);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>Dm(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(Sh),this.get(Ch).catch(()=>null)]),n=Eh(Th(e,`credit_5h_limit`)),r=Eh(Th(e,`credit_7d_limit`)),i=Eh(Th(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:Fm(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:Dh(e),balance:null}}},Ah=`GetAgentPlanAFPUsage`,jh=`GetAgentPlanUsageDetails`,Mh=`console.volcengine.com`,Nh=`2024-01-01`,Ph=`cn-beijing`,Fh={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function Ih(e){return e.find(e=>e.url.includes(Ah))}function Lh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Ph}/${Nh}`:t}function Rh(e){return e.find(e=>km(e.url)===Mh)}var zh=class extends Bm{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=Ih(t)??Rh(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!jm(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==Mh)throw Error(`非方舟控制台域`);r=e.origin,i=Lh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=Om(Dm(n.headers,`cookie`),`csrfToken`)??Dm(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}/${Ah}`,this.#t=`${i}/${jh}`}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=zm(e.AFPFiveHour,Fh),n=zm(e.AFPWeekly,Fh),r=zm(e.AFPMonthly,Fh);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:Rm(new Date(n)),EndTime:Rm(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}}},Bh=`/api/biz/account/query-customer-account-report`,Vh=`/api/finance/expenseBill/expenseBillListByDay`,Hh=200,Uh=`bigmodel_token_production`;function Wh(e){let t=Om(Dm(e.headers,`cookie`),Uh);if(t!==null&&t.trim()!==``)return t.trim();let n=Dm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var Gh=class extends Bm{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=Wh(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=Rm(e).slice(0,7),n=Rm(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(Vh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(Hh)}`),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(Bh),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:Kh(n)}}};function Kh(e){let t=e=>`${Lm(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 qh=[Xm,ih,gh,kh,zh,Gh,xh];function Jh(){return qh}function Yh(e){if(e===void 0)return null;let t=km(e);if(t===``)return null;for(let e of qh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function Xh(e,t){let n=Yh(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 Zh(e){if(e===void 0)return null;let t=km(e);if(t===``)return null;for(let e of qh)if(e.credentialSource===`deviceAuth`&&e.apiHosts?.some(e=>e===t))return e;return null}function Qh(e,t){let n=Zh(t);if(n===null)throw Error(`该供应商未支持授权登录查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);return{vendorId:n.vendorId,vendor:new n(r)}}function $h(e){return e===void 0||yh(e)===null?null:xh}function eg(e){if($h(e)===null)throw Error(`apiBase 不是插件宿主地址(须为回环 host 下的 /p/<插件名> 路径,如 http://127.0.0.1:29772/p/workbuddy):${e}`);return{vendorId:xh.vendorId,vendor:new xh(e)}}function tg(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of Am(e)){let e=km(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of qh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=km(t);if(e!==``){for(let t of qh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of qh)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=qh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=qh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=Yh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var ng=20,rg=2e3,ig=1e4,ag=3e4;function og(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function sg(e){return e instanceof Error?e.message:String(e)}var cg=class extends Error{constructor(){super(`凭据文件内容异常(非合法 JSON 或形状不符),已拒绝写入以免覆盖现有凭据;请修复或备份后删除该文件`),this.name=`AuthFileCorruptError`}};function lg(e){let t;try{t=g(e,`utf-8`)}catch{throw new cg}let n;try{n=JSON.parse(t)}catch{throw new cg}if(typeof n!=`object`||!n||Array.isArray(n))throw new cg;let r={};for(let[e,t]of Object.entries(n)){if(typeof t!=`object`||!t||Array.isArray(t))throw new cg;r[e]=t}return r}function ug(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 dg(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 fg(e,t){return p(e)?e:t.find(e=>p(e))??null}var pg=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=fg(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=ug(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:(dg(this.#e,t),this.#u(),this.#r=t,this.#i=this.#e,this.#a=x(this.#e).mtimeMs,{...t})})}#c(){let e=fg(this.#e,this.#t);return e===null?{}:lg(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()+ag}catch(e){this.#o=!0,this.#s=Date.now()+ag,this.#n?.(`[auth] 旧凭据文件处理失败(继续只读旧文件,${String(ag/1e3)}s 后重试):${sg(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()+rg;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>ig&&this.#m(t))continue}catch{}if(Date.now()>r)throw Error(`获取凭据文件锁超时:${o(t)}`);og(ng)}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}},mg=new ve;function hg(e,t,n){return mg.run({providerId:e,generation:t},n)}var gg=3e5,_g=864e5,vg=15e3,yg=3e4,bg=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 xg(e){let t=`${String(e?.refresh??``)}\0${String(e?.access??``)}`;return ie(`sha256`).update(t).digest(`hex`).slice(0,16)}function Sg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.min(e,_g):gg}function Cg(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 wg=class{#e;constructor(e){this.#e=e}clear(e){(this.#e.registry??bg).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=Cg(Sg(this.#e.leadOf(e)),t);if(!i||r<i)return;let a=this.#r(),o=`${e}\0${xg(t)}`,s=a.failed.get(o);if(s!==void 0){if(r-s<yg)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,vg)})]),clearTimeout(l)}async#t(e,t,n,r){let i=this.#r(),a=this.#e.generation(e);try{let o=await hg(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(xg(s)!==xg(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??bg}},Tg=class extends Error{status;constructor(e,t){super(t),this.name=`AuthError`,this.status=e}},Eg=class extends Error{constructor(e){super(e),this.name=`AuthFailure`}},Dg=2e3,Og=6e5;function kg(e){return e instanceof Error?e.message:String(e)}function Ag(e){return`auth`in e}function jg(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 Mg(e,t){let n=[];for(let r of e.prompts??[])typeof r.key!=`string`||r.key===``||r.key in t||jg(r,t)&&n.push(r);return n}function Ng(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 Pg(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 Fg(e,t){return t==null||t===``||typeof e.accountId==`string`&&e.accountId!==``?e:{...e,accountId:t}}var Ig=class{#e;#t;#n;#r;#i=new Map;#a=new Set;#o=new Map;#s=new Map;constructor(e){this.#e=new pg({file:e.file,legacyFiles:e.legacyFiles??[],log:e.log}),this.#t=e.now??Date.now,this.#n=e.log,this.#r=new wg({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=mg.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:Pg(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 Tg(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 Tg(400,`未知登录方式:${i}(可选:${r.map(e=>e.label??`(未命名)`).join(`、`)})`);let s=Mg(o,a);if(s.length>0)return{...this.view(e),needInputs:Ng(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 hg(e,l,()=>n.authorize(o,t))}catch(t){if(this.#p(e,l),t instanceof Eg)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 Tg?t:new Tg(502,`起登录流程失败:${kg(t)}`)}if(Ag(u))return this.save(e,Fg(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()+Og;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)},Dg);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=kg(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,Fg(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)}},Lg=`https://amr-api.open-design.ai`,Rg=`/api/v1/cli/device-authorizations`,zg=`0.1.4`,Bg=`ezllm-auth`,Vg=6e5,Hg=3e4;function Ug(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Wg(e){return typeof e==`string`?e:null}function Gg(e,t){let n=e.error,r=((typeof n==`string`?n:Wg(Ug(n)?.message))??``).replace(/\s+/g,` `).trim();return r===``||r.startsWith(`<`)?t:r.length>160?`${r.slice(0,160)}…`:r}async function Kg(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(Hg)});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=Ug(await n.json());if(r===null)throw Error(`响应不是 JSON 对象`);return r}function qg(e){let t=Wg(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}async function Jg(){let e=await Kg(`${Lg}${Rg}`,{method:`POST`,headers:{accept:`application/json`,"user-agent":Bg},body:JSON.stringify({cliVersion:zg,host:T()||`ezllm`,profile:`prod`})}),t=Wg(e.deviceId),n=Wg(e.deviceSecret),r=Wg(e.activationUrl);if(t===null||n===null||r===null)throw Error(`授权接口返回缺少必要字段(${Gg(e,`device authorization`)})`);let i=Wg(e.userCode),a=qg(e.expiresAt)??Date.now()+Vg;return{url:r,instructions:`已发起 Open Design 授权${i===null||i===``?``:`(设备码 ${i})`}:在打开的页面确认 CLI 登录,完成后这里会自动继续。`,expiresAt:a,poll:async()=>{let e;try{e=await Kg(`${Lg}${Rg}/${encodeURIComponent(t)}/token`,{method:`POST`,headers:{accept:`application/json`,"user-agent":Bg},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=Wg(e.controlKey);if(r!==null&&r!==``){let t=Ug(e.user);return{auth:{type:`api`,key:r},account:t===null?null:Wg(t.email)}}let i=(Wg(e.status)??``).toLowerCase();if([`expired`,`canceled`,`cancelled`,`denied`,`rejected`].includes(i))throw Error(`授权被${i===`expired`?`超时作废`:`拒绝或撤销`},请重新发起`);return null}}}var Yg={id:`opendesign`,priority:50,methods:()=>[{type:`oauth`,label:`登录授权`}],authorize:()=>Jg()},Xg=null;function Zg(){return Xg===null&&(Xg=new Ig({file:kt(),legacyFiles:[At()],adapters:[Yg],log:e=>D(e)})),Xg}function Qg(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function $g(){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:Qg(r)}};try{let t=Gl();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 e_(e){return $g()?.get(e)??null}function t_(e){let t=e_(e);if(t===null)return null;let n=Zh(t.apiBase);return n===null?null:n.authKey??e}function n_(e){let t=e_(e);return t===null?`key`:Zh(t.apiBase)?.authCredentialField??`key`}var r_=Ht(`quota.json`);function i_(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(r_.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 a_(e,t){r_.set(e,t)}function o_(e){r_.get(e)!==void 0&&r_.set(e,void 0)}function s_(){let e=r_.getAll(),t={};for(let n of Object.keys(e)){let e=i_(n);e!==null&&(t[n]=e)}return t}function c_(e,t,n,r){let i=i_(e);a_(e,{fetchText:i?.fetchText,authCredential:i?.authCredential,authAccount:i?.authAccount,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function l_(e,t){let n=i_(e);if(n===null){a_(e,{error:t});return}a_(e,{...n,error:t})}var u_=!1;function d_(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function f_(e){let t=t_(e);if(t===null)return;let n=Zg(),r=n.get(t),i=n_(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=i_(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=i_(e);t!==null&&a_(e,{...t,authCredential:void 0,authAccount:void 0})}}catch{}return u}}function p_(e){return f_(e)!==void 0}async function m_(e){try{let t=e_(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(t.apiBase!==void 0&&$h(t.apiBase)!==null)({vendorId:n,vendor:r}=eg(t.apiBase));else if(Zh(t.apiBase)!==null){let i=f_(e);if(i===void 0)throw Error(`尚未授权登录,无法查询额度——请在供应商卡片点「登录授权」`);({vendorId:n,vendor:r}=Qh(i,t.apiBase))}else if(Yh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=Xh(t.apiKey,t.apiBase))}else{let i=i_(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=tg(i,t.apiBase))}let i=await r.fetchQuota();c_(e,n,i,Date.now())}catch(t){l_(e,d_(t))}return i_(e)}async function h_(){let e=()=>{let e=$g();return e===null?null:new Set(e.keys())};if(!u_){u_=!0;try{let t=$g(),n=[];for(let[e,r]of t??[]){if(Yh(r.apiBase)!==null||$h(r.apiBase)!==null){n.push(e);continue}Zh(r.apiBase)!==null&&f_(e)!==void 0&&n.push(e)}for(let e of n)await m_(e);let r=e();for(let[e,t]of Object.entries(s_()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){o_(e);continue}n.includes(e)||await m_(e)}}catch(e){k(`[quota] 刷新失败:`,d_(e))}finally{u_=!1}}}var g_=new Set;function __(e){let t=t_(e);if(t===null)throw Error(`该供应商未支持授权登录查询额度`);return t}async function v_(e){if(e_(e)===null)throw Error(`供应商配置不存在(可能已被删除)`);let t=__(e);g_.delete(e);let n;try{n=await Zg().signIn(t,{restart:!0})}catch(e){throw e instanceof Tg?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 y_(e){let t=t_(e);if(t===null)return{status:`idle`};let n=Zg(),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)&&!p_(e))return{status:`idle`};let i=n.status(t).account??r.accountId??null;return r.state===`success`&&!g_.has(e)?(g_.add(e),{status:`authorized`,account:i,entry:await m_(e)}):{status:`authorized`,account:i,entry:i_(e)}}function b_(e){let t=t_(e);t!==null&&Zg().signOut(t),g_.delete(e);let n=i_(e);return n===null?null:(a_(e,{...n,authCredential:void 0,authAccount:void 0,error:void 0}),i_(e))}function x_(){let e=async e=>{let t=(await Ip(e))?.fetchText;return typeof t==`string`?t:null},t=()=>Jh().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=t_(e);if(n===null)return t;let r=Zg().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(s_())){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=e_(r)?.apiBase;if($h(i)!==null)return t.json({ok:!1,error:`该供应商的额度由插件服务查询,无需手动配置`},400);if(Yh(i)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);if(Zh(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=i_(r);a_(r,{fetchText:a,vendorId:o?.vendorId,snapshot:o?.snapshot,fetchedAt:o?.fetchedAt,error:void 0});let s=await m_(r);return t.json({ok:!0,entry:n(r,s)})}),i.delete(`/:provider`,e=>(o_(e.req.param(`provider`)),e.json({ok:!0}))),i.post(`/:provider/refresh`,async e=>{let t=e.req.param(`provider`),r=await m_(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 v_(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 y_(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=b_(t);return e.json({ok:!0,entry:n(t,r)})}),i}function S_(){let e=new j;return e.get(`/`,e=>e.json({ok:!0,providers:Zg().list()})),e}function C_(e){return e===`0.0.0.0`||e===`::`}function w_(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 T_(e,t){let n=new j;return n.get(`/`,n=>n.json({listenPort:jp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&C_(t.hostname)?{lanAddresses:w_()}:{},masterKey:eu()})),n}var E_=864e5,D_=3e5,O_=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,k_=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;k_.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function A_(){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=k_.get(e);if(!t)return null;let n=t.value.error===void 0?E_:D_;return Date.now()-t.at>=n?(k_.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of k_)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(O_.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return k_.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return k_.set(e,{value:a,at:Date.now()}),n(),a},i=new j;return i.onError(Up),i.get(`/dates`,e=>{let t=kf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=Af();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 Hp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=mf(t);return n||=(await qf(),mf(t)??Pu(Number(t))),n?e.json({...n,meta:{...n.meta,tps:_f(n.meta)}}):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Wp(async t=>{let n=t.req.query(),r=Df({...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:xu(e.headers),tps:_f(e)}))})})),i.get(`/sessions`,Wp(t=>{let n=t.req.query(),r=Mf({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Wp(async t=>{await Yf();let n=Au().length;n>0&&O(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=If(e(r));return D(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var j_=3e4,M_=9e5,N_=5242880,P_=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`],F_=[`host`,`content-length`,`connection`,`keep-alive`,`transfer-encoding`,`upgrade`,`te`,`trailer`,`proxy-authorization`,`proxy-connection`];function I_(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 L_(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(F_.includes(n.toLowerCase())||(t[n]=r));return t}function R_(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?j_:Math.min(Math.floor(e),M_)}function z_(e){if(typeof e!=`string`||e.trim()===``)throw new Hp(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 Hp(400,`不是合法的 URL:${t}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw new Hp(400,`只支持 http/https 协议(收到 ${r.protocol})`);return r.toString()}function B_(e){if(e!=null)return typeof e==`string`?e:JSON.stringify(e)}async function V_(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=N_-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 H_(e){let t={};return e.headers.forEach((e,n)=>{n.toLowerCase()!==`set-cookie`&&(t[n]=e)}),t}async function U_(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 Hp(502,e instanceof Error&&e.name===`TimeoutError`?`上游超时(${String(a)}ms):${t}`:`上游请求失败:${n}`)}let l=c.headers.get(`content-type`)??``,u=I_(l),{text:d,truncated:f}=u?await V_(c):{text:``,truncated:!1};return Response.json({ok:!0,url:t,finalUrl:c.url,status:c.status,statusText:c.statusText,headers:H_(c),contentType:l,body:u?d:null,binary:!u,truncated:f,elapsedMs:Date.now()-s})}function W_(){let e=new j;return e.onError(Up),e.post(`/`,async e=>{let t=await Ip(e);if(t===null)throw new Hp(400,`请求体不是合法 JSON 对象`);let n=typeof t.method==`string`?t.method.toUpperCase():`GET`;if(!P_.includes(n))throw new Hp(400,`不支持的请求方法:${n}(可用 ${P_.join(` / `)})`);return await U_({url:z_(t.url),method:n,headers:L_(t.headers),body:B_(t.body),timeoutMs:R_(t.timeoutMs)})}),e.get(`/`,async e=>{let t=e.req.query();return await U_({url:z_(t.url),method:`GET`,headers:L_(void 0),body:void 0,timeoutMs:R_(t.timeoutMs===void 0?void 0:Number(t.timeoutMs))})}),e}function G_(e){return`http://127.0.0.1:${String(e.port)}`}var K_=`daemon.json`;function q_(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,K_),`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:G_(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 J_=`ezllm-autostart.vbs`,Y_=`ezllm-autostart.cmd`,X_=`com.ezllm.autostart`,Z_=`ezllm.service`,Q_=`autostart.opt-out`,$_=`ezllm-v2`,ev=`Auto-generated by "npx ezllm install" (${$_}). Managed automatically by ezllm. To remove it, run \`npx ezllm uninstall\`.`;function tv(e){return c(e,Q_)}function nv(){return c((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return c(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),J_)}function rv(){return c(w(),`Library`,`LaunchAgents`,`${X_}.plist`)}function iv(){return c(w(),`.config`,`systemd`,`user`,Z_)}var av=3e4;function ov(e,t){return new Promise(n=>{let r=ce(e,t,{stdio:`ignore`,shell:!1}),i=setTimeout(()=>{r.kill(),n(124)},av),a=e=>{clearTimeout(i),n(e)};r.on(`error`,()=>a(127)),r.on(`exit`,e=>a(e??1))})}var sv={win32:{itemPath:nv,on:fv,off:hv},darwin:{itemPath:rv,on:pv,off:gv},linux:{itemPath:iv,on:mv,off:_v}};function cv(e){return sv[e]??null}function lv(e,t){return[e,t.entryJs,...t.args??[]]}function uv(e){return c(e,`logs`,`autostart.log`)}async function dv(e,t,n=ov){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 fv(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=uv(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${ev}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${lv(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
87
+ `)},i=e=>[`' ${ev}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
88
+ `),a=nv(),o=c(t.appDir,Y_);return C(o,r(e,t),`utf-8`),await dv(a,`\uFEFF${i(o)}`),a}async function pv(e,t){let n=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),r=(e,t)=>{let r=uv(t.appDir),i=Object.entries(t.env).map(([e,t])=>` <string>${n(e)}</string>\n <string>${n(t)}</string>`).join(`
89
+ `),a=lv(e,t).map(e=>` <string>${n(e)}</string>`).join(`
90
+ `);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">`,`<!-- ${$_}: launch daemon -->`,`<plist version="1.0">`,`<dict>`,` <key>Label</key><string>${n(X_)}</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(`
91
+ `)},i=rv();C(i,r(e,t),`utf-8`),await ov(`launchctl`,[`unload`,i]);let a=await ov(`launchctl`,[`load`,i]);if(a!==0)throw Error(`launchctl load 失败(退出码 ${String(a)})。请手动执行: launchctl load "${i}"`);return i}async function mv(e,t){let n=(e,t)=>{let n=Object.entries(t.env).map(([e,t])=>`Environment="${e}=${t.replace(/"/g,`\\"`)}"`).join(`
92
+ `),r=lv(e,t).map(e=>`"${e.replace(/"/g,`\\"`)}"`).join(` `);return[`[Unit]`,`Description=ezllm autostart (${$_}, launch daemon)`,`After=default.target`,``,`[Service]`,`Type=simple`,`ExecStart=${r}`,n,`Restart=on-failure`,`RestartSec=3`,``,`[Install]`,`WantedBy=default.target`,``].join(`
93
+ `)},r=iv();m(s(r),{recursive:!0}),C(r,n(e,t),`utf-8`);let i=await ov(`systemctl`,[`--user`,`daemon-reload`]);if(i!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(i)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${r}`);let a=await ov(`systemctl`,[`--user`,`enable`,Z_]);if(a!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(a)})。请手动执行: systemctl --user enable ${Z_}`);return r}async function hv(e){let t=nv(),n=p(t);return y(t,{force:!0}),y(c(e,Y_),{force:!0}),n}async function gv(){let e=rv();return p(e)?(await ov(`launchctl`,[`unload`,e]),y(e,{force:!0}),!0):!1}async function _v(){let e=iv();return p(e)?(await ov(`systemctl`,[`--user`,`disable`,Z_]),y(e,{force:!0}),await ov(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function vv(e,t){if(e.includes(t))return!0;let n=t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`);return e.includes(n)?!0:e.includes(t.replace(/"/g,`\\"`))}function yv(e,t){let n=()=>cv(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($_),a&&t!==void 0){let n=[t.nodePath,t.entryJs,...t.args??[]];if(te()===`win32`){let r=c(t.appDir,Y_),i=p(r)?g(r,`utf-8`):``;a=e.includes(r)&&i.includes($_)&&n.every(e=>vv(i,e))}else a=n.every(t=>vv(e,t))}}catch{}return{platform:te(),enabled:a,itemPath:i,optOut:p(tv(e))}}var bv=`当前为源码运行模式,更新功能不可用(仅通过 npx ezllm install 装配的实例支持)`,xv=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 npx ezllm update`,Sv=9e5;function Cv(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()?Yp()?null:xv:bv,r=new j;return r.get(`/autostart`,t=>t.json({ok:!0,...yv(e.appDir)})),r.get(`/update`,e=>{let n=Ut(),r=n.pending??null,i=r!==null&&Date.now()-r.startedAt<Sv;return e.json({ok:!0,enabled:!0,lastCheck:n.lastCheck??null,lastCheckError:n.lastCheckError??null,lastApply:n.lastApply??null,pendingUpdate:i&&r?r.toVersion:null,supported:t()&&Yp(),updating:i})}),r.post(`/update/check`,async e=>{let t=n();if(t)return e.json({ok:!1,error:t},400);let r=await Xp(`update.check`,{},4e4);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 Xp(`update.apply`);return e.json({ok:!0,accepted:r.accepted,requestedAt:r.requestedAt,note:`已开始检查更新:有新版本会自动安装并重启,结果稍后显示`})}),r}var wv=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function Tv(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=()=>Yp()?null:Response.json({ok:!1,error:wv},{status:400}),r=new j;return r.onError(Up),r.get(`/`,async e=>{let t=n();if(t)return t;let r=await Xp(`svc.list`);return e.json({ok:!0,...r})}),r.post(`/`,async e=>{let r=n();if(r)return r;let i=await Ip(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Xp(`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 Ip(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Xp(`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 Xp(`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 Xp(`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 Xp(`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 Xp(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r}var Ev=`服务未由 ezllm 主进程托管(源码运行模式),插件服务不可用;请用 ezllm 启动服务`;function Dv(e){let t=()=>Yp()?null:Response.json({ok:!1,error:Ev},{status:400}),n=new j;return n.onError(Up),n.get(`/`,async e=>{let n=t();if(n)return n;let r=await Xp(`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 Xp(`plugin.restart`);return e.json({ok:!0,available:!0,...r})}),n}function Ov(e){let t=`${e}.ellm-bak`;return!p(t)&&(p(e)&&f(e,t),!0)}function kv(e){let t=`${e}.ellm-bak`;return p(t)?(f(t,e),y(t,{force:!0}),!0):!1}function Av(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var jv=c(w(),`.claude`,`settings.json`);function Mv(){if(!p(jv))return null;try{return JSON.parse(g(jv,`utf-8`))}catch(e){throw Error(`${jv} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function Nv(e){let t=Mv();return t?Av(t?.env?.ANTHROPIC_BASE_URL,e):!1}function Pv(e){m(s(jv),{recursive:!0});let t=Mv()??{};Ov(jv),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,C(jv,JSON.stringify(t,null,2)+`
94
+ `,`utf-8`)}function Fv(e){if(kv(jv))return!0;let t=Mv();return!t||!Av(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(jv,JSON.stringify(t,null,2)+`
95
+ `,`utf-8`),!0)}var Iv=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Lv=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(Iv);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 Rv(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function zv(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+=`
95
96
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
96
- `))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Mv(t.toml,t.ptr),i=Nv(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};function Pv(e,t=0){let n=e.indexOf(`
97
- `,t);return e.charCodeAt(n-1)===13&&n--,n}function Fv(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 Iv(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;Fv(e)}}function Lv(e,t,n){let r=e.p;if(!n){r=Pv(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)Fv(e);else if(r===n||r===t)return}throw new Z(`cannot find end of structure`,{toml:e.s,ptr:r})}var Rv=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,zv=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Bv=/^[+-]?0[0-9_]/;function Vv(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+=`
98
- `;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 Hv(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Fv({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Uv(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Lv(e,44,n);let a=Hv(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=Rv.test(a);if(o||zv.test(a)){if(Bv.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 jv(a);if(!s.isValid())throw new Z(`invalid value`,i);return s}function Wv(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?Jv(e,n):qv(e,n);return e.d++,t}if(i===34||i===39)return Vv(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 Uv(e,n,t)}var Gv=/^[a-zA-Z0-9-_]+[ \t]*$/;function Kv(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=Vv(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Pv(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(!Gv.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,Iv(e,!0,!0),i}function qv(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Iv(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Kv(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=Wv(e,125,t);if(r.add(o[a]=u),Iv(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 Jv(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Iv(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Wv(e,93,t)),Iv(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 Yv(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 Xv(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Iv(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Kv(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=Yv(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=Yv(Kv(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]]=Wv(r,void 0,n)}if(Iv(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});Iv(r)}return i}var Zv=`ellm-proxy`,Qv=c(w(),`.codex`,`config.toml`),$v=`# >>> ellm-proxy codex switch >>>`,ey=`# <<< ellm-proxy codex switch <<<`;function ty(e){return p(e)?g(e,`utf-8`):null}function ny(){return RegExp(`${$v}[\\s\\S]*?${ey}\\n?`)}function ry(e,t,n=(e,t)=>se(e,t,{stdio:`ignore`}),r=process.platform,i=c(w(),`.zshrc`)){let a=e=>e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),o=(e,t,n)=>{let r=[$v,`export ${e}="${a(t)}"`,ey,``].join(`
99
- `),i=ty(n)??``,o=ny(),c=o.test(i)?i.replace(o,r):i&&!i.endsWith(`
100
- `)?`${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 iy(e,t=c(w(),`.zshrc`),n=process.platform){if(n!==`darwin`)return!1;let r=ty(t),i=r?.match(ny());return!r||!i||!i[0].includes(`export ${e}=`)?!1:(C(t,r.replace(ny(),``),`utf-8`),!0)}function ay(e){try{return Xv(e)?.model_provider===Zv}catch{return!1}}function oy(e,t){let n;try{n=Xv(e)}catch(e){throw Error(`编辑后的 config.toml 不是合法 TOML,已保留原文件: ${e.message}`)}if(t&&n?.model_provider!==Zv)throw Error(`编辑后的 config.toml 顶层 model_provider 不是 "${Zv}",已保留原文件`)}function sy(){let e=ty(Qv);return e?ay(e):!1}function cy(e){let t=(()=>{let e=Zv.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^\\s*\\[model_providers\\.(?:"|')?(?:${e}|ezllm)(?:"|')?\\]\\s*$`)})(),n=e.split(`
97
+ `))}return i}var Z=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Rv(t.toml,t.ptr),i=zv(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};function Bv(e,t=0){let n=e.indexOf(`
98
+ `,t);return e.charCodeAt(n-1)===13&&n--,n}function Vv(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 Hv(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;Vv(e)}}function Uv(e,t,n){let r=e.p;if(!n){r=Bv(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)Vv(e);else if(r===n||r===t)return}throw new Z(`cannot find end of structure`,{toml:e.s,ptr:r})}var Wv=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Gv=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Kv=/^[+-]?0[0-9_]/;function qv(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+=`
99
+ `;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 Jv(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Vv({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Yv(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Uv(e,44,n);let a=Jv(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=Wv.test(a);if(o||Gv.test(a)){if(Kv.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 Lv(a);if(!s.isValid())throw new Z(`invalid value`,i);return s}function Xv(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?ey(e,n):$v(e,n);return e.d++,t}if(i===34||i===39)return qv(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 Yv(e,n,t)}var Zv=/^[a-zA-Z0-9-_]+[ \t]*$/;function Qv(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=qv(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=Bv(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(!Zv.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,Hv(e,!0,!0),i}function $v(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Hv(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Qv(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=Xv(e,125,t);if(r.add(o[a]=u),Hv(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 ey(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Hv(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Xv(e,93,t)),Hv(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 ty(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 ny(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Hv(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Qv(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=ty(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=ty(Qv(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]]=Xv(r,void 0,n)}if(Hv(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});Hv(r)}return i}var ry=`ellm-proxy`,iy=c(w(),`.codex`,`config.toml`),ay=`# >>> ellm-proxy codex switch >>>`,oy=`# <<< ellm-proxy codex switch <<<`;function sy(e){return p(e)?g(e,`utf-8`):null}function cy(){return RegExp(`${ay}[\\s\\S]*?${oy}\\n?`)}function ly(e,t,n=(e,t)=>se(e,t,{stdio:`ignore`}),r=process.platform,i=c(w(),`.zshrc`)){let a=e=>e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),o=(e,t,n)=>{let r=[ay,`export ${e}="${a(t)}"`,oy,``].join(`
100
+ `),i=sy(n)??``,o=cy(),c=o.test(i)?i.replace(o,r):i&&!i.endsWith(`
101
+ `)?`${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 uy(e,t=c(w(),`.zshrc`),n=process.platform){if(n!==`darwin`)return!1;let r=sy(t),i=r?.match(cy());return!r||!i||!i[0].includes(`export ${e}=`)?!1:(C(t,r.replace(cy(),``),`utf-8`),!0)}function dy(e){try{return ny(e)?.model_provider===ry}catch{return!1}}function fy(e,t){let n;try{n=ny(e)}catch(e){throw Error(`编辑后的 config.toml 不是合法 TOML,已保留原文件: ${e.message}`)}if(t&&n?.model_provider!==ry)throw Error(`编辑后的 config.toml 顶层 model_provider 不是 "${ry}",已保留原文件`)}function py(){let e=sy(iy);return e?dy(e):!1}function my(e){let t=(()=>{let e=ry.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^\\s*\\[model_providers\\.(?:"|')?(?:${e}|ezllm)(?:"|')?\\]\\s*$`)})(),n=e.split(`
101
102
  `),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(`
102
103
  `).replace(/\n{3,}$/,`
103
104
 
104
- `)}function ly(e){let t=e=>{let t=e.split(`
105
- `),n=`model_provider = "${Zv}"`,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
+ `)}function hy(e){let t=e=>{let t=e.split(`
106
+ `),n=`model_provider = "${ry}"`,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(`
106
107
  `);let a=i.findIndex(e=>/^\s*\[/.test(e));return a===-1?[...i,n].join(`
107
108
  `):(i.splice(a,0,n,``),i.join(`
108
- `))};m(s(Qv),{recursive:!0});let n=ty(Qv);if(n!==null)try{Xv(n)}catch(e){throw Error(`${Qv} 不是合法 TOML,拒绝修改(请先手工修复): ${e.message}`)}let r=n??``;Sv(Qv),r=cy(r),r=t(r);let i=[`[model_providers.${Zv}]`,`name = "ezllm gateway"`,`base_url = "${e.gatewayBase}/v1"`,`wire_api = "chat"`,`env_key = "ELLM_PROXY_API_KEY"`].join(`
109
+ `))};m(s(iy),{recursive:!0});let n=sy(iy);if(n!==null)try{ny(n)}catch(e){throw Error(`${iy} 不是合法 TOML,拒绝修改(请先手工修复): ${e.message}`)}let r=n??``;Ov(iy),r=my(r),r=t(r);let i=[`[model_providers.${ry}]`,`name = "ezllm gateway"`,`base_url = "${e.gatewayBase}/v1"`,`wire_api = "chat"`,`env_key = "ELLM_PROXY_API_KEY"`].join(`
109
110
  `);return r=r.replace(/\s*$/,``)+`
110
111
 
111
112
  `+i+`
112
- `,oy(r,!0),C(Qv,r,`utf-8`),e.apiKey?ry(`ELLM_PROXY_API_KEY`,e.apiKey):!1}function uy(){let e=Cv(Qv),t=iy(`ELLM_PROXY_API_KEY`);if(delete process.env.ELLM_PROXY_API_KEY,e)return!0;let n=ty(Qv);if(!n||!ay(n))return t;let r=cy(n);return r=r.split(`
113
+ `,fy(r,!0),C(iy,r,`utf-8`),e.apiKey?ly(`ELLM_PROXY_API_KEY`,e.apiKey):!1}function gy(){let e=kv(iy),t=uy(`ELLM_PROXY_API_KEY`);if(delete process.env.ELLM_PROXY_API_KEY,e)return!0;let n=sy(iy);if(!n||!dy(n))return t;let r=my(n);return r=r.split(`
113
114
  `).filter(e=>!/^\s*model_provider\s*=\s*["']?ellm-proxy["']?\s*$/.test(e)).join(`
114
- `),oy(r,!1),C(Qv,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})),dy=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})),fy=E((e=>{var t=Q(),n=dy(),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(`
115
- `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),py=E((e=>{var t=Q(),n=dy();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})),my=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})),hy=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})),gy=E((e=>{var t=my(),n=Q(),r=hy();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}}})),_y=E((e=>{var t=py(),n=dy(),r=Q(),i=gy(),a=hy(),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=gy(),r=hy(),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})),vy=E((e=>{var t=_y(),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})),yy=E((e=>{var t=vy(),n=Q(),r=gy();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})),by=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
+ `),fy(r,!1),C(iy,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})),_y=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})),vy=E((e=>{var t=Q(),n=_y(),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(`
116
+ `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),yy=E((e=>{var t=Q(),n=_y();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})),by=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})),xy=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})),Sy=E((e=>{var t=by(),n=Q(),r=xy();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}}})),Cy=E((e=>{var t=yy(),n=_y(),r=Q(),i=Sy(),a=xy(),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=Sy(),r=xy(),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})),wy=E((e=>{var t=Cy(),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})),Ty=E((e=>{var t=wy(),n=Q(),r=Sy();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})),Ey=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(`
116
117
  `)?n(r,t):r.includes(`
117
118
  `)?`
118
- `+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),xy=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===`
119
+ `+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),Dy=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===`
119
120
  `)i===n&&(v=a(e,v,t.length)),m=v+t.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
120
121
  `&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
121
122
  `&&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!==`
122
- `);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})),Sy=E((e=>{var t=$(),n=xy(),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]===`
123
+ `);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})),Oy=E((e=>{var t=$(),n=Dy(),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]===`
123
124
  `){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)+`
124
125
 
125
126
  `;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
@@ -137,29 +138,29 @@ import{createRequire as e}from"node:module";import{createServer as t}from"http";
137
138
  $&`).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(`
138
139
  `)||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(`
139
140
  `)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
140
- `))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})),Cy=E((e=>{var t=py(),n=Q(),r=by(),i=Sy();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})),wy=E((e=>{var t=Q(),n=$(),r=Cy(),i=by();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?`
141
+ `))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})),ky=E((e=>{var t=yy(),n=Q(),r=Ey(),i=Oy();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})),Ay=E((e=>{var t=Q(),n=$(),r=ky(),i=Ey();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?`
141
142
  `:``,S){let e=p(S);ee+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?ee===`
142
143
  `&&C&&(ee=`
143
144
 
144
145
  `):ee+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
145
146
  `),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]===`
146
- `)&&(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})),Ty=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})),Ey=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})),Dy=E((e=>{var t=Ty(),n=Ey(),r=Cy(),i=Q(),a=hy();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})),Oy=E((e=>{var t=vy(),n=wy(),r=Dy(),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})),ky=E((e=>{var t=Q(),n=Cy(),r=by();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}`:`
147
+ `)&&(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})),jy=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})),My=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})),Ny=E((e=>{var t=jy(),n=My(),r=ky(),i=Q(),a=xy();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})),Py=E((e=>{var t=wy(),n=Ay(),r=Ny(),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})),Fy=E((e=>{var t=Q(),n=ky(),r=Ey();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}`:`
147
148
  `}}return e?(_+=`
148
149
  `+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(`
149
150
  `),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}`:`
150
- `;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})),Ay=E((e=>{var t=ky(),n=Dy(),r=yy(),i=Q(),a=Oy(),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})),jy=E((e=>{var t=Q(),n=Ay();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)}})),My=E((e=>{var t=vy(),n=ky(),r=yy(),i=Q(),a=$(),o=hy(),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})),Ny=E((e=>{var t=Q(),n=My();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)}})),Py=E((e=>{var t=Sy();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)}}})),Fy=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})),Iy=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})),Ly=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})),Ry=E((e=>{var t=$(),n=Ly(),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})),zy=E((e=>{var t=Ly(),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`)}})),By=E((e=>{var t=jy(),n=Fy(),r=Ny(),i=Py(),a=Iy(),o=Ry(),s=zy();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),Vy=E((e=>{var t=$(),n=jy(),r=Ny();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}})})),Hy=E((e=>{var t=we(`buffer`),n=$(),r=Sy();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?`
151
- `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),Uy=E((e=>{var t=Q(),n=Oy(),r=$(),i=My();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})),Wy=E((e=>{var t=Q(),n=hy(),r=Ay(),i=My(),a=Uy(),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})),Gy=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})),Ky=E((e=>{var t=$(),n=Ly(),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})),qy=E((e=>{var t=Ly(),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})),Jy=E((e=>{var t=Q(),n=Oy(),r=Ay(),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})),Yy=E((e=>{var t=Ly();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})),Xy=E((e=>{var t=jy(),n=Fy(),r=Ny(),i=Py(),a=Hy(),o=Gy(),s=Ky(),c=qy(),l=Ey(),u=Wy(),d=Uy(),f=Jy(),p=Yy();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]})),Zy=E((e=>{var t=jy(),n=Fy(),r=Ny(),i=Py(),a=Iy(),o=Ry(),s=zy(),c=By(),l=Vy(),u=Hy(),d=Ey(),f=Wy(),p=Uy(),m=Xy(),h=Jy(),g=Yy(),_=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})),Qy=E((e=>{var t=Q(),n=jy(),r=Ny(),i=Py(),a=Zy(),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}}})),$y=E((e=>{var t=Q(),n=Cy(),r=by();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
+ `;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})),Iy=E((e=>{var t=Fy(),n=Ny(),r=Ty(),i=Q(),a=Py(),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})),Ly=E((e=>{var t=Q(),n=Iy();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)}})),Ry=E((e=>{var t=wy(),n=Fy(),r=Ty(),i=Q(),a=$(),o=xy(),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})),zy=E((e=>{var t=Q(),n=Ry();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)}})),By=E((e=>{var t=Oy();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)}}})),Vy=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})),Hy=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})),Uy=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})),Wy=E((e=>{var t=$(),n=Uy(),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})),Gy=E((e=>{var t=Uy(),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`)}})),Ky=E((e=>{var t=Ly(),n=Vy(),r=zy(),i=By(),a=Hy(),o=Wy(),s=Gy();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),qy=E((e=>{var t=$(),n=Ly(),r=zy();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}})})),Jy=E((e=>{var t=we(`buffer`),n=$(),r=Oy();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?`
152
+ `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),Yy=E((e=>{var t=Q(),n=Py(),r=$(),i=Ry();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})),Xy=E((e=>{var t=Q(),n=xy(),r=Iy(),i=Ry(),a=Yy(),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})),Zy=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})),Qy=E((e=>{var t=$(),n=Uy(),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})),$y=E((e=>{var t=Uy(),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})),eb=E((e=>{var t=Q(),n=Py(),r=Iy(),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})),tb=E((e=>{var t=Uy();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})),nb=E((e=>{var t=Ly(),n=Vy(),r=zy(),i=By(),a=Jy(),o=Zy(),s=Qy(),c=$y(),l=My(),u=Xy(),d=Yy(),f=eb(),p=tb();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]})),rb=E((e=>{var t=Ly(),n=Vy(),r=zy(),i=By(),a=Hy(),o=Wy(),s=Gy(),c=Ky(),l=qy(),u=Jy(),d=My(),f=Xy(),p=Yy(),m=nb(),h=eb(),g=tb(),_=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})),ib=E((e=>{var t=Q(),n=Ly(),r=zy(),i=By(),a=rb(),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}}})),ab=E((e=>{var t=Q(),n=ky(),r=Ey();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(`
152
153
  `)?(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(`
153
154
  `)+`
154
- `}e.stringifyDocument=i})),eb=E((e=>{var t=_y(),n=yy(),r=Q(),i=Oy(),a=hy(),o=Qy(),s=$y(),c=py(),l=my(),u=vy(),d=fy(),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})),tb=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)+`…
155
- `),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`}}})),nb=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})),rb=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(`
156
- `))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})),ib=E((e=>{var t=rb();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})),ab=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})),ob=E((e=>{var t=Oy(),n=Ay(),r=nb(),i=rb(),a=ib(),o=ab(),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+=`
155
+ `}e.stringifyDocument=i})),ob=E((e=>{var t=Cy(),n=Ty(),r=Q(),i=Py(),a=xy(),o=ib(),s=ab(),c=yy(),l=by(),u=wy(),d=vy(),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})),sb=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)+`…
156
+ `),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`}}})),cb=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})),lb=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(`
157
+ `))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})),ub=E((e=>{var t=lb();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})),db=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})),fb=E((e=>{var t=Py(),n=Iy(),r=cb(),i=lb(),a=ub(),o=db(),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+=`
157
158
  `+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+=`
158
- `+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})),sb=E((e=>{var t=My(),n=nb(),r=ib();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})),cb=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})),lb=E((e=>{var t=Q(),n=Oy(),r=Ay(),i=My(),a=cb(),o=nb(),s=rb(),c=ab(),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+=`
159
+ `+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})),pb=E((e=>{var t=Ry(),n=cb(),r=ub();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})),mb=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})),hb=E((e=>{var t=Q(),n=Py(),r=Iy(),i=Ry(),a=mb(),o=cb(),s=lb(),c=db(),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+=`
159
160
  `+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+=`
160
161
  `+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+=`
161
162
  `+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+=`
162
- `+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})),ub=E((e=>{var t=Q(),n=$(),r=Ay(),i=My(),a=ob(),o=sb(),s=lb();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})),db=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?`
163
+ `+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})),gb=E((e=>{var t=Q(),n=$(),r=Iy(),i=Ry(),a=fb(),o=pb(),s=hb();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})),_b=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?`
163
164
  `.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)+`
164
165
  `;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=`
165
166
  `):n.length>d||r[0]===` `?(h===` `?h=`
@@ -174,7 +175,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
174
175
  `+l[e][0].slice(d);m[m.length-1]!==`
175
176
  `&&(m+=`
176
177
  `);break;default:m+=`
177
- `}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})),fb=E((e=>{var t=$(),n=cb();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?
178
+ `}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})),vb=E((e=>{var t=$(),n=mb();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?
178
179
  `,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
179
180
  `,`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===`
180
181
  `?i+=a:a=`
@@ -189,10 +190,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
189
190
  `);)r===`
190
191
  `&&(n+=`
191
192
  `),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:`
192
- `,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})),pb=E((e=>{var t=Q(),n=$(),r=db(),i=fb();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})),mb=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})),hb=E((e=>{var t=_y(),n=Q(),r=ub(),i=pb(),a=cb(),o=mb(),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})),gb=E((e=>{var t=eb(),n=hb(),r=cb(),i=nb();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})),_b=E((e=>{var t=we(`process`),n=fy(),r=eb(),i=tb(),a=Q(),o=gb(),s=cb();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?`
193
+ `,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})),yb=E((e=>{var t=Q(),n=$(),r=_b(),i=vb();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})),bb=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})),xb=E((e=>{var t=Cy(),n=Q(),r=gb(),i=yb(),a=mb(),o=bb(),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})),Sb=E((e=>{var t=ob(),n=xb(),r=mb(),i=cb();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})),Cb=E((e=>{var t=we(`process`),n=vy(),r=ob(),i=sb(),a=Q(),o=Sb(),s=mb();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?`
193
194
 
194
195
  `:`
195
- `)+(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}}}})),vb=E((e=>{var t=db(),n=fb(),r=tb(),i=Sy();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:`
196
+ `)+(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}}}})),wb=E((e=>{var t=_b(),n=vb(),r=sb(),i=Oy();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:`
196
197
  `}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
197
198
  `),t=c.substring(0,e),n=c.substring(e+1)+`
198
199
  `,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
@@ -200,9 +201,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
200
201
  `),r=t.substring(0,n),i=t.substring(n+1)+`
201
202
  `;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:`
202
203
  `});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:`
203
- `};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})),yb=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})),bb=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})),xb=E((e=>{var t=vb(),n=yb(),r=bb(),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`
204
+ `};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})),Tb=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})),Eb=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})),Db=E((e=>{var t=wb(),n=Tb(),r=Eb(),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`
204
205
  `:case`\r
205
- `: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})),Sb=E((e=>{var t=xb();function n(e){switch(e){case void 0:case` `:case`
206
+ `: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})),Ob=E((e=>{var t=Db();function n(e){switch(e){case void 0:case` `:case`
206
207
  `:case`\r`:case` `:return!0;default:return!1}}var r=new Set(`0123456789ABCDEFabcdef`),i=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=new Set(`,[]{}`),o=new Set(` ,[]{}
207
208
  \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===`
208
209
  `||t===`\r`&&this.buffer[e+1]===`
@@ -221,10 +222,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
221
222
  `,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
222
223
  `){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===`
223
224
  `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
224
- `?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)}}})),Cb=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}}}}})),wb=E((e=>{var t=we(`process`),n=xb(),r=Sb();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(`
225
+ `?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)}}})),kb=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}}}}})),Ab=E((e=>{var t=we(`process`),n=Db(),r=Ob();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(`
225
226
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
226
227
  `,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(`
227
228
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
228
- `,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())}}}})),Tb=E((e=>{var t=_b(),n=eb(),r=tb(),i=Ty(),a=Q(),o=Cb(),s=wb();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})),Eb=E((e=>{var t=_b(),n=eb(),r=Qy(),i=tb(),a=_y(),o=Q(),s=Oy(),c=$(),l=Ay(),u=My();xb();var d=Sb(),f=Cb(),p=wb(),m=Tb(),h=dy();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}))(),Db=`DEEPSEEK_API_KEY`,Ob=1,kb=`ezllm`,Ab=()=>process.env.DSH_HOME||c(w(),`.dsh`),jb=()=>c(Ab(),`settings.yaml`),Mb=()=>c(Ab(),`.credentials.yaml`);function Nb(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function Pb(e,t){let n=(0,Eb.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function Fb(e){return`${e}/v1`}function Ib(e){let t=Nb(jb());if(!t)return!1;try{return wv(Pb(t,jb()).toJS()?.[`llm-deepseek`]?.baseURL,Fb(e))}catch{return!1}}function Lb(e){let t=Fb(e.gatewayBase);m(Ab(),{recursive:!0});let n=jb(),r=Nb(n),i=Pb(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);Sv(n),i.setIn([`llm-deepseek`,`baseURL`],t),zb(n,i);let o=Mb(),s=e.masterKey||kb,c=Nb(o);if(Sv(o),c===null){let e=Pb(``,o);e.set(`version`,Ob),e.setIn([`refs`,Db],s),zb(o,e);return}let l=Pb(c,o),u=l.toJS();if(!(0,Eb.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==Ob)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(Ob)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(Db,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,Db],s)}zb(o,l)}function Rb(e,t){let n=jb(),r=Mb(),i=!1;if(Cv(n))i=!0;else{let t=Nb(n);if(t){let r=Pb(t,n);if(wv(r.toJS()?.[`llm-deepseek`]?.baseURL,Fb(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`]),zb(n,r),i=!0}}}if(Cv(r))i=!0;else{let e=Nb(r);if(e){let n=Pb(e,r),a=n.toJS(),o=e=>e===t||e===kb;a?.version===Ob&&o(a?.refs?.[Db])?(n.deleteIn([`refs`,Db]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),zb(r,n),i=!0):a?.version===void 0&&o(a?.[Db])&&(n.deleteIn([Db]),zb(r,n),i=!0)}}return i}function zb(e,t){let n=t.toString(),r=(0,Eb.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 Bb(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 Vb(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new j;return n.get(`/`,t=>{let n=z_(e);return t.json({ok:!0,claudeCode:Dv(n),codex:sy(),dsh:Ib(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Bb(n);if(r instanceof Response)return r;let i=z_(e);if(r){let e=t(Tt());return e?(Ov({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=kv(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Bb(n);if(r instanceof Response)return r;let i=z_(e);if(r){let e=t(Tt()),r=ly({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=uy();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Bb(n);if(r instanceof Response)return r;let i=z_(e),a=t(Tt());if(r)return Lb({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=Rb(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var Hb=[`/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 Ub(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,Np),e.route(`/api/setup`,Bp()),e.use(`/api/*`,Fp),e.route(`/api/config`,Kp({runtime:n})),e.route(`/api/test`,Qp(n)),e.route(`/api/latency`,vm(n)),e.route(`/api/usage`,ym()),e.route(`/api/quota`,h_()),e.route(`/api/provider-auth`,g_()),e.route(`/api/logs`,w_()),e.route(`/api/status`,y_(n,i)),e.route(`/api/fetch`,R_()),r&&(e.route(`/api/service`,V_(r)),e.route(`/api/service`,_v(r)),e.route(`/api/service/managed`,yv(r)),e.route(`/api/service/plugins`,xv(r)),e.route(`/api/harness`,Vb(r)))}var Wb=(e,t=Gb)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},Gb={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`},Kb=/^\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,qb={br:`.br`,zstd:`.zst`,gzip:`.gz`},Jb=Object.keys(qb),Yb=(()=>{let[e,t]=ye.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Xb=e=>Yb?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()}}),Zb=e=>{let t;try{t=Se(e)}catch{}return t},Qb=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},$b=e=>Qb(e,decodeURI),ex=(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=$b(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=Zb(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=Ce(o,t),s=Zb(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=Wb(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||Kb.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of Jb){if(!e.has(t))continue;let n=Zb(o+qb[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=qb[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(Xb(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(Xb(a),206)}return await e.onFound?.(o,r),l}},tx=s(ne(import.meta.url));function nx(e,t){let n=t??[c(tx,`web-ui`),l(tx,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(tx,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(tx,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await de(c(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await ex({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 rx(e,t,n){let r=new j;return r.use(`/v1/*`,kp()),Ub(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),nx(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${Hb})`},404)),r.onError(Lp),r}var ix=6e4;function ax(e){let t=()=>{let e=zl()?.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:ix,run:async()=>{try{if(hm(e)===0)return;let r=t();if(!n(r,sm()??void 0,Date.now()))return;D(`[latency] 自动测试触发`),await mm(e)}catch(e){k(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var ox=6e5,sx=3e4;function cx(){return{name:`quotaRefresh`,everyMs:ox,firstDelayMs:sx,run:async()=>{try{await l_()}catch(e){k(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var lx=6e4,ux=3e4,dx=20,fx=3e4,px=1024,mx=/^[^\u0000-\u001f\u007f]{1,24}$/u,hx=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),gx=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
229
- `);async function _x(e){let t=async(e,t)=>{let n=(e,t)=>{let n=Jp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0);return e.provider===`anthropic`?{url:`${n}/messages`,payload:{model:e.modelName,system:gx,messages:[{role:`user`,content:t}],max_tokens:px}}:e.provider===`openai-responses`?{url:`${n}/responses`,payload:{model:e.modelName,instructions:gx,input:t,max_output_tokens:px}}:{url:`${n}/chat/completions`,payload:{model:e.modelName,messages:[{role:`system`,content:gx},{role:`user`,content:t}],max_tokens:px}}},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?Yp(e.apiKey,e.provider):{}},s=await fetch(i,{method:`POST`,headers:o,body:JSON.stringify(a),signal:AbortSignal.timeout(fx)});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=xf({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();mx.test(o)&&(hx.has(o.toLowerCase())||n.set(i,o))}return n},i=op(dx);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(`
230
- `),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=sp(l,`llm`),d=i.filter(e=>!l.has(e)),f=cp(d),p=new Map;for(let e of f){let t=vp(e);t!==``&&p.set(e,t)}let m=sp(p,Jf);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 vx(e){return{name:`clientNameResolve`,everyMs:lx,firstDelayMs:ux,run:async()=>{try{await _x(e)}catch(e){k(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var yx=`--log-backfill`;function bx(e=process.argv){return e.includes(yx)}async function xx(){D(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),Nd();let e=bp({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=Cp({onProgress:e=>D(`[log-backfill] ${e}`)});D(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),D(`[log-backfill] 完成`)}function Sx(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??ce,r,i;try{return m(Dt(),{recursive:!0}),r=h(c(Dt(),`out-backfill.log`),`a`),i=h(c(Dt(),`err-backfill.log`),`a`),n(process.execPath,[...e.execArgv??process.execArgv,t,yx],{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 Cx(e={}){let t=Sx(e);return t.started||k(`[log-backfill] 存量补齐子进程未拉起:${t.reason}`),t}bx()&&(await xx(),process.exit(0));var wx=Bl();wx===null&&(k(`[ezllm] 缺少配置文件 ${Tt()}(参考 ezllm.config.example.json)`),process.exit(1));var Tx=wx;Nd(),rm();var Ex=new Du({maxBytes:su().maxBytes}),Dx=Bf({spool:Ex,getConfig:()=>su()}),Ox=Eu();Ox>0&&D(`[ezllm] spool 启动清理:回收中断残留 ${String(Ox)} 个中转文件`),await Hf(),Cx();var kx=new hp({spool:Ex}),Ax=()=>{let e=Tx;try{e=zl()??Tx}catch{e=Tx}return e.providers.flatMap(e=>e.models.map(e=>e.modelName))},jx=await Ep(Tx,{authorize(e){let t=Jl();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=Jl();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),Op(e,{knownModelNames:Ax})}},{traceSink:kx}),Mx={port:0,startedAt:Date.now(),appDir:Ct()},Nx=nu(),Px=rx(jx,Mx,Nx),Fx=Wt({jobs:[Dx,Kf({getRetention:()=>ou()}),ax(jx),cx(),vx(jx)]}),Ix=await zx(Px,Tp(jx),Nx.hostname);Mx.port=Ix;var Lx=!1;function Rx(e,t=0){Lx||(Lx=!0,Fx.stop(),D(`[ezllm] ${e},服务退出`),Promise.race([kx.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}Gp(()=>Rx(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>Rx(`收到 ${e}`));Bx(Ix,Nx);async function zx(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 Bx(e,t){let n=__(t.hostname)?`localhost`:t.hostname,r=__(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})`),__(t.hostname))for(let t of v_())D(` 局域网访问: http://${t}:${String(e)}`);D(` 模型数量: ${String(jx.current.expanded.deployments.names.length)}`),eu().completed||D(` ⚠ 首次启动:请打开 http://${n}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),D(`========================================`)}export{};
229
+ `,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())}}}})),jb=E((e=>{var t=Cb(),n=ob(),r=sb(),i=jy(),a=Q(),o=kb(),s=Ab();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})),Mb=E((e=>{var t=Cb(),n=ob(),r=ib(),i=sb(),a=Cy(),o=Q(),s=Py(),c=$(),l=Iy(),u=Ry();Db();var d=Ob(),f=kb(),p=Ab(),m=jb(),h=_y();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}))(),Nb=`DEEPSEEK_API_KEY`,Pb=1,Fb=`ezllm`,Ib=()=>process.env.DSH_HOME||c(w(),`.dsh`),Lb=()=>c(Ib(),`settings.yaml`),Rb=()=>c(Ib(),`.credentials.yaml`);function zb(e){if(!p(e))return null;let t=g(e,`utf-8`);return t.trim()===``?null:t}function Bb(e,t){let n=(0,Mb.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function Vb(e){return`${e}/v1`}function Hb(e){let t=zb(Lb());if(!t)return!1;try{return Av(Bb(t,Lb()).toJS()?.[`llm-deepseek`]?.baseURL,Vb(e))}catch{return!1}}function Ub(e){let t=Vb(e.gatewayBase);m(Ib(),{recursive:!0});let n=Lb(),r=zb(n),i=Bb(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);Ov(n),i.setIn([`llm-deepseek`,`baseURL`],t),Gb(n,i);let o=Rb(),s=e.masterKey||Fb,c=zb(o);if(Ov(o),c===null){let e=Bb(``,o);e.set(`version`,Pb),e.setIn([`refs`,Nb],s),Gb(o,e);return}let l=Bb(c,o),u=l.toJS();if(!(0,Mb.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==Pb)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(Pb)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(Nb,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,Nb],s)}Gb(o,l)}function Wb(e,t){let n=Lb(),r=Rb(),i=!1;if(kv(n))i=!0;else{let t=zb(n);if(t){let r=Bb(t,n);if(Av(r.toJS()?.[`llm-deepseek`]?.baseURL,Vb(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`]),Gb(n,r),i=!0}}}if(kv(r))i=!0;else{let e=zb(r);if(e){let n=Bb(e,r),a=n.toJS(),o=e=>e===t||e===Fb;a?.version===Pb&&o(a?.refs?.[Nb])?(n.deleteIn([`refs`,Nb]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),Gb(r,n),i=!0):a?.version===void 0&&o(a?.[Nb])&&(n.deleteIn([Nb]),Gb(r,n),i=!0)}}return i}function Gb(e,t){let n=t.toString(),r=(0,Mb.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 Kb(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 qb(e){let t=e=>{try{return JSON.parse(g(e,`utf-8`)).masterKey||``}catch{return``}},n=new j;return n.get(`/`,t=>{let n=G_(e);return t.json({ok:!0,claudeCode:Nv(n),codex:py(),dsh:Hb(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Kb(n);if(r instanceof Response)return r;let i=G_(e);if(r){let e=t(Tt());return e?(Pv({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=Fv(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Kb(n);if(r instanceof Response)return r;let i=G_(e);if(r){let e=t(Tt()),r=hy({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=gy();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Kb(n);if(r instanceof Response)return r;let i=G_(e),a=t(Tt());if(r)return Ub({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=Wb(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var Jb=[`/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 Yb(e,t){let{runtime:n,admin:r,listen:i}=t;e.route(`/api/auth`,zp),e.route(`/api/setup`,Kp()),e.use(`/api/*`,Vp),e.route(`/api/config`,Qp({runtime:n})),e.route(`/api/test`,im(n)),e.route(`/api/latency`,wm(n)),e.route(`/api/usage`,Tm()),e.route(`/api/quota`,x_()),e.route(`/api/provider-auth`,S_()),e.route(`/api/logs`,A_()),e.route(`/api/status`,T_(n,i)),e.route(`/api/fetch`,W_()),r&&(e.route(`/api/service`,q_(r)),e.route(`/api/service`,Cv(r)),e.route(`/api/service/managed`,Tv(r)),e.route(`/api/service/plugins`,Dv(r)),e.route(`/api/harness`,qb(r)))}var Xb=(e,t=Zb)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},Zb={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`},Qb=/^\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,$b={br:`.br`,zstd:`.zst`,gzip:`.gz`},ex=Object.keys($b),tx=(()=>{let[e,t]=ye.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),nx=e=>tx?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()}}),rx=e=>{let t;try{t=Se(e)}catch{}return t},ix=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},ax=e=>ix(e,decodeURI),ox=(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=ax(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=rx(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=Ce(o,t),s=rx(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=Xb(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||Qb.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of ex){if(!e.has(t))continue;let n=rx(o+$b[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=$b[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(nx(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(nx(a),206)}return await e.onFound?.(o,r),l}},sx=s(ne(import.meta.url));function cx(e,t){let n=t??[c(sx,`web-ui`),l(sx,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),l(sx,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>p(c(e,`index.html`)))??c(sx,`web-ui`);p(c(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await de(c(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await ox({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 lx(e,t,n){let r=new j;return r.use(`/v1/*`,Fp()),Yb(r,{runtime:e,admin:t,listen:n}),r.route(`/`,e.proxy),cx(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), ${Jb})`},404)),r.onError(Up),r}var ux=6e4;function dx(e){let t=()=>{let e=Gl()?.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:ux,run:async()=>{try{if(xm(e)===0)return;let r=t();if(!n(r,pm()??void 0,Date.now()))return;D(`[latency] 自动测试触发`),await bm(e)}catch(e){k(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var fx=6e5,px=3e4;function mx(){return{name:`quotaRefresh`,everyMs:fx,firstDelayMs:px,run:async()=>{try{await h_()}catch(e){k(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var hx=6e4,gx=3e4,_x=20,vx=3e4,yx=1024,bx=/^[^\u0000-\u001f\u007f]{1,24}$/u,xx=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),Sx=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
230
+ `);async function Cx(e){let t=async(e,t)=>{let n=(e,t)=>{let n=em((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0);return e.provider===`anthropic`?{url:`${n}/messages`,payload:{model:e.modelName,system:Sx,messages:[{role:`user`,content:t}],max_tokens:yx}}:e.provider===`openai-responses`?{url:`${n}/responses`,payload:{model:e.modelName,instructions:Sx,input:t,max_output_tokens:yx}}:{url:`${n}/chat/completions`,payload:{model:e.modelName,messages:[{role:`system`,content:Sx},{role:`user`,content:t}],max_tokens:yx}}},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?tm(e.apiKey,e.provider):{}},s=await fetch(i,{method:`POST`,headers:o,body:JSON.stringify(a),signal:AbortSignal.timeout(vx)});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=Df({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();bx.test(o)&&(xx.has(o.toLowerCase())||n.set(i,o))}return n},i=fp(_x);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(`
231
+ `),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=pp(l,`llm`),d=i.filter(e=>!l.has(e)),f=mp(d),p=new Map;for(let e of f){let t=wp(e);t!==``&&p.set(e,t)}let m=pp(p,ep);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 wx(e){return{name:`clientNameResolve`,everyMs:hx,firstDelayMs:gx,run:async()=>{try{await Cx(e)}catch(e){k(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var Tx=`--log-backfill`;function Ex(e=process.argv){return e.includes(Tx)}async function Dx(){D(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),zd();let e=Ep({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=kp({onProgress:e=>D(`[log-backfill] ${e}`)});D(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),D(`[log-backfill] 完成`)}function Ox(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??ce,r,i;try{return m(Dt(),{recursive:!0}),r=h(c(Dt(),`out-backfill.log`),`a`),i=h(c(Dt(),`err-backfill.log`),`a`),n(process.execPath,[...e.execArgv??process.execArgv,t,Tx],{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 kx(e={}){let t=Ox(e);return t.started||k(`[log-backfill] 存量补齐子进程未拉起:${t.reason}`),t}Ex()&&(await Dx(),process.exit(0));var Ax=Kl();Ax===null&&(k(`[ezllm] 缺少配置文件 ${Tt()}(参考 ezllm.config.example.json)`),process.exit(1));var jx=Ax;zd(),lm();var Mx=new Nu({maxBytes:pu().maxBytes}),Nx=Kf({spool:Mx,getConfig:()=>pu()}),Px=Mu();Px>0&&D(`[ezllm] spool 启动清理:回收中断残留 ${String(Px)} 个中转文件`),await Jf(),kx();var Fx=new xp({spool:Mx}),Ix=()=>{let e=jx;try{e=Gl()??jx}catch{e=jx}return e.providers.flatMap(e=>e.models.map(e=>e.modelName))},Lx=await Mp(jx,{authorize(e){let t=eu();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=eu();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),Pp(e,{knownModelNames:Ix})}},{traceSink:Fx}),Rx={port:0,startedAt:Date.now(),appDir:Ct()},zx=cu(),Bx=lx(Lx,Rx,zx),Vx=Wt({jobs:[Nx,Qf({getRetention:()=>fu()}),dx(Lx),mx(),wx(Lx)]}),Hx=await Gx(Bx,jp(Lx),zx.hostname);Rx.port=Hx;var Ux=!1;function Wx(e,t=0){Ux||(Ux=!0,Vx.stop(),D(`[ezllm] ${e},服务退出`),Promise.race([Fx.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}Zp(()=>Wx(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>Wx(`收到 ${e}`));Kx(Hx,zx);async function Gx(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 Kx(e,t){let n=C_(t.hostname)?`localhost`:t.hostname,r=C_(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})`),C_(t.hostname))for(let t of w_())D(` 局域网访问: http://${t}:${String(e)}`);D(` 模型数量: ${String(Lx.current.expanded.deployments.names.length)}`),ou().completed||D(` ⚠ 首次启动:请打开 http://${n}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),D(`========================================`)}export{};