@mlightcad/cad-llm-plugin 1.8.0-preview.5 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/cad-llm-plugin-cad-llm-plugin-DO9FgSsR.js +21575 -0
  2. package/dist/cad-llm-plugin-cad-llm-plugin-DlRbTdyT.js +514 -0
  3. package/dist/cad-llm-plugin-cad-llm-plugin-register-CwDcWhV5.js +7 -0
  4. package/dist/cad-llm-plugin-cad-llm-plugin-register-TJETetnW.js +759 -0
  5. package/dist/cad-llm-plugin-register.js +10 -611
  6. package/dist/cad-llm-plugin-register.umd.cjs +1 -1
  7. package/dist/cad-llm-plugin.js +62 -21479
  8. package/dist/cad-llm-plugin.umd.cjs +1 -514
  9. package/lib/AcApLlmOcrProviders.d.ts +17 -0
  10. package/lib/AcApLlmOcrProviders.d.ts.map +1 -0
  11. package/lib/AcApLlmOcrProviders.js +227 -0
  12. package/lib/AcApLlmOcrProviders.js.map +1 -0
  13. package/lib/AcApLlmTextRecognizer.d.ts +12 -5
  14. package/lib/AcApLlmTextRecognizer.d.ts.map +1 -1
  15. package/lib/AcApLlmTextRecognizer.js +17 -8
  16. package/lib/AcApLlmTextRecognizer.js.map +1 -1
  17. package/lib/constants.d.ts +19 -1
  18. package/lib/constants.d.ts.map +1 -1
  19. package/lib/constants.js +36 -1
  20. package/lib/constants.js.map +1 -1
  21. package/lib/i18n/ar.d.ts +4 -0
  22. package/lib/i18n/ar.d.ts.map +1 -1
  23. package/lib/i18n/ar.js +4 -0
  24. package/lib/i18n/ar.js.map +1 -1
  25. package/lib/i18n/chrome.d.ts +10 -0
  26. package/lib/i18n/chrome.d.ts.map +1 -0
  27. package/lib/i18n/chrome.js +39 -0
  28. package/lib/i18n/chrome.js.map +1 -0
  29. package/lib/i18n/cs.d.ts +4 -0
  30. package/lib/i18n/cs.d.ts.map +1 -1
  31. package/lib/i18n/cs.js +4 -0
  32. package/lib/i18n/cs.js.map +1 -1
  33. package/lib/i18n/en.d.ts +5 -0
  34. package/lib/i18n/en.d.ts.map +1 -1
  35. package/lib/i18n/en.js +5 -0
  36. package/lib/i18n/en.js.map +1 -1
  37. package/lib/i18n/index.d.ts +581 -0
  38. package/lib/i18n/index.d.ts.map +1 -1
  39. package/lib/i18n/index.js +47 -16
  40. package/lib/i18n/index.js.map +1 -1
  41. package/lib/i18n/ja.d.ts +4 -0
  42. package/lib/i18n/ja.d.ts.map +1 -1
  43. package/lib/i18n/ja.js +4 -0
  44. package/lib/i18n/ja.js.map +1 -1
  45. package/lib/i18n/ko.d.ts +4 -0
  46. package/lib/i18n/ko.d.ts.map +1 -1
  47. package/lib/i18n/ko.js +4 -0
  48. package/lib/i18n/ko.js.map +1 -1
  49. package/lib/i18n/tr.d.ts +4 -0
  50. package/lib/i18n/tr.d.ts.map +1 -1
  51. package/lib/i18n/tr.js +4 -0
  52. package/lib/i18n/tr.js.map +1 -1
  53. package/lib/i18n/zh.d.ts +4 -0
  54. package/lib/i18n/zh.d.ts.map +1 -1
  55. package/lib/i18n/zh.js +4 -0
  56. package/lib/i18n/zh.js.map +1 -1
  57. package/lib/index.d.ts +1 -0
  58. package/lib/index.d.ts.map +1 -1
  59. package/lib/index.js +1 -0
  60. package/lib/index.js.map +1 -1
  61. package/lib/register.d.ts +3 -2
  62. package/lib/register.d.ts.map +1 -1
  63. package/lib/register.js +54 -4
  64. package/lib/register.js.map +1 -1
  65. package/lib/storage/AcApLlmConfigStore.d.ts +17 -0
  66. package/lib/storage/AcApLlmConfigStore.d.ts.map +1 -1
  67. package/lib/storage/AcApLlmConfigStore.js +58 -14
  68. package/lib/storage/AcApLlmConfigStore.js.map +1 -1
  69. package/lib/storage/AcApLlmModelCatalog.d.ts +5 -0
  70. package/lib/storage/AcApLlmModelCatalog.d.ts.map +1 -1
  71. package/lib/storage/AcApLlmModelCatalog.js.map +1 -1
  72. package/lib/storage/settingsEquality.d.ts.map +1 -1
  73. package/lib/storage/settingsEquality.js +3 -2
  74. package/lib/storage/settingsEquality.js.map +1 -1
  75. package/lib/ui/AcUiLlmSettingsDialog.d.ts.map +1 -1
  76. package/lib/ui/AcUiLlmSettingsDialog.js +6 -1
  77. package/lib/ui/AcUiLlmSettingsDialog.js.map +1 -1
  78. package/lib/ui/icons.d.ts +3 -0
  79. package/lib/ui/icons.d.ts.map +1 -0
  80. package/lib/ui/icons.js +3 -0
  81. package/lib/ui/icons.js.map +1 -0
  82. package/package.json +3 -3
@@ -1,514 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const io=require("@mlightcad/cad-simple-viewer"),z=require("./cad-llm-plugin-register.umd.cjs"),Ec="1.8.0-preview.5",Cc={version:Ec},Ss={"anthropic-dangerous-direct-browser-access":"true"};function ao(e){const t=e.trim().replace(/\/+$/,"");if(t)try{const n=new URL(t);return!n.pathname||n.pathname==="/"?`${t}/v1`:t}catch{return t}}class Yt extends Error{constructor(t,n,r){super(`Model listing failed (${t}) at ${n}`),this.code=t,this.url=n,this.status=r,this.name="AcApLlmModelListingError"}}const Ac="2023-06-01",Oc=1e3;function Es(e,t){const n=ao(e)??"";return t!=="anthropic-messages"?`${n}/models`:`${n.endsWith("/v1")?n.slice(0,-3):n}/v1/models?limit=${Oc}`}function Wo(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t}function Cs(e,t=""){const n=e;let r;if(Array.isArray(n==null?void 0:n.data))r=n.data.map(i=>({raw:i}));else if(n!=null&&n.models&&typeof n.models=="object"&&!Array.isArray(n.models))r=Object.entries(n.models).filter(([,i])=>!!i&&typeof i=="object").map(([i,a])=>({key:i,raw:a}));else throw new Yt("format",t);const o=new Map;for(const{key:i,raw:a}of r){const s=a??{},l=Wo(i,s.id);if(!l||o.has(l))continue;const c=Wo(s.name,s.display_name,s.displayName);o.set(l,c&&c!==l?{id:l,name:c}:{id:l})}return[...o.values()]}async function As(e,t=globalThis.fetch.bind(globalThis),n){const r=Es(e.baseUrl,e.protocol),o=e.apiKey.trim(),i=e.protocol==="anthropic-messages"?{"x-api-key":o,"anthropic-version":Ac,...Ss}:{Authorization:`Bearer ${o}`};let a;try{a=await t(r,{method:"GET",headers:i,signal:n})}catch(l){throw n!=null&&n.aborted?l:new Yt("network",r)}if(!a.ok)throw new Yt("http",r,a.status);let s;try{s=await a.json()}catch{throw new Yt("format",r)}return Cs(s,r)}const Os=["openai-chat","openai-responses","anthropic-messages"],so=["deepseek","deepseek-vl","openai","anthropic"],$c=[{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",vision:!0},{id:"gpt-5.4",name:"GPT-5.4",vision:!0},{id:"gpt-5.5",name:"GPT-5.5",vision:!0},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",vision:!0},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",vision:!0},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",vision:!0}],Vt={deepseek:{protocol:"openai-chat",baseUrl:"https://api.deepseek.com/v1",models:[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",vision:!1},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",vision:!1},{id:"deepseek-chat",name:"DeepSeek Chat (legacy)",vision:!1},{id:"deepseek-reasoner",name:"DeepSeek Reasoner (legacy)",vision:!1}]},"deepseek-vl":{protocol:"openai-chat",baseUrl:"https://api.siliconflow.cn/v1",models:[{id:"deepseek-vl2",name:"DeepSeek VL2",vision:!0},{id:"deepseek-ai/deepseek-vl2-small",name:"DeepSeek VL2 Small",vision:!0},{id:"deepseek-ai/deepseek-vl2-tiny",name:"DeepSeek VL2 Tiny",vision:!0},{id:"deepseek-ai/deepseek-vl2",name:"DeepSeek VL2 (HF)",vision:!0}]},openai:{protocol:"openai-chat",baseUrl:"https://api.openai.com/v1",models:$c},anthropic:{protocol:"anthropic-messages",baseUrl:"https://api.anthropic.com/v1",models:[{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",vision:!0},{id:"claude-sonnet-5",name:"Claude Sonnet 5",vision:!0},{id:"claude-opus-4-6",name:"Claude Opus 4.6",vision:!0},{id:"claude-opus-4-7",name:"Claude Opus 4.7",vision:!0},{id:"claude-opus-4-8",name:"Claude Opus 4.8",vision:!0},{id:"claude-opus-5",name:"Claude Opus 5",vision:!0},{id:"claude-fable-5",name:"Claude Fable 5",vision:!0}]}};function Qe(e){return so.includes(e)}const Nc=[/gpt-5/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-turbo/i,/gpt-4-vision/i,/claude-3/i,/claude-sonnet/i,/claude-opus/i,/claude-haiku/i,/claude-fable/i,/gemini/i,/qwen.*vl/i,/deepseek-vl/i,/glm-4(\.\d+)?v/i,/kimi.*(vl|vision)/i,/llava/i,/pixtral/i];function Xt(e){return Nc.some(t=>t.test(e))}function $s(e,t){return e.vision===Xt(e.id)?Xt(t):e.vision}function Ns(e){var t;return((t=e.name)==null?void 0:t.trim())||e.id}const Rc=1,Rs="cad-agent-plugin-api-key-v1",Lr=12,zr=`enc:v${Rc}:`;function Pc(){var t;return`${typeof((t=globalThis.location)==null?void 0:t.origin)=="string"?globalThis.location.origin:"file://"}:${Rs}`}async function Ps(){const e=new TextEncoder,t=await crypto.subtle.importKey("raw",e.encode(Pc()),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e.encode(Rs),iterations:1e5,hash:"SHA-256"},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function Mc(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t)}function Lc(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}async function zc(e){if(!e)return"";const t=await Ps(),n=crypto.getRandomValues(new Uint8Array(Lr)),r=new TextEncoder().encode(e),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,r),i=new Uint8Array(n.length+o.byteLength);return i.set(n,0),i.set(new Uint8Array(o),n.length),`${zr}${Mc(i)}`}async function Ms(e){if(!e)return"";if(!e.startsWith(zr))return e;try{const t=await Ps(),n=Lc(e.slice(zr.length)),r=n.slice(0,Lr),o=n.slice(Lr),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,o);return new TextDecoder().decode(i)}catch{return""}}const Ls="cad-agent-plugin.llm-config",Dc="cad-agent-plugin.llm-settings",Fn="deepseek",lo=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function pn(){return{providers:[],activeProviderId:Fn,activeModel:Vt[Fn].models[0].id}}function At(e){return{id:e,kind:"builtin",protocol:Vt[e].protocol,baseUrl:"",apiKey:"",models:null}}function qn(){return{id:"",kind:"custom",displayName:"",protocol:"openai-chat",baseUrl:"",apiKey:"",models:[]}}function In(e,t){const n=e.providers.find(r=>r.id===t);return n||(Qe(t)?At(t):void 0)}function Ft(e){return e.models?e.models:e.kind==="builtin"&&Qe(e.id)?Vt[e.id].models:[]}function mn(e){const t=e.baseUrl.trim();return t||(e.kind==="builtin"&&Qe(e.id)?Vt[e.id].baseUrl:"")}function zs(e){const t=In(e,e.activeProviderId)??At(Fn);return{provider:t.id,kind:t.kind,protocol:t.protocol,apiKey:t.apiKey,baseUrl:mn(t),model:e.activeModel}}function Ds(e){const t=In(e,e.activeProviderId),n=t?Ft(t).find(r=>r.id===e.activeModel):void 0;return n?n.vision:Xt(e.activeModel)}function Tn(e){const t=zs(e);if(t.apiKey.trim()&&Ds(e))return t;for(const n of e.providers){if(!n.apiKey.trim())continue;const r=Ft(n).find(o=>o.vision);if(r)return{provider:n.id,kind:n.kind,protocol:n.protocol,apiKey:n.apiKey,baseUrl:mn(n),model:r.id}}}function Zs(e,t){var a;const r=e.providers.some(s=>s.id===t.id)?e.providers.map(s=>s.id===t.id?t:s):[...e.providers,t],o=Ft(t),i=e.activeProviderId===t.id&&(o.length===0||o.some(s=>s.id===e.activeModel));return{providers:r,activeProviderId:t.id,activeModel:i?e.activeModel:((a=o[0])==null?void 0:a.id)??""}}function js(e,t){const n=e.providers.filter(r=>r.id!==t);return e.activeProviderId!==t?{...e,providers:n}:uo({providers:n,activeProviderId:"",activeModel:""})}function Us(e){var i,a,s;const t=e.apiKey??"",n=((i=e.baseUrl)==null?void 0:i.trim())??"",r=e.provider??"";if(Qe(r)){const l=Vt[r],c=((a=e.model)==null?void 0:a.trim())||l.models[0].id;return{providers:[{...At(r),apiKey:t,baseUrl:n===l.baseUrl?"":n}],activeProviderId:r,activeModel:c}}const o=(s=e.model)==null?void 0:s.trim();return r!=="openai-compatible"||!o?pn():{providers:[{...qn(),id:r,baseUrl:n,apiKey:t,models:[{id:o,vision:Xt(o)}]}],activeProviderId:r,activeModel:o}}function Zc(e,t){const n=e.id??"";if(e.kind==="builtin"||Qe(n))return Qe(n)?{...At(n),baseUrl:e.baseUrl??"",apiKey:t,models:Dr(e.models)}:void 0;if(lo.test(n))return{id:n,kind:"custom",displayName:e.displayName??"",protocol:e.protocol??"openai-chat",baseUrl:e.baseUrl??"",apiKey:t,models:Dr(e.models)??[]}}function Dr(e){return Array.isArray(e)?e.flatMap(t=>{const n=t;if(!n||typeof n!="object")return[];if(typeof n.id!="string"||!n.id.trim())return[];const r=typeof n.name=="string"?n.name.trim():"";return[{id:n.id,...r?{name:r}:{},vision:!!n.vision}]}):null}function uo(e){var n;if(In(e,e.activeProviderId))return e;const t=e.providers.find(r=>r.apiKey.trim())??At(Fn);return{...e,activeProviderId:t.id,activeModel:((n=Ft(t)[0])==null?void 0:n.id)??""}}async function jc(e){const t=JSON.parse(e),n=t.apiKeyEnc?await Ms(t.apiKeyEnc):t.apiKey??"";return{...t,apiKey:n}}async function Sn(){try{const e=localStorage.getItem(Ls);if(!e){const o=localStorage.getItem(Dc);return o?Us(await jc(o)):pn()}const t=JSON.parse(e),n=[];for(const o of t.providers??[]){const i=o.apiKeyEnc?await Ms(o.apiKeyEnc):"",a=Zc(o,i);a&&!n.some(s=>s.id===a.id)&&n.push(a)}const r=pn();return uo({providers:n,activeProviderId:t.activeProviderId??r.activeProviderId,activeModel:t.activeModel??r.activeModel})}catch{return pn()}}async function Zr(e){const t=[];for(const r of e.providers)t.push({id:r.id,kind:r.kind,...r.kind==="custom"?{displayName:r.displayName,protocol:r.protocol}:{},baseUrl:r.baseUrl,models:r.models,apiKeyEnc:r.apiKey?await zc(r.apiKey):""});const n={version:2,providers:t,activeProviderId:e.activeProviderId,activeModel:e.activeModel};localStorage.setItem(Ls,JSON.stringify(n)),Ur.dispatchEvent(new CustomEvent(jr,{detail:e}))}const jr="change",Ur=new EventTarget;function Uc(e){const t=n=>e(n.detail);return Ur.addEventListener(jr,t),()=>Ur.removeEventListener(jr,t)}async function Bc(){const e=await Sn();return{configured:e.providers.some(t=>t.apiKey.trim()),vision:!!Tn(e)}}function Vc(e,t){return e===null||t===null?e===t:e.length===t.length&&e.every((n,r)=>n.id===t[r].id&&(n.name??"")===(t[r].name??"")&&n.vision===t[r].vision)}function Bs(e,t){return e.id===t.id&&e.kind===t.kind&&(e.displayName??"")===(t.displayName??"")&&e.protocol===t.protocol&&e.baseUrl===t.baseUrl&&e.apiKey===t.apiKey&&Vc(e.models,t.models)}const Fc={deepseek:"providerDeepseek","deepseek-vl":"providerDeepseekVl",openai:"providerOpenai",anthropic:"providerAnthropic"};function co(e){return z.llmT(Fc[e])}function po(e){var t;return e.kind==="builtin"&&Qe(e.id)?co(e.id):((t=e.displayName)==null?void 0:t.trim())||e.id}function Vs(e){const{activeProviderId:t,activeModel:n}=e,r=e.providers.filter(o=>o.apiKey.trim()).map(o=>o.id);return r.includes(t)||r.unshift(t),r.flatMap(o=>{const i=In(e,o);if(!i)return[];const a=[...Ft(i)];return o===t&&n&&!a.some(s=>s.id===n)&&a.push({id:n,vision:!1}),[{providerId:o,label:po(i),options:a.map(s=>({providerId:o,modelId:s.id,label:Ns(s),vision:s.vision}))}]})}const qc=`
2
- .ml-ui-dialog.ml-llm-settings-dialog {
3
- display: flex;
4
- flex-direction: column;
5
- width: min(860px, calc(100% - 32px));
6
- max-width: none;
7
- max-height: calc(100% - 24px);
8
- overflow: hidden;
9
- font-size: 12px;
10
- }
11
-
12
- .ml-llm-settings-dialog .ml-ui-dialog-header {
13
- flex-shrink: 0;
14
- margin-bottom: 10px;
15
- }
16
-
17
- /* Only the body scrolls, and only on very short hosts: the footer buttons
18
- always stay in view. */
19
- .ml-llm-settings-dialog .ml-ui-dialog-body {
20
- display: flex;
21
- flex: 1 1 auto;
22
- flex-direction: column;
23
- gap: 8px;
24
- min-height: 0;
25
- overflow-y: auto;
26
- }
27
-
28
- .ml-llm-settings-dialog .ml-ui-dialog-footer:not(:empty) {
29
- flex-shrink: 0;
30
- align-items: center;
31
- margin-top: 10px;
32
- padding-top: 10px;
33
- border-top: 1px solid var(--ml-ui-border, #dcdfe6);
34
- }
35
-
36
- /* "Model in use": label and picker on one row. */
37
- .ml-llm-section > .ml-llm-field {
38
- flex-direction: row;
39
- align-items: center;
40
- gap: 10px;
41
- }
42
-
43
- .ml-llm-section > .ml-llm-field > select {
44
- flex: 1 1 auto;
45
- }
46
-
47
- .ml-llm-columns {
48
- display: grid;
49
- grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
50
- gap: 16px;
51
- align-items: start;
52
- }
53
-
54
- .ml-llm-column {
55
- display: flex;
56
- flex-direction: column;
57
- gap: 8px;
58
- min-width: 0;
59
- }
60
-
61
- @media (max-width: 720px) {
62
- .ml-llm-columns {
63
- grid-template-columns: minmax(0, 1fr);
64
- }
65
- }
66
-
67
- .ml-llm-footer-message {
68
- display: flex;
69
- flex: 1;
70
- flex-direction: column;
71
- min-width: 0;
72
- }
73
-
74
- .ml-llm-settings-dialog input,
75
- .ml-llm-settings-dialog select {
76
- box-sizing: border-box;
77
- min-width: 0;
78
- padding: 6px 8px;
79
- border: 1px solid var(--ml-ui-border, #dcdfe6);
80
- border-radius: 4px;
81
- background: var(--ml-ui-bg, #ffffff);
82
- color: var(--ml-ui-text, #303133);
83
- font: inherit;
84
- }
85
-
86
- .ml-llm-settings-dialog input:focus,
87
- .ml-llm-settings-dialog select:focus {
88
- outline: none;
89
- border-color: var(--ml-ui-accent, #0b84ff);
90
- }
91
-
92
- .ml-llm-settings-dialog input:disabled {
93
- color: var(--ml-ui-text-muted, #606266);
94
- cursor: not-allowed;
95
- }
96
-
97
- .ml-llm-settings-dialog input[type='checkbox'] {
98
- margin: 0;
99
- padding: 0;
100
- accent-color: var(--ml-ui-accent, #0b84ff);
101
- }
102
-
103
- .ml-llm-settings-dialog [hidden] {
104
- display: none !important;
105
- }
106
-
107
- .ml-llm-section,
108
- .ml-llm-group,
109
- .ml-llm-catalog {
110
- display: flex;
111
- flex-direction: column;
112
- gap: 8px;
113
- }
114
-
115
- .ml-llm-section-title,
116
- .ml-llm-field-label {
117
- font-weight: 600;
118
- }
119
-
120
- .ml-llm-field-row {
121
- display: grid;
122
- grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
123
- gap: 8px;
124
- }
125
-
126
- .ml-llm-field {
127
- display: flex;
128
- flex-direction: column;
129
- gap: 4px;
130
- }
131
-
132
- .ml-llm-hint,
133
- .ml-llm-warning,
134
- .ml-llm-error,
135
- .ml-llm-validation,
136
- .ml-llm-status {
137
- margin: 0;
138
- font-size: 11px;
139
- line-height: 1.4;
140
- }
141
-
142
- .ml-llm-hint,
143
- .ml-llm-meta {
144
- color: var(--ml-ui-text-muted, #606266);
145
- }
146
-
147
- .ml-llm-meta {
148
- font-size: 11px;
149
- font-weight: normal;
150
- }
151
-
152
- .ml-llm-warning,
153
- .ml-llm-validation {
154
- color: #b7791f;
155
- }
156
-
157
- .ml-llm-error {
158
- color: var(--ml-ui-danger, #f56c6c);
159
- word-break: break-word;
160
- }
161
-
162
- .ml-llm-status {
163
- color: var(--ml-ui-accent, #0b84ff);
164
- }
165
-
166
- .ml-llm-divider {
167
- flex-shrink: 0;
168
- height: 1px;
169
- margin: 2px 0;
170
- background: var(--ml-ui-border, #dcdfe6);
171
- }
172
-
173
- .ml-llm-segmented {
174
- display: flex;
175
- gap: 2px;
176
- padding: 2px;
177
- border: 1px solid var(--ml-ui-border, #dcdfe6);
178
- border-radius: 6px;
179
- }
180
-
181
- .ml-llm-segmented-item {
182
- flex: 1 1 0;
183
- min-width: 0;
184
- padding: 5px 8px;
185
- border: 1px solid transparent;
186
- border-radius: 4px;
187
- background: transparent;
188
- color: var(--ml-ui-text-muted, #606266);
189
- font: inherit;
190
- cursor: pointer;
191
- white-space: nowrap;
192
- overflow: hidden;
193
- text-overflow: ellipsis;
194
- }
195
-
196
- .ml-llm-segmented-item:hover:not(.is-active) {
197
- color: var(--ml-ui-text, #303133);
198
- }
199
-
200
- .ml-llm-segmented-item.is-active {
201
- border-color: var(--ml-ui-accent, #0b84ff);
202
- background: var(--ml-ui-accent, #0b84ff);
203
- color: #ffffff;
204
- }
205
-
206
- .ml-llm-disclosure {
207
- display: inline-flex;
208
- align-items: center;
209
- align-self: flex-start;
210
- gap: 4px;
211
- padding: 2px 4px 2px 0;
212
- border: none;
213
- background: transparent;
214
- color: var(--ml-ui-text, #303133);
215
- font: inherit;
216
- cursor: pointer;
217
- }
218
-
219
- .ml-llm-disclosure-icon {
220
- width: 16px;
221
- height: 16px;
222
- transition: transform 0.15s ease;
223
- }
224
-
225
- .ml-llm-disclosure-icon.is-open {
226
- transform: rotate(90deg);
227
- }
228
-
229
- .ml-llm-link-btn {
230
- padding: 2px 0;
231
- border: none;
232
- background: transparent;
233
- color: var(--ml-ui-accent, #0b84ff);
234
- font: inherit;
235
- cursor: pointer;
236
- white-space: nowrap;
237
- }
238
-
239
- .ml-llm-link-btn:hover:not(:disabled) {
240
- text-decoration: underline;
241
- }
242
-
243
- .ml-llm-link-btn:disabled {
244
- color: var(--ml-ui-text-muted, #606266);
245
- opacity: 0.6;
246
- cursor: not-allowed;
247
- }
248
-
249
- .ml-llm-catalog-head {
250
- display: flex;
251
- align-items: flex-start;
252
- justify-content: space-between;
253
- gap: 8px;
254
- }
255
-
256
- .ml-llm-catalog-heading {
257
- display: flex;
258
- flex-direction: column;
259
- gap: 2px;
260
- min-width: 0;
261
- }
262
-
263
- .ml-llm-catalog-actions {
264
- display: flex;
265
- flex-shrink: 0;
266
- gap: 12px;
267
- }
268
-
269
- .ml-llm-empty {
270
- margin: 0;
271
- padding: 14px 10px;
272
- border: 1px dashed var(--ml-ui-border, #dcdfe6);
273
- border-radius: 6px;
274
- color: var(--ml-ui-text-muted, #606266);
275
- text-align: center;
276
- line-height: 1.5;
277
- }
278
-
279
- .ml-llm-model-rows,
280
- .ml-llm-picker-list {
281
- margin: 0;
282
- padding: 0;
283
- list-style: none;
284
- }
285
-
286
- .ml-llm-model-rows {
287
- max-height: 240px;
288
- overflow-y: auto;
289
- display: flex;
290
- flex-direction: column;
291
- gap: 6px;
292
- }
293
-
294
- .ml-llm-model-row {
295
- display: flex;
296
- align-items: center;
297
- gap: 6px;
298
- }
299
-
300
- .ml-llm-settings-dialog .ml-llm-model-id {
301
- flex: 1 1 auto;
302
- font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
303
- }
304
-
305
- .ml-llm-model-vision {
306
- display: inline-flex;
307
- flex-shrink: 0;
308
- align-items: center;
309
- gap: 4px;
310
- font-size: 11px;
311
- color: var(--ml-ui-text-muted, #606266);
312
- cursor: pointer;
313
- white-space: nowrap;
314
- }
315
-
316
- .ml-llm-model-remove {
317
- display: inline-flex;
318
- flex-shrink: 0;
319
- align-items: center;
320
- justify-content: center;
321
- width: 24px;
322
- height: 24px;
323
- padding: 0;
324
- border: none;
325
- border-radius: 4px;
326
- background: transparent;
327
- color: var(--ml-ui-text-muted, #606266);
328
- cursor: pointer;
329
- }
330
-
331
- .ml-llm-model-remove:hover {
332
- color: var(--ml-ui-danger, #f56c6c);
333
- }
334
-
335
- .ml-llm-model-remove svg,
336
- .ml-llm-add-model svg {
337
- width: 14px;
338
- height: 14px;
339
- }
340
-
341
- .ml-llm-settings-dialog .ml-llm-add-model {
342
- display: inline-flex;
343
- align-items: center;
344
- align-self: flex-start;
345
- gap: 4px;
346
- }
347
-
348
- .ml-llm-picker {
349
- display: flex;
350
- flex-direction: column;
351
- gap: 8px;
352
- padding: 8px;
353
- border: 1px solid var(--ml-ui-border, #dcdfe6);
354
- border-radius: 6px;
355
- }
356
-
357
- .ml-llm-picker-title {
358
- display: flex;
359
- align-items: baseline;
360
- justify-content: space-between;
361
- gap: 8px;
362
- font-weight: 600;
363
- }
364
-
365
- .ml-llm-picker-toolbar {
366
- display: flex;
367
- align-items: center;
368
- gap: 8px;
369
- }
370
-
371
- .ml-llm-picker-toolbar input {
372
- flex: 1 1 auto;
373
- }
374
-
375
- .ml-llm-picker-list {
376
- max-height: 180px;
377
- overflow-y: auto;
378
- }
379
-
380
- .ml-llm-picker-item {
381
- display: flex;
382
- align-items: center;
383
- gap: 8px;
384
- padding: 4px 6px;
385
- border-radius: 4px;
386
- cursor: pointer;
387
- }
388
-
389
- .ml-llm-picker-item:hover {
390
- background: color-mix(in srgb, var(--ml-ui-accent, #0b84ff) 10%, transparent);
391
- }
392
-
393
- .ml-llm-picker-id {
394
- min-width: 0;
395
- overflow: hidden;
396
- text-overflow: ellipsis;
397
- white-space: nowrap;
398
- font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
399
- }
400
-
401
- .ml-llm-picker-footer {
402
- display: flex;
403
- justify-content: flex-end;
404
- gap: 8px;
405
- }
406
-
407
- .ml-llm-settings-dialog .ml-ui-dialog-btn:disabled {
408
- opacity: 0.5;
409
- filter: none;
410
- cursor: not-allowed;
411
- }
412
-
413
- .ml-llm-settings-dialog .ml-llm-danger {
414
- color: var(--ml-ui-danger, #f56c6c);
415
- }
416
-
417
- `.trim(),Gc={"openai-chat":"protocolOpenaiChat","openai-responses":"protocolOpenaiResponses","anthropic-messages":"protocolAnthropicMessages"},Mn=`
418
- `,Hc="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z",Jc="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",Kc="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z";function Yo(e){return{...e,models:e.models?e.models.map(t=>({...t})):null}}function Xo(e){var r;const t=new Set,n=[];for(const o of e){const i=o.id.trim();if(!i||t.has(i))continue;t.add(i);const a=(r=o.name)==null?void 0:r.trim();n.push({id:i,...a?{name:a}:{},vision:o.vision})}return n}function Wc(e){try{const t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}function K(e,t="",n){const r=document.createElement(e);return t&&(r.className=t),n!==void 0&&(r.textContent=n),r}function gr(e,t=""){const n="http://www.w3.org/2000/svg",r=document.createElementNS(n,"svg");r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("aria-hidden","true"),t&&r.setAttribute("class",t);const o=document.createElementNS(n,"path");return o.setAttribute("fill","currentColor"),o.setAttribute("d",e),r.appendChild(o),r}function Xe(e,t,n){const r=K("button",e,t);return r.type="button",r.addEventListener("click",n),r}function vt(e,t,n={}){const r=K("input");return r.type=n.type??"text",r.value=e,r.spellcheck=!1,n.secret&&(r.autocomplete="off"),n.placeholder&&(r.placeholder=n.placeholder),r.addEventListener("input",()=>t(r.value)),r}function lt(e,t){const n=K("label","ml-llm-field");return n.append(K("span","ml-llm-field-label",e),t),n}function Qo(...e){const t=K("div","ml-llm-field-row");return t.append(...e),t}const Ze=class Ze extends io.AcUiDialog{constructor(t,n){var i,a;super({host:n.host,title:z.llmT("title"),closeLabel:z.llmT("close"),dialogClassName:"ml-llm-settings-dialog"}),this.fetching=!1,this.fetchError="",this.candidates=null,this.flipped=new Set,this.candidateQuery="",this.statusMessage="",this.updaters=[],Ze.ensureSettingsStyles(),this.config=t;const r=t.activeProviderId;this.mode=Qe(r)?"builtin":"custom",this.builtinId=Qe(r)?r:"deepseek",this.customId=((i=this.storedProvider(r))==null?void 0:i.kind)==="custom"?r:((a=this.customProviders()[0])==null?void 0:a.id)??"",this.builtinDraft=this.loadBuiltin(this.builtinId),this.customDraft=this.loadCustom(this.customId),this.showAdvanced=this.builtinDraft.baseUrl.trim().length>0,this.render();const o=this.bodyEl.querySelector("select, input");o&&this.focusAfterOpen(o)}static async open(t={}){if(Ze.openInstance)return Ze.openInstance.show();const n=await Sn(),r=new Ze(n,t);return Ze.openInstance=r,r.show()}close(){var t;Ze.openInstance===this&&this.isDirty()&&!window.confirm(z.llmT("discardChangesConfirm"))||(Ze.openInstance===this&&(Ze.openInstance=null),(t=this.fetchAbort)==null||t.abort(),super.close())}storedProvider(t){return this.config.providers.find(n=>n.id===t)}customProviders(){return this.config.providers.filter(t=>t.kind==="custom")}loadBuiltin(t){return Yo(this.storedProvider(t)??At(t))}loadCustom(t){const n=t?this.storedProvider(t):void 0;return Yo(n??qn())}get draft(){return this.mode==="builtin"?this.builtinDraft:this.customDraft}isNewCustom(){return this.mode==="custom"&&!this.storedProvider(this.customId)}isDirty(){const t=this.mode==="builtin"?this.storedProvider(this.builtinId)??At(this.builtinId):this.storedProvider(this.customId)??qn();return!Bs(this.draft,t)}displayModels(){return Ft(this.draft)}setModels(t){this.draft.models=t}fetchBlockedReason(){return mn(this.draft)?this.draft.apiKey.trim()?"":z.llmT("fetchNeedsKey"):z.llmT("fetchNeedsBaseUrl")}providerIdError(){if(!this.isNewCustom())return"";const t=this.customDraft.id;return t?lo.test(t)?Qe(t)||this.storedProvider(t)?z.llmT("providerIdTaken"):"":z.llmT("providerIdInvalid"):""}baseUrlError(){const t=this.draft.baseUrl.trim();return t&&!Wc(t)?z.llmT("baseUrlInvalid"):""}validationMessage(){if(this.providerIdError()||this.baseUrlError())return"";if(this.mode==="custom"){if(!this.customDraft.id)return z.llmT("needsProviderId");if(!this.customDraft.baseUrl.trim())return z.llmT("needsBaseUrl")}return Xo(this.displayModels()).length?"":z.llmT("needsModels")}canSave(){return!this.fetching&&!this.candidates&&!this.providerIdError()&&!this.baseUrlError()&&!this.validationMessage()}render(){this.updaters=[];const t=K("div","ml-llm-column");t.append(K("div","ml-llm-section-title",z.llmT("providerSettings")),...this.renderEditor());const n=K("div","ml-llm-column");n.appendChild(this.renderCatalog());const r=K("div","ml-llm-columns");r.append(t,n),this.bodyEl.replaceChildren(this.renderActiveModel(),K("div","ml-llm-divider"),r),this.footerEl.replaceChildren(...this.renderFooter()),this.refresh()}refresh(){for(const t of this.updaters)t()}onDraftEdited(){this.statusMessage="",this.refresh()}watchedText(t,n,r){const o=K(t,n);return this.updaters.push(()=>{const i=r();o.textContent=i,o.hidden=!i}),o}errorOrHint(t,n){const r=this.watchedText("p","ml-llm-error",t),o=K("p","ml-llm-hint",n);return this.updaters.push(()=>{o.hidden=!!t()}),[r,o]}renderActiveModel(){const t=K("section","ml-llm-section"),n=K("select"),r=Vs(this.config);for(const i of r){const a=K("optgroup");a.label=i.label;for(const s of i.options){const l=K("option","",s.label);l.value=`${s.providerId}${Mn}${s.modelId}`,a.appendChild(l)}n.appendChild(a)}return n.value=`${this.config.activeProviderId}${Mn}${this.config.activeModel}`,n.addEventListener("change",()=>{this.selectActiveModel(n.value)}),t.appendChild(lt(z.llmT("activeModel"),n)),this.config.providers.some(i=>i.apiKey.trim())?Tn(this.config)||t.appendChild(K("p","ml-llm-warning",z.llmT("visionMissing"))):t.appendChild(K("p","ml-llm-warning",z.llmT("activeModelNone"))),t.appendChild(K("p","ml-llm-hint",z.llmT("activeModelHint"))),t}renderEditor(){const t=K("div","ml-llm-segmented");t.setAttribute("role","tablist");for(const[r,o]of[["builtin","tabBuiltin"],["custom","tabCustom"]]){const i=Xe("ml-llm-segmented-item",z.llmT(o),()=>this.switchMode(r));i.setAttribute("role","tab"),i.setAttribute("aria-selected",String(this.mode===r)),this.mode===r&&i.classList.add("is-active"),t.appendChild(i)}const n=K("p","ml-llm-hint",z.llmT(this.mode==="builtin"?"builtinIntro":"customIntro"));return[t,n,...this.mode==="builtin"?this.renderBuiltinFields():this.renderCustomFields()]}renderBuiltinFields(){var s;const t=this.builtinDraft,n=K("select");for(const l of so){const c=co(l),p=K("option","",(s=this.storedProvider(l))!=null&&s.apiKey.trim()?`${c} · ${z.llmT("providerConfigured")}`:c);p.value=l,n.appendChild(p)}n.value=this.builtinId,n.addEventListener("change",()=>{const l=n.value;Qe(l)&&(this.resetFetch(),this.builtinId=l,this.builtinDraft=this.loadBuiltin(l),this.showAdvanced=this.builtinDraft.baseUrl.trim().length>0,this.statusMessage="",this.render())});const r=vt(t.apiKey,l=>{t.apiKey=l,this.onDraftEdited()},{type:"password",secret:!0,placeholder:z.llmT("apiKeyPlaceholder")}),o=this.watchedText("p","ml-llm-warning",()=>t.apiKey.trim()?"":z.llmT("apiKeyRequired")),i=Xe("ml-llm-disclosure","",()=>{this.showAdvanced=!this.showAdvanced,this.render()});i.setAttribute("aria-expanded",String(this.showAdvanced)),i.append(gr(Hc,`ml-llm-disclosure-icon${this.showAdvanced?" is-open":""}`),document.createTextNode(z.llmT("advancedSettings")));const a=[lt(z.llmT("provider"),n),lt(z.llmT("apiKey"),r),o,i];if(this.showAdvanced){const l=Vt[this.builtinId].baseUrl,c=K("div","ml-llm-group");c.append(lt(z.llmT("baseUrl"),vt(t.baseUrl,p=>{t.baseUrl=p,this.onDraftEdited()},{placeholder:l})),...this.errorOrHint(()=>this.baseUrlError(),z.llmT("baseUrlDefault",{url:l}))),this.builtinId==="deepseek-vl"&&c.appendChild(K("p","ml-llm-hint",z.llmT("providerDeepseekVlHint"))),a.push(c)}return a}renderCustomFields(){const t=this.customDraft,n=[],r=this.customProviders();if(r.length){const l=K("select");for(const p of r){const g=K("option","",po(p));g.value=p.id,l.appendChild(g)}const c=K("option","",z.llmT("newCustomProvider"));c.value="",l.appendChild(c),l.value=this.customId,l.addEventListener("change",()=>{this.resetFetch(),this.customId=l.value,this.customDraft=this.loadCustom(this.customId),this.statusMessage="",this.render()}),n.push(lt(z.llmT("customProvider"),l))}const o=vt(t.id,l=>{t.id=l.trim(),this.onDraftEdited()},{placeholder:"acme-gateway",secret:!0});o.disabled=!this.isNewCustom();const i=vt(t.displayName??"",l=>{t.displayName=l,this.onDraftEdited()},{placeholder:z.llmT("displayName")}),a=K("select");for(const l of Os){const c=K("option","",z.llmT(Gc[l]));c.value=l,a.appendChild(c)}a.value=t.protocol,a.addEventListener("change",()=>{t.protocol=a.value,this.onDraftEdited()});const s=vt(t.apiKey,l=>{t.apiKey=l,this.onDraftEdited()},{type:"password",secret:!0,placeholder:z.llmT("apiKeyPlaceholder")});return n.push(Qo(lt(z.llmT("providerId"),o),lt(z.llmT("displayName"),i)),...this.errorOrHint(()=>this.providerIdError(),z.llmT("providerIdHint")),lt(z.llmT("baseUrl"),vt(t.baseUrl,l=>{t.baseUrl=l,this.onDraftEdited()},{placeholder:"https://gateway.example/v1"})),...this.errorOrHint(()=>this.baseUrlError(),z.llmT("baseUrlHint")),Qo(lt(z.llmT("protocol"),a),lt(z.llmT("apiKey"),s))),n}renderCatalog(){const t=K("section","ml-llm-catalog");t.setAttribute("aria-label",z.llmT("models"));const n=K("div","ml-llm-catalog-head"),r=K("div","ml-llm-catalog-heading");r.appendChild(K("span","ml-llm-field-label",z.llmT("models"))),this.mode==="builtin"&&r.appendChild(this.watchedText("span","ml-llm-meta",()=>z.llmT(this.builtinDraft.models===null?"modelsDefault":"modelsCustomized")));const o=K("div","ml-llm-catalog-actions");if(this.mode==="builtin"){const a=Xe("ml-llm-link-btn",z.llmT("resetModels"),()=>{this.closePicker(),this.builtinDraft.models=null,this.statusMessage="",this.render()});this.updaters.push(()=>{a.hidden=this.builtinDraft.models===null,a.disabled=this.fetching}),o.appendChild(a)}const i=Xe("ml-llm-link-btn","",()=>{this.fetchModels()});return this.updaters.push(()=>{const a=this.fetchBlockedReason();i.textContent=z.llmT(this.fetching?"fetching":"fetchModels"),i.disabled=this.fetching||!!a||!!this.candidates,i.title=a}),o.appendChild(i),n.append(r,o),t.appendChild(n),t.append(...this.candidates?this.renderPicker():this.renderModelRows(),this.watchedText("p","ml-llm-error",()=>this.fetchError)),t}renderModelRows(){const t=this.displayModels();if(!t.length)return[K("div","ml-llm-empty",z.llmT("modelsEmpty"))];const n=K("ul","ml-llm-model-rows");return t.forEach((r,o)=>{const i=K("li","ml-llm-model-row"),a=K("input");a.type="checkbox",a.checked=r.vision;const s=vt(r.id,p=>{const g=this.displayModels()[o],x=$s(g,p);a.checked=x,this.updateModel(o,{id:p,vision:x})});s.className="ml-llm-model-id",s.title=r.name??r.id,s.placeholder=z.llmT("modelId"),s.setAttribute("aria-label",`${z.llmT("modelId")} ${o+1}`),a.addEventListener("change",()=>this.updateModel(o,{vision:a.checked}));const l=K("label","ml-llm-model-vision");l.title=z.llmT("modelVisionHint"),l.append(a,document.createTextNode(z.llmT("modelVision")));const c=Xe("ml-llm-model-remove","",()=>{this.setModels(this.displayModels().filter((p,g)=>g!==o).map(p=>({...p}))),this.statusMessage="",this.render()});c.title=z.llmT("removeModel"),c.setAttribute("aria-label",`${z.llmT("removeModel")} ${o+1}`),c.appendChild(gr(Jc)),i.append(s,l,c),n.appendChild(i)}),[n,this.renderAddModelButton()]}renderAddModelButton(){const t=Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary ml-llm-add-model","",()=>{var r;this.setModels([...this.displayModels().map(o=>({...o})),{id:"",vision:!1}]),this.statusMessage="",this.render();const n=this.bodyEl.querySelectorAll(".ml-llm-model-id");(r=n[n.length-1])==null||r.focus()});return t.append(gr(Kc),document.createTextNode(z.llmT("addModel"))),t}updateModel(t,n){this.setModels(this.displayModels().map((r,o)=>o===t?{...r,...n}:{...r})),this.onDraftEdited()}renderPicker(){const t=K("div","ml-llm-picker"),n=K("div","ml-llm-picker-title",z.llmT("fetchTitle"));n.appendChild(this.watchedText("span","ml-llm-meta",()=>this.pickedSummary()));const r=K("div","ml-llm-picker-toolbar"),o=K("div"),i=vt(this.candidateQuery,c=>{this.candidateQuery=c,this.renderPickerList(o),this.refresh()},{type:"search",placeholder:z.llmT("fetchSearch")});i.setAttribute("aria-label",z.llmT("fetchSearch"));const a=Xe("ml-llm-link-btn","",()=>{this.toggleVisibleCandidates(),this.renderPickerList(o),this.refresh()});this.updaters.push(()=>{a.textContent=z.llmT(this.allVisiblePicked()?"fetchDeselectAll":"fetchSelectAll"),a.disabled=!this.visibleCandidates().length}),r.append(i,a),this.renderPickerList(o);const s=K("div","ml-llm-picker-footer"),l=Xe("ml-ui-dialog-btn",z.llmT("fetchAdopt"),()=>{const c=this.pickedModels();c.length&&(this.setModels(c),this.closePicker(),this.statusMessage="",this.render())});return this.updaters.push(()=>{const c=!this.pickedModels().length;l.disabled=c,l.title=c?z.llmT("fetchKeepOne"):""}),s.append(Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary",z.llmT("cancel"),()=>{this.closePicker(),this.render()}),l),t.append(n,r,o,s),[t]}renderPickerList(t){const n=this.visibleCandidates();if(!n.length){t.replaceChildren(K("p","ml-llm-empty",z.llmT("fetchNoMatches")));return}const r=K("ul","ml-llm-picker-list");for(const o of n){const i=K("li"),a=K("label","ml-llm-picker-item"),s=K("input");s.type="checkbox",s.checked=this.isPicked(o.id),s.addEventListener("change",()=>{this.flipped.delete(o.id)||this.flipped.add(o.id),this.refresh()});const l=K("span","ml-llm-picker-id",o.id);l.title=o.name??o.id,a.append(s,l),i.appendChild(a),r.appendChild(i)}t.replaceChildren(r)}configuredIds(){return new Set(this.displayModels().map(t=>t.id).filter(Boolean))}pickedByDefault(t,n=this.configuredIds()){return n.size===0||n.has(t)}isPicked(t,n=this.configuredIds()){return this.pickedByDefault(t,n)!==this.flipped.has(t)}visibleCandidates(){const t=this.candidateQuery.trim().toLowerCase(),n=this.candidates??[];return t?n.filter(r=>{var o;return r.id.toLowerCase().includes(t)||!!((o=r.name)!=null&&o.toLowerCase().includes(t))}):n}allVisiblePicked(){const t=this.visibleCandidates(),n=this.configuredIds();return t.length>0&&t.every(r=>this.isPicked(r.id,n))}pickedSummary(){const t=this.candidates??[],n=this.configuredIds();return`${t.filter(o=>this.isPicked(o.id,n)).length} / ${t.length}`}toggleVisibleCandidates(){const t=!this.allVisiblePicked(),n=this.configuredIds();for(const r of this.visibleCandidates())this.pickedByDefault(r.id,n)===t?this.flipped.delete(r.id):this.flipped.add(r.id)}pickedModels(){const t=this.candidates??[],n=this.configuredIds(),r=new Set(t.map(s=>s.id)),o=this.displayModels().filter(s=>!r.has(s.id)||this.isPicked(s.id,n)).map(s=>({...s})),i=new Set(o.map(s=>s.id)),a=t.filter(s=>this.isPicked(s.id,n)&&!i.has(s.id)).map(s=>({id:s.id,...s.name?{name:s.name}:{},vision:Xt(s.id)}));return[...o,...a]}closePicker(){this.candidates=null,this.flipped=new Set,this.candidateQuery=""}resetFetch(){var t;(t=this.fetchAbort)==null||t.abort(),this.fetchAbort=void 0,this.fetching=!1,this.fetchError="",this.closePicker()}listingErrorMessage(t){return t instanceof Yt?t.code==="network"?z.llmT("fetchFailedNetwork",{url:t.url}):t.code==="http"?z.llmT("fetchFailedHttp",{status:String(t.status??"")}):z.llmT("fetchFailedFormat"):z.llmT("fetchFailedFormat")}async fetchModels(){var n;if(this.fetching||this.fetchBlockedReason())return;(n=this.fetchAbort)==null||n.abort();const t=new AbortController;this.fetchAbort=t,this.fetching=!0,this.fetchError="",this.refresh();try{const r=await As({protocol:this.draft.protocol,baseUrl:mn(this.draft),apiKey:this.draft.apiKey},void 0,t.signal);if(t.signal.aborted)return;if(!r.length){this.fetchError=z.llmT("fetchEmpty");return}this.flipped=new Set,this.candidateQuery="",this.candidates=r}catch(r){t.signal.aborted||(this.fetchError=this.listingErrorMessage(r))}finally{this.fetchAbort===t&&(this.fetching=!1,this.fetchAbort=void 0,this.render())}}switchMode(t){t!==this.mode&&(this.resetFetch(),this.mode=t,this.statusMessage="",this.render())}renderFooter(){const t=[];this.mode==="custom"&&!this.isNewCustom()&&t.push(Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary ml-llm-danger",z.llmT("deleteProvider"),()=>void this.deleteProvider()));const n=K("div","ml-llm-footer-message");n.append(this.watchedText("span","ml-llm-validation",()=>this.validationMessage()),this.watchedText("span","ml-llm-status",()=>this.statusMessage)),t.push(n),t.push(Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary",z.llmT("close"),()=>this.close()));const r=Xe("ml-ui-dialog-btn",z.llmT(this.isNewCustom()?"createProvider":"save"),()=>void this.save());return this.updaters.push(()=>{r.disabled=!this.canSave()}),t.push(r),t}async commit(t){this.config=t,await Zr(t),this.builtinDraft=this.loadBuiltin(this.builtinId),this.customDraft=this.loadCustom(this.customId),this.statusMessage=z.llmT("saved"),this.render()}async save(){var r;if(!this.canSave())return;const t=this.draft,n={...t,id:t.id.trim(),displayName:(r=t.displayName)==null?void 0:r.trim(),baseUrl:t.baseUrl.trim(),apiKey:t.apiKey.trim(),models:t.models?Xo(t.models):null};n.kind==="builtin"&&delete n.displayName,n.kind==="custom"&&(this.customId=n.id),await this.commit(Zs(this.config,n))}async deleteProvider(){var r;const t=this.customId;if(!this.storedProvider(t)||!window.confirm(z.llmT("deleteProviderConfirm",{id:t})))return;const n=js(this.config,t);this.customId=((r=n.providers.find(o=>o.kind==="custom"))==null?void 0:r.id)??"",await this.commit(n)}async selectActiveModel(t){const n=t.indexOf(Mn);if(n<0)return;const r=t.slice(0,n),o=t.slice(n+Mn.length);r===this.config.activeProviderId&&o===this.config.activeModel||(this.config={...this.config,activeProviderId:r,activeModel:o},await Zr(this.config),this.statusMessage=z.llmT("saved"),this.render())}static ensureSettingsStyles(){if(document.getElementById(Ze.settingsStyleId))return;const t=document.createElement("style");t.id=Ze.settingsStyleId,t.textContent=qc,document.head.appendChild(t)}};Ze.settingsStyleId="ml-llm-settings-styles",Ze.openInstance=null;let Gn=Ze;class Fs extends io.AcEdCommand{constructor(){super(...arguments),this.recordsUndoStack=!1}async execute(t){var n;await Gn.open({host:((n=t.view)==null?void 0:n.container)??document.body})}}class qs{constructor(){this.name=z.LLM_PLUGIN_NAME,this.version=Cc.version,this.description="Shared AI model settings (llmsettings) and LLM text recognition",this.registeredCommands=[]}onLoad(t,n){const r=io.AcEdCommandStack.SYSTEMT_COMMAND_GROUP_NAME;n.addCommand(r,"llmsettings","llmsettings",new Fs),this.registeredCommands.push({group:r,name:"llmsettings"})}onUnload(t,n){for(const r of this.registeredCommands)n.removeCmd(r.group,r.name);this.registeredCommands=[]}}async function Yc(){return new qs}var Gs="vercel.ai.error",Xc=Symbol.for(Gs),ei,ti,te=class Hs extends(ti=Error,ei=Xc,ti){constructor({name:t,message:n,cause:r}){super(n),this[ei]=!0,this.name=t,this.cause=r}static isInstance(t){return Hs.hasMarker(t,Gs)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},Js="AI_APICallError",Ks=`vercel.ai.error.${Js}`,Qc=Symbol.for(Ks),ni,ri,$e=class extends(ri=te,ni=Qc,ri){constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:i,cause:a,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:Js,message:e,cause:a}),this[ni]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=i,this.isRetryable=s,this.data=l}static isInstance(e){return te.hasMarker(e,Ks)}},Ws="AI_EmptyResponseBodyError",Ys=`vercel.ai.error.${Ws}`,ed=Symbol.for(Ys),oi,ii,td=class extends(ii=te,oi=ed,ii){constructor({message:e="Empty response body"}={}){super({name:Ws,message:e}),this[oi]=!0}static isInstance(e){return te.hasMarker(e,Ys)}};function En(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Xs="AI_InvalidArgumentError",Qs=`vercel.ai.error.${Xs}`,nd=Symbol.for(Qs),ai,si,el=class extends(si=te,ai=nd,si){constructor({message:t,cause:n,argument:r}){super({name:Xs,message:t,cause:n}),this[ai]=!0,this.argument=r}static isInstance(t){return te.hasMarker(t,Qs)}},tl="AI_InvalidPromptError",nl=`vercel.ai.error.${tl}`,rd=Symbol.for(nl),li,ui,wt=class extends(ui=te,li=rd,ui){constructor({prompt:e,message:t,cause:n}){super({name:tl,message:`Invalid prompt: ${t}`,cause:n}),this[li]=!0,this.prompt=e}static isInstance(e){return te.hasMarker(e,nl)}},rl="AI_InvalidResponseDataError",ol=`vercel.ai.error.${rl}`,od=Symbol.for(ol),ci,di,yr=class extends(di=te,ci=od,di){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:rl,message:t}),this[ci]=!0,this.data=e}static isInstance(e){return te.hasMarker(e,ol)}},il="AI_JSONParseError",al=`vercel.ai.error.${il}`,id=Symbol.for(al),pi,hi,Hn=class extends(hi=te,pi=id,hi){constructor({text:e,cause:t}){super({name:il,message:`JSON parsing failed: Text: ${e}.
419
- Error message: ${En(t)}`,cause:t}),this[pi]=!0,this.text=e}static isInstance(e){return te.hasMarker(e,al)}},sl="AI_LoadAPIKeyError",ll=`vercel.ai.error.${sl}`,ad=Symbol.for(ll),fi,mi,Ln=class extends(mi=te,fi=ad,mi){constructor({message:e}){super({name:sl,message:e}),this[fi]=!0}static isInstance(e){return te.hasMarker(e,ll)}},ul="AI_NoSuchModelError",cl=`vercel.ai.error.${ul}`,sd=Symbol.for(cl),_i,gi,yi=class extends(gi=te,_i=sd,gi){constructor({errorName:e=ul,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[_i]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return te.hasMarker(e,cl)}},dl="AI_TooManyEmbeddingValuesForCallError",pl=`vercel.ai.error.${dl}`,ld=Symbol.for(pl),vi,bi,ud=class extends(bi=te,vi=ld,bi){constructor(e){super({name:dl,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[vi]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return te.hasMarker(e,pl)}},hl="AI_TypeValidationError",fl=`vercel.ai.error.${hl}`,cd=Symbol.for(fl),wi,xi,_n=class Br extends(xi=te,wi=cd,xi){constructor({value:t,cause:n}){super({name:hl,message:`Type validation failed: Value: ${JSON.stringify(t)}.
420
- Error message: ${En(n)}`,cause:n}),this[wi]=!0,this.value=t}static isInstance(t){return te.hasMarker(t,fl)}static wrap({value:t,cause:n}){return Br.isInstance(n)&&n.value===t?n:new Br({value:t,cause:n})}},ml="AI_UnsupportedFunctionalityError",_l=`vercel.ai.error.${ml}`,dd=Symbol.for(_l),ki,Ii,je=class extends(Ii=te,ki=dd,Ii){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:ml,message:t}),this[ki]=!0,this.functionality=e}static isInstance(e){return te.hasMarker(e,_l)}};class vr extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}const Ti=10,pd=13,zt=32;function br(e){}function hd(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:t=br,onError:n=br,onRetry:r=br,onComment:o,maxBufferSize:i}=e,a=[];let s=0,l=!0,c,p="",g=0,x,T=!1;function I(b){if(T)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,b.charCodeAt(0)===239&&b.charCodeAt(1)===187&&b.charCodeAt(2)===191&&(b=b.slice(3))),a.length===0){const N=k(b);N!==""&&(a.push(N),s=N.length),E();return}if(b.indexOf(`
421
- `)===-1&&b.indexOf("\r")===-1){a.push(b),s+=b.length,E();return}a.push(b);const S=a.join("");a.length=0,s=0;const m=k(S);m!==""&&(a.push(m),s=m.length),E()}function E(){i!==void 0&&(s+p.length<=i||(T=!0,a.length=0,s=0,c=void 0,p="",g=0,x=void 0,n(new vr(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function k(b){let S=0;if(b.indexOf("\r")===-1){let m=b.indexOf(`
422
- `,S);for(;m!==-1;){if(S===m){g>0&&t({id:c,event:x,data:p}),c=void 0,p="",g=0,x=void 0,S=m+1,m=b.indexOf(`
423
- `,S);continue}const N=b.charCodeAt(S);if(Si(b,S,N)){const Z=b.charCodeAt(S+5)===zt?S+6:S+5,B=b.slice(Z,m);if(g===0&&b.charCodeAt(m+1)===Ti){t({id:c,event:x,data:B}),c=void 0,p="",x=void 0,S=m+2,m=b.indexOf(`
424
- `,S);continue}p=g===0?B:`${p}
425
- ${B}`,g++}else Ei(b,S,N)?x=b.slice(b.charCodeAt(S+6)===zt?S+7:S+6,m)||void 0:_(b,S,m);S=m+1,m=b.indexOf(`
426
- `,S)}return b.slice(S)}for(;S<b.length;){const m=b.indexOf("\r",S),N=b.indexOf(`
427
- `,S);let Z=-1;if(m!==-1&&N!==-1?Z=m<N?m:N:m!==-1?m===b.length-1?Z=-1:Z=m:N!==-1&&(Z=N),Z===-1)break;_(b,S,Z),S=Z+1,b.charCodeAt(S-1)===pd&&b.charCodeAt(S)===Ti&&S++}return b.slice(S)}function _(b,S,m){if(S===m){y();return}const N=b.charCodeAt(S);if(Si(b,S,N)){const V=b.charCodeAt(S+5)===zt?S+6:S+5,J=b.slice(V,m);p=g===0?J:`${p}
428
- ${J}`,g++;return}if(Ei(b,S,N)){x=b.slice(b.charCodeAt(S+6)===zt?S+7:S+6,m)||void 0;return}if(N===105&&b.charCodeAt(S+1)===100&&b.charCodeAt(S+2)===58){const V=b.slice(b.charCodeAt(S+3)===zt?S+4:S+3,m);c=V.includes("\0")?void 0:V;return}if(N===58){if(o){const V=b.slice(S,m);o(V.slice(b.charCodeAt(S+1)===zt?2:1))}return}const Z=b.slice(S,m),B=Z.indexOf(":");if(B===-1){v(Z,"",Z);return}const D=Z.slice(0,B),oe=Z.charCodeAt(B+1)===zt?2:1,L=Z.slice(B+oe);v(D,L,Z)}function v(b,S,m){switch(b){case"event":x=S||void 0;break;case"data":p=g===0?S:`${p}
429
- ${S}`,g++;break;case"id":c=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?r(parseInt(S,10)):n(new vr(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:m}));break;default:n(new vr(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:S,line:m}));break}}function y(){g>0&&t({id:c,event:x,data:p}),c=void 0,p="",g=0,x=void 0}function $(b={}){if(b.consume&&a.length>0){const S=a.join("");_(S,0,S.length)}l=!0,c=void 0,p="",g=0,x=void 0,a.length=0,s=0,T=!1}return{feed:I,reset:$}}function Si(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ei(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class fd extends TransformStream{constructor({onError:t,onRetry:n,onComment:r,maxBufferSize:o}={}){let i;super({start(a){i=hd({onEvent:s=>{a.enqueue(s)},onError(s){typeof t=="function"&&t(s),(t==="terminate"||s.type==="max-buffer-size-exceeded")&&a.error(s)},onRetry:n,onComment:r,maxBufferSize:o})},transform(a){i.feed(a)}})}}function A(e,t,n){function r(s,l){var c;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(c=s._zod).traits??(c.traits=new Set),s._zod.traits.add(e),t(s,l);for(const p in a.prototype)p in s||Object.defineProperty(s,p,{value:a.prototype[p].bind(s)});s._zod.constr=a,s._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function a(s){var l;const c=n!=null&&n.Parent?new i:this;r(c,s),(l=c._zod).deferred??(l.deferred=[]);for(const p of c._zod.deferred)p();return c}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>{var l,c;return n!=null&&n.Parent&&s instanceof n.Parent?!0:(c=(l=s==null?void 0:s._zod)==null?void 0:l.traits)==null?void 0:c.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class gn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const gl={};function Ot(e){return gl}function yl(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function md(e,t){return typeof t=="bigint"?t.toString():t}function ho(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function fo(e){return e==null}function mo(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function _d(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return i%a/10**o}function fe(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function sr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function sn(e){return JSON.stringify(e)}const vl=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const gd=ho(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Kn(e){if(Jn(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Jn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const yd=new Set(["string","number","symbol"]);function Cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function q(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function vd(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const bd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function wd(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return qt(e,{...e._zod.def,shape:n,checks:[]})}function xd(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return qt(e,{...e._zod.def,shape:n,checks:[]})}function kd(e,t){if(!Kn(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return sr(this,"shape",r),r},checks:[]};return qt(e,n)}function Id(e,t){return qt(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return sr(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Td(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=e?new e({type:"optional",innerType:r[i]}):r[i])}else for(const i in r)o[i]=e?new e({type:"optional",innerType:r[i]}):r[i];return qt(t,{...t._zod.def,shape:o,checks:[]})}function Sd(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const i in n){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=new e({type:"nonoptional",innerType:r[i]}))}else for(const i in r)o[i]=new e({type:"nonoptional",innerType:r[i]});return qt(t,{...t._zod.def,shape:o,checks:[]})}function hn(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function kt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function zn(e){return typeof e=="string"?e:e==null?void 0:e.message}function $t(e,t,n){var o,i,a,s,l,c;const r={...e,path:e.path??[]};if(!e.message){const p=zn((a=(i=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:i.error)==null?void 0:a.call(i,e))??zn((s=t==null?void 0:t.error)==null?void 0:s.call(t,e))??zn((l=n.customError)==null?void 0:l.call(n,e))??zn((c=n.localeError)==null?void 0:c.call(n,e))??"Invalid input";r.message=p}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function _o(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function yn(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const bl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,md,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},wl=A("$ZodError",bl),xl=A("$ZodError",bl,{Parent:Error});function Ed(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Cd(e,t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>o({issues:s}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let s=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(n(a))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(e),r}const Ad=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new gn;if(a.issues.length){const s=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>$t(l,i,Ot())));throw vl(s,o==null?void 0:o.callee),s}return a.value},Od=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const s=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>$t(l,i,Ot())));throw vl(s,o==null?void 0:o.callee),s}return a.value},kl=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new gn;return i.issues.length?{success:!1,error:new(e??wl)(i.issues.map(a=>$t(a,o,Ot())))}:{success:!0,data:i.value}},$d=kl(xl),Il=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>$t(a,o,Ot())))}:{success:!0,data:i.value}},Nd=Il(xl),Rd=/^[cC][^\s-]{8,}$/,Pd=/^[0-9a-z]+$/,Md=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ld=/^[0-9a-vA-V]{20}$/,zd=/^[A-Za-z0-9]{27}$/,Dd=/^[a-zA-Z0-9_-]{21}$/,Zd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ci=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Ud=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Bd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Vd(){return new RegExp(Bd,"u")}const Fd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Gd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Hd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tl=/^[A-Za-z0-9_-]*$/,Kd=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Wd=/^\+(?:[0-9]){6,14}[0-9]$/,Sl="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Yd=new RegExp(`^${Sl}$`);function El(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Xd(e){return new RegExp(`^${El(e)}$`)}function Qd(e){const t=El({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Sl}T(?:${r})$`)}const ep=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},tp=/^\d+$/,np=/^-?\d+(?:\.\d+)?/i,rp=/true|false/i,op=/null/i,ip=/^[^A-Z]*$/,ap=/^[^a-z]*$/,Ve=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Cl={number:"number",bigint:"bigint",object:"date"},Al=A("$ZodCheckLessThan",(e,t)=>{Ve.init(e,t);const n=Cl[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ol=A("$ZodCheckGreaterThan",(e,t)=>{Ve.init(e,t);const n=Cl[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sp=A("$ZodCheckMultipleOf",(e,t)=>{Ve.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):_d(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),lp=A("$ZodCheckNumberFormat",(e,t)=>{var a;Ve.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),r=n?"int":"number",[o,i]=bd[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=i,n&&(l.pattern=tp)}),e._zod.check=s=>{const l=s.value;if(n){if(!Number.isInteger(l)){s.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>i&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inst:e})}}),up=A("$ZodCheckMaxLength",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!fo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=_o(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),cp=A("$ZodCheckMinLength",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!fo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=_o(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),dp=A("$ZodCheckLengthEquals",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!fo(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,i=o.length;if(i===t.length)return;const a=_o(o),s=i>t.length;r.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),lr=A("$ZodCheckStringFormat",(e,t)=>{var n,r;Ve.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),pp=A("$ZodCheckRegex",(e,t)=>{lr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hp=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ip),lr.init(e,t)}),fp=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ap),lr.init(e,t)}),mp=A("$ZodCheckIncludes",(e,t)=>{Ve.init(e,t);const n=Cn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),_p=A("$ZodCheckStartsWith",(e,t)=>{Ve.init(e,t);const n=new RegExp(`^${Cn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),gp=A("$ZodCheckEndsWith",(e,t)=>{Ve.init(e,t);const n=new RegExp(`.*${Cn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),yp=A("$ZodCheckOverwrite",(e,t)=>{Ve.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class vp{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
430
- `).filter(a=>a),o=Math.min(...r.map(a=>a.length-a.trimStart().length)),i=r.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of i)this.content.push(a)}compile(){const t=Function,n=this==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...n,o.join(`
431
- `))}}const bp={major:4,minor:0,patch:0},_e=A("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=bp;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const a of i._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const i=(a,s,l)=>{let c=hn(a),p;for(const g of s){if(g._zod.def.when){if(!g._zod.def.when(a))continue}else if(c)continue;const x=a.issues.length,T=g._zod.check(a);if(T instanceof Promise&&(l==null?void 0:l.async)===!1)throw new gn;if(p||T instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await T,a.issues.length!==x&&(c||(c=hn(a,x)))});else{if(a.issues.length===x)continue;c||(c=hn(a,x))}}return p?p.then(()=>a):a};e._zod.run=(a,s)=>{const l=e._zod.parse(a,s);if(l instanceof Promise){if(s.async===!1)throw new gn;return l.then(c=>i(c,r,s))}return i(l,r,s)}}e["~standard"]={validate:i=>{var a;try{const s=$d(e,i);return s.success?{value:s.data}:{issues:(a=s.error)==null?void 0:a.issues}}catch{return Nd(e,i).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),go=A("$ZodString",(e,t)=>{var n;_e.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??ep(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),xe=A("$ZodStringFormat",(e,t)=>{lr.init(e,t),go.init(e,t)}),wp=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jd),xe.init(e,t)}),xp=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ci(r))}else t.pattern??(t.pattern=Ci());xe.init(e,t)}),kp=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ud),xe.init(e,t)}),Ip=A("$ZodURL",(e,t)=>{xe.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),i=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Kd.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Tp=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Vd()),xe.init(e,t)}),Sp=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Dd),xe.init(e,t)}),Ep=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rd),xe.init(e,t)}),Cp=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pd),xe.init(e,t)}),Ap=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Md),xe.init(e,t)}),Op=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ld),xe.init(e,t)}),$p=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=zd),xe.init(e,t)}),Np=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Qd(t)),xe.init(e,t)}),Rp=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Yd),xe.init(e,t)}),Pp=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Xd(t)),xe.init(e,t)}),Mp=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Zd),xe.init(e,t)}),Lp=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Fd),xe.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),zp=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=qd),xe.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Dp=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Gd),xe.init(e,t)}),Zp=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Hd),xe.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function $l(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const jp=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Jd),xe.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{$l(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Up(e){if(!Tl.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return $l(n)}const Bp=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Tl),xe.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Up(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Vp=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Wd),xe.init(e,t)});function Fp(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const qp=A("$ZodJWT",(e,t)=>{xe.init(e,t),e._zod.check=n=>{Fp(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Nl=A("$ZodNumber",(e,t)=>{_e.init(e,t),e._zod.pattern=e._zod.bag.pattern??np,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Gp=A("$ZodNumber",(e,t)=>{lp.init(e,t),Nl.init(e,t)}),Hp=A("$ZodBoolean",(e,t)=>{_e.init(e,t),e._zod.pattern=rp,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Jp=A("$ZodNull",(e,t)=>{_e.init(e,t),e._zod.pattern=op,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Kp=A("$ZodAny",(e,t)=>{_e.init(e,t),e._zod.parse=n=>n}),Wp=A("$ZodUnknown",(e,t)=>{_e.init(e,t),e._zod.parse=n=>n}),Yp=A("$ZodNever",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Ai(e,t,n){e.issues.length&&t.issues.push(...kt(n,e.issues)),t.value[n]=e.value}const Xp=A("$ZodArray",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let a=0;a<o.length;a++){const s=o[a],l=t.element._zod.run({value:s,issues:[]},r);l instanceof Promise?i.push(l.then(c=>Ai(c,n,a))):Ai(l,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function Dn(e,t,n){e.issues.length&&t.issues.push(...kt(n,e.issues)),t.value[n]=e.value}function Oi(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...kt(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Qp=A("$ZodObject",(e,t)=>{_e.init(e,t);const n=ho(()=>{const g=Object.keys(t.shape);for(const T of g)if(!(t.shape[T]instanceof _e))throw new Error(`Invalid element at key "${T}": expected a Zod schema`);const x=vd(t.shape);return{shape:t.shape,keys:g,keySet:new Set(g),numKeys:g.length,optionalKeys:new Set(x)}});fe(e._zod,"propValues",()=>{const g=t.shape,x={};for(const T in g){const I=g[T]._zod;if(I.values){x[T]??(x[T]=new Set);for(const E of I.values)x[T].add(E)}}return x});const r=g=>{const x=new vp(["shape","payload","ctx"]),T=n.value,I=v=>{const y=sn(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let k=0;for(const v of T.keys)E[v]=`key_${k++}`;x.write("const newResult = {}");for(const v of T.keys)if(T.optionalKeys.has(v)){const y=E[v];x.write(`const ${y} = ${I(v)};`);const $=sn(v);x.write(`
432
- if (${y}.issues.length) {
433
- if (input[${$}] === undefined) {
434
- if (${$} in input) {
435
- newResult[${$}] = undefined;
436
- }
437
- } else {
438
- payload.issues = payload.issues.concat(
439
- ${y}.issues.map((iss) => ({
440
- ...iss,
441
- path: iss.path ? [${$}, ...iss.path] : [${$}],
442
- }))
443
- );
444
- }
445
- } else if (${y}.value === undefined) {
446
- if (${$} in input) newResult[${$}] = undefined;
447
- } else {
448
- newResult[${$}] = ${y}.value;
449
- }
450
- `)}else{const y=E[v];x.write(`const ${y} = ${I(v)};`),x.write(`
451
- if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
452
- ...iss,
453
- path: iss.path ? [${sn(v)}, ...iss.path] : [${sn(v)}]
454
- })));`),x.write(`newResult[${sn(v)}] = ${y}.value`)}x.write("payload.value = newResult;"),x.write("return payload;");const _=x.compile();return(v,y)=>_(g,v,y)};let o;const i=Jn,a=!gl.jitless,l=a&&gd.value,c=t.catchall;let p;e._zod.parse=(g,x)=>{p??(p=n.value);const T=g.value;if(!i(T))return g.issues.push({expected:"object",code:"invalid_type",input:T,inst:e}),g;const I=[];if(a&&l&&(x==null?void 0:x.async)===!1&&x.jitless!==!0)o||(o=r(t.shape)),g=o(g,x);else{g.value={};const y=p.shape;for(const $ of p.keys){const b=y[$],S=b._zod.run({value:T[$],issues:[]},x),m=b._zod.optin==="optional"&&b._zod.optout==="optional";S instanceof Promise?I.push(S.then(N=>m?Oi(N,g,$,T):Dn(N,g,$))):m?Oi(S,g,$,T):Dn(S,g,$)}}if(!c)return I.length?Promise.all(I).then(()=>g):g;const E=[],k=p.keySet,_=c._zod,v=_.def.type;for(const y of Object.keys(T)){if(k.has(y))continue;if(v==="never"){E.push(y);continue}const $=_.run({value:T[y],issues:[]},x);$ instanceof Promise?I.push($.then(b=>Dn(b,g,y))):Dn($,g,y)}return E.length&&g.issues.push({code:"unrecognized_keys",keys:E,input:T,inst:e}),I.length?Promise.all(I).then(()=>g):g}});function $i(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(i=>$t(i,r,Ot())))}),t}const Rl=A("$ZodUnion",(e,t)=>{_e.init(e,t),fe(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),fe(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),fe(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),fe(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>mo(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const i=[];for(const a of t.options){const s=a._zod.run({value:n.value,issues:[]},r);if(s instanceof Promise)i.push(s),o=!0;else{if(s.issues.length===0)return s;i.push(s)}}return o?Promise.all(i).then(a=>$i(a,n,e,r)):$i(i,n,e,r)}}),eh=A("$ZodDiscriminatedUnion",(e,t)=>{Rl.init(e,t);const n=e._zod.parse;fe(e._zod,"propValues",()=>{const o={};for(const i of t.options){const a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[s,l]of Object.entries(a)){o[s]||(o[s]=new Set);for(const c of l)o[s].add(c)}}return o});const r=ho(()=>{const o=t.options,i=new Map;for(const a of o){const s=a._zod.propValues[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of s){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,a)}}return i});e._zod.parse=(o,i)=>{const a=o.value;if(!Jn(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const s=r.value.get(a==null?void 0:a[t.discriminator]);return s?s._zod.run(o,i):t.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),th=A("$ZodIntersection",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([l,c])=>Ni(n,l,c)):Ni(n,i,a)}});function Vr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Kn(e)&&Kn(t)){const n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of r){const a=Vr(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],i=t[r],a=Vr(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ni(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),hn(e))return e;const r=Vr(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const nh=A("$ZodTuple",(e,t)=>{_e.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex(o=>o._zod.optin!=="optional");e._zod.parse=(o,i)=>{const a=o.value;if(!Array.isArray(a))return o.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];const s=[];if(!t.rest){const c=a.length>n.length,p=a.length<r-1;if(c||p)return o.issues.push({input:a,inst:e,origin:"array",...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),o}let l=-1;for(const c of n){if(l++,l>=a.length&&l>=r)continue;const p=c._zod.run({value:a[l],issues:[]},i);p instanceof Promise?s.push(p.then(g=>Zn(g,o,l))):Zn(p,o,l)}if(t.rest){const c=a.slice(n.length);for(const p of c){l++;const g=t.rest._zod.run({value:p,issues:[]},i);g instanceof Promise?s.push(g.then(x=>Zn(x,o,l))):Zn(g,o,l)}}return s.length?Promise.all(s).then(()=>o):o}});function Zn(e,t,n){e.issues.length&&t.issues.push(...kt(n,e.issues)),t.value[n]=e.value}const rh=A("$ZodRecord",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Kn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?i.push(c.then(p=>{p.issues.length&&n.issues.push(...kt(l,p.issues)),n.value[l]=p.value})):(c.issues.length&&n.issues.push(...kt(l,c.issues)),n.value[l]=c.value)}let s;for(const l in o)a.has(l)||(s=s??[],s.push(l));s&&s.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:s})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const s=t.keyType._zod.run({value:a,issues:[]},r);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(c=>$t(c,r,Ot())),input:a,path:[a],inst:e}),n.value[s.value]=s.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?i.push(l.then(c=>{c.issues.length&&n.issues.push(...kt(a,c.issues)),n.value[s.value]=c.value})):(l.issues.length&&n.issues.push(...kt(a,l.issues)),n.value[s.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),oh=A("$ZodEnum",(e,t)=>{_e.init(e,t);const n=yl(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>yd.has(typeof r)).map(r=>typeof r=="string"?Cn(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:e}),r}}),ih=A("$ZodLiteral",(e,t)=>{_e.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Cn(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),ah=A("$ZodTransform",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new gn;return n.value=o,n}}),sh=A("$ZodOptional",(e,t)=>{_e.init(e,t),e._zod.optin="optional",e._zod.optout="optional",fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),fe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mo(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),lh=A("$ZodNullable",(e,t)=>{_e.init(e,t),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mo(n.source)}|null)$`):void 0}),fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),uh=A("$ZodDefault",(e,t)=>{_e.init(e,t),e._zod.optin="optional",fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Ri(i,t)):Ri(o,t)}});function Ri(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const ch=A("$ZodPrefault",(e,t)=>{_e.init(e,t),e._zod.optin="optional",fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),dh=A("$ZodNonOptional",(e,t)=>{_e.init(e,t),fe(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Pi(i,e)):Pi(o,e)}});function Pi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const ph=A("$ZodCatch",(e,t)=>{_e.init(e,t),e._zod.optin="optional",fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(a=>$t(a,r,Ot()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>$t(i,r,Ot()))},input:n.value}),n.issues=[]),n)}}),hh=A("$ZodPipe",(e,t)=>{_e.init(e,t),fe(e._zod,"values",()=>t.in._zod.values),fe(e._zod,"optin",()=>t.in._zod.optin),fe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(i=>Mi(i,t,r)):Mi(o,t,r)}});function Mi(e,t,n){return hn(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const fh=A("$ZodReadonly",(e,t)=>{_e.init(e,t),fe(e._zod,"propValues",()=>t.innerType._zod.propValues),fe(e._zod,"values",()=>t.innerType._zod.values),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Li):Li(o)}});function Li(e){return e.value=Object.freeze(e.value),e}const mh=A("$ZodLazy",(e,t)=>{_e.init(e,t),fe(e._zod,"innerType",()=>t.getter()),fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),_h=A("$ZodCustom",(e,t)=>{Ve.init(e,t),_e.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>zi(i,n,r,e));zi(o,n,r,e)}});function zi(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(yn(o))}}class Pl{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function gh(){return new Pl}const cn=gh();function yh(e,t){return new e({type:"string",...q(t)})}function vh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}function Di(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}function bh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}function wh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}function xh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}function kh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}function Ih(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}function Th(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}function Sh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}function Eh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}function Ch(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}function Ah(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}function Oh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}function $h(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}function Nh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}function Rh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}function Ph(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}function Mh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}function Lh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}function zh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}function Dh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}function Zh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}function jh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}function Uh(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}function Bh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}function Vh(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}function Fh(e,t){return new e({type:"number",checks:[],...q(t)})}function qh(e,t){return new e({type:"number",coerce:!0,checks:[],...q(t)})}function Gh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}function Hh(e,t){return new e({type:"boolean",...q(t)})}function Jh(e,t){return new e({type:"null",...q(t)})}function Kh(e){return new e({type:"any"})}function Wh(e){return new e({type:"unknown"})}function Yh(e,t){return new e({type:"never",...q(t)})}function Zi(e,t){return new Al({check:"less_than",...q(t),value:e,inclusive:!1})}function wr(e,t){return new Al({check:"less_than",...q(t),value:e,inclusive:!0})}function ji(e,t){return new Ol({check:"greater_than",...q(t),value:e,inclusive:!1})}function xr(e,t){return new Ol({check:"greater_than",...q(t),value:e,inclusive:!0})}function Ui(e,t){return new sp({check:"multiple_of",...q(t),value:e})}function Ml(e,t){return new up({check:"max_length",...q(t),maximum:e})}function Wn(e,t){return new cp({check:"min_length",...q(t),minimum:e})}function Ll(e,t){return new dp({check:"length_equals",...q(t),length:e})}function Xh(e,t){return new pp({check:"string_format",format:"regex",...q(t),pattern:e})}function Qh(e){return new hp({check:"string_format",format:"lowercase",...q(e)})}function ef(e){return new fp({check:"string_format",format:"uppercase",...q(e)})}function tf(e,t){return new mp({check:"string_format",format:"includes",...q(t),includes:e})}function nf(e,t){return new _p({check:"string_format",format:"starts_with",...q(t),prefix:e})}function rf(e,t){return new gp({check:"string_format",format:"ends_with",...q(t),suffix:e})}function An(e){return new yp({check:"overwrite",tx:e})}function of(e){return An(t=>t.normalize(e))}function af(){return An(e=>e.trim())}function sf(){return An(e=>e.toLowerCase())}function lf(){return An(e=>e.toUpperCase())}function uf(e,t,n){return new e({type:"array",element:t,...q(n)})}function cf(e,t,n){const r=q(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function df(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}class Bi{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??cn,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var g,x,T;var r;const o=t._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,s);const l=(x=(g=t._zod).toJSONSchema)==null?void 0:x.call(g);if(l)s.schema=l;else{const I={...n,schemaPath:[...n.schemaPath,t],path:n.path},E=t._zod.parent;if(E)s.ref=E,this.process(E,I),this.seen.get(E).isParent=!0;else{const k=s.schema;switch(o.type){case"string":{const _=k;_.type="string";const{minimum:v,maximum:y,format:$,patterns:b,contentEncoding:S}=t._zod.bag;if(typeof v=="number"&&(_.minLength=v),typeof y=="number"&&(_.maxLength=y),$&&(_.format=i[$]??$,_.format===""&&delete _.format),S&&(_.contentEncoding=S),b&&b.size>0){const m=[...b];m.length===1?_.pattern=m[0].source:m.length>1&&(s.schema.allOf=[...m.map(N=>({...this.target==="draft-7"?{type:"string"}:{},pattern:N.source}))])}break}case"number":{const _=k,{minimum:v,maximum:y,format:$,multipleOf:b,exclusiveMaximum:S,exclusiveMinimum:m}=t._zod.bag;typeof $=="string"&&$.includes("int")?_.type="integer":_.type="number",typeof m=="number"&&(_.exclusiveMinimum=m),typeof v=="number"&&(_.minimum=v,typeof m=="number"&&(m>=v?delete _.minimum:delete _.exclusiveMinimum)),typeof S=="number"&&(_.exclusiveMaximum=S),typeof y=="number"&&(_.maximum=y,typeof S=="number"&&(S<=y?delete _.maximum:delete _.exclusiveMaximum)),typeof b=="number"&&(_.multipleOf=b);break}case"boolean":{const _=k;_.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{k.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{k.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const _=k,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(_.minItems=v),typeof y=="number"&&(_.maxItems=y),_.type="array",_.items=this.process(o.element,{...I,path:[...I.path,"items"]});break}case"object":{const _=k;_.type="object",_.properties={};const v=o.shape;for(const b in v)_.properties[b]=this.process(v[b],{...I,path:[...I.path,"properties",b]});const y=new Set(Object.keys(v)),$=new Set([...y].filter(b=>{const S=o.shape[b]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));$.size>0&&(_.required=Array.from($)),((T=o.catchall)==null?void 0:T._zod.def.type)==="never"?_.additionalProperties=!1:o.catchall?o.catchall&&(_.additionalProperties=this.process(o.catchall,{...I,path:[...I.path,"additionalProperties"]})):this.io==="output"&&(_.additionalProperties=!1);break}case"union":{const _=k;_.anyOf=o.options.map((v,y)=>this.process(v,{...I,path:[...I.path,"anyOf",y]}));break}case"intersection":{const _=k,v=this.process(o.left,{...I,path:[...I.path,"allOf",0]}),y=this.process(o.right,{...I,path:[...I.path,"allOf",1]}),$=S=>"allOf"in S&&Object.keys(S).length===1,b=[...$(v)?v.allOf:[v],...$(y)?y.allOf:[y]];_.allOf=b;break}case"tuple":{const _=k;_.type="array";const v=o.items.map((b,S)=>this.process(b,{...I,path:[...I.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?_.prefixItems=v:_.items=v,o.rest){const b=this.process(o.rest,{...I,path:[...I.path,"items"]});this.target==="draft-2020-12"?_.items=b:_.additionalItems=b}o.rest&&(_.items=this.process(o.rest,{...I,path:[...I.path,"items"]}));const{minimum:y,maximum:$}=t._zod.bag;typeof y=="number"&&(_.minItems=y),typeof $=="number"&&(_.maxItems=$);break}case"record":{const _=k;_.type="object",_.propertyNames=this.process(o.keyType,{...I,path:[...I.path,"propertyNames"]}),_.additionalProperties=this.process(o.valueType,{...I,path:[...I.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const _=k,v=yl(o.entries);v.every(y=>typeof y=="number")&&(_.type="number"),v.every(y=>typeof y=="string")&&(_.type="string"),_.enum=v;break}case"literal":{const _=k,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];_.type=y===null?"null":typeof y,_.const=y}else v.every(y=>typeof y=="number")&&(_.type="number"),v.every(y=>typeof y=="string")&&(_.type="string"),v.every(y=>typeof y=="boolean")&&(_.type="string"),v.every(y=>y===null)&&(_.type="null"),_.enum=v;break}case"file":{const _=k,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:$,mime:b}=t._zod.bag;y!==void 0&&(v.minLength=y),$!==void 0&&(v.maxLength=$),b?b.length===1?(v.contentMediaType=b[0],Object.assign(_,v)):_.anyOf=b.map(S=>({...v,contentMediaType:S})):Object.assign(_,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const _=this.process(o.innerType,I);k.anyOf=[_,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,I),s.ref=o.innerType;break}case"success":{const _=k;_.type="boolean";break}case"default":{this.process(o.innerType,I),s.ref=o.innerType,k.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,I),s.ref=o.innerType,this.io==="input"&&(k._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,I),s.ref=o.innerType;let _;try{_=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}k.default=_;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const _=k,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");_.type="string",_.pattern=v.source;break}case"pipe":{const _=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(_,I),s.ref=_;break}case"readonly":{this.process(o.innerType,I),s.ref=o.innerType,k.readOnly=!0;break}case"promise":{this.process(o.innerType,I),s.ref=o.innerType;break}case"optional":{this.process(o.innerType,I),s.ref=o.innerType;break}case"lazy":{const _=t._zod.innerType;this.process(_,I),s.ref=_;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),this.io==="input"&&Oe(t)&&(delete s.schema.examples,delete s.schema.default),this.io==="input"&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,this.seen.get(t).schema}emit(t,n){var p,g,x,T,I,E;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=k=>{var b;const _=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const S=(b=r.external.registry.get(k[0]))==null?void 0:b.id,m=r.external.uri??(Z=>Z);if(S)return{ref:m(S)};const N=k[1].defId??k[1].schema.id??`schema${this.counter++}`;return k[1].defId=N,{defId:N,ref:`${m("__shared")}#/${_}/${N}`}}if(k[1]===o)return{ref:"#"};const y=`#/${_}/`,$=k[1].schema.id??`__schema${this.counter++}`;return{defId:$,ref:y+$}},a=k=>{if(k[1].schema.$ref)return;const _=k[1],{ref:v,defId:y}=i(k);_.def={..._.schema},y&&(_.defId=y);const $=_.schema;for(const b in $)delete $[b];$.$ref=v};if(r.cycles==="throw")for(const k of this.seen.entries()){const _=k[1];if(_.cycle)throw new Error(`Cycle detected: #/${(p=_.cycle)==null?void 0:p.join("/")}/<root>
455
-
456
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const k of this.seen.entries()){const _=k[1];if(t===k[0]){a(k);continue}if(r.external){const y=(g=r.external.registry.get(k[0]))==null?void 0:g.id;if(t!==k[0]&&y){a(k);continue}}if((x=this.metadataRegistry.get(k[0]))==null?void 0:x.id){a(k);continue}if(_.cycle){a(k);continue}if(_.count>1&&r.reused==="ref"){a(k);continue}}const s=(k,_)=>{const v=this.seen.get(k),y=v.def??v.schema,$={...y};if(v.ref===null)return;const b=v.ref;if(v.ref=null,b){s(b,_);const S=this.seen.get(b).schema;S.$ref&&_.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(S)):(Object.assign(y,S),Object.assign(y,$))}v.isParent||this.override({zodSchema:k,jsonSchema:y,path:v.path??[]})};for(const k of[...this.seen.entries()].reverse())s(k[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(T=r.external)!=null&&T.uri){const k=(I=r.external.registry.get(t))==null?void 0:I.id;if(!k)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(k)}Object.assign(l,o.def);const c=((E=r.external)==null?void 0:E.defs)??{};for(const k of this.seen.entries()){const _=k[1];_.def&&_.defId&&(c[_.defId]=_.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function pf(e,t){if(e instanceof Pl){const r=new Bi(t),o={};for(const s of e._idmap.entries()){const[l,c]=s;r.process(c)}const i={},a={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const s of e._idmap.entries()){const[l,c]=s;i[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const s=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[s]:o}}return{schemas:i}}const n=new Bi(t);return n.process(e),n.emit(e,t)}function Oe(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Oe(o.element,n);case"object":{for(const i in o.shape)if(Oe(o.shape[i],n))return!0;return!1}case"union":{for(const i of o.options)if(Oe(i,n))return!0;return!1}case"intersection":return Oe(o.left,n)||Oe(o.right,n);case"tuple":{for(const i of o.items)if(Oe(i,n))return!0;return!!(o.rest&&Oe(o.rest,n))}case"record":return Oe(o.keyType,n)||Oe(o.valueType,n);case"map":return Oe(o.keyType,n)||Oe(o.valueType,n);case"set":return Oe(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Oe(o.innerType,n);case"lazy":return Oe(o.getter(),n);case"default":return Oe(o.innerType,n);case"prefault":return Oe(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Oe(o.in,n)||Oe(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const hf=A("ZodISODateTime",(e,t)=>{Np.init(e,t),Te.init(e,t)});function ff(e){return jh(hf,e)}const mf=A("ZodISODate",(e,t)=>{Rp.init(e,t),Te.init(e,t)});function _f(e){return Uh(mf,e)}const gf=A("ZodISOTime",(e,t)=>{Pp.init(e,t),Te.init(e,t)});function yf(e){return Bh(gf,e)}const vf=A("ZodISODuration",(e,t)=>{Mp.init(e,t),Te.init(e,t)});function bf(e){return Vh(vf,e)}const wf=(e,t)=>{wl.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Cd(e,n)},flatten:{value:n=>Ed(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},ur=A("ZodError",wf,{Parent:Error}),xf=Ad(ur),kf=Od(ur),If=kl(ur),zl=Il(ur),ve=A("ZodType",(e,t)=>(_e.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>qt(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>xf(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>If(e,n,r),e.parseAsync=async(n,r)=>kf(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>zl(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(bm(n,r)),e.superRefine=n=>e.check(wm(n)),e.overwrite=n=>e.check(An(n)),e.optional=()=>qi(e),e.nullable=()=>Gi(e),e.nullish=()=>qi(Gi(e)),e.nonoptional=n=>dm(e,n),e.array=()=>R(e),e.or=n=>ee([e,n]),e.and=n=>em(e,n),e.transform=n=>Hi(e,im(n)),e.default=n=>lm(e,n),e.prefault=n=>cm(e,n),e.catch=n=>hm(e,n),e.pipe=n=>Hi(e,n),e.readonly=()=>_m(e),e.describe=n=>{const r=e.clone();return cn.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=cn.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return cn.get(e);const r=e.clone();return cn.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Dl=A("_ZodString",(e,t)=>{go.init(e,t),ve.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(Xh(...r)),e.includes=(...r)=>e.check(tf(...r)),e.startsWith=(...r)=>e.check(nf(...r)),e.endsWith=(...r)=>e.check(rf(...r)),e.min=(...r)=>e.check(Wn(...r)),e.max=(...r)=>e.check(Ml(...r)),e.length=(...r)=>e.check(Ll(...r)),e.nonempty=(...r)=>e.check(Wn(1,...r)),e.lowercase=r=>e.check(Qh(r)),e.uppercase=r=>e.check(ef(r)),e.trim=()=>e.check(af()),e.normalize=(...r)=>e.check(of(...r)),e.toLowerCase=()=>e.check(sf()),e.toUpperCase=()=>e.check(lf())}),Tf=A("ZodString",(e,t)=>{go.init(e,t),Dl.init(e,t),e.email=n=>e.check(vh(Sf,n)),e.url=n=>e.check(Ih(Ef,n)),e.jwt=n=>e.check(Zh(Bf,n)),e.emoji=n=>e.check(Th(Cf,n)),e.guid=n=>e.check(Di(Vi,n)),e.uuid=n=>e.check(bh(jn,n)),e.uuidv4=n=>e.check(wh(jn,n)),e.uuidv6=n=>e.check(xh(jn,n)),e.uuidv7=n=>e.check(kh(jn,n)),e.nanoid=n=>e.check(Sh(Af,n)),e.guid=n=>e.check(Di(Vi,n)),e.cuid=n=>e.check(Eh(Of,n)),e.cuid2=n=>e.check(Ch($f,n)),e.ulid=n=>e.check(Ah(Nf,n)),e.base64=n=>e.check(Lh(Zf,n)),e.base64url=n=>e.check(zh(jf,n)),e.xid=n=>e.check(Oh(Rf,n)),e.ksuid=n=>e.check($h(Pf,n)),e.ipv4=n=>e.check(Nh(Mf,n)),e.ipv6=n=>e.check(Rh(Lf,n)),e.cidrv4=n=>e.check(Ph(zf,n)),e.cidrv6=n=>e.check(Mh(Df,n)),e.e164=n=>e.check(Dh(Uf,n)),e.datetime=n=>e.check(ff(n)),e.date=n=>e.check(_f(n)),e.time=n=>e.check(yf(n)),e.duration=n=>e.check(bf(n))});function u(e){return yh(Tf,e)}const Te=A("ZodStringFormat",(e,t)=>{xe.init(e,t),Dl.init(e,t)}),Sf=A("ZodEmail",(e,t)=>{kp.init(e,t),Te.init(e,t)}),Vi=A("ZodGUID",(e,t)=>{wp.init(e,t),Te.init(e,t)}),jn=A("ZodUUID",(e,t)=>{xp.init(e,t),Te.init(e,t)}),Ef=A("ZodURL",(e,t)=>{Ip.init(e,t),Te.init(e,t)}),Cf=A("ZodEmoji",(e,t)=>{Tp.init(e,t),Te.init(e,t)}),Af=A("ZodNanoID",(e,t)=>{Sp.init(e,t),Te.init(e,t)}),Of=A("ZodCUID",(e,t)=>{Ep.init(e,t),Te.init(e,t)}),$f=A("ZodCUID2",(e,t)=>{Cp.init(e,t),Te.init(e,t)}),Nf=A("ZodULID",(e,t)=>{Ap.init(e,t),Te.init(e,t)}),Rf=A("ZodXID",(e,t)=>{Op.init(e,t),Te.init(e,t)}),Pf=A("ZodKSUID",(e,t)=>{$p.init(e,t),Te.init(e,t)}),Mf=A("ZodIPv4",(e,t)=>{Lp.init(e,t),Te.init(e,t)}),Lf=A("ZodIPv6",(e,t)=>{zp.init(e,t),Te.init(e,t)}),zf=A("ZodCIDRv4",(e,t)=>{Dp.init(e,t),Te.init(e,t)}),Df=A("ZodCIDRv6",(e,t)=>{Zp.init(e,t),Te.init(e,t)}),Zf=A("ZodBase64",(e,t)=>{jp.init(e,t),Te.init(e,t)}),jf=A("ZodBase64URL",(e,t)=>{Bp.init(e,t),Te.init(e,t)}),Uf=A("ZodE164",(e,t)=>{Vp.init(e,t),Te.init(e,t)}),Bf=A("ZodJWT",(e,t)=>{qp.init(e,t),Te.init(e,t)}),yo=A("ZodNumber",(e,t)=>{Nl.init(e,t),ve.init(e,t),e.gt=(r,o)=>e.check(ji(r,o)),e.gte=(r,o)=>e.check(xr(r,o)),e.min=(r,o)=>e.check(xr(r,o)),e.lt=(r,o)=>e.check(Zi(r,o)),e.lte=(r,o)=>e.check(wr(r,o)),e.max=(r,o)=>e.check(wr(r,o)),e.int=r=>e.check(Fi(r)),e.safe=r=>e.check(Fi(r)),e.positive=r=>e.check(ji(0,r)),e.nonnegative=r=>e.check(xr(0,r)),e.negative=r=>e.check(Zi(0,r)),e.nonpositive=r=>e.check(wr(0,r)),e.multipleOf=(r,o)=>e.check(Ui(r,o)),e.step=(r,o)=>e.check(Ui(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function f(e){return Fh(yo,e)}const Vf=A("ZodNumberFormat",(e,t)=>{Gp.init(e,t),yo.init(e,t)});function Fi(e){return Gh(Vf,e)}const Ff=A("ZodBoolean",(e,t)=>{Hp.init(e,t),ve.init(e,t)});function ue(e){return Hh(Ff,e)}const qf=A("ZodNull",(e,t)=>{Jp.init(e,t),ve.init(e,t)});function Gf(e){return Jh(qf,e)}const Hf=A("ZodAny",(e,t)=>{Kp.init(e,t),ve.init(e,t)});function He(){return Kh(Hf)}const Jf=A("ZodUnknown",(e,t)=>{Wp.init(e,t),ve.init(e,t)});function Le(){return Wh(Jf)}const Kf=A("ZodNever",(e,t)=>{Yp.init(e,t),ve.init(e,t)});function Wf(e){return Yh(Kf,e)}const Yf=A("ZodArray",(e,t)=>{Xp.init(e,t),ve.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Wn(n,r)),e.nonempty=n=>e.check(Wn(1,n)),e.max=(n,r)=>e.check(Ml(n,r)),e.length=(n,r)=>e.check(Ll(n,r)),e.unwrap=()=>e.element});function R(e,t){return uf(Yf,e,t)}const Zl=A("ZodObject",(e,t)=>{Qp.init(e,t),ve.init(e,t),fe(e,"shape",()=>t.shape),e.keyof=()=>X(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Le()}),e.loose=()=>e.clone({...e._zod.def,catchall:Le()}),e.strict=()=>e.clone({...e._zod.def,catchall:Wf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>kd(e,n),e.merge=n=>Id(e,n),e.pick=n=>wd(e,n),e.omit=n=>xd(e,n),e.partial=(...n)=>Td(Ul,e,n[0]),e.required=(...n)=>Sd(Bl,e,n[0])});function d(e,t){const n={type:"object",get shape(){return sr(this,"shape",{...e}),this.shape},...q(t)};return new Zl(n)}function Fr(e,t){return new Zl({type:"object",get shape(){return sr(this,"shape",{...e}),this.shape},catchall:Le(),...q(t)})}const jl=A("ZodUnion",(e,t)=>{Rl.init(e,t),ve.init(e,t),e.options=t.options});function ee(e,t){return new jl({type:"union",options:e,...q(t)})}const Xf=A("ZodDiscriminatedUnion",(e,t)=>{jl.init(e,t),eh.init(e,t)});function se(e,t,n){return new Xf({type:"union",options:t,discriminator:e,...q(n)})}const Qf=A("ZodIntersection",(e,t)=>{th.init(e,t),ve.init(e,t)});function em(e,t){return new Qf({type:"intersection",left:e,right:t})}const tm=A("ZodTuple",(e,t)=>{nh.init(e,t),ve.init(e,t),e.rest=n=>e.clone({...e._zod.def,rest:n})});function qr(e,t,n){const r=t instanceof _e,o=r?n:t,i=r?t:null;return new tm({type:"tuple",items:e,rest:i,...q(o)})}const nm=A("ZodRecord",(e,t)=>{rh.init(e,t),ve.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Se(e,t,n){return new nm({type:"record",keyType:e,valueType:t,...q(n)})}const Gr=A("ZodEnum",(e,t)=>{oh.init(e,t),ve.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const i={};for(const a of r)if(n.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Gr({...t,checks:[],...q(o),entries:i})},e.exclude=(r,o)=>{const i={...t.entries};for(const a of r)if(n.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Gr({...t,checks:[],...q(o),entries:i})}});function X(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Gr({type:"enum",entries:n,...q(t)})}const rm=A("ZodLiteral",(e,t)=>{ih.init(e,t),ve.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new rm({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}const om=A("ZodTransform",(e,t)=>{ah.init(e,t),ve.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(yn(i,n.value,t));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(yn(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n)):(n.value=o,n)}});function im(e){return new om({type:"transform",transform:e})}const Ul=A("ZodOptional",(e,t)=>{sh.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function qi(e){return new Ul({type:"optional",innerType:e})}const am=A("ZodNullable",(e,t)=>{lh.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gi(e){return new am({type:"nullable",innerType:e})}const sm=A("ZodDefault",(e,t)=>{uh.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function lm(e,t){return new sm({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const um=A("ZodPrefault",(e,t)=>{ch.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function cm(e,t){return new um({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Bl=A("ZodNonOptional",(e,t)=>{dh.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function dm(e,t){return new Bl({type:"nonoptional",innerType:e,...q(t)})}const pm=A("ZodCatch",(e,t)=>{ph.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function hm(e,t){return new pm({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const fm=A("ZodPipe",(e,t)=>{hh.init(e,t),ve.init(e,t),e.in=t.in,e.out=t.out});function Hi(e,t){return new fm({type:"pipe",in:e,out:t})}const mm=A("ZodReadonly",(e,t)=>{fh.init(e,t),ve.init(e,t)});function _m(e){return new mm({type:"readonly",innerType:e})}const gm=A("ZodLazy",(e,t)=>{mh.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Vl(e){return new gm({type:"lazy",getter:e})}const vo=A("ZodCustom",(e,t)=>{_h.init(e,t),ve.init(e,t)});function ym(e){const t=new Ve({check:"custom"});return t._zod.check=e,t}function vm(e,t){return cf(vo,e??(()=>!0),t)}function bm(e,t={}){return df(vo,e,t)}function wm(e){const t=ym(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(yn(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(yn(o))}},e(n.value,n)));return t}function Yn(e,t={error:`Input not instance of ${e.name}`}){const n=new vo({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...q(t)});return n._zod.bag.Class=e,n}function xm(e){return qh(yo,e)}var pe;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const a of o)i[a]=a;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),a={};for(const s of i)a[s]=o[s];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},e.find=(o,i)=>{for(const a of o)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var Ji;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ji||(Ji={}));const F=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=e=>{switch(typeof e){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(e)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(e)?F.array:e===null?F.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?F.promise:typeof Map<"u"&&e instanceof Map?F.map:typeof Set<"u"&&e instanceof Set?F.set:typeof Date<"u"&&e instanceof Date?F.date:F.object;default:return F.unknown}},P=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class _t extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let s=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(n(a))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof _t))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const i=o.path[0];n[i]=n[i]||[],n[i].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}_t.create=e=>new _t(e);const Hr=(e,t)=>{let n;switch(e.code){case P.invalid_type:e.received===F.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,pe.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${pe.joinValues(e.keys,", ")}`;break;case P.invalid_union:n="Invalid input";break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${pe.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${pe.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n="Invalid function arguments";break;case P.invalid_return_type:n="Invalid function return type";break;case P.invalid_date:n="Invalid date";break;case P.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:pe.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case P.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case P.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case P.custom:n="Invalid input";break;case P.invalid_intersection_types:n="Intersection results could not be merged";break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n="Number must be finite";break;default:n=t.defaultError,pe.assertNever(e)}return{message:n}};let km=Hr;function Im(){return km}const Tm=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let s="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)s=c(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}};function U(e,t){const n=Im(),r=Tm({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Hr?void 0:Hr].filter(o=>!!o)});e.common.issues.push(r)}class Ke{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Q;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const i=await o.key,a=await o.value;r.push({key:i,value:a})}return Ke.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return Q;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const Q=Object.freeze({status:"aborted"}),dn=e=>({status:"dirty",value:e}),tt=e=>({status:"valid",value:e}),Ki=e=>e.status==="aborted",Wi=e=>e.status==="dirty",Qt=e=>e.status==="valid",Xn=e=>typeof Promise<"u"&&e instanceof Promise;var G;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(G||(G={}));class Nt{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Yi=(e,t)=>{if(Qt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new _t(e.common.issues);return this._error=n,this._error}}};function ae(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,s)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??r??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:l??n??s.defaultError}},description:o}}class ce{get description(){return this._def.description}_getType(t){return xt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ke,ctx:{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Xn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Yi(r,o)}"~validate"(t){var r,o;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xt(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:n});return Qt(i)?{value:i.value}:{issues:n.common.issues}}catch(i){(o=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(i=>Qt(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xt(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(Xn(o)?o:Promise.resolve(o));return Yi(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const a=t(o),s=()=>i.addIssue({code:P.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new nn({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Et.create(this,this._def)}nullable(){return rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return nr.create(this,this._def)}or(t){return er.create([this,t],this._def)}and(t){return tr.create(this,t,this._def)}transform(t){return new nn({...ae(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Kr({...ae(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Jm({typeName:M.ZodBranded,type:this,...ae(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Wr({...ae(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return bo.create(this,t)}readonly(){return Yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Sm=/^c[^\s-]{8,}$/i,Em=/^[0-9a-z]+$/,Cm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Am=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Om=/^[a-z0-9_-]{21}$/i,$m=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nm=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Rm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let kr;const Mm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Lm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,zm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Dm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fl="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Um=new RegExp(`^${Fl}$`);function ql(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Bm(e){return new RegExp(`^${ql(e)}$`)}function Vm(e){let t=`${Fl}T${ql(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Fm(e,t){return!!((t==="v4"||!t)&&Mm.test(e)||(t==="v6"||!t)&&zm.test(e))}function qm(e,t){if(!$m.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Gm(e,t){return!!((t==="v4"||!t)&&Lm.test(e)||(t==="v6"||!t)&&Dm.test(e))}class It extends ce{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==F.string){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_type,expected:F.string,received:i.parsedType}),Q}const r=new Ke;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,s=t.data.length<i.value;(a||s)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&U(o,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Rm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")kr||(kr=new RegExp(Pm,"u")),kr.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Am.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Om.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Sm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Em.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Cm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:P.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:P.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Vm(i).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Um.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Bm(i).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Nm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Fm(t.data,i.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?qm(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Gm(t.data,i.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Zm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?jm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:P.invalid_string,message:i.message}),r.dirty()):pe.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:P.invalid_string,...G.errToObj(r)})}_addCheck(t){return new It({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...G.errToObj(t)})}url(t){return this._addCheck({kind:"url",...G.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...G.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...G.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...G.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...G.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...G.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...G.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...G.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...G.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...G.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...G.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...G.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...G.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...G.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...G.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...G.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...G.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...G.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...G.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...G.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...G.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...G.errToObj(n)})}nonempty(t){return this.min(1,G.errToObj(t))}trim(){return new It({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new It({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new It({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}It.create=e=>new It({checks:[],typeName:M.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...ae(e)});function Hm(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return i%a/10**o}class en extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==F.number){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_type,expected:F.number,received:i.parsedType}),Q}let r;const o=new Ke;for(const i of this._def.checks)i.kind==="int"?pe.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:P.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Hm(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:P.not_finite,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,G.toString(n))}gt(t,n){return this.setLimit("min",t,!1,G.toString(n))}lte(t,n){return this.setLimit("max",t,!0,G.toString(n))}lt(t,n){return this.setLimit("max",t,!1,G.toString(n))}setLimit(t,n,r,o){return new en({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:G.toString(o)}]})}_addCheck(t){return new en({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:G.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:G.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:G.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&pe.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}en.create=e=>new en({checks:[],typeName:M.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...ae(e)});class vn extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==F.bigint)return this._getInvalidInput(t);let r;const o=new Ke;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:P.invalid_type,expected:F.bigint,received:n.parsedType}),Q}gte(t,n){return this.setLimit("min",t,!0,G.toString(n))}gt(t,n){return this.setLimit("min",t,!1,G.toString(n))}lte(t,n){return this.setLimit("max",t,!0,G.toString(n))}lt(t,n){return this.setLimit("max",t,!1,G.toString(n))}setLimit(t,n,r,o){return new vn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:G.toString(o)}]})}_addCheck(t){return new vn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:G.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}vn.create=e=>new vn({checks:[],typeName:M.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...ae(e)});class Xi extends ce{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==F.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.boolean,received:r.parsedType}),Q}return tt(t.data)}}Xi.create=e=>new Xi({typeName:M.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...ae(e)});class Qn extends ce{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==F.date){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_type,expected:F.date,received:i.parsedType}),Q}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_date}),Q}const r=new Ke;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):pe.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Qn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:G.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:G.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}Qn.create=e=>new Qn({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:M.ZodDate,...ae(e)});class Qi extends ce{_parse(t){if(this._getType(t)!==F.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.symbol,received:r.parsedType}),Q}return tt(t.data)}}Qi.create=e=>new Qi({typeName:M.ZodSymbol,...ae(e)});class ea extends ce{_parse(t){if(this._getType(t)!==F.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.undefined,received:r.parsedType}),Q}return tt(t.data)}}ea.create=e=>new ea({typeName:M.ZodUndefined,...ae(e)});class ta extends ce{_parse(t){if(this._getType(t)!==F.null){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.null,received:r.parsedType}),Q}return tt(t.data)}}ta.create=e=>new ta({typeName:M.ZodNull,...ae(e)});class na extends ce{constructor(){super(...arguments),this._any=!0}_parse(t){return tt(t.data)}}na.create=e=>new na({typeName:M.ZodAny,...ae(e)});class ra extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(t){return tt(t.data)}}ra.create=e=>new ra({typeName:M.ZodUnknown,...ae(e)});class Rt extends ce{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:P.invalid_type,expected:F.never,received:n.parsedType}),Q}}Rt.create=e=>new Rt({typeName:M.ZodNever,...ae(e)});class oa extends ce{_parse(t){if(this._getType(t)!==F.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.void,received:r.parsedType}),Q}return tt(t.data)}}oa.create=e=>new oa({typeName:M.ZodVoid,...ae(e)});class dt extends ce{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==F.array)return U(n,{code:P.invalid_type,expected:F.array,received:n.parsedType}),Q;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,s=n.data.length<o.exactLength.value;(a||s)&&(U(n,{code:a?P.too_big:P.too_small,minimum:s?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:P.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:P.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,s)=>o.type._parseAsync(new Nt(n,a,n.path,s)))).then(a=>Ke.mergeArray(r,a));const i=[...n.data].map((a,s)=>o.type._parseSync(new Nt(n,a,n.path,s)));return Ke.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new dt({...this._def,minLength:{value:t,message:G.toString(n)}})}max(t,n){return new dt({...this._def,maxLength:{value:t,message:G.toString(n)}})}length(t,n){return new dt({...this._def,exactLength:{value:t,message:G.toString(n)}})}nonempty(t){return this.min(1,t)}}dt.create=(e,t)=>new dt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ae(t)});function Kt(e){if(e instanceof Ae){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Et.create(Kt(r))}return new Ae({...e._def,shape:()=>t})}else return e instanceof dt?new dt({...e._def,type:Kt(e.element)}):e instanceof Et?Et.create(Kt(e.unwrap())):e instanceof rn?rn.create(Kt(e.unwrap())):e instanceof jt?jt.create(e.items.map(t=>Kt(t))):e}class Ae extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=pe.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==F.object){const c=this._getOrReturnCtx(t);return U(c,{code:P.invalid_type,expected:F.object,received:c.parsedType}),Q}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Rt&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||s.push(c);const l=[];for(const c of a){const p=i[c],g=o.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new Nt(o,g,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Rt){const c=this._def.unknownKeys;if(c==="passthrough")for(const p of s)l.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")s.length>0&&(U(o,{code:P.unrecognized_keys,keys:s}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const p of s){const g=o.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new Nt(o,g,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const p of l){const g=await p.key,x=await p.value;c.push({key:g,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>Ke.mergeObjectSync(r,c)):Ke.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return G.errToObj,new Ae({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var i,a;const o=((a=(i=this._def).errorMap)==null?void 0:a.call(i,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:G.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ae({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ae({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ae({...this._def,catchall:t})}pick(t){const n={};for(const r of pe.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Ae({...this._def,shape:()=>n})}omit(t){const n={};for(const r of pe.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Ae({...this._def,shape:()=>n})}deepPartial(){return Kt(this)}partial(t){const n={};for(const r of pe.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new Ae({...this._def,shape:()=>n})}required(t){const n={};for(const r of pe.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Et;)i=i._def.innerType;n[r]=i}return new Ae({...this._def,shape:()=>n})}keyof(){return Gl(pe.objectKeys(this.shape))}}Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:Rt.create(),typeName:M.ZodObject,...ae(t)});Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:Rt.create(),typeName:M.ZodObject,...ae(t)});Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:Rt.create(),typeName:M.ZodObject,...ae(t)});class er extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const s of i)if(s.result.status==="valid")return s.result;for(const s of i)if(s.result.status==="dirty")return n.common.issues.push(...s.ctx.common.issues),s.result;const a=i.map(s=>new _t(s.ctx.common.issues));return U(n,{code:P.invalid_union,unionErrors:a}),Q}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let i;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const s=a.map(l=>new _t(l));return U(n,{code:P.invalid_union,unionErrors:s}),Q}}get options(){return this._def.options}}er.create=(e,t)=>new er({options:e,typeName:M.ZodUnion,...ae(t)});function Jr(e,t){const n=xt(e),r=xt(t);if(e===t)return{valid:!0,data:e};if(n===F.object&&r===F.object){const o=pe.objectKeys(t),i=pe.objectKeys(e).filter(s=>o.indexOf(s)!==-1),a={...e,...t};for(const s of i){const l=Jr(e[s],t[s]);if(!l.valid)return{valid:!1};a[s]=l.data}return{valid:!0,data:a}}else if(n===F.array&&r===F.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i<e.length;i++){const a=e[i],s=t[i],l=Jr(a,s);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===F.date&&r===F.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class tr extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(i,a)=>{if(Ki(i)||Ki(a))return Q;const s=Jr(i.value,a.value);return s.valid?((Wi(i)||Wi(a))&&n.dirty(),{status:n.value,value:s.data}):(U(r,{code:P.invalid_intersection_types}),Q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}tr.create=(e,t,n)=>new tr({left:e,right:t,typeName:M.ZodIntersection,...ae(n)});class jt extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==F.array)return U(r,{code:P.invalid_type,expected:F.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return U(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,s)=>{const l=this._def.items[s]||this._def.rest;return l?l._parse(new Nt(r,a,r.path,s)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Ke.mergeArray(n,a)):Ke.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new jt({...this._def,rest:t})}}jt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new jt({items:e,typeName:M.ZodTuple,rest:null,...ae(t)})};class ia extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==F.map)return U(r,{code:P.invalid_type,expected:F.map,received:r.parsedType}),Q;const o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([s,l],c)=>({key:o._parse(new Nt(r,s,r.path,[c,"key"])),value:i._parse(new Nt(r,l,r.path,[c,"value"]))}));if(r.common.async){const s=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return Q;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(c.value,p.value)}return{status:n.value,value:s}})}else{const s=new Map;for(const l of a){const c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return Q;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(c.value,p.value)}return{status:n.value,value:s}}}}ia.create=(e,t,n)=>new ia({valueType:t,keyType:e,typeName:M.ZodMap,...ae(n)});class bn extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==F.set)return U(r,{code:P.invalid_type,expected:F.set,received:r.parsedType}),Q;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:P.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:P.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const c=new Set;for(const p of l){if(p.status==="aborted")return Q;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}const s=[...r.data.values()].map((l,c)=>i._parse(new Nt(r,l,r.path,c)));return r.common.async?Promise.all(s).then(l=>a(l)):a(s)}min(t,n){return new bn({...this._def,minSize:{value:t,message:G.toString(n)}})}max(t,n){return new bn({...this._def,maxSize:{value:t,message:G.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}bn.create=(e,t)=>new bn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...ae(t)});class aa extends ce{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}aa.create=(e,t)=>new aa({getter:e,typeName:M.ZodLazy,...ae(t)});class sa extends ce{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:P.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:t.data}}get value(){return this._def.value}}sa.create=(e,t)=>new sa({value:e,typeName:M.ZodLiteral,...ae(t)});function Gl(e,t){return new tn({values:e,typeName:M.ZodEnum,...ae(t)})}class tn extends ce{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:pe.joinValues(r),received:n.parsedType,code:P.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:P.invalid_enum_value,options:r}),Q}return tt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return tn.create(t,{...this._def,...n})}exclude(t,n=this._def){return tn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}tn.create=Gl;class la extends ce{_parse(t){const n=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==F.string&&r.parsedType!==F.number){const o=pe.objectValues(n);return U(r,{expected:pe.joinValues(o),received:r.parsedType,code:P.invalid_type}),Q}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=pe.objectValues(n);return U(r,{received:r.data,code:P.invalid_enum_value,options:o}),Q}return tt(t.data)}get enum(){return this._def.values}}la.create=(e,t)=>new la({values:e,typeName:M.ZodNativeEnum,...ae(t)});class nr extends ce{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==F.promise&&n.common.async===!1)return U(n,{code:P.invalid_type,expected:F.promise,received:n.parsedType}),Q;const r=n.parsedType===F.promise?n.data:Promise.resolve(n.data);return tt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}nr.create=(e,t)=>new nr({type:e,typeName:M.ZodPromise,...ae(t)});class nn extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async s=>{if(n.value==="aborted")return Q;const l=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return l.status==="aborted"?Q:l.status==="dirty"||n.value==="dirty"?dn(l.value):l});{if(n.value==="aborted")return Q;const s=this._def.schema._parseSync({data:a,path:r.path,parent:r});return s.status==="aborted"?Q:s.status==="dirty"||n.value==="dirty"?dn(s.value):s}}if(o.type==="refinement"){const a=s=>{const l=o.refinement(s,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Q:(s.status==="dirty"&&n.dirty(),a(s.value),{status:n.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?Q:(s.status==="dirty"&&n.dirty(),a(s.value).then(()=>({status:n.value,value:s.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Qt(a))return Q;const s=o.transform(a.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Qt(a)?Promise.resolve(o.transform(a.value,i)).then(s=>({status:n.value,value:s})):Q);pe.assertNever(o)}}nn.create=(e,t,n)=>new nn({schema:e,typeName:M.ZodEffects,effect:t,...ae(n)});nn.createWithPreprocess=(e,t,n)=>new nn({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...ae(n)});class Et extends ce{_parse(t){return this._getType(t)===F.undefined?tt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Et.create=(e,t)=>new Et({innerType:e,typeName:M.ZodOptional,...ae(t)});class rn extends ce{_parse(t){return this._getType(t)===F.null?tt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}rn.create=(e,t)=>new rn({innerType:e,typeName:M.ZodNullable,...ae(t)});class Kr extends ce{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===F.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Kr.create=(e,t)=>new Kr({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ae(t)});class Wr extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Xn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new _t(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Wr.create=(e,t)=>new Wr({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ae(t)});class ua extends ce{_parse(t){if(this._getType(t)!==F.nan){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.nan,received:r.parsedType}),Q}return{status:"valid",value:t.data}}}ua.create=e=>new ua({typeName:M.ZodNaN,...ae(e)});class Jm extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class bo extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Q:i.status==="dirty"?(n.dirty(),dn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Q:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new bo({in:t,out:n,typeName:M.ZodPipeline})}}class Yr extends ce{_parse(t){const n=this._def.innerType._parse(t),r=o=>(Qt(o)&&(o.value=Object.freeze(o.value)),o);return Xn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Yr.create=(e,t)=>new Yr({innerType:e,typeName:M.ZodReadonly,...ae(t)});var M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));const ye=It.create,ct=en.create;Rt.create;const Ct=dt.create,at=Ae.create,wo=er.create;tr.create;jt.create;const cr=tn.create;nr.create;Et.create;rn.create;function ze(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function Km(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(ca());return}const i=setTimeout(()=>{a(),r()},e),a=()=>{clearTimeout(i),n==null||n.removeEventListener("abort",s)},s=()=>{a(),o(ca())};n==null||n.addEventListener("abort",s)})}function ca(){return new DOMException("Delay was aborted","AbortError")}function an(e){return Object.fromEntries([...e.headers])}var Hl="AI_DownloadError",Jl=`vercel.ai.error.${Hl}`,Wm=Symbol.for(Jl),da,pa,qe=class extends(pa=te,da=Wm,pa){constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:Hl,message:o,cause:r}),this[da]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return te.hasMarker(e,Jl)}};async function xo(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch{}}function Ym(e=globalThis){return e.window!=null}function Xm(e){let t;try{t=new URL(e)}catch{throw new qe({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new qe({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const n=t.hostname.toLowerCase().replace(/\.+$/,"");if(!n)throw new qe({url:e,message:"URL must have a hostname"});if(n==="localhost"||n.endsWith(".local")||n.endsWith(".localhost"))throw new qe({url:e,message:`URL with hostname ${n} is not allowed`});if(n.startsWith("[")&&n.endsWith("]")){const r=n.slice(1,-1);if(e_(r))throw new qe({url:e,message:`URL with IPv6 address ${n} is not allowed`});return}if(Kl(n)){if(Wl(n))throw new qe({url:e,message:`URL with IP address ${n} is not allowed`});return}}function Kl(e){const t=e.split(".");return t.length!==4?!1:t.every(n=>{const r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255&&String(r)===n})}function Wl(e){const t=e.split(".").map(Number),[n,r,o]=t;return n===0||n===10||n===100&&r>=64&&r<=127||n===127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===0&&o===0||n===192&&r===168||n===198&&(r===18||r===19)||n>=240}function Qm(e){let t=e.toLowerCase();const n=t.indexOf("%");n!==-1&&(t=t.slice(0,n));const r=t.split("::");if(r.length>2)return null;const o=a=>{if(a==="")return[];const s=[],l=a.split(":");for(let c=0;c<l.length;c++){const p=l[c];if(p.includes(".")){if(c!==l.length-1||!Kl(p))return null;const[g,x,T,I]=p.split(".").map(Number);s.push(g<<8|x,T<<8|I);continue}if(!/^[0-9a-f]{1,4}$/.test(p))return null;s.push(parseInt(p,16))}return s},i=o(r[0]);if(i===null)return null;if(r.length===2){const a=o(r[1]);if(a===null)return null;const s=8-i.length-a.length;return s<0?null:[...i,...new Array(s).fill(0),...a]}return i.length===8?i:null}function e_(e){const t=Qm(e);if(t===null)return!0;const n=o=>t.slice(0,o).every(i=>i===0);if(n(7)&&(t[7]===0||t[7]===1)||(t[0]&65024)===64512||(t[0]&65472)===65152||(t[0]&65472)===65216||(t[0]&65280)===65280)return!0;if(n(6)||n(5)&&t[5]===65535||n(4)&&t[4]===65535&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===1){const o=t[6]>>8&255,i=t[6]&255,a=t[7]>>8&255,s=t[7]&255;return Wl(`${o}.${i}.${a}.${s}`)}return!1}var t_=10;async function n_({url:e,headers:t,abortSignal:n,maxRedirects:r=t_}){const o={signal:n};t!==void 0&&(o.headers=t);let i=e;for(let a=0;a<=r;a++){Xm(i);const s=await fetch(i,{...o,redirect:"manual"});if(s.type==="opaqueredirect"){if(!Ym())throw new qe({url:e,message:`Redirect from ${i} could not be validated and was blocked`});return await fetch(i,{...o,redirect:"follow"})}const l=s.headers.get("location");if(s.status>=300&&s.status<400&&l){await xo(s),i=new URL(l,i).toString();continue}return s}throw new qe({url:e,message:`Too many redirects (max ${r})`})}var Yl=2*1024*1024*1024;async function Xl({response:e,url:t,maxBytes:n=Yl}){const r=e.headers.get("content-length");if(r!=null){const p=parseInt(r,10);if(!isNaN(p)&&p>n)throw await xo(e),new qe({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${p}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const i=o.getReader(),a=[];let s=0;try{for(;;){const{done:p,value:g}=await i.read();if(p)break;if(s+=g.length,s>n)throw new qe({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});a.push(g)}}finally{try{await i.cancel()}finally{i.releaseLock()}}const l=new Uint8Array(s);let c=0;for(const p of a)l.set(p,c),c+=p.length;return l}var On=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const i=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*i|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new el({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},Ge=On();function Ql(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function on(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var r_=["fetch failed","failed to fetch"];function eu({error:e,url:t,requestBodyValues:n}){if(on(e))return e;if(e instanceof TypeError&&r_.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new $e({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function ko(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function o_(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}function Gt(e,...t){const n=new Headers(o_(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var tu="3.0.28",i_=()=>globalThis.fetch,rr=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:i=i_()})=>{try{const a=await i(e,{method:"GET",headers:Gt(t,`ai-sdk/provider-utils/${tu}`,ko()),signal:o}),s=an(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw on(c)||$e.isInstance(c)?c:new $e({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(on(l)||$e.isInstance(l))?l:new $e({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(a){throw eu({error:a,url:e,requestBodyValues:{}})}};function a_({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const i=r.toLowerCase();return i==="*"||i==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:i.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}function nu({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new Ln({message:`${r} API key must be a string.`});if(typeof process>"u")throw new Ln({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Ln({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ln({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Dt({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function s_(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}var l_=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,u_=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function ha(e){const t=JSON.parse(e);return t===null||typeof t!="object"||l_.test(e)===!1&&u_.test(e)===!1?t:c_(t)}function c_(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&r.constructor!==null&&typeof r.constructor=="object"&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const i=r[o];i&&typeof i=="object"&&t.push(i)}}}return e}function Io(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return ha(e)}try{return ha(e)}finally{Error.stackTraceLimit=t}}var or=Symbol.for("vercel.ai.validator");function d_(e){return{[or]:!0,validate:e}}function p_(e){return typeof e=="object"&&e!==null&&or in e&&e[or]===!0&&"validate"in e}function Ee(e){let t;return()=>(t==null&&(t=e()),t)}function h_(e){return p_(e)?e:typeof e=="function"?e():f_(e)}function f_(e){return d_(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new _n({value:t,cause:n.issues})}})}async function Me({value:e,schema:t}){const n=await gt({value:e,schema:t});if(!n.success)throw _n.wrap({value:e,cause:n.error});return n.value}async function gt({value:e,schema:t}){const n=h_(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:_n.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:_n.wrap({value:e,cause:r}),rawValue:e}}}async function m_({text:e,schema:t}){try{const n=Io(e);return t==null?n:Me({value:n,schema:t})}catch(n){throw Hn.isInstance(n)||_n.isInstance(n)?n:new Hn({text:e,cause:n})}}async function Ut({text:e,schema:t}){try{const n=Io(e);return t==null?{success:!0,value:n,rawValue:n}:await gt({value:n,schema:t})}catch(n){return{success:!1,error:Hn.isInstance(n)?n:new Hn({text:e,cause:n}),rawValue:void 0}}}function fa(e){try{return Io(e),!0}catch{return!1}}function __({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new fd).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await Ut({text:n,schema:t}))}}))}async function Je({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await gt({value:t[e],schema:n});if(!r.success)throw new el({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var g_=()=>globalThis.fetch,De=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a})=>ru({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a}),y_=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a})=>ru({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a}),ru=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:i,fetch:a=g_()})=>{try{const s=await a(e,{method:"POST",headers:Gt(t,`ai-sdk/provider-utils/${tu}`,ko()),body:n.content,signal:i}),l=an(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:n.values})}catch(p){throw on(p)||$e.isInstance(p)?p:new $e({message:"Failed to process error response",cause:p,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(on(c)||$e.isInstance(c))?c:new $e({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(s){throw eu({error:s,url:e,requestBodyValues:n.values})}};function yt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:n,outputSchema:o,execute:r,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l})}function Ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:n,outputSchema:r,execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l})}async function Ue(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var v_=new TextDecoder;async function ou({response:e,url:t}){return v_.decode(await Xl({response:e,url:t}))}var pt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:i})=>{const a=await ou({response:r,url:o}),s=an(r);if(a.trim()==="")return{responseHeaders:s,value:new $e({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:s,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await m_({text:a,schema:e});return{responseHeaders:s,value:new $e({message:t(l),url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:s,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:s,value:new $e({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:s,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},$n=e=>async({response:t})=>{const n=an(t);if(t.body==null)throw new td({});return{responseHeaders:n,value:__({stream:t.body,schema:e})}},Be=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await ou({response:t,url:n}),i=await Ut({text:o,schema:e}),a=an(t);if(!i.success)throw new $e({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}},b_=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=an(e);if(!e.body)throw new $e({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new $e({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},Xr=Symbol.for("vercel.ai.schema");function W(e){let t;return()=>(t==null&&(t=e()),t)}function To(e,{validate:t}={}){return{[Xr]:!0,_type:void 0,[or]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Bn(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const n in t)t[n]=Bn(t[n])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Bn(t)):e.items=Bn(e.items)),e}var w_=Symbol("Let zodToJsonSchema decide on which parser to use"),ma={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},x_=e=>typeof e=="string"?{...ma,name:e}:{...ma,...e};function We(){return{}}function k_(e,t){var n,r,o;const i={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==M.ZodAny&&(i.items=me(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}function I_(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function T_(){return{type:"boolean"}}function iu(e,t){return me(e.type._def,t)}var S_=(e,t)=>me(e.innerType._def,t);function au(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,i)=>au(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return E_(e)}}var E_=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function C_(e,t){return{...me(e.innerType._def,t),default:e.defaultValue()}}function A_(e,t){return t.effectStrategy==="input"?me(e.schema._def,t):We()}function O_(e){return{type:"string",enum:Array.from(e.values)}}var $_=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function N_(e,t){const n=[me(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),me(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if($_(o))r.push(...o.allOf);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...s}=o;i=s}r.push(i)}}),r.length?{allOf:r}:void 0}function R_(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Ir=void 0,ot={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ir===void 0&&(Ir=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ir),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function su(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":it(n,"email",r.message,t);break;case"format:idn-email":it(n,"idn-email",r.message,t);break;case"pattern:zod":Pe(n,ot.email,r.message,t);break}break;case"url":it(n,"uri",r.message,t);break;case"uuid":it(n,"uuid",r.message,t);break;case"regex":Pe(n,r.regex,r.message,t);break;case"cuid":Pe(n,ot.cuid,r.message,t);break;case"cuid2":Pe(n,ot.cuid2,r.message,t);break;case"startsWith":Pe(n,RegExp(`^${Tr(r.value,t)}`),r.message,t);break;case"endsWith":Pe(n,RegExp(`${Tr(r.value,t)}$`),r.message,t);break;case"datetime":it(n,"date-time",r.message,t);break;case"date":it(n,"date",r.message,t);break;case"time":it(n,"time",r.message,t);break;case"duration":it(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{Pe(n,RegExp(Tr(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&it(n,"ipv4",r.message,t),r.version!=="v4"&&it(n,"ipv6",r.message,t);break}case"base64url":Pe(n,ot.base64url,r.message,t);break;case"jwt":Pe(n,ot.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Pe(n,ot.ipv4Cidr,r.message,t),r.version!=="v4"&&Pe(n,ot.ipv6Cidr,r.message,t);break}case"emoji":Pe(n,ot.emoji(),r.message,t);break;case"ulid":{Pe(n,ot.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{it(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Pe(n,ot.base64,r.message,t);break}}break}case"nanoid":Pe(n,ot.nanoid,r.message,t)}return n}function Tr(e,t){return t.patternStrategy==="escape"?M_(e):e}var P_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function M_(e){let t="";for(let n=0;n<e.length;n++)P_.has(e[n])||(t+="\\"),t+=e[n];return t}function it(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function Pe(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:_a(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=_a(t,r)}function _a(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let i="",a=!1,s=!1,l=!1;for(let c=0;c<o.length;c++){if(a){i+=o[c],a=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){l?(i+=o[c],i+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(i+=o[c],l=!0):i+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){i+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){i+=`(^|(?<=[\r
457
- ]))`;continue}else if(o[c]==="$"){i+=`($|(?=[\r
458
- ]))`;continue}}if(r.s&&o[c]==="."){i+=s?`${o[c]}\r
459
- `:`[${o[c]}\r
460
- ]`;continue}i+=o[c],o[c]==="\\"?a=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function lu(e,t){var n,r,o,i,a,s;const l={type:"object",additionalProperties:(n=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...p}=su(e.keyType._def,t);return{...l,propertyNames:p}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===M.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:c,...p}=iu(e.keyType._def,t);return{...l,propertyNames:p}}}return l}function L_(e,t){if(t.mapStrategy==="record")return lu(e,t);const n=me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||We(),r=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||We();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function z_(e){const t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function D_(){return{not:We()}}function Z_(){return{type:"null"}}var Qr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function j_(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Qr&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,i)=>{const a=Qr[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return U_(e,t)}var U_=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>me(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function B_(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Qr[e.innerType._def.typeName],"null"]};const n=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function V_(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function F_(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let s=o[a];if(s===void 0||s._def===void 0)continue;const l=G_(s),c=me(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const i=q_(e,t);return i!==void 0&&(n.additionalProperties=i),n}function q_(e,t){if(e.catchall._def.typeName!=="ZodNever")return me(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function G_(e){try{return e.isOptional()}catch{return!0}}var H_=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return me(e.innerType._def,t);const r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:We()},r]}:We()},J_=(e,t)=>{if(t.pipeStrategy==="input")return me(e.in._def,t);if(t.pipeStrategy==="output")return me(e.out._def,t);const n=me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function K_(e,t){return me(e.type._def,t)}function W_(e,t){const r={type:"array",uniqueItems:!0,items:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function Y_(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>me(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>me(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function X_(){return{not:We()}}function Q_(){return We()}var eg=(e,t)=>me(e.innerType._def,t),tg=(e,t,n)=>{switch(t){case M.ZodString:return su(e,n);case M.ZodNumber:return V_(e);case M.ZodObject:return F_(e,n);case M.ZodBigInt:return I_(e);case M.ZodBoolean:return T_();case M.ZodDate:return au(e,n);case M.ZodUndefined:return X_();case M.ZodNull:return Z_();case M.ZodArray:return k_(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return j_(e,n);case M.ZodIntersection:return N_(e,n);case M.ZodTuple:return Y_(e,n);case M.ZodRecord:return lu(e,n);case M.ZodLiteral:return R_(e);case M.ZodEnum:return O_(e);case M.ZodNativeEnum:return z_(e);case M.ZodNullable:return B_(e,n);case M.ZodOptional:return H_(e,n);case M.ZodMap:return L_(e,n);case M.ZodSet:return W_(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return K_(e,n);case M.ZodNaN:case M.ZodNever:return D_();case M.ZodEffects:return A_(e,n);case M.ZodAny:return We();case M.ZodUnknown:return Q_();case M.ZodDefault:return C_(e,n);case M.ZodBranded:return iu(e,n);case M.ZodReadonly:return eg(e,n);case M.ZodCatch:return S_(e,n);case M.ZodPipeline:return J_(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}},ng=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function me(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==w_)return l}if(o&&!n){const l=rg(o,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=tg(e,e.typeName,t),s=typeof a=="function"?me(a(),t):a;if(s&&og(e,t,s),t.postProcess){const l=t.postProcess(s,e,t);return i.jsonSchema=s,l}return i.jsonSchema=s,s}var rg=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ng(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),We()):t.$refStrategy==="seen"?We():void 0}},og=(e,t,n)=>(e.description&&(n.description=e.description),n),ig=e=>{const t=x_(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},ag=(e,t)=>{var n;const r=ig(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[p,g])=>{var x;return{...c,[p]:(x=me(g._def,{...r,currentPath:[...r.basePath,r.definitionPath,p]},!0))!=null?x:We()}},{}):void 0;const i=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,a=(n=me(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1))!=null?n:We(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const l=i===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...o,[i]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},sg=ag;function lg(e,t){var n;const r=(n=void 0)!=null?n:!1;return To(()=>sg(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const i=await e.safeParseAsync(o);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function ug(e,t){var n;const r=(n=void 0)!=null?n:!1;return To(()=>Bn(pf(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:async o=>{const i=await zl(e,o);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function cg(e){return"_zod"in e}function j(e,t){return cg(e)?ug(e):lg(e)}function dg(e){return typeof e=="object"&&e!==null&&Xr in e&&e[Xr]===!0&&"jsonSchema"in e&&"validate"in e}function dr(e){return e==null?To({properties:{},additionalProperties:!1}):dg(e)?e:typeof e=="function"?e():j(e)}var{btoa:pg,atob:hg}=globalThis;function pr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=hg(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function ir(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return pg(t)}function Tt(e){return e instanceof Uint8Array?ir(e):e}function So(e){return e==null?void 0:e.replace(/\/$/,"")}function fg(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*mg({execute:e,input:t,options:n}){const r=e(t,n);if(fg(r)){let o;for await(const i of r)o=i,yield{type:"preliminary",output:i};yield{type:"final",output:o}}else yield{type:"final",output:await r}}var Sr,ga;function _g(){if(ga)return Sr;ga=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=(p,g)=>{for(var x in g)e(p,x,{get:g[x],enumerable:!0})},i=(p,g,x,T)=>{if(g&&typeof g=="object"||typeof g=="function")for(let I of n(g))!r.call(p,I)&&I!==x&&e(p,I,{get:()=>g[I],enumerable:!(T=t(g,I))||T.enumerable});return p},a=p=>i(e({},"__esModule",{value:!0}),p),s={};o(s,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Sr=a(s);const l=Symbol.for("@vercel/request-context");function c(){var g,x;return((x=(g=globalThis[l])==null?void 0:g.get)==null?void 0:x.call(g))??{}}return Sr}var Er,ya;function gg(){if(ya)return Er;ya=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=(g,x)=>{for(var T in x)e(g,T,{get:x[T],enumerable:!0})},i=(g,x,T,I)=>{if(x&&typeof x=="object"||typeof x=="function")for(let E of n(x))!r.call(g,E)&&E!==T&&e(g,E,{get:()=>x[E],enumerable:!(I=t(x,E))||I.enumerable});return g},a=g=>i(e({},"__esModule",{value:!0}),g),s={};o(s,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>p}),Er=a(s);var l=_g();async function c(){return""}function p(){return""}return Er}var uu=gg(),yg="vercel.ai.gateway.error",Cr=Symbol.for(yg),va,ba,Ne=class cu extends(ba=Error,va=Cr,ba){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[va]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return cu.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Cr in t&&t[Cr]===!0}},du="GatewayAuthenticationError",vg=`vercel.ai.gateway.error.${du}`,wa=Symbol.for(vg),xa,ka,Eo=class pu extends(ka=Ne,xa=wa,ka){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[xa]=!0,this.name=du,this.type="authentication_error"}static isInstance(t){return Ne.hasMarker(t)&&wa in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:i}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
461
-
462
- Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
463
-
464
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token.
465
-
466
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
467
-
468
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
469
-
470
- Option 1 - API key:
471
- Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
472
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
473
-
474
- Option 2 - OIDC token:
475
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new pu({message:a,statusCode:o,cause:i})}},hu="GatewayForbiddenError",bg=`vercel.ai.gateway.error.${hu}`,Ia=Symbol.for(bg),Ta,Sa,wg=class extends(Sa=Ne,Ta=Ia,Sa){constructor({message:e="Forbidden",statusCode:t=403,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Ta]=!0,this.name=hu,this.type="forbidden"}static isInstance(e){return Ne.hasMarker(e)&&Ia in e}},fu="GatewayInvalidRequestError",xg=`vercel.ai.gateway.error.${fu}`,Ea=Symbol.for(xg),Ca,Aa,kg=class extends(Aa=Ne,Ca=Ea,Aa){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Ca]=!0,this.name=fu,this.type="invalid_request_error"}static isInstance(e){return Ne.hasMarker(e)&&Ea in e}},mu="GatewayRateLimitError",Ig=`vercel.ai.gateway.error.${mu}`,Oa=Symbol.for(Ig),$a,Na,Tg=class extends(Na=Ne,$a=Oa,Na){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[$a]=!0,this.name=mu,this.type="rate_limit_exceeded"}static isInstance(e){return Ne.hasMarker(e)&&Oa in e}},_u="GatewayModelNotFoundError",Sg=`vercel.ai.gateway.error.${_u}`,Ra=Symbol.for(Sg),Eg=Ee(()=>j(d({modelId:u()}))),Pa,Ma,Cg=class extends(Ma=Ne,Pa=Ra,Ma){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Pa]=!0,this.name=_u,this.type="model_not_found",this.modelId=n}static isInstance(e){return Ne.hasMarker(e)&&Ra in e}},gu="GatewayInternalServerError",Ag=`vercel.ai.gateway.error.${gu}`,La=Symbol.for(Ag),za,Da,Za=class extends(Da=Ne,za=La,Da){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[za]=!0,this.name=gu,this.type="internal_server_error"}static isInstance(e){return Ne.hasMarker(e)&&La in e}},yu="GatewayResponseError",Og=`vercel.ai.gateway.error.${yu}`,ja=Symbol.for(Og),Ua,Ba,$g=class extends(Ba=Ne,Ua=ja,Ba){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[Ua]=!0,this.name=yu,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return Ne.hasMarker(e)&&ja in e}};async function Va({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const i=await gt({value:e,schema:Ng});if(!i.success)return new $g({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:i.error,cause:r});const a=i.value,s=a.error.type,l=a.error.message;switch(s){case"authentication_error":return Eo.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new kg({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new Tg({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await gt({value:a.error.param,schema:Eg});return new Cg({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new Za({message:l,statusCode:t,cause:r});case"forbidden":return new wg({message:l,statusCode:t,cause:r});default:return new Za({message:l,statusCode:t,cause:r})}}var Ng=Ee(()=>j(d({error:d({message:u(),type:u().nullish(),param:Le().nullish(),code:ee([u(),f()]).nullish()})})));function Rg(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var vu="GatewayTimeoutError",Pg=`vercel.ai.gateway.error.${vu}`,Fa=Symbol.for(Pg),qa,Ga,Ha=class bu extends(Ga=Ne,qa=Fa,Ga){constructor({message:t="Request timed out",statusCode:n=408,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[qa]=!0,this.name=vu,this.type="timeout_error"}static isInstance(t){return Ne.hasMarker(t)&&Fa in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r}){const o=`Gateway request timed out: ${t}
476
-
477
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new bu({message:o,statusCode:n,cause:r})}};function Ja(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function et(e,t){var n;return Ne.isInstance(e)?e:Ja(e)?Ha.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):$e.isInstance(e)?e.cause&&Ja(e.cause)?Ha.createTimeoutError({originalMessage:e.message,cause:e}):await Va({response:Rg(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Va({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var wu="ai-gateway-auth-method";async function St(e){const t=await gt({value:e[wu],schema:Mg});return t.success?t.value:void 0}var Mg=Ee(()=>j(ee([h("api-key"),h("oidc")]))),Lg=["embedding","image","language"],Ka=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await rr({url:`${this.config.baseURL}/config`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(zg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await et(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await rr({url:`${e.origin}/v1/credits`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(Dg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await et(e)}}},zg=Ee(()=>j(d({models:R(d({id:u(),name:u(),description:u().nullish(),pricing:d({input:u(),output:u(),input_cache_read:u().nullish(),input_cache_write:u().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:d({specificationVersion:h("v2"),provider:u(),modelId:u()}),modelType:u().nullish()})).transform(e=>e.filter(t=>t.modelType==null||Lg.includes(t.modelType)))}))),Dg=Ee(()=>j(d({balance:u(),total_used:u()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),Zg=class{constructor(e){this.config=e}async getSpendReport(e){try{const t=new URL(this.config.baseURL),n=new URLSearchParams;n.set("start_date",e.startDate),n.set("end_date",e.endDate),e.groupBy&&n.set("group_by",e.groupBy),e.datePart&&n.set("date_part",e.datePart),e.userId&&n.set("user_id",e.userId),e.model&&n.set("model",e.model),e.provider&&n.set("provider",e.provider),e.credentialType&&n.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&n.set("tags",e.tags.join(","));const{value:r}=await rr({url:`${t.origin}/v1/report?${n.toString()}`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(jg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:o=>o}),fetch:this.config.fetch});return r}catch(t){throw await et(t)}}},jg=W(()=>j(d({results:R(d({day:u().optional(),hour:u().optional(),user:u().optional(),model:u().optional(),tag:u().optional(),provider:u().optional(),credential_type:X(["byok","system"]).optional(),total_cost:f(),market_cost:f().optional(),input_tokens:f().optional(),output_tokens:f().optional(),cached_input_tokens:f().optional(),cache_creation_input_tokens:f().optional(),reasoning_tokens:f().optional(),request_count:f().optional()}).transform(({credential_type:e,total_cost:t,market_cost:n,input_tokens:r,output_tokens:o,cached_input_tokens:i,cache_creation_input_tokens:a,reasoning_tokens:s,request_count:l,...c})=>({...c,...e!==void 0?{credentialType:e}:{},totalCost:t,...n!==void 0?{marketCost:n}:{},...r!==void 0?{inputTokens:r}:{},...o!==void 0?{outputTokens:o}:{},...i!==void 0?{cachedInputTokens:i}:{},...a!==void 0?{cacheCreationInputTokens:a}:{},...s!==void 0?{reasoningTokens:s}:{},...l!==void 0?{requestCount:l}:{}})))}))),Ug=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:n}=await rr({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(Bg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:r=>r}),fetch:this.config.fetch});return n}catch(t){throw await et(t)}}},Bg=W(()=>j(d({data:d({id:u(),total_cost:f(),upstream_inference_cost:f(),usage:f(),created_at:u(),model:u(),is_byok:ue(),provider_name:u(),streamed:ue(),finish_reason:u(),latency:f(),generation_time:f(),native_tokens_prompt:f(),native_tokens_completion:f(),native_tokens_reasoning:f(),native_tokens_cached:f(),native_tokens_cache_creation:f(),billable_web_search_calls:f()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:n,is_byok:r,provider_name:o,finish_reason:i,generation_time:a,native_tokens_prompt:s,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:p,native_tokens_cache_creation:g,billable_web_search_calls:x,...T})=>({...T,totalCost:e,upstreamInferenceCost:t,createdAt:n,isByok:r,providerName:o,finishReason:i,generationTime:a,promptTokens:s,completionTokens:l,reasoningTokens:c,cachedTokens:p,cacheCreationTokens:g,billableWebSearchCalls:x}))}).transform(({data:e})=>e))),Vg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Ue(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:s}=await De({url:this.getUrl(),headers:ze(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ue(this.config.o11yHeaders)),body:t,successfulResponseHandler:Be(He()),failedResponseHandler:pt({errorSchema:He(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:i,body:s},warnings:n}}catch(i){throw await et(i,await St(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Ue(this.config.headers());try{const{value:i,responseHeaders:a}=await De({url:this.getUrl(),headers:ze(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ue(this.config.o11yHeaders)),body:t,successfulResponseHandler:$n(He()),failedResponseHandler:pt({errorSchema:He(),errorToMessage:s=>s}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:i.pipeThrough(new TransformStream({start(s){n.length>0&&s.enqueue({type:"stream-start",warnings:n})},transform(s,l){if(s.success){const c=s.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(s.error)}})),request:{body:t},response:{headers:a}}}catch(i){throw await et(i,await St(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),i=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${i}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Fg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const i=await Ue(this.config.headers());try{const{responseHeaders:a,value:s,rawValue:l}=await De({url:this.getUrl(),headers:ze(i,t??{},this.getModelConfigHeaders(),await Ue(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:Be(qg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(o=s.usage)!=null?o:void 0,providerMetadata:s.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await et(a,await St(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},qg=Ee(()=>j(d({embeddings:R(R(f())),usage:d({tokens:f()}).nullish(),providerMetadata:Se(u(),Se(u(),Le())).optional()}))),Gg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:a,abortSignal:s}){var l,c,p,g;const x=await Ue(this.config.headers());try{const{responseHeaders:T,value:I,rawValue:E}=await De({url:this.getUrl(),headers:ze(x,a??{},this.getModelConfigHeaders(),await Ue(this.config.o11yHeaders)),body:{prompt:e,n:t,...n&&{size:n},...r&&{aspectRatio:r},...o&&{seed:o},...i&&{providerOptions:i}},successfulResponseHandler:Be(Kg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:k=>k}),...s&&{abortSignal:s},fetch:this.config.fetch});return{images:I.images,warnings:(l=I.warnings)!=null?l:[],providerMetadata:I.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:T},...I.usage!=null&&{usage:{inputTokens:(c=I.usage.inputTokens)!=null?c:void 0,outputTokens:(p=I.usage.outputTokens)!=null?p:void 0,totalTokens:(g=I.usage.totalTokens)!=null?g:void 0}}}}catch(T){throw await et(T,await St(x))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},Hg=d({images:R(Le()).optional()}).catchall(Le()),Jg=d({inputTokens:f().nullish(),outputTokens:f().nullish(),totalTokens:f().nullish()}),Kg=d({images:R(u()),warnings:R(d({type:h("other"),message:u()})).optional(),providerMetadata:Se(u(),Hg).optional(),usage:Jg.optional()}),Wg=W(()=>j(at({objective:ye().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Ct(ye()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:cr(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:ct().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:at({include_domains:Ct(ye()).optional().describe("List of domains to include in search results."),exclude_domains:Ct(ye()).optional().describe("List of domains to exclude from search results."),after_date:ye().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:at({max_chars_per_result:ct().optional().describe("Maximum characters per result."),max_chars_total:ct().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:at({max_age_seconds:ct().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),Yg=W(()=>j(wo([at({searchId:ye(),results:Ct(at({url:ye(),title:ye(),excerpt:ye(),publishDate:ye().nullable().optional(),relevanceScore:ct().optional()}))}),at({error:cr(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:ct().optional(),message:ye()})]))),Xg=Ye({id:"gateway.parallel_search",name:"parallel_search",inputSchema:Wg,outputSchema:Yg}),Qg=(e={})=>Xg(e),ey=W(()=>j(at({query:wo([ye(),Ct(ye())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:ct().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:ct().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:ct().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:ye().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Ct(ye()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Ct(ye()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:ye().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:ye().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:ye().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:ye().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:cr(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),ty=W(()=>j(wo([at({results:Ct(at({title:ye(),url:ye(),snippet:ye(),date:ye().optional(),lastUpdated:ye().optional()})),id:ye()}),at({error:cr(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:ct().optional(),message:ye()})]))),ny=Ye({id:"gateway.perplexity_search",name:"perplexity_search",inputSchema:ey,outputSchema:ty}),ry=(e={})=>ny(e),oy={parallelSearch:Qg,perplexitySearch:ry};async function iy(){var e;return(e=uu.getContext().headers)==null?void 0:e["x-vercel-id"]}var ay="2.0.107",sy="0.0.1";function ly(e={}){var t,n;let r=null,o=null;const i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const s=(n=So(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const k=await cy(e);if(k)return Gt({Authorization:`Bearer ${k.token}`,"ai-gateway-protocol-version":sy,[wu]:k.authMethod,...e.headers},`ai-sdk/gateway/${ay}`);throw Eo.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const k=Dt({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),_=Dt({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),v=Dt({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),y=Dt({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const $=await iy();return{...k&&{"ai-o11y-deployment-id":k},..._&&{"ai-o11y-environment":_},...v&&{"ai-o11y-region":v},...$&&{"ai-o11y-request-id":$},...y&&{"ai-o11y-project-id":y}}}},p=k=>new Vg(k,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),g=async()=>{var k,_,v;const y=(v=(_=(k=e._internal)==null?void 0:k.currentDate)==null?void 0:_.call(k).getTime())!=null?v:Date.now();return(!r||y-a>i)&&(a=y,r=new Ka({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then($=>(o=$,$)).catch(async $=>{throw await et($,await St(await l()))})),o?Promise.resolve(o):r},x=async()=>new Ka({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async k=>{throw await et(k,await St(await l()))}),T=async k=>new Zg({baseURL:s,headers:l,fetch:e.fetch}).getSpendReport(k).catch(async _=>{throw await et(_,await St(await l()))}),I=async k=>new Ug({baseURL:s,headers:l,fetch:e.fetch}).getGenerationInfo(k).catch(async _=>{throw await et(_,await St(await l()))}),E=function(k){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(k)};return E.getAvailableModels=g,E.getCredits=x,E.getSpendReport=T,E.getGenerationInfo=I,E.imageModel=k=>new Gg(k,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),E.languageModel=p,E.textEmbeddingModel=k=>new Fg(k,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),E.tools=oy,E}var uy=ly();async function cy(e){const t=Dt({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await uu.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var dy=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Zt="1.9.0",Wa=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function py(e){var t=new Set([e]),n=new Set,r=e.match(Wa);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function i(s){return n.add(s),!1}function a(s){return t.add(s),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(Wa);if(!c)return i(l);var p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||o.major!==p.major?i(l):o.major===0?o.minor===p.minor&&o.patch<=p.patch?a(l):i(l):o.minor<=p.minor?a(l):i(l)}}var hy=py(Zt),fy=Zt.split(".")[0],wn=Symbol.for("opentelemetry.js.api."+fy),xn=dy;function Nn(e,t,n,r){var o;r===void 0&&(r=!1);var i=xn[wn]=(o=xn[wn])!==null&&o!==void 0?o:{version:Zt};if(!r&&i[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(i.version!==Zt){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+e+" does not match previously registered API v"+Zt);return n.error(a.stack||a.message),!1}return i[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+Zt+"."),!0}function Bt(e){var t,n,r=(t=xn[wn])===null||t===void 0?void 0:t.version;if(!(!r||!hy(r)))return(n=xn[wn])===null||n===void 0?void 0:n[e]}function Rn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Zt+".");var n=xn[wn];n&&delete n[e]}var my=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},_y=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},gy=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ln("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ln("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ln("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ln("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return ln("verbose",this._namespace,t)},e})();function ln(e,t,n){var r=Bt("diag");if(r)return n.unshift(t),r[e].apply(r,_y([],my(n),!1))}var Fe;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Fe||(Fe={}));function yy(e,t){e<Fe.NONE?e=Fe.NONE:e>Fe.ALL&&(e=Fe.ALL),t=t||{};function n(r,o){var i=t[r];return typeof i=="function"&&e>=o?i.bind(t):function(){}}return{error:n("error",Fe.ERROR),warn:n("warn",Fe.WARN),info:n("info",Fe.INFO),debug:n("debug",Fe.DEBUG),verbose:n("verbose",Fe.VERBOSE)}}var vy=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},by=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},wy="diag",ht=(function(){function e(){function t(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Bt("diag");if(s)return s[o].apply(s,by([],vy(i),!1))}}var n=this,r=function(o,i){var a,s,l;if(i===void 0&&(i={logLevel:Fe.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof i=="number"&&(i={logLevel:i});var p=Bt("diag"),g=yy((s=i.logLevel)!==null&&s!==void 0?s:Fe.INFO,o);if(p&&!i.suppressOverrideMessage){var x=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+x),g.warn("Current logger will overwrite one already registered from "+x)}return Nn("diag",g,n,!0)};n.setLogger=r,n.disable=function(){Rn(wy,n)},n.createComponentLogger=function(o){return new gy(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),xy=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},ky=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Iy=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=xy(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var i=new e(this._entries);try{for(var a=ky(r),s=a.next();!s.done;s=a.next()){var l=s.value;i._entries.delete(l)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return i},e.prototype.clear=function(){return new e},e})();ht.instance();function Ty(e){return e===void 0&&(e={}),new Iy(new Map(Object.entries(e)))}function xu(e){return Symbol.for(e)}var Sy=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var i=new e(n._currentContext);return i._currentContext.set(r,o),i},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e})(),Ey=new Sy,Ht=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(r[i]=o[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Cy=(function(){function e(){}return e.prototype.createGauge=function(t,n){return Dy},e.prototype.createHistogram=function(t,n){return Zy},e.prototype.createCounter=function(t,n){return zy},e.prototype.createUpDownCounter=function(t,n){return jy},e.prototype.createObservableGauge=function(t,n){return By},e.prototype.createObservableCounter=function(t,n){return Uy},e.prototype.createObservableUpDownCounter=function(t,n){return Vy},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e})(),hr=(function(){function e(){}return e})(),Ay=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t})(hr),Oy=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t})(hr),$y=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t})(hr),Ny=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t})(hr),Co=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Ry=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Co),Py=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Co),My=(function(e){Ht(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Co),Ly=new Cy,zy=new Ay,Dy=new $y,Zy=new Ny,jy=new Oy,Uy=new Ry,By=new Py,Vy=new My,Fy={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},qy={set:function(e,t,n){e!=null&&(e[t]=n)}},Gy=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},Hy=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},Jy=(function(){function e(){}return e.prototype.active=function(){return Ey},e.prototype.with=function(t,n,r){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return n.call.apply(n,Hy([r],Gy(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),Ky=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},Wy=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},Ar="context",Yy=new Jy,fr=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Nn(Ar,t,ht.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,Wy([t,n,r],Ky(i),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Bt(Ar)||Yy},e.prototype.disable=function(){this._getContextManager().disable(),Rn(Ar,ht.instance())},e})(),eo;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(eo||(eo={}));var ku="0000000000000000",Iu="00000000000000000000000000000000",Xy={traceId:Iu,spanId:ku,traceFlags:eo.NONE},fn=(function(){function e(t){t===void 0&&(t=Xy),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),Ao=xu("OpenTelemetry Context Key SPAN");function Oo(e){return e.getValue(Ao)||void 0}function Qy(){return Oo(fr.getInstance().active())}function $o(e,t){return e.setValue(Ao,t)}function ev(e){return e.deleteValue(Ao)}function tv(e,t){return $o(e,new fn(t))}function Tu(e){var t;return(t=Oo(e))===null||t===void 0?void 0:t.spanContext()}var nv=/^([0-9a-f]{32})$/i,rv=/^[0-9a-f]{16}$/i;function ov(e){return nv.test(e)&&e!==Iu}function iv(e){return rv.test(e)&&e!==ku}function Su(e){return ov(e.traceId)&&iv(e.spanId)}function av(e){return new fn(e)}var Or=fr.getInstance(),Eu=(function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=Or.active());var o=!!(n!=null&&n.root);if(o)return new fn;var i=r&&Tu(r);return sv(i)&&Su(i)?new fn(i):new fn},e.prototype.startActiveSpan=function(t,n,r,o){var i,a,s;if(!(arguments.length<2)){arguments.length===2?s=n:arguments.length===3?(i=n,s=r):(i=n,a=r,s=o);var l=a??Or.active(),c=this.startSpan(t,i,l),p=$o(l,c);return Or.with(p,s,void 0,c)}},e})();function sv(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var lv=new Eu,uv=(function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):lv},e})(),cv=(function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new Eu},e})(),dv=new cv,Ya=(function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new uv(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:dv},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e})(),ar;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(ar||(ar={}));fr.getInstance();ht.instance();var pv=(function(){function e(){}return e.prototype.getMeter=function(t,n,r){return Ly},e})(),hv=new pv,$r="metrics",fv=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Nn($r,t,ht.instance())},e.prototype.getMeterProvider=function(){return Bt($r)||hv},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){Rn($r,ht.instance())},e})();fv.getInstance();var mv=(function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e})(),No=xu("OpenTelemetry Baggage Key");function Cu(e){return e.getValue(No)||void 0}function _v(){return Cu(fr.getInstance().active())}function gv(e,t){return e.setValue(No,t)}function yv(e){return e.deleteValue(No)}var Nr="propagation",vv=new mv,bv=(function(){function e(){this.createBaggage=Ty,this.getBaggage=Cu,this.getActiveBaggage=_v,this.setBaggage=gv,this.deleteBaggage=yv}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Nn(Nr,t,ht.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=qy),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=Fy),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Rn(Nr,ht.instance())},e.prototype._getGlobalPropagator=function(){return Bt(Nr)||vv},e})();bv.getInstance();var Rr="trace",wv=(function(){function e(){this._proxyTracerProvider=new Ya,this.wrapSpanContext=av,this.isSpanContextValid=Su,this.deleteSpan=ev,this.getSpan=Oo,this.getActiveSpan=Qy,this.getSpanContext=Tu,this.setSpan=$o,this.setSpanContext=tv}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Nn(Rr,this._proxyTracerProvider,ht.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Bt(Rr)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Rn(Rr,ht.instance()),this._proxyTracerProvider=new Ya},e})(),xv=wv.getInstance(),kv=Object.defineProperty,Iv=(e,t)=>{for(var n in t)kv(e,n,{get:t[n],enumerable:!0})},Au="AI_NoOutputSpecifiedError",Ou=`vercel.ai.error.${Au}`,Tv=Symbol.for(Ou),$u,Sv=class extends te{constructor({message:e="No output specified."}={}){super({name:Au,message:e}),this[$u]=!0}static isInstance(e){return te.hasMarker(e,Ou)}};$u=Tv;function Ev(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"unsupported-tool":{const n="name"in e.tool?e.tool.name:"unknown tool";let r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var Cv="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Xa=!1,Av=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Xa||(Xa=!0,console.info(Cv));for(const n of e)console.warn(Ev(n))}},Nu="AI_InvalidArgumentError",Ru=`vercel.ai.error.${Nu}`,Ov=Symbol.for(Ru),Pu,ut=class extends te{constructor({parameter:e,value:t,message:n}){super({name:Nu,message:`Invalid argument for parameter ${e}: ${n}`}),this[Pu]=!0,this.parameter=e,this.value=t}static isInstance(e){return te.hasMarker(e,Ru)}};Pu=Ov;var Mu="AI_InvalidToolInputError",Lu=`vercel.ai.error.${Mu}`,$v=Symbol.for(Lu),zu,Du=class extends te{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${En(n)}`}){super({name:Mu,message:r,cause:n}),this[zu]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return te.hasMarker(e,Lu)}};zu=$v;var Zu="AI_NoObjectGeneratedError",ju=`vercel.ai.error.${Zu}`,Nv=Symbol.for(ju),Uu,Qa=class extends te{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:Zu,message:e,cause:t}),this[Uu]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return te.hasMarker(e,ju)}};Uu=Nv;var Bu="AI_NoSuchToolError",Vu=`vercel.ai.error.${Bu}`,Rv=Symbol.for(Vu),Fu,to=class extends te{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Bu,message:n}),this[Fu]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return te.hasMarker(e,Vu)}};Fu=Rv;var qu="AI_ToolCallRepairError",Gu=`vercel.ai.error.${qu}`,Pv=Symbol.for(Gu),Hu,Mv=class extends te{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${En(e)}`}){super({name:qu,message:n,cause:e}),this[Hu]=!0,this.originalError=t}static isInstance(e){return te.hasMarker(e,Gu)}};Hu=Pv;var Lv=class extends te{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Ju="AI_InvalidMessageRoleError",Ku=`vercel.ai.error.${Ju}`,zv=Symbol.for(Ku),Wu,Dv=class extends te{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ju,message:t}),this[Wu]=!0,this.role=e}static isInstance(e){return te.hasMarker(e,Ku)}};Wu=zv;var Yu="AI_RetryError",Xu=`vercel.ai.error.${Yu}`,Zv=Symbol.for(Xu),Qu,es=class extends te{constructor({message:e,reason:t,errors:n}){super({name:Yu,message:e}),this[Qu]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return te.hasMarker(e,Xu)}};Qu=Zv;function ts(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new Lv({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return jv().languageModel(e)}function jv(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:uy}var Uv=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],Bv=e=>{const t=typeof e=="string"?pr(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function Vv(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Bv(e):e}function Fv({data:e,signatures:t}){const n=Vv(e),r=typeof n=="string"?pr(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((i,a)=>i===null||r[a]===i))return o.mediaType}var ec="5.0.208",tc=async({url:e,maxBytes:t,abortSignal:n})=>{var r;const o=e.toString();try{const i=Gt({},`ai-sdk/${ec}`,ko()),a=await n_({url:o,headers:i,abortSignal:n});if(!a.ok)throw await xo(a),new qe({url:o,statusCode:a.status,statusText:a.statusText});return{data:await Xl({response:a,url:o,maxBytes:t??Yl}),mediaType:(r=a.headers.get("content-type"))!=null?r:void 0}}catch(i){throw qe.isInstance(i)?i:new qe({url:o,cause:i})}},qv=(e=tc)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function Gv(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var nc=ee([u(),Yn(Uint8Array),Yn(ArrayBuffer),vm(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function rc(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=Gv(e.toString());if(t==null||n==null)throw new te({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Hv(e){return typeof e=="string"?e:e instanceof ArrayBuffer?ir(new Uint8Array(e)):ir(e)}async function Jv({prompt:e,supportedUrls:t,download:n=qv()}){const r=await Wv(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>Kv({message:o,downloadedAssets:r}))]}function Kv({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>Yv(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:i,mediaType:a}=rc(r.data);return{type:"file",data:i,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new Dv({role:r})}}}async function Wv(e,t,n){const r=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var a;const s=(a=i.mediaType)!=null?a:i.type==="image"?"image/*":void 0;let l=i.type==="image"?i.image:i.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:s,data:l}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&a_({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((i,a)=>i==null?null:[r[a].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}function Yv(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:i,mediaType:a}=rc(r);let s=a??e.mediaType,l=i;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,s??(s=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(n=Fv({data:l,signatures:Uv}))!=null?n:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function ns({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:i,seed:a,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new ut({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new ut({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new ut({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new ut({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new ut({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new ut({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new ut({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new ut({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:i,stopSequences:s,seed:a}}function Xv(e){return e!=null&&Object.keys(e).length>0}function Qv({tools:e,toolChoice:t,activeTools:n}){return Xv(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,i])=>{const a=i.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:i.description,inputSchema:dr(i.inputSchema).jsonSchema,providerOptions:i.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:i.id,args:i.args};default:{const s=a;throw new Error(`Unsupported tool type: ${s}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var kn=Vl(()=>ee([Gf(),u(),f(),ue(),Se(u(),kn),R(kn)])),mt=Se(u(),Se(u(),kn)),oc=d({type:h("text"),text:u(),providerOptions:mt.optional()}),eb=d({type:h("image"),image:ee([nc,Yn(URL)]),mediaType:u().optional(),providerOptions:mt.optional()}),ic=d({type:h("file"),data:ee([nc,Yn(URL)]),filename:u().optional(),mediaType:u(),providerOptions:mt.optional()}),tb=d({type:h("reasoning"),text:u(),providerOptions:mt.optional()}),nb=d({type:h("tool-call"),toolCallId:u(),toolName:u(),input:Le(),providerOptions:mt.optional(),providerExecuted:ue().optional()}),rb=se("type",[d({type:h("text"),value:u()}),d({type:h("json"),value:kn}),d({type:h("error-text"),value:u()}),d({type:h("error-json"),value:kn}),d({type:h("content"),value:R(ee([d({type:h("text"),text:u()}),d({type:h("media"),data:u(),mediaType:u()})]))})]),ac=d({type:h("tool-result"),toolCallId:u(),toolName:u(),output:rb,providerOptions:mt.optional()}),ob=d({role:h("system"),content:u(),providerOptions:mt.optional()}),ib=d({role:h("user"),content:ee([u(),R(ee([oc,eb,ic]))]),providerOptions:mt.optional()}),ab=d({role:h("assistant"),content:ee([u(),R(ee([oc,ic,tb,nb,ac]))]),providerOptions:mt.optional()}),sb=d({role:h("tool"),content:R(ac),providerOptions:mt.optional()}),lb=ee([ob,ib,ab,sb]);async function ub({allowSystemInMessages:e,system:t,prompt:n,messages:r}){if(n==null&&r==null)throw new wt({prompt:n,message:"prompt or messages must be defined"});if(n!=null&&r!=null)throw new wt({prompt:n,message:"prompt and messages cannot be defined at the same time"});if(t!=null&&typeof t!="string")throw new wt({prompt:n,message:"system must be a string"});if(n!=null&&typeof n=="string")r=[{role:"user",content:n}];else if(n!=null&&Array.isArray(n))r=n;else if(r==null)throw new wt({prompt:n,message:"prompt or messages must be defined"});if(r.length===0)throw new wt({prompt:n,message:"messages must not be empty"});if(r.some(i=>i.role==="system")){if(e===!1)throw new wt({prompt:n,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});e===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}const o=await gt({value:r,schema:R(lb)});if(!o.success)throw new wt({prompt:n,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:o.error});return{messages:r,system:t}}function cb(e){if(!Eo.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://v5.ai-sdk.dev/unauthenticated-ai-gateway";return t?new te({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
478
-
479
- To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
480
-
481
- Alternatively, you can use a provider module instead of the AI Gateway.
482
-
483
- Learn more: \x1B[34m${n}\x1B[0m
484
-
485
- `),{name:"GatewayAuthenticationError"})}function no({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function db({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[a,s])=>(i[`ai.settings.${a}`]=s,i),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((i,[a,s])=>(i[`ai.telemetry.metadata.${a}`]=s,i),{}),...Object.entries(r??{}).reduce((i,[a,s])=>(s!==void 0&&(i[`ai.request.headers.${a}`]=s),i),{})}}var pb={startSpan(){return Un},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Un);if(typeof n=="function")return n(Un);if(typeof r=="function")return r(Un)}},Un={spanContext(){return hb},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},hb={traceId:"",spanId:"",traceFlags:0};function fb({isEnabled:e=!1,tracer:t}={}){return e?t||xv.getTracer("ai"):pb}function ro({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async i=>{try{const a=await r(i);return o&&i.end(),a}catch(a){try{sc(i,a)}finally{i.end()}throw a}})}function sc(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:ar.ERROR,message:t.message})):e.setStatus({code:ar.ERROR})}function Wt({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const i=o.input();return i==null?n:{...n,[r]:i}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const i=o.output();return i==null?n:{...n,[r]:i}}return{...n,[r]:o}},{})}function mb(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Hv(n.data):n.data}:n)})))}function _b(e,t){return{inputTokens:un(e.inputTokens,t.inputTokens),outputTokens:un(e.outputTokens,t.outputTokens),totalTokens:un(e.totalTokens,t.totalTokens),reasoningTokens:un(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:un(e.cachedInputTokens,t.cachedInputTokens)}}function un(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function gb(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function yb({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const i=n["retry-after"];if(i&&r===void 0){const a=parseFloat(i);Number.isNaN(a)?r=Date.parse(i)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var vb=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>lc(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function lc(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},i=[]){try{return await e()}catch(a){if(on(a)||t===0)throw a;const s=Ql(a),l=[...i,a],c=l.length;if(c>t)throw new es({message:`Failed after ${c} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&$e.isInstance(a)&&a.isRetryable===!0&&c<=t)return await Km(yb({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),lc(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new es({message:`Failed after ${c} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function bb({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new ut({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new ut({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:vb({maxRetries:n,abortSignal:t})}}function rs(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var wb=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=ir(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=pr(this.base64Data)),this.uint8ArrayData}};async function xb({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new to({toolName:e.toolName});try{return await os({toolCall:e,tools:t})}catch(i){if(n==null||!(to.isInstance(i)||Du.isInstance(i)))throw i;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:s})=>{const{inputSchema:l}=t[s];return dr(l).jsonSchema},system:r,messages:o,error:i})}catch(s){throw new Mv({cause:s,originalError:i})}if(a==null)throw i;return await os({toolCall:a,tools:t})}}catch(i){const a=await Ut({text:e.input}),s=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:i,providerMetadata:e.providerMetadata}}}async function os({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new to({toolName:e.toolName,availableTools:Object.keys(t)});const o=dr(r.inputSchema),i=e.input.trim()===""?await gt({value:{},schema:o}):await Ut({text:e.input,schema:o});if(i.success===!1)throw new Du({toolName:n,toolInput:e.input,cause:i.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var kb=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:i,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=i,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Ib(e){return({steps:t})=>t.length===e}async function Tb({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function Pr({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:En(e)}:n==="json"?{type:"error-json",value:is(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:is(e)}}function is(e){return e===void 0?null:e}function Sb({content:e,tools:t}){const n=[],r=e.filter(i=>i.type!=="source").filter(i=>(i.type!=="tool-result"||i.providerExecuted)&&(i.type!=="tool-error"||i.providerExecuted)).filter(i=>i.type!=="text"||i.text.length>0).map(i=>{switch(i.type){case"text":return{type:"text",text:i.text,providerOptions:i.providerMetadata};case"reasoning":return{type:"reasoning",text:i.text,providerOptions:i.providerMetadata};case"file":return{type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:Pr({tool:t==null?void 0:t[i.toolName],output:i.output,errorMode:"none"}),providerExecuted:!0,providerOptions:i.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:Pr({tool:t==null?void 0:t[i.toolName],output:i.error,errorMode:"json"}),providerOptions:i.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(i=>i.type==="tool-result"||i.type==="tool-error").filter(i=>!i.providerExecuted).map(i=>({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:Pr({tool:t==null?void 0:t[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"}),...i.providerMetadata!=null?{providerOptions:i.providerMetadata}:{}}));return o.length>0&&n.push({role:"tool",content:o}),n}var Eb=On({prefix:"aitxt",size:24});async function uc({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:i,allowSystemInMessages:a,maxRetries:s,abortSignal:l,headers:c,stopWhen:p=Ib(1),experimental_output:g,experimental_telemetry:x,providerOptions:T,experimental_activeTools:I,activeTools:E=I,experimental_prepareStep:k,prepareStep:_=k,experimental_repairToolCall:v,experimental_download:y,experimental_context:$,_internal:{generateId:b=Eb,currentDate:S=()=>new Date}={},onStepFinish:m,...N}){const Z=ts(e),B=gb(p),{maxRetries:D,retry:oe}=bb({maxRetries:s,abortSignal:l}),L=ns(N),V=Gt(c??{},`ai/${ec}`),J=db({model:Z,telemetry:x,headers:V,settings:{...L,maxRetries:D}}),be=await ub({system:r,prompt:o,messages:i,allowSystemInMessages:a}),Y=fb(x);try{return await ro({name:"ai.generateText",attributes:Wt({telemetry:x,attributes:{...no({operationId:"ai.generateText",telemetry:x}),...J,"ai.model.provider":Z.provider,"ai.model.id":Z.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:i})}}}),tracer:Y,fn:async we=>{var ge,Ce,le,he,de,ke,O;const ne=ns(N);let C,H=[],re=[];const w=[],ie=[];do{const rt=[...be.messages,...w],st=await(_==null?void 0:_({model:Z,steps:ie,stepNumber:ie.length,messages:rt})),Mt=ts((ge=st==null?void 0:st.model)!=null?ge:Z),Do=await Jv({prompt:{system:(Ce=st==null?void 0:st.system)!=null?Ce:be.system,messages:(le=st==null?void 0:st.messages)!=null?le:rt},supportedUrls:await Mt.supportedUrls,download:y}),{toolChoice:mr,tools:_r}=Qv({tools:t,toolChoice:(he=st==null?void 0:st.toolChoice)!=null?he:n,activeTools:(de=st==null?void 0:st.activeTools)!=null?de:E});C=await oe(()=>{var Ie;return ro({name:"ai.generateText.doGenerate",attributes:Wt({telemetry:x,attributes:{...no({operationId:"ai.generateText.doGenerate",telemetry:x}),...J,"ai.model.provider":Mt.provider,"ai.model.id":Mt.modelId,"ai.prompt.messages":{input:()=>mb(Do)},"ai.prompt.tools":{input:()=>_r==null?void 0:_r.map(Lt=>JSON.stringify(Lt))},"ai.prompt.toolChoice":{input:()=>mr!=null?JSON.stringify(mr):void 0},"gen_ai.system":Mt.provider,"gen_ai.request.model":Mt.modelId,"gen_ai.request.frequency_penalty":N.frequencyPenalty,"gen_ai.request.max_tokens":N.maxOutputTokens,"gen_ai.request.presence_penalty":N.presencePenalty,"gen_ai.request.stop_sequences":N.stopSequences,"gen_ai.request.temperature":(Ie=N.temperature)!=null?Ie:void 0,"gen_ai.request.top_k":N.topK,"gen_ai.request.top_p":N.topP}}),tracer:Y,fn:async Lt=>{var Uo,Bo,Vo,Fo,qo,Go,Ho,Jo;const Re=await Mt.doGenerate({...ne,tools:_r,toolChoice:mr,responseFormat:g==null?void 0:g.responseFormat,prompt:Do,providerOptions:T,abortSignal:l,headers:V}),Jt={id:(Bo=(Uo=Re.response)==null?void 0:Uo.id)!=null?Bo:b(),timestamp:(Fo=(Vo=Re.response)==null?void 0:Vo.timestamp)!=null?Fo:S(),modelId:(Go=(qo=Re.response)==null?void 0:qo.modelId)!=null?Go:Mt.modelId,headers:(Ho=Re.response)==null?void 0:Ho.headers,body:(Jo=Re.response)==null?void 0:Jo.body};return Lt.setAttributes(Wt({telemetry:x,attributes:{"ai.response.finishReason":Re.finishReason,"ai.response.text":{output:()=>rs(Re.content)},"ai.response.toolCalls":{output:()=>{const Ko=as(Re.content);return Ko==null?void 0:JSON.stringify(Ko)}},"ai.response.id":Jt.id,"ai.response.model":Jt.modelId,"ai.response.timestamp":Jt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Re.providerMetadata),"ai.usage.promptTokens":Re.usage.inputTokens,"ai.usage.completionTokens":Re.usage.outputTokens,"gen_ai.response.finish_reasons":[Re.finishReason],"gen_ai.response.id":Jt.id,"gen_ai.response.model":Jt.modelId,"gen_ai.usage.input_tokens":Re.usage.inputTokens,"gen_ai.usage.output_tokens":Re.usage.outputTokens}})),{...Re,response:Jt}}})});const Pn=await Promise.all(C.content.filter(Ie=>Ie.type==="tool-call").map(Ie=>xb({toolCall:Ie,tools:t,repairToolCall:v,system:r,messages:rt})));for(const Ie of Pn){if(Ie.invalid)continue;const Lt=t[Ie.toolName];(Lt==null?void 0:Lt.onInputAvailable)!=null&&await Lt.onInputAvailable({input:Ie.input,toolCallId:Ie.toolCallId,messages:rt,abortSignal:l,experimental_context:$})}const Sc=Pn.filter(Ie=>Ie.invalid&&Ie.dynamic);re=[];for(const Ie of Sc)re.push({type:"tool-error",toolCallId:Ie.toolCallId,toolName:Ie.toolName,input:Ie.input,error:Ql(Ie.error),dynamic:!0});H=Pn.filter(Ie=>!Ie.providerExecuted),t!=null&&re.push(...await Cb({toolCalls:H.filter(Ie=>!Ie.invalid),tools:t,tracer:Y,telemetry:x,messages:rt,abortSignal:l,experimental_context:$}));const Zo=Ob({content:C.content,toolCalls:Pn,toolOutputs:re});w.push(...Sb({content:Zo,tools:t}));const jo=new kb({content:Zo,finishReason:C.finishReason,usage:C.usage,warnings:C.warnings,providerMetadata:C.providerMetadata,request:(ke=C.request)!=null?ke:{},response:{...C.response,messages:structuredClone(w)}});Av((O=C.warnings)!=null?O:[]),ie.push(jo),await(m==null?void 0:m(jo))}while(H.length>0&&re.length===H.length&&!await Tb({stopConditions:B,steps:ie}));we.setAttributes(Wt({telemetry:x,attributes:{"ai.response.finishReason":C.finishReason,"ai.response.text":{output:()=>rs(C.content)},"ai.response.toolCalls":{output:()=>{const rt=as(C.content);return rt==null?void 0:JSON.stringify(rt)}},"ai.response.providerMetadata":JSON.stringify(C.providerMetadata),"ai.usage.promptTokens":C.usage.inputTokens,"ai.usage.completionTokens":C.usage.outputTokens}}));const nt=ie[ie.length-1];let Pt;return nt.finishReason==="stop"&&(Pt=await(g==null?void 0:g.parseOutput({text:nt.text},{response:nt.response,usage:nt.usage,finishReason:nt.finishReason}))),new Ab({steps:ie,resolvedOutput:Pt})}})}catch(we){throw cb(we)}}async function Cb({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:i,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:p})=>{const g=t[c];if((g==null?void 0:g.execute)!=null)return ro({name:"ai.toolCall",attributes:Wt({telemetry:r,attributes:{...no({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(p)}}}),tracer:n,fn:async x=>{try{const T=mg({execute:g.execute.bind(g),input:p,options:{toolCallId:l,messages:o,abortSignal:i,experimental_context:a}});let I;for await(const E of T)E.type==="final"&&(I=E.output);try{x.setAttributes(Wt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(I)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:p,output:I,dynamic:g.type==="dynamic"}}catch(T){return sc(x,T),{type:"tool-error",toolCallId:l,toolName:c,input:p,error:T,dynamic:g.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Ab=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>_b(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new Sv;return this.resolvedOutput}};function as(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function Ob({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new wb(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(i=>i.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}(class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
486
-
487
- `)},flush(e){e.enqueue(`data: [DONE]
488
-
489
- `)}})}});function $b(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,p){switch(l){case'"':{n=c,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(r,l+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let s=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{s+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{s+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{s+="]";break}case"INSIDE_LITERAL":{const p=e.substring(r,e.length);"true".startsWith(p)?s+="true".slice(p.length):"false".startsWith(p)?s+="false".slice(p.length):"null".startsWith(p)&&(s+="null".slice(p.length))}}return s}async function Nb(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ut({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ut({text:$b(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}On({prefix:"aitxt",size:24});On({prefix:"aiobj",size:24});function Rb(e){return({url:t,abortSignal:n})=>tc({url:t,maxBytes:void 0,abortSignal:n})}On({prefix:"aiobj",size:24});var Pb={};Iv(Pb,{object:()=>Lb,text:()=>Mb});var Mb=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Lb=({schema:e})=>{const t=dr(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Nb(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await Ut({text:n});if(!o.success)throw new Qa({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const i=await gt({value:o.value,schema:t});if(!i.success)throw new Qa({message:"No object generated: response did not match schema.",cause:i.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return i.value}}},zb="2.0.84",Db=W(()=>j(d({type:h("error"),error:d({type:u(),message:u()})}))),ss=pt({errorSchema:Db,errorToMessage:e=>e.error.message}),cc=d({type:u(),category:u().nullish(),explanation:u().nullish(),recommended_model:u().nullish()}),Zb=W(()=>j(d({type:h("message"),id:u().nullish(),model:u().nullish(),content:R(se("type",[d({type:h("text"),text:u(),citations:R(se("type",[d({type:h("web_search_result_location"),cited_text:u(),url:u(),title:u(),encrypted_index:u()}),d({type:h("page_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_page_number:f(),end_page_number:f()}),d({type:h("char_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_char_index:f(),end_char_index:f()})])).optional()}),d({type:h("thinking"),thinking:u(),signature:u()}),d({type:h("redacted_thinking"),data:u()}),d({type:h("compaction"),content:u()}),d({type:h("tool_use"),id:u(),name:u(),input:Le()}),d({type:h("server_tool_use"),id:u(),name:u(),input:Se(u(),Le()).nullish()}),d({type:h("web_fetch_tool_result"),tool_use_id:u(),content:ee([d({type:h("web_fetch_result"),url:u(),retrieved_at:u(),content:d({type:h("document"),title:u().nullable(),citations:d({enabled:ue()}).optional(),source:ee([d({type:h("base64"),media_type:h("application/pdf"),data:u()}),d({type:h("text"),media_type:h("text/plain"),data:u()})])})}),d({type:h("web_fetch_tool_result_error"),error_code:u()})])}),d({type:h("web_search_tool_result"),tool_use_id:u(),content:ee([R(d({type:h("web_search_result"),url:u(),title:u(),encrypted_content:u(),page_age:u().nullish()})),d({type:h("web_search_tool_result_error"),error_code:u()})])}),d({type:h("code_execution_tool_result"),tool_use_id:u(),content:ee([d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f()}),d({type:h("code_execution_tool_result_error"),error_code:u()})])}),d({type:h("bash_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()})])}),d({type:h("text_editor_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})])}),d({type:h("fallback")})])),stop_reason:u().nullish(),stop_sequence:u().nullish(),stop_details:cc.nullish(),usage:Fr({input_tokens:f(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish(),iterations:R(d({type:ee([h("compaction"),h("message"),h("advisor_message"),h("fallback_message")]),model:u().nullish(),input_tokens:f(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish()})).nullish()}),context_management:d({applied_edits:R(ee([d({type:h("clear_tool_uses_20250919"),cleared_tool_uses:f(),cleared_input_tokens:f()}),d({type:h("clear_thinking_20251015"),cleared_thinking_turns:f(),cleared_input_tokens:f()}),d({type:h("compact_20260112")})]))}).nullish(),container:d({expires_at:u(),id:u(),skills:R(d({type:ee([h("anthropic"),h("custom")]),skill_id:u(),version:u()})).nullish()}).nullish()}))),jb=W(()=>j(se("type",[d({type:h("message_start"),message:d({id:u().nullish(),model:u().nullish(),usage:Fr({input_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish()})})}),d({type:h("content_block_start"),index:f(),content_block:se("type",[d({type:h("text"),text:u()}),d({type:h("thinking"),thinking:u()}),d({type:h("tool_use"),id:u(),name:u()}),d({type:h("redacted_thinking"),data:u()}),d({type:h("compaction"),content:u().nullish()}),d({type:h("server_tool_use"),id:u(),name:u(),input:Se(u(),Le()).nullish()}),d({type:h("web_fetch_tool_result"),tool_use_id:u(),content:ee([d({type:h("web_fetch_result"),url:u(),retrieved_at:u(),content:d({type:h("document"),title:u().nullable(),citations:d({enabled:ue()}).optional(),source:ee([d({type:h("base64"),media_type:h("application/pdf"),data:u()}),d({type:h("text"),media_type:h("text/plain"),data:u()})])})}),d({type:h("web_fetch_tool_result_error"),error_code:u()})])}),d({type:h("web_search_tool_result"),tool_use_id:u(),content:ee([R(d({type:h("web_search_result"),url:u(),title:u(),encrypted_content:u(),page_age:u().nullish()})),d({type:h("web_search_tool_result_error"),error_code:u()})])}),d({type:h("code_execution_tool_result"),tool_use_id:u(),content:ee([d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f()}),d({type:h("code_execution_tool_result_error"),error_code:u()})])}),d({type:h("bash_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()})])}),d({type:h("text_editor_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})])}),d({type:h("fallback")})])}),d({type:h("content_block_delta"),index:f(),delta:se("type",[d({type:h("input_json_delta"),partial_json:u()}),d({type:h("text_delta"),text:u()}),d({type:h("thinking_delta"),thinking:u()}),d({type:h("signature_delta"),signature:u()}),d({type:h("compaction_delta"),content:u().nullish()}),d({type:h("citations_delta"),citation:se("type",[d({type:h("web_search_result_location"),cited_text:u(),url:u(),title:u(),encrypted_index:u()}),d({type:h("page_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_page_number:f(),end_page_number:f()}),d({type:h("char_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_char_index:f(),end_char_index:f()})])})])}),d({type:h("content_block_stop"),index:f()}),d({type:h("error"),error:d({type:u(),message:u()})}),d({type:h("message_delta"),delta:d({stop_reason:u().nullish(),stop_sequence:u().nullish(),stop_details:cc.nullish(),container:d({expires_at:u(),id:u(),skills:R(d({type:ee([h("anthropic"),h("custom")]),skill_id:u(),version:u()})).nullish()}).nullish()}),usage:Fr({input_tokens:f().nullish(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish(),iterations:R(d({type:ee([h("compaction"),h("message"),h("advisor_message"),h("fallback_message")]),model:u().nullish(),input_tokens:f(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish()})).nullish()}),context_management:d({applied_edits:R(ee([d({type:h("clear_tool_uses_20250919"),cleared_tool_uses:f(),cleared_input_tokens:f()}),d({type:h("clear_thinking_20251015"),cleared_thinking_turns:f(),cleared_input_tokens:f()}),d({type:h("compact_20260112")})]))}).nullish()}),d({type:h("message_stop")}),d({type:h("ping")})]))),Ub=W(()=>j(d({signature:u().optional(),redactedData:u().optional()}))),ls=d({citations:d({enabled:ue()}).optional(),title:u().optional(),context:u().optional()}),Bb=d({sendReasoning:ue().optional(),structuredOutputMode:X(["outputFormat","jsonTool","auto"]).optional(),thinking:se("type",[d({type:h("adaptive"),display:X(["omitted","summarized"]).optional()}),d({type:h("enabled"),budgetTokens:f().optional()}),d({type:h("disabled")})]).optional(),disableParallelToolUse:ue().optional(),cacheControl:d({type:h("ephemeral"),ttl:ee([h("5m"),h("1h")]).optional()}).optional(),metadata:d({userId:u().optional()}).optional(),container:d({id:u().optional(),skills:R(d({type:ee([h("anthropic"),h("custom")]),skillId:u(),version:u().optional()})).optional()}).optional(),effort:X(["low","medium","high","xhigh","max"]).optional(),taskBudget:d({type:h("tokens"),total:f().int().min(2e4),remaining:f().int().min(0).optional()}).optional(),speed:X(["fast","standard"]).optional(),inferenceGeo:X(["us","global"]).optional(),fallbacks:R(d({model:u(),max_tokens:f().int().optional(),thinking:Se(u(),Le()).optional(),output_config:Se(u(),Le()).optional(),speed:X(["fast","standard"]).optional()})).optional(),contextManagement:d({edits:R(se("type",[d({type:h("clear_tool_uses_20250919"),trigger:se("type",[d({type:h("input_tokens"),value:f()}),d({type:h("tool_uses"),value:f()})]).optional(),keep:d({type:h("tool_uses"),value:f()}).optional(),clearAtLeast:d({type:h("input_tokens"),value:f()}).optional(),clearToolInputs:ue().optional(),excludeTools:R(u()).optional()}),d({type:h("clear_thinking_20251015"),keep:ee([h("all"),d({type:h("thinking_turns"),value:f()})]).optional()}),d({type:h("compact_20260112"),trigger:d({type:h("input_tokens"),value:f()}).optional(),pauseAfterCompaction:ue().optional(),instructions:u().optional()})]))}).optional(),anthropicBeta:R(u()).optional()}),us=4;function Vb(e){var t;const n=e==null?void 0:e.anthropic;return(t=n==null?void 0:n.cacheControl)!=null?t:n==null?void 0:n.cache_control}var Ro=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){const n=Vb(e);if(n){if(!t.canCache){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>us){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`Maximum ${us} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},Fb=W(()=>j(d({maxCharacters:f().optional()}))),qb=W(()=>j(d({command:X(["view","create","str_replace","insert"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),Gb=yt({id:"anthropic.text_editor_20250728",name:"str_replace_based_edit_tool",inputSchema:qb}),Hb=(e={})=>Gb(e),Jb=W(()=>j(d({maxUses:f().optional(),allowedDomains:R(u()).optional(),blockedDomains:R(u()).optional(),userLocation:d({type:h("approximate"),city:u().optional(),region:u().optional(),country:u().optional(),timezone:u().optional()}).optional()}))),dc=W(()=>j(R(d({url:u(),title:u().nullable(),pageAge:u().nullable(),encryptedContent:u(),type:h("web_search_result")})))),Kb=W(()=>j(d({query:u()}))),Wb=Ye({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Kb,outputSchema:dc}),Yb=(e={})=>Wb(e),Xb=W(()=>j(d({maxUses:f().optional(),allowedDomains:R(u()).optional(),blockedDomains:R(u()).optional(),citations:d({enabled:ue()}).optional(),maxContentTokens:f().optional()}))),pc=W(()=>j(d({type:h("web_fetch_result"),url:u(),content:d({type:h("document"),title:u().nullable(),citations:d({enabled:ue()}).optional(),source:ee([d({type:h("base64"),mediaType:h("application/pdf"),data:u()}),d({type:h("text"),mediaType:h("text/plain"),data:u()})])}),retrievedAt:u().nullable()}))),Qb=W(()=>j(d({url:u()}))),ew=Ye({id:"anthropic.web_fetch_20250910",name:"web_fetch",inputSchema:Qb,outputSchema:pc}),tw=(e={})=>ew(e);async function nw({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:r}){var o;e=e!=null&&e.length?e:void 0;const i=[],a=new Set,s=r||new Ro;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};const l=[];for(const p of e)switch(p.type){case"function":{const g=s.getCacheControl(p.providerOptions,{type:"tool definition",canCache:!0}),x=(o=p.providerOptions)==null?void 0:o.anthropic,T=x==null?void 0:x.eagerInputStreaming;l.push({name:p.name,description:p.description,input_schema:p.inputSchema,cache_control:g,...T?{eager_input_streaming:!0}:{}});break}case"provider-defined":{switch(p.id){case"anthropic.code_execution_20250522":{a.add("code-execution-2025-05-22"),l.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{a.add("code-execution-2025-08-25"),l.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{l.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{a.add("computer-use-2025-01-24"),l.push({name:"computer",type:"computer_20250124",display_width_px:p.args.displayWidthPx,display_height_px:p.args.displayHeightPx,display_number:p.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{a.add("computer-use-2024-10-22"),l.push({name:"computer",type:"computer_20241022",display_width_px:p.args.displayWidthPx,display_height_px:p.args.displayHeightPx,display_number:p.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{a.add("computer-use-2025-01-24"),l.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{a.add("computer-use-2024-10-22"),l.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{a.add("computer-use-2025-01-24"),l.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{const g=await Me({value:p.args,schema:Fb});l.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:g.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{a.add("computer-use-2025-01-24"),l.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{a.add("computer-use-2024-10-22"),l.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{a.add("context-management-2025-06-27"),l.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{a.add("web-fetch-2025-09-10");const g=await Me({value:p.args,schema:Xb});l.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,citations:g.citations,max_content_tokens:g.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{const g=await Me({value:p.args,schema:Jb});l.push({type:"web_search_20250305",name:"web_search",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,user_location:g.userLocation,cache_control:void 0});break}default:{i.push({type:"unsupported-tool",tool:p});break}}break}default:{i.push({type:"unsupported-tool",tool:p});break}}if(t==null)return{tools:l,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:i,betas:a};const c=t.type;switch(c){case"auto":return{tools:l,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:i,betas:a};case"required":return{tools:l,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:i,betas:a};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case"tool":return{tools:l,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:i,betas:a};default:{const p=c;throw new je({functionality:`tool choice type: ${p}`})}}}var hc=W(()=>j(d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f()}))),rw=W(()=>j(d({code:u()}))),ow=Ye({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:rw,outputSchema:hc}),iw=(e={})=>ow(e),fc=W(()=>j(se("type",[d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})]))),aw=W(()=>j(se("type",[d({type:h("bash_code_execution"),command:u()}),se("command",[d({type:h("text_editor_code_execution"),command:h("view"),path:u()}),d({type:h("text_editor_code_execution"),command:h("create"),path:u(),file_text:u().nullish()}),d({type:h("text_editor_code_execution"),command:h("str_replace"),path:u(),old_str:u(),new_str:u()})])]))),sw=Ye({id:"anthropic.code_execution_20250825",name:"code_execution",inputSchema:aw,outputSchema:fc}),lw=(e={})=>sw(e);function uw(e){if(typeof e=="string")return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new je({functionality:"URL-based text documents are not supported for citations"}):new je({functionality:`unsupported data type for text documents: ${typeof e}`})}async function cw({prompt:e,sendReasoning:t,warnings:n,cacheControlValidator:r}){var o,i,a,s,l,c;const p=new Set,g=dw(e),x=r||new Ro;let T;const I=[];async function E(_){var v,y;const $=await Je({provider:"anthropic",providerOptions:_,schema:ls});return(y=(v=$==null?void 0:$.citations)==null?void 0:v.enabled)!=null?y:!1}async function k(_){const v=await Je({provider:"anthropic",providerOptions:_,schema:ls});return{title:v==null?void 0:v.title,context:v==null?void 0:v.context}}for(let _=0;_<g.length;_++){const v=g[_],y=_===g.length-1,$=v.type;switch($){case"system":{const b=v.messages.map(({content:S,providerOptions:m})=>({type:"text",text:S,cache_control:x.getCacheControl(m,{type:"system message",canCache:!0})}));T==null?T=b:(I.push({role:"system",content:b}),p.add("mid-conversation-system-2026-04-07"));break}case"user":{const b=[];for(const S of v.messages){const{role:m,content:N}=S;switch(m){case"user":{for(let Z=0;Z<N.length;Z++){const B=N[Z],D=Z===N.length-1,oe=(o=x.getCacheControl(B.providerOptions,{type:"user message part",canCache:!0}))!=null?o:D?x.getCacheControl(S.providerOptions,{type:"user message",canCache:!0}):void 0;switch(B.type){case"text":{b.push({type:"text",text:B.text,cache_control:oe});break}case"file":{if(B.mediaType.startsWith("image/"))b.push({type:"image",source:B.data instanceof URL?{type:"url",url:B.data.toString()}:{type:"base64",media_type:B.mediaType==="image/*"?"image/jpeg":B.mediaType,data:Tt(B.data)},cache_control:oe});else if(B.mediaType==="application/pdf"){p.add("pdfs-2024-09-25");const L=await E(B.providerOptions),V=await k(B.providerOptions);b.push({type:"document",source:B.data instanceof URL?{type:"url",url:B.data.toString()}:{type:"base64",media_type:"application/pdf",data:Tt(B.data)},title:(i=V.title)!=null?i:B.filename,...V.context&&{context:V.context},...L&&{citations:{enabled:!0}},cache_control:oe})}else if(B.mediaType==="text/plain"){const L=await E(B.providerOptions),V=await k(B.providerOptions);b.push({type:"document",source:B.data instanceof URL?{type:"url",url:B.data.toString()}:{type:"text",media_type:"text/plain",data:uw(B.data)},title:(a=V.title)!=null?a:B.filename,...V.context&&{context:V.context},...L&&{citations:{enabled:!0}},cache_control:oe})}else throw new je({functionality:`media type: ${B.mediaType}`});break}}}break}case"tool":{for(let Z=0;Z<N.length;Z++){const B=N[Z],D=Z===N.length-1,oe=(s=x.getCacheControl(B.providerOptions,{type:"tool result part",canCache:!0}))!=null?s:D?x.getCacheControl(S.providerOptions,{type:"tool result message",canCache:!0}):void 0,L=B.output;let V;switch(L.type){case"content":V=L.value.map(J=>{switch(J.type){case"text":return{type:"text",text:J.text};case"media":{if(J.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:J.mediaType,data:J.data}};if(J.mediaType==="application/pdf")return p.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:J.mediaType,data:J.data}};throw new je({functionality:`media type: ${J.mediaType}`})}}});break;case"text":case"error-text":V=L.value;break;case"json":case"error-json":default:V=JSON.stringify(L.value);break}b.push({type:"tool_result",tool_use_id:B.toolCallId,content:V,is_error:L.type==="error-text"||L.type==="error-json"?!0:void 0,cache_control:oe})}break}default:{const Z=m;throw new Error(`Unsupported role: ${Z}`)}}}I.push({role:"user",content:b});break}case"assistant":{const b=[];for(let S=0;S<v.messages.length;S++){const m=v.messages[S],N=S===v.messages.length-1,{content:Z}=m;for(let B=0;B<Z.length;B++){const D=Z[B],oe=B===Z.length-1,L=(l=x.getCacheControl(D.providerOptions,{type:"assistant message part",canCache:!0}))!=null?l:oe?x.getCacheControl(m.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(D.type){case"text":{const V=(c=D.providerOptions)==null?void 0:c.anthropic;(V==null?void 0:V.type)==="compaction"?b.push({type:"compaction",content:D.text,cache_control:L}):b.push({type:"text",text:y&&N&&oe?D.text.trim():D.text,cache_control:L});break}case"reasoning":{if(t){const V=await Je({provider:"anthropic",providerOptions:D.providerOptions,schema:Ub});V!=null?V.signature!=null?(x.getCacheControl(D.providerOptions,{type:"thinking block",canCache:!1}),b.push({type:"thinking",thinking:D.text,signature:V.signature})):V.redactedData!=null?(x.getCacheControl(D.providerOptions,{type:"redacted thinking block",canCache:!1}),b.push({type:"redacted_thinking",data:V.redactedData})):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(D.providerExecuted){D.toolName==="code_execution"&&D.input!=null&&typeof D.input=="object"&&"type"in D.input&&typeof D.input.type=="string"&&(D.input.type==="bash_code_execution"||D.input.type==="text_editor_code_execution")?b.push({type:"server_tool_use",id:D.toolCallId,name:D.input.type,input:D.input,cache_control:L}):D.toolName==="code_execution"||D.toolName==="web_fetch"||D.toolName==="web_search"?b.push({type:"server_tool_use",id:D.toolCallId,name:D.toolName,input:D.input,cache_control:L}):n.push({type:"other",message:`provider executed tool call for tool ${D.toolName} is not supported`});break}b.push({type:"tool_use",id:D.toolCallId,name:D.toolName,input:D.input,cache_control:L});break}case"tool-result":{if(D.toolName==="code_execution"){const V=D.output;if(V.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${V.type} for tool ${D.toolName} is not supported`});break}if(V.value==null||typeof V.value!="object"||!("type"in V.value)||typeof V.value.type!="string"){n.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${D.toolName}`});break}if(V.value.type==="code_execution_result"){const J=await Me({value:V.value,schema:hc});b.push({type:"code_execution_tool_result",tool_use_id:D.toolCallId,content:{type:J.type,stdout:J.stdout,stderr:J.stderr,return_code:J.return_code},cache_control:L})}else{const J=await Me({value:V.value,schema:fc});b.push(J.type==="bash_code_execution_result"||J.type==="bash_code_execution_tool_result_error"?{type:"bash_code_execution_tool_result",tool_use_id:D.toolCallId,cache_control:L,content:J}:{type:"text_editor_code_execution_tool_result",tool_use_id:D.toolCallId,cache_control:L,content:J})}break}if(D.toolName==="web_fetch"){const V=D.output;if(V.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${V.type} for tool ${D.toolName} is not supported`});break}const J=await Me({value:V.value,schema:pc});b.push({type:"web_fetch_tool_result",tool_use_id:D.toolCallId,content:{type:"web_fetch_result",url:J.url,retrieved_at:J.retrievedAt,content:{type:"document",title:J.content.title,citations:J.content.citations,source:{type:J.content.source.type,media_type:J.content.source.mediaType,data:J.content.source.data}}},cache_control:L});break}if(D.toolName==="web_search"){const V=D.output;if(V.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${V.type} for tool ${D.toolName} is not supported`});break}const J=await Me({value:V.value,schema:dc});b.push({type:"web_search_tool_result",tool_use_id:D.toolCallId,content:J.map(be=>({url:be.url,title:be.title,page_age:be.pageAge,encrypted_content:be.encryptedContent,type:be.type})),cache_control:L});break}n.push({type:"other",message:`provider executed tool result for tool ${D.toolName} is not supported`});break}}}}I.push({role:"assistant",content:b});break}default:{const b=$;throw new Error(`content type: ${b}`)}}}return{prompt:{system:T,messages:I},betas:p}}function dw(e){const t=[];let n;for(const r of e){const{role:o}=r;switch(o){case"system":{(n==null?void 0:n.type)!=="system"&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break}case"assistant":{(n==null?void 0:n.type)!=="assistant"&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break}case"user":{(n==null?void 0:n.type)!=="user"&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break}case"tool":{(n==null?void 0:n.type)!=="user"&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break}default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}}return t}function cs({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";case"compaction":return"other";default:return"unknown"}}var mc=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),pw=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function hw(e){return _c(e)}function bt(e){return typeof e=="boolean"||!gw(e)?e:_c(e)}function _c(e){const t={},n=e;if(e.$ref!=null)return{$ref:e.$ref};if(e.$schema!=null&&(t.$schema=e.$schema),e.$id!=null&&(t.$id=e.$id),e.title!=null&&(t.title=e.title),e.description!=null&&(t.description=e.description),e.default!==void 0&&(t.default=e.default),e.const!==void 0&&(t.const=e.const),e.enum!=null&&(t.enum=e.enum),e.type!=null&&(t.type=e.type),e.anyOf!=null?t.anyOf=e.anyOf.map(bt):e.oneOf!=null&&(t.anyOf=e.oneOf.map(bt)),e.allOf!=null&&(t.allOf=e.allOf.map(bt)),e.definitions!=null&&(t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([o,i])=>[o,bt(i)]))),n.$defs!=null){const o=t;o.$defs=Object.fromEntries(Object.entries(n.$defs).map(([i,a])=>[i,bt(a)]))}(e.type==="object"||e.properties!=null)&&(e.properties!=null&&(t.properties=Object.fromEntries(Object.entries(e.properties).map(([o,i])=>[o,bt(i)]))),t.additionalProperties=!1,e.required!=null&&(t.required=e.required)),e.items!=null&&(t.items=Array.isArray(e.items)?e.items.map(bt):bt(e.items)),typeof e.format=="string"&&mc.has(e.format)&&(t.format=e.format);const r=fw(e);return r!=null&&(t.description=t.description==null?r:`${t.description}
490
- ${r}`),t}function fw(e){const t=pw.flatMap(n=>{const r=e[n];return r==null||r===!1?[]:`${mw(n)}: ${_w(r)}`});return typeof e.format=="string"&&!mc.has(e.format)&&t.push(`format: ${e.format}`),t.length===0?void 0:`${t.join("; ")}.`}function mw(e){return e.replace(/[A-Z]/g,t=>` ${t.toLowerCase()}`)}function _w(e){return typeof e=="string"?e:JSON.stringify(e)}function gw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ds(e,t,n){var r;if(e.type!=="page_location"&&e.type!=="char_location")return;const o=t[e.document_index];if(o)return{type:"source",sourceType:"document",id:n(),mediaType:o.mediaType,title:(r=e.document_title)!=null?r:o.title,filename:o.filename,providerMetadata:{anthropic:e.type==="page_location"?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}var yw=class{constructor(e,t){this.specificationVersion="v2";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Ge}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,seed:p,tools:g,toolChoice:x,providerOptions:T}){var I,E,k,_,v,y,$,b;const S=[];a!=null&&S.push({type:"unsupported-setting",setting:"frequencyPenalty"}),s!=null&&S.push({type:"unsupported-setting",setting:"presencePenalty"}),p!=null&&S.push({type:"unsupported-setting",setting:"seed"}),r!=null&&r>1?(S.push({type:"unsupported-setting",setting:"temperature",details:`${r} exceeds anthropic maximum of 1.0. clamped to 1.0`}),r=1):r!=null&&r<0&&(S.push({type:"unsupported-setting",setting:"temperature",details:`${r} is below anthropic minimum of 0. clamped to 0`}),r=0),(c==null?void 0:c.type)==="json"&&(c.schema==null?S.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):g!=null&&S.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const m=await Je({provider:"anthropic",providerOptions:T,schema:Bb}),{maxOutputTokens:N,supportsStructuredOutput:Z,rejectsSamplingParameters:B,isKnownModel:D}=vw(this.modelId);B&&(r!=null&&(S.push({type:"unsupported-setting",setting:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),r=void 0),i!=null&&(S.push({type:"unsupported-setting",setting:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),i=void 0),o!=null&&(S.push({type:"unsupported-setting",setting:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),o=void 0)),D||this.modelId.startsWith("claude-");const oe=(I=m==null?void 0:m.structuredOutputMode)!=null?I:"jsonTool",L=oe==="outputFormat"||oe==="auto"&&Z,V=(c==null?void 0:c.type)==="json"&&c.schema!=null&&!L?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,J=new Ro,{prompt:be,betas:Y}=await cw({prompt:t,sendReasoning:(E=m==null?void 0:m.sendReasoning)!=null?E:!0,warnings:S,cacheControlValidator:J}),we=(k=m==null?void 0:m.thinking)==null?void 0:k.type,ge=we==="enabled"||we==="adaptive";let Ce=we==="enabled"?(_=m==null?void 0:m.thinking)==null?void 0:_.budgetTokens:void 0;const le=we==="adaptive"?(v=m==null?void 0:m.thinking)==null?void 0:v.display:void 0,he=n??N,de={model:this.modelId,max_tokens:he,temperature:r,top_k:i,top_p:o,stop_sequences:l,...ge&&{thinking:{type:we,...Ce!=null&&{budget_tokens:Ce},...le!=null&&{display:le}}},...((m==null?void 0:m.effort)||(m==null?void 0:m.taskBudget)||L&&(c==null?void 0:c.type)==="json"&&c.schema!=null)&&{output_config:{...(m==null?void 0:m.effort)&&{effort:m.effort},...(m==null?void 0:m.taskBudget)&&{task_budget:{type:m.taskBudget.type,total:m.taskBudget.total,...m.taskBudget.remaining!=null&&{remaining:m.taskBudget.remaining}}},...L&&(c==null?void 0:c.type)==="json"&&c.schema!=null&&{format:{type:"json_schema",schema:hw(c.schema)}}}},...(m==null?void 0:m.speed)&&{speed:m.speed},...(m==null?void 0:m.inferenceGeo)&&{inference_geo:m.inferenceGeo},...(m==null?void 0:m.fallbacks)&&m.fallbacks.length>0&&{fallbacks:m.fallbacks},...(m==null?void 0:m.cacheControl)&&{cache_control:m.cacheControl},...((y=m==null?void 0:m.metadata)==null?void 0:y.userId)!=null&&{metadata:{user_id:m.metadata.userId}},...(m==null?void 0:m.container)&&{container:{id:m.container.id,skills:($=m.container.skills)==null?void 0:$.map(w=>({type:w.type,skill_id:w.skillId,version:w.version}))}},...(m==null?void 0:m.contextManagement)&&{context_management:{edits:m.contextManagement.edits.map(w=>{const ie=w.type;switch(ie){case"clear_tool_uses_20250919":return{type:w.type,...w.trigger!==void 0&&{trigger:w.trigger},...w.keep!==void 0&&{keep:w.keep},...w.clearAtLeast!==void 0&&{clear_at_least:w.clearAtLeast},...w.clearToolInputs!==void 0&&{clear_tool_inputs:w.clearToolInputs},...w.excludeTools!==void 0&&{exclude_tools:w.excludeTools}};case"clear_thinking_20251015":return{type:w.type,...w.keep!==void 0&&{keep:w.keep}};case"compact_20260112":return{type:w.type,...w.trigger!==void 0&&{trigger:w.trigger},...w.pauseAfterCompaction!==void 0&&{pause_after_compaction:w.pauseAfterCompaction},...w.instructions!==void 0&&{instructions:w.instructions}};default:S.push({type:"other",message:`Unknown context management strategy: ${ie}`});return}}).filter(w=>w!==void 0)}},system:be.system,messages:be.messages};ge&&(we==="enabled"&&Ce==null&&(S.push({type:"other",message:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),de.thinking={type:"enabled",budget_tokens:1024},Ce=1024),de.temperature!=null&&(de.temperature=void 0,S.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),i!=null&&(de.top_k=void 0,S.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(de.top_p=void 0,S.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),de.max_tokens=he+(Ce??0)),D&&de.max_tokens>N&&(n!=null&&S.push({type:"unsupported-setting",setting:"maxOutputTokens",details:`${de.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${N} max output tokens. The max output tokens have been limited to ${N}.`}),de.max_tokens=N),m!=null&&m.container&&m.container.skills&&m.container.skills.length>0&&(Y.add("code-execution-2025-08-25"),Y.add("skills-2025-10-02"),Y.add("files-api-2025-04-14"),g!=null&&g.some(w=>w.type==="provider-defined"&&(w.id==="anthropic.code_execution_20250825"||w.id==="anthropic.code_execution_20260120"))||S.push({type:"other",message:"code execution tool is required when using skills"})),m!=null&&m.effort&&Y.add("effort-2025-11-24"),m!=null&&m.taskBudget&&Y.add("task-budgets-2026-03-13"),(m==null?void 0:m.speed)==="fast"&&Y.add("fast-mode-2026-02-01"),m!=null&&m.fallbacks&&m.fallbacks.length>0&&Y.add("server-side-fallback-2026-06-01"),L&&Y.add("structured-outputs-2025-11-13");const ke=m==null?void 0:m.contextManagement;ke&&(Y.add("context-management-2025-06-27"),ke.edits.some(w=>w.type==="compact_20260112")&&Y.add("compact-2026-01-12"));const{tools:O,toolChoice:ne,toolWarnings:C,betas:H}=await nw(V!=null?{tools:[V],toolChoice:{type:"tool",toolName:V.name},disableParallelToolUse:!0,cacheControlValidator:J}:{tools:g??[],toolChoice:x,disableParallelToolUse:m==null?void 0:m.disableParallelToolUse,cacheControlValidator:J}),re=J.getWarnings();return{args:{...de,tools:O,tool_choice:ne},warnings:[...S,...C,...re],betas:new Set([...Y,...H,...e,...(b=m==null?void 0:m.anthropicBeta)!=null?b:[]]),usesJsonResponseTool:V!=null}}async getHeaders({betas:e,headers:t}){return ze(await Ue(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,n;const o=(t=(await Ue(this.config.headers))["anthropic-beta"])!=null?t:"",i=(n=e==null?void 0:e["anthropic-beta"])!=null?n:"";return new Set([...o.toLowerCase().split(","),...i.toLowerCase().split(",")].map(a=>a.trim()).filter(a=>a!==""))}buildRequestUrl(e){var t,n,r;return(r=(n=(t=this.config).buildRequestUrl)==null?void 0:n.call(t,this.config.baseURL,e))!=null?r:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var n,r,o;return(o=(r=(n=this.config).transformRequestBody)==null?void 0:r.call(n,e,t))!=null?o:e}extractCitationDocuments(e){const t=n=>{var r,o;if(n.type!=="file"||n.mediaType!=="application/pdf"&&n.mediaType!=="text/plain")return!1;const i=(r=n.providerOptions)==null?void 0:r.anthropic,a=i==null?void 0:i.citations;return(o=a==null?void 0:a.enabled)!=null?o:!1};return e.filter(n=>n.role==="user").flatMap(n=>n.content).filter(t).map(n=>{var r;const o=n;return{title:(r=o.filename)!=null?r:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(e){var t,n,r,o,i,a,s,l,c;const{args:p,warnings:g,betas:x,usesJsonResponseTool:T}=await this.getArgs({...e,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),I=this.extractCitationDocuments(e.prompt),{responseHeaders:E,value:k,rawValue:_}=await De({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:x,headers:e.headers}),body:this.transformRequestBody(p,x),failedResponseHandler:ss,successfulResponseHandler:Be(Zb),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=[];for(const m of k.content)switch(m.type){case"text":{if(!T&&(v.push({type:"text",text:m.text}),m.citations))for(const N of m.citations){const Z=ds(N,I,this.generateId);Z&&v.push(Z)}break}case"thinking":{v.push({type:"reasoning",text:m.thinking,providerMetadata:{anthropic:{signature:m.signature}}});break}case"redacted_thinking":{v.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:m.data}}});break}case"compaction":{v.push({type:"text",text:m.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{v.push(T?{type:"text",text:JSON.stringify(m.input)}:{type:"tool-call",toolCallId:m.id,toolName:m.name,input:JSON.stringify(m.input)});break}case"server_tool_use":{m.name==="text_editor_code_execution"||m.name==="bash_code_execution"?v.push({type:"tool-call",toolCallId:m.id,toolName:"code_execution",input:JSON.stringify({type:m.name,...m.input}),providerExecuted:!0}):(m.name==="web_search"||m.name==="code_execution"||m.name==="web_fetch")&&v.push({type:"tool-call",toolCallId:m.id,toolName:m.name,input:JSON.stringify(m.input),providerExecuted:!0});break}case"web_fetch_tool_result":{m.content.type==="web_fetch_result"?v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:m.content.url,retrievedAt:m.content.retrieved_at,content:{type:m.content.content.type,title:m.content.content.title,citations:m.content.content.citations,source:{type:m.content.content.source.type,mediaType:m.content.content.source.media_type,data:m.content.content.source.data}}},providerExecuted:!0}):m.content.type==="web_fetch_tool_result_error"&&v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:m.content.error_code},providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(m.content)){v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_search",result:m.content.map(N=>{var Z;return{url:N.url,title:N.title,pageAge:(Z=N.page_age)!=null?Z:null,encryptedContent:N.encrypted_content,type:N.type}}),providerExecuted:!0});for(const N of m.content)v.push({type:"source",sourceType:"url",id:this.generateId(),url:N.url,title:N.title,providerMetadata:{anthropic:{pageAge:(t=N.page_age)!=null?t:null}}})}else v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:m.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{m.content.type==="code_execution_result"?v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"code_execution",result:{type:m.content.type,stdout:m.content.stdout,stderr:m.content.stderr,return_code:m.content.return_code},providerExecuted:!0}):m.content.type==="code_execution_tool_result_error"&&v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:m.content.error_code},providerExecuted:!0});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"code_execution",result:m.content,providerExecuted:!0});break}}let y,$;const b=(n=k.usage.iterations)==null?void 0:n.some(m=>m.type==="fallback_message");if(k.usage.iterations&&k.usage.iterations.length>0&&!b){const m=k.usage.iterations.reduce((N,Z)=>({input:N.input+Z.input_tokens,output:N.output+Z.output_tokens}),{input:0,output:0});y=m.input,$=m.output}else y=k.usage.input_tokens,$=k.usage.output_tokens;const S=ps(k.stop_details);return{content:v,finishReason:cs({finishReason:k.stop_reason,isJsonResponseFromTool:T}),usage:{inputTokens:y,outputTokens:$,totalTokens:y+$,cachedInputTokens:(r=k.usage.cache_read_input_tokens)!=null?r:void 0},request:{body:p},response:{id:(o=k.id)!=null?o:void 0,modelId:(i=k.model)!=null?i:void 0,headers:E,body:_},warnings:g,providerMetadata:{anthropic:{usage:k.usage,cacheCreationInputTokens:(a=k.usage.cache_creation_input_tokens)!=null?a:null,stopSequence:(s=k.stop_sequence)!=null?s:null,...S!=null?{stopDetails:S}:{},iterations:k.usage.iterations?k.usage.iterations.map(m=>({type:m.type,...m.model!=null?{model:m.model}:{},inputTokens:m.input_tokens,outputTokens:m.output_tokens})):null,container:k.container?{expiresAt:k.container.expires_at,id:k.container.id,skills:(c=(l=k.container.skills)==null?void 0:l.map(m=>({type:m.type,skillId:m.skill_id,version:m.version})))!=null?c:null}:null,contextManagement:k.context_management?{appliedEdits:k.context_management.applied_edits.map(m=>{switch(m.type){case"clear_tool_uses_20250919":return{type:m.type,clearedToolUses:m.cleared_tool_uses,clearedInputTokens:m.cleared_input_tokens};case"clear_thinking_20251015":return{type:m.type,clearedThinkingTurns:m.cleared_thinking_turns,clearedInputTokens:m.cleared_input_tokens};case"compact_20260112":return{type:m.type}}}).filter(m=>m!==void 0)}:null}}}}async doStream(e){var t,n;const{args:r,warnings:o,betas:i,usesJsonResponseTool:a}=await this.getArgs({...e,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),s=this.extractCitationDocuments(e.prompt),l={...r,stream:!0},c=this.buildRequestUrl(!0),{responseHeaders:p,value:g}=await De({url:c,headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(l,i),failedResponseHandler:ss,successfulResponseHandler:$n(jb),abortSignal:e.abortSignal,fetch:this.config.fetch});let x="unknown";const T={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},I={};let E,k=null,_=null,v,y=null,$=null,b=null,S;const m=this.generateId,N=g.pipeThrough(new TransformStream({start(oe){oe.enqueue({type:"stream-start",warnings:o})},transform(oe,L){var V,J,be,Y,we,ge,Ce,le,he,de,ke;if(e.includeRawChunks&&L.enqueue({type:"raw",rawValue:oe.rawValue}),!oe.success){L.enqueue({type:"error",error:oe.error});return}const O=oe.value;switch(O.type){case"ping":return;case"content_block_start":{const ne=O.content_block.type;if(ne==="fallback")return;switch(S=ne,ne){case"text":{I[O.index]={type:"text"},L.enqueue({type:"text-start",id:String(O.index)});return}case"thinking":{I[O.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(O.index)});return}case"redacted_thinking":{I[O.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(O.index),providerMetadata:{anthropic:{redactedData:O.content_block.data}}});return}case"compaction":{I[O.index]={type:"text"},L.enqueue({type:"text-start",id:String(O.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{I[O.index]=a?{type:"text"}:{type:"tool-call",toolCallId:O.content_block.id,toolName:O.content_block.name,input:"",firstDelta:!0},L.enqueue(a?{type:"text-start",id:String(O.index)}:{type:"tool-input-start",id:O.content_block.id,toolName:O.content_block.name});return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(O.content_block.name)){I[O.index]={type:"tool-call",toolCallId:O.content_block.id,toolName:O.content_block.name,input:"",providerExecuted:!0,firstDelta:!0};const C=O.content_block.name==="text_editor_code_execution"||O.content_block.name==="bash_code_execution"?"code_execution":O.content_block.name;L.enqueue({type:"tool-input-start",id:O.content_block.id,toolName:C,providerExecuted:!0})}return}case"web_fetch_tool_result":{const C=O.content_block;C.content.type==="web_fetch_result"?L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:C.content.url,retrievedAt:C.content.retrieved_at,content:{type:C.content.content.type,title:C.content.content.title,citations:C.content.content.citations,source:{type:C.content.content.source.type,mediaType:C.content.content.source.media_type,data:C.content.content.source.data}}},providerExecuted:!0}):C.content.type==="web_fetch_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:C.content.error_code},providerExecuted:!0});return}case"web_search_tool_result":{const C=O.content_block;if(Array.isArray(C.content)){L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_search",result:C.content.map(H=>{var re;return{url:H.url,title:H.title,pageAge:(re=H.page_age)!=null?re:null,encryptedContent:H.encrypted_content,type:H.type}}),providerExecuted:!0});for(const H of C.content)L.enqueue({type:"source",sourceType:"url",id:m(),url:H.url,title:H.title,providerMetadata:{anthropic:{pageAge:(V=H.page_age)!=null?V:null}}})}else L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:C.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const C=O.content_block;C.content.type==="code_execution_result"?L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"code_execution",result:{type:C.content.type,stdout:C.content.stdout,stderr:C.content.stderr,return_code:C.content.return_code},providerExecuted:!0}):C.content.type==="code_execution_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:C.content.error_code},providerExecuted:!0});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{const C=O.content_block;L.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"code_execution",result:C.content,providerExecuted:!0});return}default:{const C=ne;throw new Error(`Unsupported content block type: ${C}`)}}}case"content_block_stop":{if(I[O.index]!=null){const ne=I[O.index];switch(ne.type){case"text":{L.enqueue({type:"text-end",id:String(O.index)});break}case"reasoning":{L.enqueue({type:"reasoning-end",id:String(O.index)});break}case"tool-call":if(!a){L.enqueue({type:"tool-input-end",id:ne.toolCallId});const C=ne.toolName==="text_editor_code_execution"||ne.toolName==="bash_code_execution"?"code_execution":ne.toolName;L.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:C,input:ne.input===""?"{}":ne.input,providerExecuted:ne.providerExecuted})}break}delete I[O.index]}S=void 0;return}case"content_block_delta":{const ne=O.delta.type;switch(ne){case"text_delta":{if(a)return;L.enqueue({type:"text-delta",id:String(O.index),delta:O.delta.text});return}case"thinking_delta":{L.enqueue({type:"reasoning-delta",id:String(O.index),delta:O.delta.thinking});return}case"signature_delta":{S==="thinking"&&L.enqueue({type:"reasoning-delta",id:String(O.index),delta:"",providerMetadata:{anthropic:{signature:O.delta.signature}}});return}case"compaction_delta":{O.delta.content!=null&&L.enqueue({type:"text-delta",id:String(O.index),delta:O.delta.content});return}case"input_json_delta":{const C=I[O.index];let H=O.delta.partial_json;if(H.length===0)return;if(a){if((C==null?void 0:C.type)!=="text")return;L.enqueue({type:"text-delta",id:String(O.index),delta:H})}else{if((C==null?void 0:C.type)!=="tool-call")return;C.firstDelta&&(C.toolName==="bash_code_execution"||C.toolName==="text_editor_code_execution")&&(H=`{"type": "${C.toolName}",${H.substring(1)}`),L.enqueue({type:"tool-input-delta",id:C.toolCallId,delta:H}),C.input+=H,C.firstDelta=!1}return}case"citations_delta":{const C=O.delta.citation,H=ds(C,s,m);H&&L.enqueue(H);return}default:{const C=ne;throw new Error(`Unsupported delta type: ${C}`)}}}case"message_start":{T.inputTokens=O.message.usage.input_tokens,T.cachedInputTokens=(J=O.message.usage.cache_read_input_tokens)!=null?J:void 0,E={...O.message.usage},k=(be=O.message.usage.cache_creation_input_tokens)!=null?be:null,L.enqueue({type:"response-metadata",id:(Y=O.message.id)!=null?Y:void 0,modelId:(we=O.message.model)!=null?we:void 0});return}case"message_delta":{O.usage.cache_read_input_tokens!=null&&(T.cachedInputTokens=O.usage.cache_read_input_tokens),O.usage.cache_creation_input_tokens!=null&&(k=O.usage.cache_creation_input_tokens),O.usage.iterations!=null&&($=O.usage.iterations);const ne=(ge=O.usage.iterations)==null?void 0:ge.some(C=>C.type==="fallback_message");if(O.usage.iterations&&O.usage.iterations.length>0&&!ne){const C=O.usage.iterations.reduce((H,re)=>({input:H.input+re.input_tokens,output:H.output+re.output_tokens}),{input:0,output:0});T.inputTokens=C.input,T.outputTokens=C.output}else O.usage.input_tokens!=null&&T.inputTokens!==O.usage.input_tokens&&(T.inputTokens=O.usage.input_tokens),T.outputTokens=O.usage.output_tokens;T.totalTokens=((Ce=T.inputTokens)!=null?Ce:0)+((le=T.outputTokens)!=null?le:0),x=cs({finishReason:O.delta.stop_reason,isJsonResponseFromTool:a}),v=ps(O.delta.stop_details),_=(he=O.delta.stop_sequence)!=null?he:null,y=O.delta.container!=null?{expiresAt:O.delta.container.expires_at,id:O.delta.container.id,skills:(ke=(de=O.delta.container.skills)==null?void 0:de.map(C=>({type:C.type,skillId:C.skill_id,version:C.version})))!=null?ke:null}:null,O.context_management!=null&&(b={appliedEdits:O.context_management.applied_edits.map(C=>{switch(C.type){case"clear_tool_uses_20250919":return{type:C.type,clearedToolUses:C.cleared_tool_uses,clearedInputTokens:C.cleared_input_tokens};case"clear_thinking_20251015":return{type:C.type,clearedThinkingTurns:C.cleared_thinking_turns,clearedInputTokens:C.cleared_input_tokens};case"compact_20260112":return{type:C.type}}}).filter(C=>C!==void 0)}),E={...E,...O.usage};return}case"message_stop":{L.enqueue({type:"finish",finishReason:x,usage:T,providerMetadata:{anthropic:{usage:E??null,cacheCreationInputTokens:k,stopSequence:_,...v!=null?{stopDetails:v}:{},iterations:$?$.map(ne=>({type:ne.type,...ne.model!=null?{model:ne.model}:{},inputTokens:ne.input_tokens,outputTokens:ne.output_tokens})):null,container:y,contextManagement:b}}});return}case"error":{L.enqueue({type:"error",error:O.error});return}default:{const ne=O;throw new Error(`Unsupported chunk type: ${ne}`)}}}})),[Z,B]=N.tee(),D=Z.getReader();try{await D.read();let oe=await D.read();if(((t=oe.value)==null?void 0:t.type)==="raw"&&(oe=await D.read()),((n=oe.value)==null?void 0:n.type)==="error"){const L=oe.value.error;throw new $e({message:L.message,url:c,requestBodyValues:l,statusCode:L.type==="overloaded_error"?529:500,responseHeaders:p,responseBody:JSON.stringify(L),isRetryable:L.type==="overloaded_error"})}}finally{D.cancel().catch(()=>{}),D.releaseLock()}return{stream:B,request:{body:l},response:{headers:p}}}};function vw(e){return e.includes("claude-opus-4-8")||e.includes("claude-opus-4-7")||e.includes("claude-fable-5")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0}:e.includes("claude-sonnet-4-6")||e.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-5")||e.includes("claude-opus-4-5")||e.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-")||e.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}function ps(e){if(e!=null)return{type:e.type,...e.category!=null?{category:e.category}:{},...e.explanation!=null?{explanation:e.explanation}:{},...e.recommended_model!=null?{recommendedModel:e.recommended_model}:{}}}var bw=W(()=>j(d({command:u(),restart:ue().optional()}))),ww=yt({id:"anthropic.bash_20241022",name:"bash",inputSchema:bw}),xw=W(()=>j(d({command:u(),restart:ue().optional()}))),kw=yt({id:"anthropic.bash_20250124",name:"bash",inputSchema:xw}),Iw=W(()=>j(se("type",[d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f(),content:R(d({type:h("code_execution_output"),file_id:u()})).optional().default([])}),d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})]))),Tw=W(()=>j(se("type",[d({type:h("programmatic-tool-call"),code:u()}),d({type:h("bash_code_execution"),command:u()}),se("command",[d({type:h("text_editor_code_execution"),command:h("view"),path:u()}),d({type:h("text_editor_code_execution"),command:h("create"),path:u(),file_text:u().nullish()}),d({type:h("text_editor_code_execution"),command:h("str_replace"),path:u(),old_str:u(),new_str:u()})])]))),Sw=Ye({id:"anthropic.code_execution_20260120",name:"code_execution",inputSchema:Tw,outputSchema:Iw}),Ew=(e={})=>Sw(e),Cw=W(()=>j(d({action:X(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:R(f().int()).optional(),text:u().optional()}))),Aw=yt({id:"anthropic.computer_20241022",name:"computer",inputSchema:Cw}),Ow=W(()=>j(d({action:X(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:qr([f().int(),f().int()]).optional(),duration:f().optional(),scroll_amount:f().optional(),scroll_direction:X(["up","down","left","right"]).optional(),start_coordinate:qr([f().int(),f().int()]).optional(),text:u().optional()}))),$w=yt({id:"anthropic.computer_20250124",name:"computer",inputSchema:Ow}),Nw=W(()=>j(se("command",[d({command:h("view"),path:u(),view_range:qr([f(),f()]).optional()}),d({command:h("create"),path:u(),file_text:u()}),d({command:h("str_replace"),path:u(),old_str:u(),new_str:u()}),d({command:h("insert"),path:u(),insert_line:f(),insert_text:u()}),d({command:h("delete"),path:u()}),d({command:h("rename"),old_path:u(),new_path:u()})]))),Rw=yt({id:"anthropic.memory_20250818",name:"memory",inputSchema:Nw}),Pw=W(()=>j(d({command:X(["view","create","str_replace","insert","undo_edit"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),Mw=yt({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:Pw}),Lw=W(()=>j(d({command:X(["view","create","str_replace","insert","undo_edit"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),zw=yt({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:Lw}),Dw=W(()=>j(d({command:X(["view","create","str_replace","insert"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),Zw=yt({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Dw}),jw={bash_20241022:ww,bash_20250124:kw,codeExecution_20250522:iw,codeExecution_20250825:lw,codeExecution_20260120:Ew,computer_20241022:Aw,computer_20250124:$w,memory_20250818:Rw,textEditor_20241022:Mw,textEditor_20250124:zw,textEditor_20250429:Zw,textEditor_20250728:Hb,webFetch_20250910:tw,webSearch_20250305:Yb};function gc(e={}){var t,n;const r=(t=So(Dt({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:"https://api.anthropic.com/v1",o=(n=e.name)!=null?n:"anthropic.messages",i=()=>Gt({"anthropic-version":"2023-06-01","x-api-key":nu({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers},`ai-sdk/anthropic/${zb}`),a=l=>{var c;return new yw(l,{provider:o,baseURL:r,headers:i,fetch:e.fetch,generateId:(c=e.generateId)!=null?c:Ge,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},s=function(l){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return a(l)};return s.languageModel=a,s.chat=a,s.messages=a,s.textEmbeddingModel=l=>{throw new yi({modelId:l,modelType:"textEmbeddingModel"})},s.imageModel=l=>{throw new yi({modelId:l,modelType:"imageModel"})},s.tools=jw,s}gc();var Po=d({error:d({message:u(),type:u().nullish(),param:He().nullish(),code:ee([u(),f()]).nullish()})}),ft=pt({errorSchema:Po,errorToMessage:e=>e.error.message});function yc(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),r=!(e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("chatgpt-4o")||e.startsWith("gpt-5-chat")),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:o}}function Uw({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:i}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:i});break}case"developer":{n.push({role:"developer",content:i});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,s)=>{var l,c,p;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const g=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${g};base64,${Tt(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new je({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Tt(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Tt(a.data),format:"mp3"}};default:throw new je({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new je({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(p=a.filename)!=null?p:`part-${s}.pdf`,file_data:`data:application/pdf;base64,${Tt(a.data)}`}}}else throw new je({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const s=[];for(const l of i)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{s.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:a,tool_calls:s.length>0?s:void 0});break}case"tool":{for(const a of i){const s=a.output;let l;switch(s.type){case"text":case"error-text":l=s.value;break;case"content":case"json":case"error-json":l=JSON.stringify(s.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:r}}function Mr({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function hs(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Bw=Ee(()=>j(d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({message:d({role:h("assistant").nullish(),content:u().nullish(),tool_calls:R(d({id:u().nullish(),type:h("function"),function:d({name:u(),arguments:u()})})).nullish(),annotations:R(d({type:h("url_citation"),url_citation:d({start_index:f(),end_index:f(),url:u(),title:u()})})).nullish()}),index:f(),logprobs:d({content:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish()}).nullish(),finish_reason:u().nullish()})),usage:d({prompt_tokens:f().nullish(),completion_tokens:f().nullish(),total_tokens:f().nullish(),prompt_tokens_details:d({cached_tokens:f().nullish()}).nullish(),completion_tokens_details:d({reasoning_tokens:f().nullish(),accepted_prediction_tokens:f().nullish(),rejected_prediction_tokens:f().nullish()}).nullish()}).nullish()}))),Vw=Ee(()=>j(ee([d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({delta:d({role:X(["assistant"]).nullish(),content:u().nullish(),tool_calls:R(d({index:f(),id:u().nullish(),type:h("function").nullish(),function:d({name:u().nullish(),arguments:u().nullish()})})).nullish(),annotations:R(d({type:h("url_citation"),url_citation:d({start_index:f(),end_index:f(),url:u(),title:u()})})).nullish()}).nullish(),logprobs:d({content:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish()}).nullish(),finish_reason:u().nullish(),index:f()})),usage:d({prompt_tokens:f().nullish(),completion_tokens:f().nullish(),total_tokens:f().nullish(),prompt_tokens_details:d({cached_tokens:f().nullish()}).nullish(),completion_tokens_details:d({reasoning_tokens:f().nullish(),accepted_prediction_tokens:f().nullish(),rejected_prediction_tokens:f().nullish()}).nullish()}).nullish()}),Po]))),Fw=Ee(()=>j(d({logitBias:Se(xm(),f()).optional(),logprobs:ee([ue(),f()]).optional(),parallelToolCalls:ue().optional(),user:u().optional(),reasoningEffort:X(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:f().optional(),store:ue().optional(),metadata:Se(u().max(64),u().max(512)).optional(),prediction:Se(u(),He()).optional(),structuredOutputs:ue().optional(),serviceTier:X(["auto","flex","priority","default"]).optional(),strictJsonSchema:ue().optional(),textVerbosity:X(["low","medium","high"]).optional(),promptCacheKey:u().optional(),promptCacheRetention:X(["in_memory","24h"]).optional(),safetyIdentifier:u().optional()})));function qw({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const i=[];for(const s of e)switch(s.type){case"function":i.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,strict:n?r:void 0}});break;default:o.push({type:"unsupported-tool",tool:s});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:i,toolChoice:a,toolWarnings:o};case"tool":return{tools:i,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const s=a;throw new je({functionality:`tool choice type: ${s}`})}}}var Gw=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:g,providerOptions:x}){var T,I,E,k;const _=[],v=(T=await Je({provider:"openai",providerOptions:x,schema:Fw}))!=null?T:{},y=(I=v.structuredOutputs)!=null?I:!0,$=yc(this.modelId);o!=null&&_.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!y&&_.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:S}=Uw({prompt:e,systemMessageMode:$.systemMessageMode});_.push(...S);const m=(E=v.strictJsonSchema)!=null?E:!1,N={model:this.modelId,logit_bias:v.logitBias,logprobs:v.logprobs===!0||typeof v.logprobs=="number"?!0:void 0,top_logprobs:typeof v.logprobs=="number"?v.logprobs:typeof v.logprobs=="boolean"&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:a,response_format:(l==null?void 0:l.type)==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:m,name:(k=l.name)!=null?k:"response",description:l.description}}:{type:"json_object"}:void 0,stop:s,seed:c,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,prompt_cache_retention:v.promptCacheRetention,safety_identifier:v.safetyIdentifier,messages:b};$.isReasoningModel?((v.reasoningEffort!=="none"||!$.supportsNonReasoningParameters)&&(N.temperature!=null&&(N.temperature=void 0,_.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),N.top_p!=null&&(N.top_p=void 0,_.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),N.logprobs!=null&&(N.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),N.frequency_penalty!=null&&(N.frequency_penalty=void 0,_.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),N.presence_penalty!=null&&(N.presence_penalty=void 0,_.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),N.logit_bias!=null&&(N.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),N.top_logprobs!=null&&(N.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),N.max_tokens!=null&&(N.max_completion_tokens==null&&(N.max_completion_tokens=N.max_tokens),N.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&N.temperature!=null&&(N.temperature=void 0,_.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),v.serviceTier==="flex"&&!$.supportsFlexProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),N.service_tier=void 0),v.serviceTier==="priority"&&!$.supportsPriorityProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),N.service_tier=void 0);const{tools:Z,toolChoice:B,toolWarnings:D}=qw({tools:p,toolChoice:g,structuredOutputs:y,strictJsonSchema:m});return{args:{...N,tools:Z,tool_choice:B},warnings:[..._,...D]}}async doGenerate(e){var t,n,r,o,i,a,s,l,c,p,g,x,T,I;const{args:E,warnings:k}=await this.getArgs(e),{responseHeaders:_,value:v,rawValue:y}=await De({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),body:E,failedResponseHandler:ft,successfulResponseHandler:Be(Bw),abortSignal:e.abortSignal,fetch:this.config.fetch}),$=v.choices[0],b=[],S=$.message.content;S!=null&&S.length>0&&b.push({type:"text",text:S});for(const B of(t=$.message.tool_calls)!=null?t:[])b.push({type:"tool-call",toolCallId:(n=B.id)!=null?n:Ge(),toolName:B.function.name,input:B.function.arguments});for(const B of(r=$.message.annotations)!=null?r:[])b.push({type:"source",sourceType:"url",id:Ge(),url:B.url_citation.url,title:B.url_citation.title});const m=(o=v.usage)==null?void 0:o.completion_tokens_details,N=(i=v.usage)==null?void 0:i.prompt_tokens_details,Z={openai:{}};return(m==null?void 0:m.accepted_prediction_tokens)!=null&&(Z.openai.acceptedPredictionTokens=m==null?void 0:m.accepted_prediction_tokens),(m==null?void 0:m.rejected_prediction_tokens)!=null&&(Z.openai.rejectedPredictionTokens=m==null?void 0:m.rejected_prediction_tokens),((a=$.logprobs)==null?void 0:a.content)!=null&&(Z.openai.logprobs=$.logprobs.content),{content:b,finishReason:hs($.finish_reason),usage:{inputTokens:(l=(s=v.usage)==null?void 0:s.prompt_tokens)!=null?l:void 0,outputTokens:(p=(c=v.usage)==null?void 0:c.completion_tokens)!=null?p:void 0,totalTokens:(x=(g=v.usage)==null?void 0:g.total_tokens)!=null?x:void 0,reasoningTokens:(T=m==null?void 0:m.reasoning_tokens)!=null?T:void 0,cachedInputTokens:(I=N==null?void 0:N.cached_tokens)!=null?I:void 0},request:{body:E},response:{...Mr(v),headers:_,body:y},warnings:k,providerMetadata:Z}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await De({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),body:r,failedResponseHandler:ft,successfulResponseHandler:$n(Vw),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let s="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,p=!1;const g={openai:{}};return{stream:i.pipeThrough(new TransformStream({start(x){x.enqueue({type:"stream-start",warnings:n})},transform(x,T){var I,E,k,_,v,y,$,b,S,m,N,Z,B,D,oe,L,V,J,be,Y,we,ge,Ce,le;if(e.includeRawChunks&&T.enqueue({type:"raw",rawValue:x.rawValue}),!x.success){s="error",T.enqueue({type:"error",error:x.error});return}const he=x.value;if("error"in he){s="error",T.enqueue({type:"error",error:he.error});return}if(!c){const O=Mr(he);Object.values(O).some(Boolean)&&(c=!0,T.enqueue({type:"response-metadata",...Mr(he)}))}he.usage!=null&&(l.inputTokens=(I=he.usage.prompt_tokens)!=null?I:void 0,l.outputTokens=(E=he.usage.completion_tokens)!=null?E:void 0,l.totalTokens=(k=he.usage.total_tokens)!=null?k:void 0,l.reasoningTokens=(v=(_=he.usage.completion_tokens_details)==null?void 0:_.reasoning_tokens)!=null?v:void 0,l.cachedInputTokens=($=(y=he.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?$:void 0,((b=he.usage.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens)!=null&&(g.openai.acceptedPredictionTokens=(S=he.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((m=he.usage.completion_tokens_details)==null?void 0:m.rejected_prediction_tokens)!=null&&(g.openai.rejectedPredictionTokens=(N=he.usage.completion_tokens_details)==null?void 0:N.rejected_prediction_tokens));const de=he.choices[0];if((de==null?void 0:de.finish_reason)!=null&&(s=hs(de.finish_reason)),((Z=de==null?void 0:de.logprobs)==null?void 0:Z.content)!=null&&(g.openai.logprobs=de.logprobs.content),(de==null?void 0:de.delta)==null)return;const ke=de.delta;if(ke.content!=null&&(p||(T.enqueue({type:"text-start",id:"0"}),p=!0),T.enqueue({type:"text-delta",id:"0",delta:ke.content})),ke.tool_calls!=null)for(const O of ke.tool_calls){const ne=O.index;if(a[ne]==null){if(O.type!=null&&O.type!=="function")throw new yr({data:O,message:"Expected 'function' type."});if(O.id==null)throw new yr({data:O,message:"Expected 'id' to be a string."});if(((B=O.function)==null?void 0:B.name)==null)throw new yr({data:O,message:"Expected 'function.name' to be a string."});T.enqueue({type:"tool-input-start",id:O.id,toolName:O.function.name}),a[ne]={id:O.id,type:"function",function:{name:O.function.name,arguments:(D=O.function.arguments)!=null?D:""},hasFinished:!1};const H=a[ne];((oe=H.function)==null?void 0:oe.name)!=null&&((L=H.function)==null?void 0:L.arguments)!=null&&(H.function.arguments.length>0&&T.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),fa(H.function.arguments)&&(T.enqueue({type:"tool-input-end",id:H.id}),T.enqueue({type:"tool-call",toolCallId:(V=H.id)!=null?V:Ge(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0));continue}const C=a[ne];C.hasFinished||(((J=O.function)==null?void 0:J.arguments)!=null&&(C.function.arguments+=(Y=(be=O.function)==null?void 0:be.arguments)!=null?Y:""),T.enqueue({type:"tool-input-delta",id:C.id,delta:(we=O.function.arguments)!=null?we:""}),((ge=C.function)==null?void 0:ge.name)!=null&&((Ce=C.function)==null?void 0:Ce.arguments)!=null&&fa(C.function.arguments)&&(T.enqueue({type:"tool-input-end",id:C.id}),T.enqueue({type:"tool-call",toolCallId:(le=C.id)!=null?le:Ge(),toolName:C.function.name,input:C.function.arguments}),C.hasFinished=!0))}if(ke.annotations!=null)for(const O of ke.annotations)T.enqueue({type:"source",sourceType:"url",id:Ge(),url:O.url_citation.url,title:O.url_citation.title})},flush(x){p&&x.enqueue({type:"text-end",id:"0"}),x.enqueue({type:"finish",finishReason:s,usage:l,...g!=null?{providerMetadata:g}:{}})}})),request:{body:r},response:{headers:o}}}};function Hw({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
491
-
492
- `,e=e.slice(1));for(const{role:o,content:i}of e)switch(o){case"system":throw new wt({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=i.map(s=>{switch(s.type){case"text":return s.text}}).filter(Boolean).join("");r+=`${t}:
493
- ${a}
494
-
495
- `;break}case"assistant":{const a=i.map(s=>{switch(s.type){case"text":return s.text;case"tool-call":throw new je({functionality:"tool-call messages"})}}).join("");r+=`${n}:
496
- ${a}
497
-
498
- `;break}case"tool":throw new je({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
499
- `,{prompt:r,stopSequences:[`
500
- ${t}:`]}}function fs({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function ms(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Jw=Ee(()=>j(d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({text:u(),finish_reason:u(),logprobs:d({tokens:R(u()),token_logprobs:R(f()),top_logprobs:R(Se(u(),f())).nullish()}).nullish()})),usage:d({prompt_tokens:f(),completion_tokens:f(),total_tokens:f()}).nullish()}))),Kw=Ee(()=>j(ee([d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({text:u(),finish_reason:u().nullish(),index:f(),logprobs:d({tokens:R(u()),token_logprobs:R(f()),top_logprobs:R(Se(u(),f())).nullish()}).nullish()})),usage:d({prompt_tokens:f(),completion_tokens:f(),total_tokens:f()}).nullish()}),Po]))),_s=Ee(()=>j(d({echo:ue().optional(),logitBias:Se(u(),f()).optional(),suffix:u().optional(),user:u().optional(),logprobs:ee([ue(),f()]).optional()}))),Ww=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:l,tools:c,toolChoice:p,seed:g,providerOptions:x}){const T=[],I={...await Je({provider:"openai",providerOptions:x,schema:_s}),...await Je({provider:this.providerOptionsName,providerOptions:x,schema:_s})};o!=null&&T.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&T.push({type:"unsupported-setting",setting:"tools"}),p!=null&&T.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&T.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:E,stopSequences:k}=Hw({prompt:e}),_=[...k??[],...s??[]];return{args:{model:this.modelId,echo:I.echo,logit_bias:I.logitBias,logprobs:(I==null?void 0:I.logprobs)===!0?0:(I==null?void 0:I.logprobs)===!1||I==null?void 0:I.logprobs,suffix:I.suffix,user:I.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:a,seed:g,prompt:E,stop:_.length>0?_:void 0},warnings:T}}async doGenerate(e){var t,n,r;const{args:o,warnings:i}=await this.getArgs(e),{responseHeaders:a,value:s,rawValue:l}=await De({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),body:o,failedResponseHandler:ft,successfulResponseHandler:Be(Jw),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=s.choices[0],p={openai:{}};return c.logprobs!=null&&(p.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=s.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=s.usage)==null?void 0:n.completion_tokens,totalTokens:(r=s.usage)==null?void 0:r.total_tokens},finishReason:ms(c.finish_reason),request:{body:o},response:{...fs(s),headers:a,body:l},providerMetadata:p,warnings:i}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await De({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),body:r,failedResponseHandler:ft,successfulResponseHandler:$n(Kw),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const s={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:i.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:n})},transform(p,g){if(e.includeRawChunks&&g.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){a="error",g.enqueue({type:"error",error:p.error});return}const x=p.value;if("error"in x){a="error",g.enqueue({type:"error",error:x.error});return}c&&(c=!1,g.enqueue({type:"response-metadata",...fs(x)}),g.enqueue({type:"text-start",id:"0"})),x.usage!=null&&(l.inputTokens=x.usage.prompt_tokens,l.outputTokens=x.usage.completion_tokens,l.totalTokens=x.usage.total_tokens);const T=x.choices[0];(T==null?void 0:T.finish_reason)!=null&&(a=ms(T.finish_reason)),(T==null?void 0:T.logprobs)!=null&&(s.openai.logprobs=T.logprobs),(T==null?void 0:T.text)!=null&&T.text.length>0&&g.enqueue({type:"text-delta",id:"0",delta:T.text})},flush(p){c||p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:a,providerMetadata:s,usage:l})}})),request:{body:r},response:{headers:o}}}},Yw=Ee(()=>j(d({dimensions:f().optional(),user:u().optional()}))),Xw=Ee(()=>j(d({data:R(d({embedding:R(f())})),usage:d({prompt_tokens:f()}).nullish()}))),Qw=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new ud({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=(o=await Je({provider:"openai",providerOptions:r,schema:Yw}))!=null?o:{},{responseHeaders:a,value:s,rawValue:l}=await De({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:ze(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:ft,successfulResponseHandler:Be(Xw),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.data.map(c=>c.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},e0=Ee(()=>j(d({created:f().nullish(),data:R(d({b64_json:u(),revised_prompt:u().nullish()})),background:u().nullish(),output_format:u().nullish(),size:u().nullish(),quality:u().nullish(),usage:d({input_tokens:f().nullish(),output_tokens:f().nullish(),total_tokens:f().nullish(),input_tokens_details:d({image_tokens:f().nullish(),text_tokens:f().nullish()}).nullish()}).nullish()}))),t0={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10},n0=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2"]),r0=d({quality:X(["standard","hd","low","medium","high","auto"]).optional(),background:X(["transparent","opaque","auto"]).optional(),outputFormat:X(["png","jpeg","webp"]).optional(),outputCompression:f().int().min(0).max(100).optional(),user:u().optional()}),o0=Ee(()=>j(r0.extend({style:X(["vivid","natural"]).optional(),moderation:X(["auto","low"]).optional()}))),i0=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=t0[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:a,abortSignal:s}){var l,c,p,g;const x=[];r!=null&&x.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&x.push({type:"unsupported-setting",setting:"seed"});const T=(p=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?p:new Date,I=(g=await Je({provider:"openai",providerOptions:i,schema:o0}))!=null?g:{},{value:E,responseHeaders:k}=await De({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:ze(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,quality:I.quality,style:I.style,background:I.background,moderation:I.moderation,output_format:I.outputFormat,output_compression:I.outputCompression,user:I.user,...n0.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ft,successfulResponseHandler:Be(e0),abortSignal:s,fetch:this.config.fetch});return{images:E.data.map(_=>_.b64_json),warnings:x,response:{timestamp:T,modelId:this.modelId,headers:k},providerMetadata:{openai:{images:E.data.map((_,v)=>({..._.revised_prompt?{revisedPrompt:_.revised_prompt}:{},...E.created!=null?{created:E.created}:{},...E.size!=null?{size:E.size}:{},...E.quality!=null?{quality:E.quality}:{},...E.background!=null?{background:E.background}:{},...E.output_format!=null?{outputFormat:E.output_format}:{},...a0(E.usage,v,E.data.length)}))}}}}};function a0(e,t,n){if(e==null)return{};const r={},o=e.input_tokens_details;if((o==null?void 0:o.image_tokens)!=null){const i=Math.floor(o.image_tokens/n),a=o.image_tokens-i*(n-1);r.imageTokens=t===n-1?a:i}if((o==null?void 0:o.text_tokens)!=null){const i=Math.floor(o.text_tokens/n),a=o.text_tokens-i*(n-1);r.textTokens=t===n-1?a:i}if(e.input_tokens!=null){const i=Math.floor(e.input_tokens/n),a=e.input_tokens-i*(n-1);r.inputTokens=t===n-1?a:i}if(e.output_tokens!=null){const i=Math.floor(e.output_tokens/n),a=e.output_tokens-i*(n-1);r.outputTokens=t===n-1?a:i}return r}var s0=W(()=>j(d({code:u().nullish(),containerId:u()}))),l0=W(()=>j(d({outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullish()}))),u0=W(()=>j(d({container:ee([u(),d({fileIds:R(u()).optional()})]).optional()}))),c0=Ye({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:s0,outputSchema:l0}),d0=(e={})=>c0(e),vc=d({key:u(),type:X(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([u(),f(),ue(),R(u())])}),bc=d({type:X(["and","or"]),filters:R(ee([vc,Vl(()=>bc)]))}),p0=W(()=>j(d({vectorStoreIds:R(u()),maxNumResults:f().optional(),ranking:d({ranker:u().optional(),scoreThreshold:f().optional()}).optional(),filters:ee([vc,bc]).optional()}))),h0=W(()=>j(d({queries:R(u()),results:R(d({attributes:Se(u(),Le()),fileId:u(),filename:u(),score:f(),text:u()})).nullable()}))),f0=Ye({id:"openai.file_search",name:"file_search",inputSchema:d({}),outputSchema:h0}),m0=W(()=>j(d({background:X(["auto","opaque","transparent"]).optional(),inputFidelity:X(["low","high"]).optional(),inputImageMask:d({fileId:u().optional(),imageUrl:u().optional()}).optional(),model:u().optional(),moderation:X(["auto"]).optional(),outputCompression:f().int().min(0).max(100).optional(),outputFormat:X(["png","jpeg","webp"]).optional(),partialImages:f().int().min(0).max(3).optional(),quality:X(["auto","low","medium","high"]).optional(),size:X(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),_0=W(()=>j(d({}))),g0=W(()=>j(d({result:u()}))),y0=Ye({id:"openai.image_generation",name:"image_generation",inputSchema:_0,outputSchema:g0}),v0=(e={})=>y0(e),wc=W(()=>j(d({action:d({type:h("exec"),command:R(u()),timeoutMs:f().optional(),user:u().optional(),workingDirectory:u().optional(),env:Se(u(),u()).optional()})}))),xc=W(()=>j(d({output:u()}))),b0=Ye({id:"openai.local_shell",name:"local_shell",inputSchema:wc,outputSchema:xc}),w0=W(()=>j(d({externalWebAccess:ue().optional(),filters:d({allowedDomains:R(u()).optional()}).optional(),searchContextSize:X(["low","medium","high"]).optional(),userLocation:d({type:h("approximate"),country:u().optional(),city:u().optional(),region:u().optional(),timezone:u().optional()}).optional()}))),x0=W(()=>j(d({}))),k0=W(()=>j(d({action:se("type",[d({type:h("search"),query:u().optional()}),d({type:h("openPage"),url:u().nullish()}),d({type:h("findInPage"),url:u().nullish(),pattern:u().nullish()})]).optional(),sources:R(se("type",[d({type:h("url"),url:u()}),d({type:h("api"),name:u()})])).optional()}))),I0=Ye({id:"openai.web_search",name:"web_search",inputSchema:x0,outputSchema:k0}),T0=(e={})=>I0(e),S0=W(()=>j(d({searchContextSize:X(["low","medium","high"]).optional(),userLocation:d({type:h("approximate"),country:u().optional(),city:u().optional(),region:u().optional(),timezone:u().optional()}).optional()}))),E0=W(()=>j(d({}))),C0=W(()=>j(d({action:se("type",[d({type:h("search"),query:u().optional()}),d({type:h("openPage"),url:u().nullish()}),d({type:h("findInPage"),url:u().nullish(),pattern:u().nullish()})]).optional()}))),A0=Ye({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:E0,outputSchema:C0}),O0={codeInterpreter:d0,fileSearch:f0,imageGeneration:v0,localShell:b0,webSearchPreview:A0,webSearch:T0};function gs(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function $0({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:o=!1}){var i,a,s,l,c,p;let g=[];const x=[];for(const{role:T,content:I}of e)switch(T){case"system":{switch(t){case"system":{g.push({role:"system",content:I});break}case"developer":{g.push({role:"developer",content:I});break}case"remove":{x.push({type:"other",message:"system messages are removed for this model"});break}default:{const E=t;throw new Error(`Unsupported system message mode: ${E}`)}}break}case"user":{g.push({role:"user",content:I.map((E,k)=>{var _,v,y;switch(E.type){case"text":return{type:"input_text",text:E.text};case"file":if(E.mediaType.startsWith("image/")){const $=E.mediaType==="image/*"?"image/jpeg":E.mediaType;return{type:"input_image",...E.data instanceof URL?{image_url:E.data.toString()}:typeof E.data=="string"&&gs(E.data,n)?{file_id:E.data}:{image_url:`data:${$};base64,${Tt(E.data)}`},detail:(v=(_=E.providerOptions)==null?void 0:_.openai)==null?void 0:v.imageDetail}}else{if(E.mediaType==="application/pdf")return E.data instanceof URL?{type:"input_file",file_url:E.data.toString()}:{type:"input_file",...typeof E.data=="string"&&gs(E.data,n)?{file_id:E.data}:{filename:(y=E.filename)!=null?y:`part-${k}.pdf`,file_data:`data:application/pdf;base64,${Tt(E.data)}`}};throw new je({functionality:`file part media type ${E.mediaType}`})}}})});break}case"assistant":{const E={},k={};for(const _ of I)switch(_.type){case"text":{const v=(a=(i=_.providerOptions)==null?void 0:i.openai)==null?void 0:a.itemId,y=(l=(s=_.providerOptions)==null?void 0:s.openai)==null?void 0:l.phase;if(r&&v!=null){g.push({type:"item_reference",id:v});break}g.push({role:"assistant",content:[{type:"output_text",text:_.text}],id:v,...y!=null&&{phase:y}});break}case"tool-call":{if(k[_.toolCallId]=_,_.providerExecuted)break;const v=(p=(c=_.providerOptions)==null?void 0:c.openai)==null?void 0:p.itemId;if(r&&v!=null){g.push({type:"item_reference",id:v});break}if(o&&_.toolName==="local_shell"){const y=await Me({value:_.input,schema:wc});g.push({type:"local_shell_call",call_id:_.toolCallId,id:v,action:{type:"exec",command:y.action.command,timeout_ms:y.action.timeoutMs,user:y.action.user,working_directory:y.action.workingDirectory,env:y.action.env}});break}g.push({type:"function_call",call_id:_.toolCallId,name:_.toolName,arguments:JSON.stringify(_.input),id:v});break}case"tool-result":{r?g.push({type:"item_reference",id:_.toolCallId}):x.push({type:"other",message:`Results for OpenAI tool ${_.toolName} are not sent to the API when store is false`});break}case"reasoning":{const v=await Je({provider:"openai",providerOptions:_.providerOptions,schema:N0}),y=v==null?void 0:v.itemId;if(y!=null){const $=E[y];if(r)$===void 0&&(g.push({type:"item_reference",id:y}),E[y]={type:"reasoning",id:y,summary:[]});else{const b=[];_.text.length>0?b.push({type:"summary_text",text:_.text}):$!==void 0&&x.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(_)}.`}),$===void 0?(E[y]={type:"reasoning",id:y,encrypted_content:v==null?void 0:v.reasoningEncryptedContent,summary:b},g.push(E[y])):($.summary.push(...b),(v==null?void 0:v.reasoningEncryptedContent)!=null&&($.encrypted_content=v.reasoningEncryptedContent))}}else x.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(_)}.`});break}}break}case"tool":{for(const E of I){const k=E.output;if(o&&E.toolName==="local_shell"&&k.type==="json"){const v=await Me({value:k.value,schema:xc});g.push({type:"local_shell_call_output",call_id:E.toolCallId,output:v.output});break}let _;switch(k.type){case"text":case"error-text":_=k.value;break;case"json":case"error-json":_=JSON.stringify(k.value);break;case"content":_=k.value.map(v=>{switch(v.type){case"text":return{type:"input_text",text:v.text};case"media":return v.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${v.mediaType};base64,${v.data}`}:{type:"input_file",filename:"data",file_data:`data:${v.mediaType};base64,${v.data}`}}});break}g.push({type:"function_call_output",call_id:E.toolCallId,output:_})}break}default:{const E=T;throw new Error(`Unsupported role: ${E}`)}}return!r&&g.some(T=>"type"in T&&T.type==="reasoning"&&T.encrypted_content==null)&&(x.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),g=g.filter(T=>!("type"in T)||T.type!=="reasoning"||T.encrypted_content!=null)),{input:g,warnings:x}}var N0=d({itemId:u().nullish(),reasoningEncryptedContent:u().nullish()});function ys({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var R0=Ee(()=>j(ee([d({type:h("response.output_text.delta"),item_id:u(),delta:u(),logprobs:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish()}),d({type:X(["response.completed","response.incomplete"]),response:d({incomplete_details:d({reason:u()}).nullish(),usage:d({input_tokens:f(),input_tokens_details:d({cached_tokens:f().nullish(),orchestration_input_tokens:f().nullish(),orchestration_input_cached_tokens:f().nullish()}).nullish(),output_tokens:f(),output_tokens_details:d({reasoning_tokens:f().nullish(),orchestration_output_tokens:f().nullish()}).nullish()}),service_tier:u().nullish()})}),d({type:h("response.created"),response:d({id:u(),created_at:f(),model:u(),service_tier:u().nullish()})}),d({type:h("response.output_item.added"),output_index:f(),item:se("type",[d({type:h("message"),id:u(),phase:X(["commentary","final_answer"]).nullish()}),d({type:h("reasoning"),id:u(),encrypted_content:u().nullish()}),d({type:h("function_call"),id:u(),call_id:u(),name:u(),arguments:u()}),d({type:h("web_search_call"),id:u(),status:u()}),d({type:h("computer_call"),id:u(),status:u()}),d({type:h("file_search_call"),id:u()}),d({type:h("image_generation_call"),id:u()}),d({type:h("code_interpreter_call"),id:u(),container_id:u(),code:u().nullable(),outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullable(),status:u()})])}),d({type:h("response.output_item.done"),output_index:f(),item:se("type",[d({type:h("message"),id:u(),phase:X(["commentary","final_answer"]).nullish()}),d({type:h("reasoning"),id:u(),encrypted_content:u().nullish()}),d({type:h("function_call"),id:u(),call_id:u(),name:u(),arguments:u(),status:h("completed")}),d({type:h("code_interpreter_call"),id:u(),code:u().nullable(),container_id:u(),outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullable()}),d({type:h("image_generation_call"),id:u(),result:u()}),d({type:h("web_search_call"),id:u(),status:u(),action:se("type",[d({type:h("search"),query:u().nullish(),sources:R(se("type",[d({type:h("url"),url:u()}),d({type:h("api"),name:u()})])).nullish()}),d({type:h("open_page"),url:u().nullish()}),d({type:h("find_in_page"),url:u().nullish(),pattern:u().nullish()})]).nullish()}),d({type:h("file_search_call"),id:u(),queries:R(u()),results:R(d({attributes:Se(u(),Le()),file_id:u(),filename:u(),score:f(),text:u()})).nullish()}),d({type:h("local_shell_call"),id:u(),call_id:u(),action:d({type:h("exec"),command:R(u()),timeout_ms:f().optional(),user:u().optional(),working_directory:u().optional(),env:Se(u(),u()).optional()})}),d({type:h("computer_call"),id:u(),status:h("completed")})])}),d({type:h("response.function_call_arguments.delta"),item_id:u(),output_index:f(),delta:u()}),d({type:h("response.image_generation_call.partial_image"),item_id:u(),output_index:f(),partial_image_b64:u()}),d({type:h("response.code_interpreter_call_code.delta"),item_id:u(),output_index:f(),delta:u()}),d({type:h("response.code_interpreter_call_code.done"),item_id:u(),output_index:f(),code:u()}),d({type:h("response.output_text.annotation.added"),annotation:se("type",[d({type:h("url_citation"),start_index:f(),end_index:f(),url:u(),title:u()}),d({type:h("file_citation"),file_id:u(),filename:u().nullish(),index:f().nullish(),start_index:f().nullish(),end_index:f().nullish(),quote:u().nullish()})])}),d({type:h("response.reasoning_summary_part.added"),item_id:u(),summary_index:f()}),d({type:h("response.reasoning_summary_text.delta"),item_id:u(),summary_index:f(),delta:u()}),d({type:h("response.reasoning_summary_part.done"),item_id:u(),summary_index:f()}),d({type:h("error"),sequence_number:f(),error:d({type:u(),code:u(),message:u(),param:u().nullish()})}),d({type:u()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),P0=Ee(()=>j(d({id:u().optional(),created_at:f().optional(),error:d({message:u(),type:u(),param:u().nullish(),code:u()}).nullish(),model:u().optional(),output:R(se("type",[d({type:h("message"),role:h("assistant"),id:u(),phase:X(["commentary","final_answer"]).nullish(),content:R(d({type:h("output_text"),text:u(),logprobs:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish(),annotations:R(se("type",[d({type:h("url_citation"),start_index:f(),end_index:f(),url:u(),title:u()}),d({type:h("file_citation"),file_id:u(),filename:u().nullish(),index:f().nullish(),start_index:f().nullish(),end_index:f().nullish(),quote:u().nullish()}),d({type:h("container_file_citation"),container_id:u(),file_id:u(),filename:u().nullish(),start_index:f().nullish(),end_index:f().nullish(),index:f().nullish()}),d({type:h("file_path"),file_id:u(),index:f().nullish()})]))}))}),d({type:h("web_search_call"),id:u(),status:u(),action:se("type",[d({type:h("search"),query:u().nullish(),sources:R(se("type",[d({type:h("url"),url:u()}),d({type:h("api"),name:u()})])).nullish()}),d({type:h("open_page"),url:u().nullish()}),d({type:h("find_in_page"),url:u().nullish(),pattern:u().nullish()})]).nullish()}),d({type:h("file_search_call"),id:u(),queries:R(u()),results:R(d({attributes:Se(u(),ee([u(),f(),ue()])),file_id:u(),filename:u(),score:f(),text:u()})).nullish()}),d({type:h("code_interpreter_call"),id:u(),code:u().nullable(),container_id:u(),outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullable()}),d({type:h("image_generation_call"),id:u(),result:u()}),d({type:h("local_shell_call"),id:u(),call_id:u(),action:d({type:h("exec"),command:R(u()),timeout_ms:f().optional(),user:u().optional(),working_directory:u().optional(),env:Se(u(),u()).optional()})}),d({type:h("function_call"),call_id:u(),name:u(),arguments:u(),id:u()}),d({type:h("computer_call"),id:u(),status:u().optional()}),d({type:h("reasoning"),id:u(),encrypted_content:u().nullish(),summary:R(d({type:h("summary_text"),text:u()}))})])).optional(),service_tier:u().nullish(),incomplete_details:d({reason:u()}).nullish(),usage:d({input_tokens:f(),input_tokens_details:d({cached_tokens:f().nullish(),orchestration_input_tokens:f().nullish(),orchestration_input_cached_tokens:f().nullish()}).nullish(),output_tokens:f(),output_tokens_details:d({reasoning_tokens:f().nullish(),orchestration_output_tokens:f().nullish()}).nullish()}).optional()}))),kc=20,M0=Ee(()=>j(d({conversation:u().nullish(),include:R(X(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:u().nullish(),logprobs:ee([ue(),f().min(1).max(kc)]).optional(),maxToolCalls:f().nullish(),metadata:He().nullish(),parallelToolCalls:ue().nullish(),previousResponseId:u().nullish(),promptCacheKey:u().nullish(),promptCacheRetention:X(["in_memory","24h"]).nullish(),reasoningEffort:u().nullish(),reasoningSummary:u().nullish(),safetyIdentifier:u().nullish(),serviceTier:X(["auto","flex","priority","default"]).nullish(),store:ue().nullish(),strictJsonSchema:ue().nullish(),textVerbosity:X(["low","medium","high"]).nullish(),truncation:X(["auto","disabled"]).nullish(),user:u().nullish()})));async function L0({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const s=await Me({value:a.args,schema:p0});o.push({type:"file_search",vector_store_ids:s.vectorStoreIds,max_num_results:s.maxNumResults,ranking_options:s.ranking?{ranker:s.ranking.ranker,score_threshold:s.ranking.scoreThreshold}:void 0,filters:s.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const s=await Me({value:a.args,schema:S0});o.push({type:"web_search_preview",search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.web_search":{const s=await Me({value:a.args,schema:w0});o.push({type:"web_search",filters:s.filters!=null?{allowed_domains:s.filters.allowedDomains}:void 0,external_web_access:s.externalWebAccess,search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.code_interpreter":{const s=await Me({value:a.args,schema:u0});o.push({type:"code_interpreter",container:s.container==null?{type:"auto",file_ids:void 0}:typeof s.container=="string"?s.container:{type:"auto",file_ids:s.container.fileIds}});break}case"openai.image_generation":{const s=await Me({value:a.args,schema:m0});o.push({type:"image_generation",background:s.background,input_fidelity:s.inputFidelity,input_image_mask:s.inputImageMask?{file_id:s.inputImageMask.fileId,image_url:s.inputImageMask.imageUrl}:void 0,model:s.model,size:s.size,quality:s.quality,moderation:s.moderation,output_format:s.outputFormat,output_compression:s.outputCompression});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=i;throw new je({functionality:`tool choice type: ${a}`})}}}var z0=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:i,frequencyPenalty:a,seed:s,prompt:l,providerOptions:c,tools:p,toolChoice:g,responseFormat:x}){var T,I,E,k;const _=[],v=yc(this.modelId);o!=null&&_.push({type:"unsupported-setting",setting:"topK"}),s!=null&&_.push({type:"unsupported-setting",setting:"seed"}),i!=null&&_.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&_.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&_.push({type:"unsupported-setting",setting:"stopSequences"});const y=await Je({provider:"openai",providerOptions:c,schema:M0});y!=null&&y.conversation&&(y!=null&&y.previousResponseId)&&_.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:$,warnings:b}=await $0({prompt:l,systemMessageMode:v.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(T=y==null?void 0:y.store)!=null?T:!0,hasLocalShellTool:Z("openai.local_shell")});_.push(...b);const S=(I=y==null?void 0:y.strictJsonSchema)!=null?I:!1;let m=y==null?void 0:y.include;function N(Y){m==null?m=[Y]:m.includes(Y)||(m=[...m,Y])}function Z(Y){return(p==null?void 0:p.find(we=>we.type==="provider-defined"&&we.id===Y))!=null}const B=typeof(y==null?void 0:y.logprobs)=="number"?y==null?void 0:y.logprobs:(y==null?void 0:y.logprobs)===!0?kc:void 0;B&&N("message.output_text.logprobs");const D=(E=p==null?void 0:p.find(Y=>Y.type==="provider-defined"&&(Y.id==="openai.web_search"||Y.id==="openai.web_search_preview")))==null?void 0:E.name;D&&N("web_search_call.action.sources"),Z("openai.code_interpreter")&&N("code_interpreter_call.outputs");const oe=y==null?void 0:y.store;oe===!1&&v.isReasoningModel&&N("reasoning.encrypted_content");const L={model:this.modelId,input:$,temperature:t,top_p:r,max_output_tokens:e,...((x==null?void 0:x.type)==="json"||(y==null?void 0:y.textVerbosity))&&{text:{...(x==null?void 0:x.type)==="json"&&{format:x.schema!=null?{type:"json_schema",strict:S,name:(k=x.name)!=null?k:"response",description:x.description,schema:x.schema}:{type:"json_object"}},...(y==null?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},conversation:y==null?void 0:y.conversation,max_tool_calls:y==null?void 0:y.maxToolCalls,metadata:y==null?void 0:y.metadata,parallel_tool_calls:y==null?void 0:y.parallelToolCalls,previous_response_id:y==null?void 0:y.previousResponseId,store:oe,user:y==null?void 0:y.user,instructions:y==null?void 0:y.instructions,service_tier:y==null?void 0:y.serviceTier,include:m,prompt_cache_key:y==null?void 0:y.promptCacheKey,prompt_cache_retention:y==null?void 0:y.promptCacheRetention,safety_identifier:y==null?void 0:y.safetyIdentifier,top_logprobs:B,truncation:y==null?void 0:y.truncation,...v.isReasoningModel&&((y==null?void 0:y.reasoningEffort)!=null||(y==null?void 0:y.reasoningSummary)!=null)&&{reasoning:{...(y==null?void 0:y.reasoningEffort)!=null&&{effort:y.reasoningEffort},...(y==null?void 0:y.reasoningSummary)!=null&&{summary:y.reasoningSummary}}}};v.isReasoningModel?(y==null?void 0:y.reasoningEffort)==="none"&&v.supportsNonReasoningParameters||(L.temperature!=null&&(L.temperature=void 0,_.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),L.top_p!=null&&(L.top_p=void 0,_.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((y==null?void 0:y.reasoningEffort)!=null&&_.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(y==null?void 0:y.reasoningSummary)!=null&&_.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(y==null?void 0:y.serviceTier)==="flex"&&!v.supportsFlexProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete L.service_tier),(y==null?void 0:y.serviceTier)==="priority"&&!v.supportsPriorityProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete L.service_tier);const{tools:V,toolChoice:J,toolWarnings:be}=await L0({tools:p,toolChoice:g,strictJsonSchema:S});return{webSearchToolName:D,args:{...L,tools:V,tool_choice:J},warnings:[..._,...be],store:oe}}async doGenerate(e){var t,n,r,o,i,a,s,l,c,p,g,x,T,I,E,k,_,v,y,$,b,S,m,N,Z,B,D,oe;const{args:L,warnings:V,webSearchToolName:J}=await this.getArgs(e),be=this.config.url({path:"/responses",modelId:this.modelId}),Y=this.config.provider.replace(".responses",""),{responseHeaders:we,value:ge,rawValue:Ce}=await De({url:be,headers:ze(this.config.headers(),e.headers),body:L,failedResponseHandler:ft,successfulResponseHandler:Be(P0),abortSignal:e.abortSignal,fetch:this.config.fetch});if(ge.error)throw new $e({message:ge.error.message,url:be,requestBodyValues:L,statusCode:400,responseHeaders:we,responseBody:Ce,isRetryable:!1});const le=[],he=[];let de=!1;for(const C of ge.output)switch(C.type){case"reasoning":{C.summary.length===0&&C.summary.push({type:"summary_text",text:""});for(const H of C.summary)le.push({type:"reasoning",text:H.text,providerMetadata:{[Y]:{itemId:C.id,reasoningEncryptedContent:(t=C.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"image_generation",result:{result:C.result},providerExecuted:!0});break}case"local_shell_call":{le.push({type:"tool-call",toolCallId:C.call_id,toolName:"local_shell",input:JSON.stringify({action:C.action}),providerMetadata:{[Y]:{itemId:C.id}}});break}case"message":{for(const H of C.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&H.logprobs&&he.push(H.logprobs),le.push({type:"text",text:H.text,providerMetadata:{[Y]:{itemId:C.id,...C.phase!=null&&{phase:C.phase}}}});for(const re of H.annotations)re.type==="url_citation"?le.push({type:"source",sourceType:"url",id:(a=(i=(o=this.config).generateId)==null?void 0:i.call(o))!=null?a:Ge(),url:re.url,title:re.title}):re.type==="file_citation"?le.push({type:"source",sourceType:"document",id:(c=(l=(s=this.config).generateId)==null?void 0:l.call(s))!=null?c:Ge(),mediaType:"text/plain",title:(g=(p=re.quote)!=null?p:re.filename)!=null?g:"Document",filename:(x=re.filename)!=null?x:re.file_id,...re.file_id?{providerMetadata:{[Y]:{fileId:re.file_id}}}:{}}):re.type==="container_file_citation"?le.push({type:"source",sourceType:"document",id:(E=(I=(T=this.config).generateId)==null?void 0:I.call(T))!=null?E:Ge(),mediaType:"text/plain",title:(_=(k=re.filename)!=null?k:re.file_id)!=null?_:"Document",filename:(v=re.filename)!=null?v:re.file_id,providerMetadata:{[Y]:{fileId:re.file_id,containerId:re.container_id,...re.index!=null?{index:re.index}:{}}}}):re.type==="file_path"&&le.push({type:"source",sourceType:"document",id:(b=($=(y=this.config).generateId)==null?void 0:$.call(y))!=null?b:Ge(),mediaType:"application/octet-stream",title:re.file_id,filename:re.file_id,providerMetadata:{[Y]:{fileId:re.file_id,...re.index!=null?{index:re.index}:{}}}})}break}case"function_call":{de=!0,le.push({type:"tool-call",toolCallId:C.call_id,toolName:C.name,input:C.arguments,providerMetadata:{[Y]:{itemId:C.id}}});break}case"web_search_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:J??"web_search",input:JSON.stringify({}),providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:J??"web_search",result:bs(C.action),providerExecuted:!0});break}case"computer_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"computer_use",input:"",providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:C.status||"completed"},providerExecuted:!0});break}case"file_search_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"file_search",input:"{}",providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"file_search",result:{queries:C.queries,results:(m=(S=C.results)==null?void 0:S.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?m:null},providerExecuted:!0});break}case"code_interpreter_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"code_interpreter",input:JSON.stringify({code:C.code,containerId:C.container_id}),providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"code_interpreter",result:{outputs:C.outputs},providerExecuted:!0});break}}const ke={[Y]:{...ge.id!=null?{responseId:ge.id}:{}}};he.length>0&&(ke[Y].logprobs=he),typeof ge.service_tier=="string"&&(ke[Y].serviceTier=ge.service_tier);const O=ge.usage,ne=ws(O);return ne!=null&&(ke[Y].usage=ne),{content:le,finishReason:ys({finishReason:(N=ge.incomplete_details)==null?void 0:N.reason,hasFunctionCall:de}),usage:{inputTokens:O.input_tokens,outputTokens:O.output_tokens,totalTokens:O.input_tokens+O.output_tokens,reasoningTokens:(B=(Z=O.output_tokens_details)==null?void 0:Z.reasoning_tokens)!=null?B:void 0,cachedInputTokens:(oe=(D=O.input_tokens_details)==null?void 0:D.cached_tokens)!=null?oe:void 0},request:{body:L},response:{id:ge.id,timestamp:new Date(ge.created_at*1e3),modelId:ge.model,headers:we,body:Ce},providerMetadata:ke,warnings:V}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r,store:o}=await this.getArgs(e),{responseHeaders:i,value:a}=await De({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:ft,successfulResponseHandler:$n(R0),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this,l=this.config.provider.replace(".responses","");let c="unknown";const p={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},g=[];let x=null;const T={},I=[];let E,k=!1;const _={};let v,y;return{stream:a.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:n})},transform($,b){var S,m,N,Z,B,D,oe,L,V,J,be,Y,we,ge,Ce,le,he,de,ke,O,ne,C,H,re;if(e.includeRawChunks&&b.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){c="error",b.enqueue({type:"error",error:$.error});return}const w=$.value;if(vs(w))w.item.type==="function_call"?(T[w.output_index]={toolName:w.item.name,toolCallId:w.item.call_id},b.enqueue({type:"tool-input-start",id:w.item.call_id,toolName:w.item.name})):w.item.type==="web_search_call"?(T[w.output_index]={toolName:r??"web_search",toolCallId:w.item.id},b.enqueue({type:"tool-input-start",id:w.item.id,toolName:r??"web_search",providerExecuted:!0}),b.enqueue({type:"tool-input-end",id:w.item.id}),b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:r??"web_search",input:JSON.stringify({}),providerExecuted:!0})):w.item.type==="computer_call"?(T[w.output_index]={toolName:"computer_use",toolCallId:w.item.id},b.enqueue({type:"tool-input-start",id:w.item.id,toolName:"computer_use",providerExecuted:!0})):w.item.type==="code_interpreter_call"?(T[w.output_index]={toolName:"code_interpreter",toolCallId:w.item.id,codeInterpreter:{containerId:w.item.container_id}},b.enqueue({type:"tool-input-start",id:w.item.id,toolName:"code_interpreter",providerExecuted:!0}),b.enqueue({type:"tool-input-delta",id:w.item.id,delta:`{"containerId":"${w.item.container_id}","code":"`})):w.item.type==="file_search_call"?b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):w.item.type==="image_generation_call"?b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):w.item.type==="message"?(I.splice(0,I.length),E=(S=w.item.phase)!=null?S:void 0,b.enqueue({type:"text-start",id:w.item.id,providerMetadata:{[l]:{itemId:w.item.id,...w.item.phase!=null&&{phase:w.item.phase}}}})):vs(w)&&w.item.type==="reasoning"&&(_[w.item.id]={encryptedContent:w.item.encrypted_content,summaryParts:{0:"active"}},b.enqueue({type:"reasoning-start",id:`${w.item.id}:0`,providerMetadata:{[l]:{itemId:w.item.id,reasoningEncryptedContent:(m=w.item.encrypted_content)!=null?m:null}}}));else if(Z0(w)){if(w.item.type==="message"){const ie=(N=w.item.phase)!=null?N:E;E=void 0,b.enqueue({type:"text-end",id:w.item.id,providerMetadata:{[l]:{itemId:w.item.id,...ie!=null&&{phase:ie},...I.length>0&&{annotations:I}}}})}else if(w.item.type==="function_call")T[w.output_index]=void 0,k=!0,b.enqueue({type:"tool-input-end",id:w.item.call_id}),b.enqueue({type:"tool-call",toolCallId:w.item.call_id,toolName:w.item.name,input:w.item.arguments,providerMetadata:{[l]:{itemId:w.item.id}}});else if(w.item.type==="web_search_call")T[w.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:r??"web_search",result:bs(w.item.action),providerExecuted:!0});else if(w.item.type==="computer_call")T[w.output_index]=void 0,b.enqueue({type:"tool-input-end",id:w.item.id}),b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:w.item.status||"completed"},providerExecuted:!0});else if(w.item.type==="file_search_call")T[w.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"file_search",result:{queries:w.item.queries,results:(B=(Z=w.item.results)==null?void 0:Z.map(ie=>({attributes:ie.attributes,fileId:ie.file_id,filename:ie.filename,score:ie.score,text:ie.text})))!=null?B:null},providerExecuted:!0});else if(w.item.type==="code_interpreter_call")T[w.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"code_interpreter",result:{outputs:w.item.outputs},providerExecuted:!0});else if(w.item.type==="image_generation_call")b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"image_generation",result:{result:w.item.result},providerExecuted:!0});else if(w.item.type==="local_shell_call")T[w.output_index]=void 0,b.enqueue({type:"tool-call",toolCallId:w.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:w.item.action.command,timeoutMs:w.item.action.timeout_ms,user:w.item.action.user,workingDirectory:w.item.action.working_directory,env:w.item.action.env}}),providerMetadata:{[l]:{itemId:w.item.id}}});else if(w.item.type==="reasoning"){const ie=_[w.item.id],nt=Object.entries(ie.summaryParts).filter(([Pt,rt])=>rt==="active"||rt==="can-conclude").map(([Pt])=>Pt);for(const Pt of nt)b.enqueue({type:"reasoning-end",id:`${w.item.id}:${Pt}`,providerMetadata:{[l]:{itemId:w.item.id,reasoningEncryptedContent:(D=w.item.encrypted_content)!=null?D:null}}});delete _[w.item.id]}}else if(B0(w)){const ie=T[w.output_index];ie!=null&&b.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:w.delta})}else if(V0(w)){const ie=T[w.output_index];ie!=null&&b.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:JSON.stringify(w.delta).slice(1,-1)})}else if(F0(w)){const ie=T[w.output_index];ie!=null&&(b.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:'"}'}),b.enqueue({type:"tool-input-end",id:ie.toolCallId}),b.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:w.code,containerId:ie.codeInterpreter.containerId}),providerExecuted:!0}))}else if(U0(w))x=w.response.id,b.enqueue({type:"response-metadata",id:w.response.id,timestamp:new Date(w.response.created_at*1e3),modelId:w.response.model});else if(D0(w))b.enqueue({type:"text-delta",id:w.item_id,delta:w.delta}),(L=(oe=e.providerOptions)==null?void 0:oe.openai)!=null&&L.logprobs&&w.logprobs&&g.push(w.logprobs);else if(w.type==="response.reasoning_summary_part.added"){if(w.summary_index>0){const ie=_[w.item_id];ie.summaryParts[w.summary_index]="active";for(const nt of Object.keys(ie.summaryParts))ie.summaryParts[nt]==="can-conclude"&&(b.enqueue({type:"reasoning-end",id:`${w.item_id}:${nt}`,providerMetadata:{[l]:{itemId:w.item_id}}}),ie.summaryParts[nt]="concluded");b.enqueue({type:"reasoning-start",id:`${w.item_id}:${w.summary_index}`,providerMetadata:{[l]:{itemId:w.item_id,reasoningEncryptedContent:(J=(V=_[w.item_id])==null?void 0:V.encryptedContent)!=null?J:null}}})}}else w.type==="response.reasoning_summary_text.delta"?b.enqueue({type:"reasoning-delta",id:`${w.item_id}:${w.summary_index}`,delta:w.delta,providerMetadata:{[l]:{itemId:w.item_id}}}):w.type==="response.reasoning_summary_part.done"?o?(b.enqueue({type:"reasoning-end",id:`${w.item_id}:${w.summary_index}`,providerMetadata:{[l]:{itemId:w.item_id}}}),_[w.item_id].summaryParts[w.summary_index]="concluded"):_[w.item_id].summaryParts[w.summary_index]="can-conclude":j0(w)?(c=ys({finishReason:(be=w.response.incomplete_details)==null?void 0:be.reason,hasFunctionCall:k}),p.inputTokens=w.response.usage.input_tokens,p.outputTokens=w.response.usage.output_tokens,p.totalTokens=w.response.usage.input_tokens+w.response.usage.output_tokens,p.reasoningTokens=(we=(Y=w.response.usage.output_tokens_details)==null?void 0:Y.reasoning_tokens)!=null?we:void 0,p.cachedInputTokens=(Ce=(ge=w.response.usage.input_tokens_details)==null?void 0:ge.cached_tokens)!=null?Ce:void 0,typeof w.response.service_tier=="string"&&(v=w.response.service_tier),y=ws(w.response.usage)):q0(w)?(I.push(w.annotation),w.annotation.type==="url_citation"?b.enqueue({type:"source",sourceType:"url",id:(de=(he=(le=s.config).generateId)==null?void 0:he.call(le))!=null?de:Ge(),url:w.annotation.url,title:w.annotation.title}):w.annotation.type==="file_citation"&&b.enqueue({type:"source",sourceType:"document",id:(ne=(O=(ke=s.config).generateId)==null?void 0:O.call(ke))!=null?ne:Ge(),mediaType:"text/plain",title:(H=(C=w.annotation.quote)!=null?C:w.annotation.filename)!=null?H:"Document",filename:(re=w.annotation.filename)!=null?re:w.annotation.file_id,...w.annotation.file_id?{providerMetadata:{[l]:{fileId:w.annotation.file_id}}}:{}})):G0(w)&&b.enqueue({type:"error",error:w})},flush($){const b={[l]:{responseId:x}};g.length>0&&(b[l].logprobs=g),v!==void 0&&(b[l].serviceTier=v),y!=null&&(b[l].usage=y),$.enqueue({type:"finish",finishReason:c,usage:p,providerMetadata:b})}})),request:{body:t},response:{headers:i}}}};function D0(e){return e.type==="response.output_text.delta"}function Z0(e){return e.type==="response.output_item.done"}function j0(e){return e.type==="response.completed"||e.type==="response.incomplete"}function U0(e){return e.type==="response.created"}function B0(e){return e.type==="response.function_call_arguments.delta"}function V0(e){return e.type==="response.code_interpreter_call_code.delta"}function F0(e){return e.type==="response.code_interpreter_call_code.done"}function vs(e){return e.type==="response.output_item.added"}function q0(e){return e.type==="response.output_text.annotation.added"}function G0(e){return e.type==="error"}function bs(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function ws(e){var t,n,r;const o=(t=e==null?void 0:e.input_tokens_details)==null?void 0:t.orchestration_input_tokens,i=(n=e==null?void 0:e.input_tokens_details)==null?void 0:n.orchestration_input_cached_tokens,a=(r=e==null?void 0:e.output_tokens_details)==null?void 0:r.orchestration_output_tokens;if(!(o==null&&i==null&&a==null))return{...o!=null&&{orchestrationInputTokens:o},...i!=null&&{orchestrationInputCachedTokens:i},...a!=null&&{orchestrationOutputTokens:a}}}var H0=Ee(()=>j(d({instructions:u().nullish(),speed:f().min(.25).max(4).default(1).nullish()}))),J0=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:i,providerOptions:a}){const s=[],l=await Je({provider:"openai",providerOptions:a,schema:H0}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?c.response_format=n:s.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const p={};for(const g in p){const x=p[g];x!==void 0&&(c[g]=x)}}return i&&s.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:c,warnings:s}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:i,warnings:a}=await this.getArgs(e),{value:s,responseHeaders:l,rawValue:c}=await De({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),body:i,failedResponseHandler:ft,successfulResponseHandler:b_(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:a,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},K0=Ee(()=>j(d({text:u(),language:u().nullish(),duration:f().nullish(),words:R(d({word:u(),start:f(),end:f()})).nullish(),segments:R(d({id:f(),seek:f(),start:f(),end:f(),text:u(),tokens:R(f()),temperature:f(),avg_logprob:f(),compression_ratio:f(),no_speech_prob:f()})).nullish()}))),W0=Ee(()=>j(d({include:R(u()).optional(),language:u().optional(),prompt:u().optional(),temperature:f().min(0).max(1).default(0).optional(),timestampGranularities:R(X(["word","segment"])).default(["segment"]).optional()}))),xs={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Y0=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await Je({provider:"openai",providerOptions:n,schema:W0}),i=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([pr(e)]);i.append("model",this.modelId);const s=s_(t);if(i.append("file",new File([a],"audio",{type:t}),`audio.${s}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,p]of Object.entries(l))if(p!=null)if(Array.isArray(p))for(const g of p)i.append(`${c}[]`,String(g));else i.append(c,String(p))}return{formData:i,warnings:r}}async doGenerate(e){var t,n,r,o,i,a,s,l;const c=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:p,warnings:g}=await this.getArgs(e),{value:x,responseHeaders:T,rawValue:I}=await y_({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:ze(this.config.headers(),e.headers),formData:p,failedResponseHandler:ft,successfulResponseHandler:Be(K0),abortSignal:e.abortSignal,fetch:this.config.fetch}),E=x.language!=null&&x.language in xs?xs[x.language]:void 0;return{text:x.text,segments:(s=(a=(o=x.segments)==null?void 0:o.map(k=>({text:k.text,startSecond:k.start,endSecond:k.end})))!=null?a:(i=x.words)==null?void 0:i.map(k=>({text:k.word,startSecond:k.start,endSecond:k.end})))!=null?s:[],language:E,durationInSeconds:(l=x.duration)!=null?l:void 0,warnings:g,response:{timestamp:c,modelId:this.modelId,headers:T,body:I}}}},X0="2.0.110";function Vn(e={}){var t,n;const r=(t=So(Dt({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",i=()=>Gt({Authorization:`Bearer ${nu({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${X0}`),a=E=>new Gw(E,{provider:`${o}.chat`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),s=E=>new Ww(E,{provider:`${o}.completion`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),l=E=>new Qw(E,{provider:`${o}.embedding`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),c=E=>new i0(E,{provider:`${o}.image`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),p=E=>new Y0(E,{provider:`${o}.transcription`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),g=E=>new J0(E,{provider:`${o}.speech`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),x=E=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(E)},T=E=>new z0(E,{provider:`${o}.responses`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch,fileIdPrefixes:["file-"]}),I=function(E){return x(E)};return I.languageModel=x,I.chat=a,I.completion=s,I.responses=T,I.embedding=l,I.textEmbedding=l,I.textEmbeddingModel=l,I.image=c,I.imageModel=c,I.transcription=p,I.transcriptionModel=p,I.speech=g,I.speechModel=g,I.tools=O0,I}Vn();function ks(e){if(e)for(const t of e)t.role==="developer"&&(t.role="system")}function Q0(e=globalThis.fetch.bind(globalThis)){return async(t,n)=>{if(!(n!=null&&n.body)||typeof n.body!="string"||!n.body.includes('"role":"developer"')&&!n.body.includes('"role": "developer"'))return e(t,n);try{const r=JSON.parse(n.body);return ks(r.messages),ks(r.input),e(t,{...n,body:JSON.stringify(r)})}catch{return e(t,n)}}}function Mo(e){if(!e.apiKey.trim())throw new Error("API key is required. Run LLMSETTINGS to configure a model.");const t=ao(e.baseUrl);return e.protocol==="anthropic-messages"?gc({apiKey:e.apiKey,baseURL:t,headers:Ss})(e.model):e.protocol==="openai-responses"?Vn({apiKey:e.apiKey,baseURL:t}).responses(e.model):e.kind==="builtin"&&e.provider==="openai"?Vn({apiKey:e.apiKey,baseURL:t}).chat(e.model):Vn({apiKey:e.apiKey,baseURL:t,fetch:Q0()}).chat(e.model)}const ex=Rb(),Lo=e=>Promise.all(e.map(async t=>t.isUrlSupportedByModel||t.url.protocol==="data:"?null:ex({url:t.url}))),tx=`You read text from images of CAD drawings.
501
-
502
- The image shows one line of text drawn as strokes (for example SHX single-line
503
- fonts), dark on white, upright. Reply with exactly the text shown, preserving
504
- case, digits, punctuation, CAD symbols such as Ø ± ° and spaces between words.
505
- Do not explain, translate, quote or add anything else. If nothing is legible,
506
- reply with an empty message.`,nx=`You read text from images of CAD drawings.
507
-
508
- You get several numbered images. Each shows one line of text drawn as strokes
509
- (for example SHX single-line fonts), dark on white, upright. Read every image
510
- exactly: preserve case, digits, punctuation, CAD symbols such as Ø ± ° and
511
- spaces between words. Do not explain, translate or correct the text.
512
-
513
- Reply with only a JSON array of strings, one per image in the given order,
514
- and exactly as many entries as images. Use "" for an image that is not legible.`,oo=12e4;async function Ic(e,t){const n=new AbortController,r=()=>n.abort(e==null?void 0:e.reason);e!=null&&e.aborted?r():e==null||e.addEventListener("abort",r,{once:!0});let o;const i=new Promise((a,s)=>{o=setTimeout(()=>{const l=new Error(z.llmT("recognitionTimeout",{seconds:Math.round(oo/1e3)}));n.abort(l),s(l)},oo)});try{return await Promise.race([t(n.signal),i])}finally{clearTimeout(o),e==null||e.removeEventListener("abort",r)}}const Is=20,Ts=3;async function rx(e){const t=await Sn(),n=Tn(t),r=e.images.map(()=>{});if(!n||e.images.length===0)return r;const o=[];for(let l=0;l<e.images.length;l+=Is)o.push(e.images.slice(l,l+Is));const i=async l=>{const{text:c}=await Ic(e.signal,p=>uc({model:Mo(n),system:nx,abortSignal:p,experimental_download:Lo,messages:[{role:"user",content:[{type:"text",text:[`Read the text in these ${l.length} images.`,e.locale?`UI language: ${e.locale}.`:""].filter(Boolean).join(" ")},...l.flatMap((g,x)=>[{type:"text",text:`Image ${x+1}:`},{type:"image",image:g}])]}]}));return Tc(c,l.length)},a=[];for(let l=0;l<o.length;l+=Ts)a.push(...await Promise.allSettled(o.slice(l,l+Ts).map(i)));const s=a.find(l=>l.status==="rejected");if(s&&a.every(l=>l.status==="rejected"))throw s.reason;return a.flatMap((l,c)=>l.status==="fulfilled"?l.value:o[c].map(()=>{}))}function Tc(e,t){const n=e.indexOf("["),r=e.lastIndexOf("]"),o=n>=0&&r>n?JSON.parse(e.slice(n,r+1)):null;if(!Array.isArray(o))throw new Error(`Unexpected text recognition answer: ${e.trim().slice(0,80)}`);return Array.from({length:t},(i,a)=>typeof o[a]=="string"?zo(o[a]):void 0)}async function ox(e){const t=await Sn(),n=Tn(t);if(!n)return;const r=[e.locale?`UI language: ${e.locale}.`:"",e.hint?`The previous line of this drawing read: "${e.hint}".`:""].filter(Boolean),{text:o}=await Ic(e.signal,i=>uc({model:Mo(n),system:tx,abortSignal:i,experimental_download:Lo,messages:[{role:"user",content:[{type:"text",text:["Read the text in this image.",...r].join(" ")},{type:"image",image:e.image}]}]}));return zo(o)}function zo(e){let t=e.trim();return t=t.replace(/^```[a-z]*\s*|\s*```$/gi,"").trim(),(/^(["'“”‘’`]).*\1$/.test(t)||/^“.*”$/.test(t))&&(t=t.slice(1,-1).trim()),t||void 0}exports.LLM_PLUGIN_NAME=z.LLM_PLUGIN_NAME;exports.LLM_PLUGIN_TRIGGERS=z.LLM_PLUGIN_TRIGGERS;exports.LLM_SERVICE_ID=z.LLM_SERVICE_ID;exports.llmT=z.llmT;exports.mergeLlmI18nIntoVueI18n=z.mergeLlmI18nIntoVueI18n;exports.registerLlmI18n=z.registerLlmI18n;exports.ACAP_LLM_API_PROTOCOLS=Os;exports.ACAP_LLM_BUILTIN_PROVIDERS=Vt;exports.ACAP_LLM_BUILTIN_PROVIDER_IDS=so;exports.ACAP_LLM_CUSTOM_PROVIDER_ID_PATTERN=lo;exports.ACAP_LLM_RECOGNITION_TIMEOUT_MS=oo;exports.AcApLlmModelListingError=Yt;exports.AcApLlmPlugin=qs;exports.AcApLlmSettingsCmd=Fs;exports.AcUiLlmSettingsDialog=Gn;exports.acapLlmActiveModelSupportsVision=Ds;exports.acapLlmAreProvidersEqual=Bs;exports.acapLlmBuiltinProviderLabel=co;exports.acapLlmCleanRecognizedText=zo;exports.acapLlmCreateBuiltinProvider=At;exports.acapLlmCreateCustomProvider=qn;exports.acapLlmCreateDefaultConfig=pn;exports.acapLlmCreateModel=Mo;exports.acapLlmEffectiveBaseUrl=mn;exports.acapLlmEffectiveModels=Ft;exports.acapLlmEnsureActiveProvider=uo;exports.acapLlmFetchAvailableModels=As;exports.acapLlmFindProvider=In;exports.acapLlmGetStatus=Bc;exports.acapLlmGuessModelVision=Xt;exports.acapLlmIsBuiltinProviderId=Qe;exports.acapLlmLoadConfig=Sn;exports.acapLlmMigrateLegacySettings=Us;exports.acapLlmModelChoices=Vs;exports.acapLlmModelLabel=Ns;exports.acapLlmModelListingUrl=Es;exports.acapLlmNormalizeBaseUrl=ao;exports.acapLlmOnConfigChange=Uc;exports.acapLlmParseBatchText=Tc;exports.acapLlmParseModelListing=Cs;exports.acapLlmProviderLabel=po;exports.acapLlmRecognizeText=ox;exports.acapLlmRecognizeTextBatch=rx;exports.acapLlmRemoveProvider=js;exports.acapLlmResolveActiveSettings=zs;exports.acapLlmResolveVisionSettings=Tn;exports.acapLlmRestoreModelEntries=Dr;exports.acapLlmSaveConfig=Zr;exports.acapLlmSkipDataUrlDownload=Lo;exports.acapLlmUpsertProvider=Zs;exports.acapLlmVisionAfterIdEdit=$s;exports.createLlmPlugin=Yc;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./cad-llm-plugin-cad-llm-plugin-DlRbTdyT.js"),e=require("./cad-llm-plugin-cad-llm-plugin-register-CwDcWhV5.js");exports.ACAP_LLM_API_PROTOCOLS=a.ACAP_LLM_API_PROTOCOLS;exports.ACAP_LLM_BUILTIN_PROVIDERS=a.ACAP_LLM_BUILTIN_PROVIDERS;exports.ACAP_LLM_BUILTIN_PROVIDER_IDS=a.ACAP_LLM_BUILTIN_PROVIDER_IDS;exports.ACAP_LLM_CUSTOM_PROVIDER_ID_PATTERN=a.ACAP_LLM_CUSTOM_PROVIDER_ID_PATTERN;exports.ACAP_LLM_RECOGNITION_TIMEOUT_MS=a.ACAP_LLM_RECOGNITION_TIMEOUT_MS;exports.AcApLlmModelListingError=a.AcApLlmModelListingError;exports.AcApLlmPlugin=a.AcApLlmPlugin;exports.AcApLlmSettingsCmd=a.AcApLlmSettingsCmd;exports.AcUiLlmSettingsDialog=a.AcUiLlmSettingsDialog;exports.acapLlmActiveModelSupportsVision=a.acapLlmActiveModelSupportsVision;exports.acapLlmAreProvidersEqual=a.acapLlmAreProvidersEqual;exports.acapLlmBuiltinProviderLabel=a.acapLlmBuiltinProviderLabel;exports.acapLlmCleanRecognizedText=a.acapLlmCleanRecognizedText;exports.acapLlmCreateBuiltinProvider=a.acapLlmCreateBuiltinProvider;exports.acapLlmCreateCustomProvider=a.acapLlmCreateCustomProvider;exports.acapLlmCreateDefaultConfig=a.acapLlmCreateDefaultConfig;exports.acapLlmCreateModel=a.acapLlmCreateModel;exports.acapLlmEffectiveBaseUrl=a.acapLlmEffectiveBaseUrl;exports.acapLlmEffectiveModels=a.acapLlmEffectiveModels;exports.acapLlmEnsureActiveProvider=a.acapLlmEnsureActiveProvider;exports.acapLlmFetchAvailableModels=a.acapLlmFetchAvailableModels;exports.acapLlmFindProvider=a.acapLlmFindProvider;exports.acapLlmGetStatus=a.acapLlmGetStatus;exports.acapLlmGuessModelVision=a.acapLlmGuessModelVision;exports.acapLlmIsBuiltinProviderId=a.acapLlmIsBuiltinProviderId;exports.acapLlmLoadConfig=a.acapLlmLoadConfig;exports.acapLlmMigrateLegacySettings=a.acapLlmMigrateLegacySettings;exports.acapLlmModelChoices=a.acapLlmModelChoices;exports.acapLlmModelLabel=a.acapLlmModelLabel;exports.acapLlmModelListingUrl=a.acapLlmModelListingUrl;exports.acapLlmNormalizeBaseUrl=a.acapLlmNormalizeBaseUrl;exports.acapLlmOnConfigChange=a.acapLlmOnConfigChange;exports.acapLlmParseBatchText=a.acapLlmParseBatchText;exports.acapLlmParseModelListing=a.acapLlmParseModelListing;exports.acapLlmProviderLabel=a.acapLlmProviderLabel;exports.acapLlmRecognizeText=a.acapLlmRecognizeText;exports.acapLlmRecognizeTextBatch=a.acapLlmRecognizeTextBatch;exports.acapLlmRemoveProvider=a.acapLlmRemoveProvider;exports.acapLlmResolveActiveSettings=a.acapLlmResolveActiveSettings;exports.acapLlmResolveVisionSettings=a.acapLlmResolveVisionSettings;exports.acapLlmResolveVisionSettingsForModel=a.acapLlmResolveVisionSettingsForModel;exports.acapLlmResolveVisionSettingsForProvider=a.acapLlmResolveVisionSettingsForProvider;exports.acapLlmRestoreModelEntries=a.acapLlmRestoreModelEntries;exports.acapLlmSaveConfig=a.acapLlmSaveConfig;exports.acapLlmSkipDataUrlDownload=a.acapLlmSkipDataUrlDownload;exports.acapLlmSyncOcrRecognizers=a.acapLlmSyncOcrRecognizers;exports.acapLlmUpsertProvider=a.acapLlmUpsertProvider;exports.acapLlmVisionAfterIdEdit=a.acapLlmVisionAfterIdEdit;exports.acapLlmWatchOcrRecognizers=a.acapLlmWatchOcrRecognizers;exports.createLlmPlugin=a.createLlmPlugin;exports.LLM_OCR_ID_PREFIX=e.LLM_OCR_ID_PREFIX;exports.LLM_PLUGIN_NAME=e.LLM_PLUGIN_NAME;exports.LLM_PLUGIN_TRIGGERS=e.LLM_PLUGIN_TRIGGERS;exports.LLM_SERVICE_ID=e.LLM_SERVICE_ID;exports.acapLlmIsOcrRecognizerId=e.acapLlmIsOcrRecognizerId;exports.acapLlmOcrRecognizerId=e.acapLlmOcrRecognizerId;exports.acapLlmParseOcrRecognizerId=e.acapLlmParseOcrRecognizerId;exports.llmT=e.llmT;exports.mergeLlmI18nIntoVueI18n=e.mergeLlmI18nIntoVueI18n;exports.registerLlmI18n=e.registerLlmI18n;