bangonit 0.3.4 → 0.4.1

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 (47) hide show
  1. package/README.md +24 -33
  2. package/app/desktopapp/dist/main/index.js +4 -2
  3. package/app/desktopapp/dist/main/ipc.js +96 -20
  4. package/app/desktopapp/dist/main/preload.js +4 -3
  5. package/app/desktopapp/dist/main/tabs.js +43 -3
  6. package/app/replay/dist/replay.css +1 -1
  7. package/app/replay/dist/replay.js +24 -24
  8. package/app/webapp/.next/standalone/app/webapp/.next/BUILD_ID +1 -1
  9. package/app/webapp/.next/standalone/app/webapp/.next/app-build-manifest.json +1 -1
  10. package/app/webapp/.next/standalone/app/webapp/.next/app-path-routes-manifest.json +1 -1
  11. package/app/webapp/.next/standalone/app/webapp/.next/build-manifest.json +2 -2
  12. package/app/webapp/.next/standalone/app/webapp/.next/prerender-manifest.json +1 -1
  13. package/app/webapp/.next/standalone/app/webapp/.next/server/app/_not-found.html +1 -1
  14. package/app/webapp/.next/standalone/app/webapp/.next/server/app/_not-found.rsc +1 -1
  15. package/app/webapp/.next/standalone/app/webapp/.next/server/app/app/page.js +3 -3
  16. package/app/webapp/.next/standalone/app/webapp/.next/server/app/app/page_client-reference-manifest.js +1 -1
  17. package/app/webapp/.next/standalone/app/webapp/.next/server/app/app.html +1 -1
  18. package/app/webapp/.next/standalone/app/webapp/.next/server/app/app.rsc +2 -2
  19. package/app/webapp/.next/standalone/app/webapp/.next/server/app/index.html +1 -1
  20. package/app/webapp/.next/standalone/app/webapp/.next/server/app/index.rsc +1 -1
  21. package/app/webapp/.next/standalone/app/webapp/.next/server/app/page.js +1 -1
  22. package/app/webapp/.next/standalone/app/webapp/.next/server/app-paths-manifest.json +2 -2
  23. package/app/webapp/.next/standalone/app/webapp/.next/server/chunks/124.js +9 -9
  24. package/app/webapp/.next/standalone/app/webapp/.next/server/chunks/708.js +5 -4
  25. package/app/webapp/.next/standalone/app/webapp/.next/server/pages/404.html +1 -1
  26. package/app/webapp/.next/standalone/app/webapp/.next/server/pages/500.html +1 -1
  27. package/app/webapp/.next/standalone/app/webapp/.next/server/server-reference-manifest.json +1 -1
  28. package/app/webapp/.next/standalone/app/webapp/.next/static/chunks/app/app/page-74ec5ee2f3d3d4a0.js +1 -0
  29. package/app/webapp/.next/standalone/package.json +7 -4
  30. package/app/webapp/.next/static/chunks/app/app/page-74ec5ee2f3d3d4a0.js +1 -0
  31. package/app/webapp/src/shared/api/chat.ts +7 -4
  32. package/app/webapp/src/shared/components/AppShell.tsx +6 -5
  33. package/app/webapp/src/shared/components/SessionView.tsx +4 -3
  34. package/app/webapp/src/shared/lib/browser/index.ts +17 -27
  35. package/app/webapp/src/shared/lib/browser/recorder.ts +13 -4
  36. package/app/webapp/src/shared/lib/browser/snapshot.ts +25 -5
  37. package/app/webapp/src/shared/lib/browser/types.ts +21 -6
  38. package/app/webapp/src/shared/types/global.d.ts +6 -4
  39. package/bin/src/cli/bangonit.js +19 -11
  40. package/package.json +7 -4
  41. package/scripts/regen-replays.sh +101 -0
  42. package/app/webapp/.next/standalone/app/webapp/.next/static/chunks/app/app/page-df00a757f649931a.js +0 -1
  43. package/app/webapp/.next/static/chunks/app/app/page-df00a757f649931a.js +0 -1
  44. /package/app/webapp/.next/standalone/app/webapp/.next/static/{bBZVP6sUilA3wyt0vYqDc → CfMl7etZBP4Q0LYMXf4ZP}/_buildManifest.js +0 -0
  45. /package/app/webapp/.next/standalone/app/webapp/.next/static/{bBZVP6sUilA3wyt0vYqDc → CfMl7etZBP4Q0LYMXf4ZP}/_ssgManifest.js +0 -0
  46. /package/app/webapp/.next/static/{bBZVP6sUilA3wyt0vYqDc → CfMl7etZBP4Q0LYMXf4ZP}/_buildManifest.js +0 -0
  47. /package/app/webapp/.next/static/{bBZVP6sUilA3wyt0vYqDc → CfMl7etZBP4Q0LYMXf4ZP}/_ssgManifest.js +0 -0
@@ -1,5 +1,5 @@
1
- "use strict";exports.id=124,exports.ids=[124],exports.modules={6939:e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,r)=>{for(var a in r)t(e,a,{get:r[a],enumerable:!0})})(o,{SYMBOL_FOR_REQ_CONTEXT:()=>i,getContext:()=>s}),e.exports=((e,o,i,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let l of a(o))n.call(e,l)||l===i||t(e,l,{get:()=>o[l],enumerable:!(s=r(o,l))||s.enumerable});return e})(t({},"__esModule",{value:!0}),o);let i=Symbol.for("@vercel/request-context");function s(){let e=globalThis;return e[i]?.get?.()??{}}},1552:(e,t,r)=>{Object.create;var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,i=(Object.getPrototypeOf,Object.prototype.hasOwnProperty),s={};((e,t)=>{for(var r in t)a(e,r,{get:t[r],enumerable:!0})})(s,{getVercelOidcToken:()=>d,getVercelOidcTokenSync:()=>c}),e.exports=((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of o(t))i.call(e,l)||l===r||a(e,l,{get:()=>t[l],enumerable:!(s=n(t,l))||s.enumerable});return e})(a({},"__esModule",{value:!0}),s);var l=r(6939),u=r(1403);async function d(){let e,t="";try{t=c()}catch(t){e=t}try{let[{getTokenPayload:e,isExpired:a},{refreshToken:n}]=await Promise.all([await r.e(361).then(r.t.bind(r,1934,23)),await r.e(136).then(r.t.bind(r,9136,23))]);(!t||a(e(t)))&&(await n(),t=c())}catch(r){let t=e instanceof Error?e.message:"";if(r instanceof Error&&(t=`${t}
2
- ${r.message}`),t)throw new u.VercelOidcTokenError(t);throw r}return t}function c(){let e=l.getContext().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return e}},489:(e,t,r)=>{var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,s={};((e,t)=>{for(var r in t)a(e,r,{get:t[r],enumerable:!0})})(s,{getContext:()=>u.getContext,getVercelOidcToken:()=>l.getVercelOidcToken,getVercelOidcTokenSync:()=>l.getVercelOidcTokenSync}),e.exports=((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of o(t))i.call(e,l)||l===r||a(e,l,{get:()=>t[l],enumerable:!(s=n(t,l))||s.enumerable});return e})(a({},"__esModule",{value:!0}),s);var l=r(1552),u=r(6939)},1403:e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,r)=>{for(var a in r)t(e,a,{get:r[a],enumerable:!0})})(o,{VercelOidcTokenError:()=>i}),e.exports=((e,o,i,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let l of a(o))n.call(e,l)||l===i||t(e,l,{get:()=>o[l],enumerable:!(s=r(o,l))||s.enumerable});return e})(t({},"__esModule",{value:!0}),o);class i extends Error{constructor(e,t){super(e),this.name="VercelOidcTokenError",this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}},3036:(e,t,r)=>{e.exports=r(517)},4523:(e,t,r)=>{r.d(t,{D3:()=>ek});var a=r(9519),n=r(6365),o=r(2943),i=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("error"),error:o.Ry({type:o.Z_(),message:o.Z_()})}))),s=(0,n.Sq)({errorSchema:i,errorToMessage:e=>e.error.message}),l=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("message"),id:o.Z_().nullish(),model:o.Z_().nullish(),content:o.IX(o.VK("type",[o.Ry({type:o.i0("text"),text:o.Z_(),citations:o.IX(o.VK("type",[o.Ry({type:o.i0("web_search_result_location"),cited_text:o.Z_(),url:o.Z_(),title:o.Z_(),encrypted_index:o.Z_()}),o.Ry({type:o.i0("page_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_page_number:o.Rx(),end_page_number:o.Rx()}),o.Ry({type:o.i0("char_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_char_index:o.Rx(),end_char_index:o.Rx()})])).optional()}),o.Ry({type:o.i0("thinking"),thinking:o.Z_(),signature:o.Z_()}),o.Ry({type:o.i0("redacted_thinking"),data:o.Z_()}),o.Ry({type:o.i0("compaction"),content:o.Z_()}),o.Ry({type:o.i0("tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),caller:o.G0([o.Ry({type:o.i0("code_execution_20250825"),tool_id:o.Z_()}),o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("server_tool_use"),id:o.Z_(),name:o.Z_(),input:o.IM(o.Z_(),o._4()).nullish(),caller:o.G0([o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("mcp_tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),server_name:o.Z_()}),o.Ry({type:o.i0("mcp_tool_result"),tool_use_id:o.Z_(),is_error:o.O7(),content:o.IX(o.G0([o.Z_(),o.Ry({type:o.i0("text"),text:o.Z_()})]))}),o.Ry({type:o.i0("web_fetch_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),retrieved_at:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),media_type:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),media_type:o.i0("text/plain"),data:o.Z_()})])})}),o.Ry({type:o.i0("web_fetch_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("web_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.IX(o.Ry({type:o.i0("web_search_result"),url:o.Z_(),title:o.Z_(),encrypted_content:o.Z_(),page_age:o.Z_().nullish()})),o.Ry({type:o.i0("web_search_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("code_execution_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("encrypted_code_execution_result"),encrypted_stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("bash_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("text_editor_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})])}),o.Ry({type:o.i0("tool_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("tool_search_tool_search_result"),tool_references:o.IX(o.Ry({type:o.i0("tool_reference"),tool_name:o.Z_()}))}),o.Ry({type:o.i0("tool_search_tool_result_error"),error_code:o.Z_()})])})])),stop_reason:o.Z_().nullish(),stop_sequence:o.Z_().nullish(),usage:o.d7({input_tokens:o.Rx(),output_tokens:o.Rx(),cache_creation_input_tokens:o.Rx().nullish(),cache_read_input_tokens:o.Rx().nullish(),iterations:o.IX(o.Ry({type:o.G0([o.i0("compaction"),o.i0("message")]),input_tokens:o.Rx(),output_tokens:o.Rx()})).nullish()}),container:o.Ry({expires_at:o.Z_(),id:o.Z_(),skills:o.IX(o.Ry({type:o.G0([o.i0("anthropic"),o.i0("custom")]),skill_id:o.Z_(),version:o.Z_()})).nullish()}).nullish(),context_management:o.Ry({applied_edits:o.IX(o.G0([o.Ry({type:o.i0("clear_tool_uses_20250919"),cleared_tool_uses:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("clear_thinking_20251015"),cleared_thinking_turns:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("compact_20260112")})]))}).nullish()}))),u=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("message_start"),message:o.Ry({id:o.Z_().nullish(),model:o.Z_().nullish(),role:o.Z_().nullish(),usage:o.d7({input_tokens:o.Rx(),cache_creation_input_tokens:o.Rx().nullish(),cache_read_input_tokens:o.Rx().nullish()}),content:o.IX(o.VK("type",[o.Ry({type:o.i0("tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),caller:o.G0([o.Ry({type:o.i0("code_execution_20250825"),tool_id:o.Z_()}),o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()})])).nullish(),stop_reason:o.Z_().nullish(),container:o.Ry({expires_at:o.Z_(),id:o.Z_()}).nullish()})}),o.Ry({type:o.i0("content_block_start"),index:o.Rx(),content_block:o.VK("type",[o.Ry({type:o.i0("text"),text:o.Z_()}),o.Ry({type:o.i0("thinking"),thinking:o.Z_()}),o.Ry({type:o.i0("tool_use"),id:o.Z_(),name:o.Z_(),input:o.IM(o.Z_(),o._4()).optional(),caller:o.G0([o.Ry({type:o.i0("code_execution_20250825"),tool_id:o.Z_()}),o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("redacted_thinking"),data:o.Z_()}),o.Ry({type:o.i0("compaction"),content:o.Z_().nullish()}),o.Ry({type:o.i0("server_tool_use"),id:o.Z_(),name:o.Z_(),input:o.IM(o.Z_(),o._4()).nullish(),caller:o.G0([o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("mcp_tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),server_name:o.Z_()}),o.Ry({type:o.i0("mcp_tool_result"),tool_use_id:o.Z_(),is_error:o.O7(),content:o.IX(o.G0([o.Z_(),o.Ry({type:o.i0("text"),text:o.Z_()})]))}),o.Ry({type:o.i0("web_fetch_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),retrieved_at:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),media_type:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),media_type:o.i0("text/plain"),data:o.Z_()})])})}),o.Ry({type:o.i0("web_fetch_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("web_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.IX(o.Ry({type:o.i0("web_search_result"),url:o.Z_(),title:o.Z_(),encrypted_content:o.Z_(),page_age:o.Z_().nullish()})),o.Ry({type:o.i0("web_search_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("code_execution_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("encrypted_code_execution_result"),encrypted_stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("bash_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("text_editor_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})])}),o.Ry({type:o.i0("tool_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("tool_search_tool_search_result"),tool_references:o.IX(o.Ry({type:o.i0("tool_reference"),tool_name:o.Z_()}))}),o.Ry({type:o.i0("tool_search_tool_result_error"),error_code:o.Z_()})])})])}),o.Ry({type:o.i0("content_block_delta"),index:o.Rx(),delta:o.VK("type",[o.Ry({type:o.i0("input_json_delta"),partial_json:o.Z_()}),o.Ry({type:o.i0("text_delta"),text:o.Z_()}),o.Ry({type:o.i0("thinking_delta"),thinking:o.Z_()}),o.Ry({type:o.i0("signature_delta"),signature:o.Z_()}),o.Ry({type:o.i0("compaction_delta"),content:o.Z_().nullish()}),o.Ry({type:o.i0("citations_delta"),citation:o.VK("type",[o.Ry({type:o.i0("web_search_result_location"),cited_text:o.Z_(),url:o.Z_(),title:o.Z_(),encrypted_index:o.Z_()}),o.Ry({type:o.i0("page_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_page_number:o.Rx(),end_page_number:o.Rx()}),o.Ry({type:o.i0("char_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_char_index:o.Rx(),end_char_index:o.Rx()})])})])}),o.Ry({type:o.i0("content_block_stop"),index:o.Rx()}),o.Ry({type:o.i0("error"),error:o.Ry({type:o.Z_(),message:o.Z_()})}),o.Ry({type:o.i0("message_delta"),delta:o.Ry({stop_reason:o.Z_().nullish(),stop_sequence:o.Z_().nullish(),container:o.Ry({expires_at:o.Z_(),id:o.Z_(),skills:o.IX(o.Ry({type:o.G0([o.i0("anthropic"),o.i0("custom")]),skill_id:o.Z_(),version:o.Z_()})).nullish()}).nullish()}),usage:o.d7({input_tokens:o.Rx().nullish(),output_tokens:o.Rx(),cache_creation_input_tokens:o.Rx().nullish(),cache_read_input_tokens:o.Rx().nullish(),iterations:o.IX(o.Ry({type:o.G0([o.i0("compaction"),o.i0("message")]),input_tokens:o.Rx(),output_tokens:o.Rx()})).nullish()}),context_management:o.Ry({applied_edits:o.IX(o.G0([o.Ry({type:o.i0("clear_tool_uses_20250919"),cleared_tool_uses:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("clear_thinking_20251015"),cleared_thinking_turns:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("compact_20260112")})]))}).nullish()}),o.Ry({type:o.i0("message_stop")}),o.Ry({type:o.i0("ping")})]))),d=(0,n.DG)(()=>(0,n.r0)(o.Ry({signature:o.Z_().optional(),redactedData:o.Z_().optional()}))),c=o.Ry({citations:o.Ry({enabled:o.O7()}).optional(),title:o.Z_().optional(),context:o.Z_().optional()}),p=o.Ry({sendReasoning:o.O7().optional(),structuredOutputMode:o.Km(["outputFormat","jsonTool","auto"]).optional(),thinking:o.VK("type",[o.Ry({type:o.i0("adaptive")}),o.Ry({type:o.i0("enabled"),budgetTokens:o.Rx().optional()}),o.Ry({type:o.i0("disabled")})]).optional(),disableParallelToolUse:o.O7().optional(),cacheControl:o.Ry({type:o.i0("ephemeral"),ttl:o.G0([o.i0("5m"),o.i0("1h")]).optional()}).optional(),mcpServers:o.IX(o.Ry({type:o.i0("url"),name:o.Z_(),url:o.Z_(),authorizationToken:o.Z_().nullish(),toolConfiguration:o.Ry({enabled:o.O7().nullish(),allowedTools:o.IX(o.Z_()).nullish()}).nullish()})).optional(),container:o.Ry({id:o.Z_().optional(),skills:o.IX(o.Ry({type:o.G0([o.i0("anthropic"),o.i0("custom")]),skillId:o.Z_(),version:o.Z_().optional()})).optional()}).optional(),toolStreaming:o.O7().optional(),effort:o.Km(["low","medium","high","max"]).optional(),speed:o.Km(["fast","standard"]).optional(),anthropicBeta:o.IX(o.Z_()).optional(),contextManagement:o.Ry({edits:o.IX(o.VK("type",[o.Ry({type:o.i0("clear_tool_uses_20250919"),trigger:o.VK("type",[o.Ry({type:o.i0("input_tokens"),value:o.Rx()}),o.Ry({type:o.i0("tool_uses"),value:o.Rx()})]).optional(),keep:o.Ry({type:o.i0("tool_uses"),value:o.Rx()}).optional(),clearAtLeast:o.Ry({type:o.i0("input_tokens"),value:o.Rx()}).optional(),clearToolInputs:o.O7().optional(),excludeTools:o.IX(o.Z_()).optional()}),o.Ry({type:o.i0("clear_thinking_20251015"),keep:o.G0([o.i0("all"),o.Ry({type:o.i0("thinking_turns"),value:o.Rx()})]).optional()}),o.Ry({type:o.i0("compact_20260112"),trigger:o.Ry({type:o.i0("input_tokens"),value:o.Rx()}).optional(),pauseAfterCompaction:o.O7().optional(),instructions:o.Z_().optional()})]))}).optional()}),h=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let r=function(e){var t;let r=null==e?void 0:e.anthropic;return null!=(t=null==r?void 0:r.cacheControl)?t:null==r?void 0:r.cache_control}(e);if(r){if(!t.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>4){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum 4 cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return r}}getWarnings(){return this.warnings}},m=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxCharacters:o.Rx().optional()}))),f=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),y=(0,n.W0)({id:"anthropic.text_editor_20250728",inputSchema:f}),_=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),userLocation:o.Ry({type:o.i0("approximate"),city:o.Z_().optional(),region:o.Z_().optional(),country:o.Z_().optional(),timezone:o.Z_().optional()}).optional()}))),g=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({url:o.Z_(),title:o.Z_().nullable(),pageAge:o.Z_().nullable(),encryptedContent:o.Z_(),type:o.i0("web_search_result")})))),v=(0,n.DG)(()=>(0,n.r0)(o.Ry({query:o.Z_()}))),b=(0,n.ql)({id:"anthropic.web_search_20260209",inputSchema:v,outputSchema:g,supportsDeferredResults:!0}),w=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),userLocation:o.Ry({type:o.i0("approximate"),city:o.Z_().optional(),region:o.Z_().optional(),country:o.Z_().optional(),timezone:o.Z_().optional()}).optional()}))),x=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({url:o.Z_(),title:o.Z_().nullable(),pageAge:o.Z_().nullable(),encryptedContent:o.Z_(),type:o.i0("web_search_result")})))),k=(0,n.DG)(()=>(0,n.r0)(o.Ry({query:o.Z_()}))),I=(0,n.ql)({id:"anthropic.web_search_20250305",inputSchema:k,outputSchema:x,supportsDeferredResults:!0}),T=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),citations:o.Ry({enabled:o.O7()}).optional(),maxContentTokens:o.Rx().optional()}))),R=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),mediaType:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),mediaType:o.i0("text/plain"),data:o.Z_()})])}),retrievedAt:o.Z_().nullable()}))),S=(0,n.DG)(()=>(0,n.r0)(o.Ry({url:o.Z_()}))),Z=(0,n.ql)({id:"anthropic.web_fetch_20260209",inputSchema:S,outputSchema:R,supportsDeferredResults:!0}),C=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),citations:o.Ry({enabled:o.O7()}).optional(),maxContentTokens:o.Rx().optional()}))),E=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),mediaType:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),mediaType:o.i0("text/plain"),data:o.Z_()})])}),retrievedAt:o.Z_().nullable()}))),O=(0,n.DG)(()=>(0,n.r0)(o.Ry({url:o.Z_()}))),A=(0,n.ql)({id:"anthropic.web_fetch_20250910",inputSchema:O,outputSchema:E,supportsDeferredResults:!0});async function N({tools:e,toolChoice:t,disableParallelToolUse:r,cacheControlValidator:o,supportsStructuredOutput:i}){var s;e=(null==e?void 0:e.length)?e:void 0;let l=[],u=new Set,d=o||new h;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:l,betas:u};let c=[];for(let t of e)switch(t.type){case"function":{let e=d.getCacheControl(t.providerOptions,{type:"tool definition",canCache:!0}),r=null==(s=t.providerOptions)?void 0:s.anthropic,a=null==r?void 0:r.eagerInputStreaming,n=null==r?void 0:r.deferLoading,o=null==r?void 0:r.allowedCallers;c.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...a?{eager_input_streaming:!0}:{},...!0===i&&null!=t.strict?{strict:t.strict}:{},...null!=n?{defer_loading:n}:{},...null!=o?{allowed_callers:o}:{},...null!=t.inputExamples?{input_examples:t.inputExamples.map(e=>e.input)}:{}}),!0===i&&u.add("structured-outputs-2025-11-13"),(null!=t.inputExamples||null!=o)&&u.add("advanced-tool-use-2025-11-20");break}case"provider":switch(t.id){case"anthropic.code_execution_20250522":u.add("code-execution-2025-05-22"),c.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break;case"anthropic.code_execution_20250825":u.add("code-execution-2025-08-25"),c.push({type:"code_execution_20250825",name:"code_execution"});break;case"anthropic.code_execution_20260120":c.push({type:"code_execution_20260120",name:"code_execution"});break;case"anthropic.computer_20250124":u.add("computer-use-2025-01-24"),c.push({name:"computer",type:"computer_20250124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.computer_20251124":u.add("computer-use-2025-11-24"),c.push({name:"computer",type:"computer_20251124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,enable_zoom:t.args.enableZoom,cache_control:void 0});break;case"anthropic.computer_20241022":u.add("computer-use-2024-10-22"),c.push({name:"computer",type:"computer_20241022",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.text_editor_20250124":u.add("computer-use-2025-01-24"),c.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break;case"anthropic.text_editor_20241022":u.add("computer-use-2024-10-22"),c.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break;case"anthropic.text_editor_20250429":u.add("computer-use-2025-01-24"),c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break;case"anthropic.text_editor_20250728":{let e=await (0,n.rJ)({value:t.args,schema:m});c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:e.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":u.add("computer-use-2025-01-24"),c.push({name:"bash",type:"bash_20250124",cache_control:void 0});break;case"anthropic.bash_20241022":u.add("computer-use-2024-10-22"),c.push({name:"bash",type:"bash_20241022",cache_control:void 0});break;case"anthropic.memory_20250818":u.add("context-management-2025-06-27"),c.push({name:"memory",type:"memory_20250818"});break;case"anthropic.web_fetch_20250910":{u.add("web-fetch-2025-09-10");let e=await (0,n.rJ)({value:t.args,schema:C});c.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{u.add("code-execution-web-tools-2026-02-09");let e=await (0,n.rJ)({value:t.args,schema:T});c.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let e=await (0,n.rJ)({value:t.args,schema:w});c.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{u.add("code-execution-web-tools-2026-02-09");let e=await (0,n.rJ)({value:t.args,schema:_});c.push({type:"web_search_20260209",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":u.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break;case"anthropic.tool_search_bm25_20251119":u.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break;default:l.push({type:"unsupported",feature:`provider-defined tool ${t.id}`})}break;default:l.push({type:"unsupported",feature:`tool ${t}`})}if(null==t)return{tools:c,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:l,betas:u};let p=t.type;switch(p){case"auto":return{tools:c,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:l,betas:u};case"required":return{tools:c,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:l,betas:u};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:l,betas:u};case"tool":return{tools:c,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:r},toolWarnings:l,betas:u};default:throw new a.A_({functionality:`tool choice type: ${p}`})}}function M({usage:e,rawUsage:t}){var r,a;let n,o;let i=null!=(r=e.cache_creation_input_tokens)?r:0,s=null!=(a=e.cache_read_input_tokens)?a:0;if(e.iterations&&e.iterations.length>0){let t=e.iterations.reduce((e,t)=>({input:e.input+t.input_tokens,output:e.output+t.output_tokens}),{input:0,output:0});n=t.input,o=t.output}else n=e.input_tokens,o=e.output_tokens;return{inputTokens:{total:n+i+s,noCache:n,cacheRead:s,cacheWrite:i},outputTokens:{total:o,text:void 0,reasoning:void 0},raw:null!=t?t:e}}var $=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}))),P=(0,n.DG)(()=>(0,n.r0)(o.Ry({code:o.Z_()}))),j=(0,n.ql)({id:"anthropic.code_execution_20250522",inputSchema:P,outputSchema:$}),F=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})]))),z=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("programmatic-tool-call"),code:o.Z_()}),o.Ry({type:o.i0("bash_code_execution"),command:o.Z_()}),o.VK("command",[o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("view"),path:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("create"),path:o.Z_(),file_text:o.Z_().nullish()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("str_replace"),path:o.Z_(),old_str:o.Z_(),new_str:o.Z_()})])]))),D=(0,n.ql)({id:"anthropic.code_execution_20250825",inputSchema:z,outputSchema:F,supportsDeferredResults:!0}),q=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("encrypted_code_execution_result"),encrypted_stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})]))),U=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("programmatic-tool-call"),code:o.Z_()}),o.Ry({type:o.i0("bash_code_execution"),command:o.Z_()}),o.VK("command",[o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("view"),path:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("create"),path:o.Z_(),file_text:o.Z_().nullish()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("str_replace"),path:o.Z_(),old_str:o.Z_(),new_str:o.Z_()})])]))),L=(0,n.ql)({id:"anthropic.code_execution_20260120",inputSchema:U,outputSchema:q,supportsDeferredResults:!0}),V=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({type:o.i0("tool_reference"),toolName:o.Z_()})))),G=(0,n.DG)(()=>(0,n.r0)(o.Ry({pattern:o.Z_(),limit:o.Rx().optional()}))),W=(0,n.ql)({id:"anthropic.tool_search_regex_20251119",inputSchema:G,outputSchema:V,supportsDeferredResults:!0});function X(e){return e instanceof URL||"string"==typeof e&&/^https?:\/\//i.test(e)}function B(e){return e instanceof URL?e.toString():e}async function K({prompt:e,sendReasoning:t,warnings:r,cacheControlValidator:o,toolNameMapping:i}){var s,l,u,p,m,f,y,_,g,v,b,w,k,I,T,R,S,Z,C;let O;let A=new Set,N=function(e){let t;let r=[];for(let a of e){let{role:e}=a;switch(e){case"system":(null==t?void 0:t.type)!=="system"&&(t={type:"system",messages:[]},r.push(t)),t.messages.push(a);break;case"assistant":(null==t?void 0:t.type)!=="assistant"&&(t={type:"assistant",messages:[]},r.push(t)),t.messages.push(a);break;case"user":case"tool":(null==t?void 0:t.type)!=="user"&&(t={type:"user",messages:[]},r.push(t)),t.messages.push(a);break;default:throw Error(`Unsupported role: ${e}`)}}return r}(e),M=o||new h,P=[];async function j(e){var t,r;let a=await (0,n.c1)({provider:"anthropic",providerOptions:e,schema:c});return null!=(r=null==(t=null==a?void 0:a.citations)?void 0:t.enabled)&&r}async function z(e){let t=await (0,n.c1)({provider:"anthropic",providerOptions:e,schema:c});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let e=0;e<N.length;e++){let o=N[e],c=e===N.length-1,h=o.type;switch(h){case"system":if(null!=O)throw new a.A_({functionality:"Multiple system messages that are separated by user/assistant messages"});O=o.messages.map(({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:M.getCacheControl(t,{type:"system message",canCache:!0})}));break;case"user":{let e=[];for(let t of o.messages){let{role:o,content:i}=t;switch(o){case"user":for(let r=0;r<i.length;r++){let o=i[r],d=r===i.length-1,c=null!=(s=M.getCacheControl(o.providerOptions,{type:"user message part",canCache:!0}))?s:d?M.getCacheControl(t.providerOptions,{type:"user message",canCache:!0}):void 0;switch(o.type){case"text":e.push({type:"text",text:o.text,cache_control:c});break;case"file":if(o.mediaType.startsWith("image/"))e.push({type:"image",source:X(o.data)?{type:"url",url:B(o.data)}:{type:"base64",media_type:"image/*"===o.mediaType?"image/jpeg":o.mediaType,data:(0,n.QF)(o.data)},cache_control:c});else if("application/pdf"===o.mediaType){A.add("pdfs-2024-09-25");let t=await j(o.providerOptions),r=await z(o.providerOptions);e.push({type:"document",source:X(o.data)?{type:"url",url:B(o.data)}:{type:"base64",media_type:"application/pdf",data:(0,n.QF)(o.data)},title:null!=(l=r.title)?l:o.filename,...r.context&&{context:r.context},...t&&{citations:{enabled:!0}},cache_control:c})}else if("text/plain"===o.mediaType){let t=await j(o.providerOptions),r=await z(o.providerOptions);e.push({type:"document",source:X(o.data)?{type:"url",url:B(o.data)}:{type:"text",media_type:"text/plain",data:function(e){if("string"==typeof e)return new TextDecoder().decode((0,n.MS)(e));if(e instanceof Uint8Array)return new TextDecoder().decode(e);if(e instanceof URL)throw new a.A_({functionality:"URL-based text documents are not supported for citations"});throw new a.A_({functionality:`unsupported data type for text documents: ${typeof e}`})}(o.data)},title:null!=(u=r.title)?u:o.filename,...r.context&&{context:r.context},...t&&{citations:{enabled:!0}},cache_control:c})}else throw new a.A_({functionality:`media type: ${o.mediaType}`})}}break;case"tool":for(let a=0;a<i.length;a++){let o;let s=i[a];if("tool-approval-response"===s.type)continue;let l=a===i.length-1,u=null!=(p=M.getCacheControl(s.providerOptions,{type:"tool result part",canCache:!0}))?p:l?M.getCacheControl(t.providerOptions,{type:"tool result message",canCache:!0}):void 0,d=s.output;switch(d.type){case"content":o=d.value.map(e=>{var t;switch(e.type){case"text":return{type:"text",text:e.text};case"image-data":return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}};case"image-url":return{type:"image",source:{type:"url",url:e.url}};case"file-url":return{type:"document",source:{type:"url",url:e.url}};case"file-data":if("application/pdf"===e.mediaType)return A.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:e.mediaType,data:e.data}};r.push({type:"other",message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return;case"custom":{let a=null==(t=e.providerOptions)?void 0:t.anthropic;if((null==a?void 0:a.type)==="tool-reference")return{type:"tool_reference",tool_name:a.toolName};r.push({type:"other",message:"unsupported custom tool content part"});return}default:r.push({type:"other",message:`unsupported tool content part type: ${e.type}`});return}}).filter(n.C_);break;case"text":case"error-text":o=d.value;break;case"execution-denied":o=null!=(m=d.reason)?m:"Tool execution denied.";break;default:o=JSON.stringify(d.value)}e.push({type:"tool_result",tool_use_id:s.toolCallId,content:o,is_error:"error-text"===d.type||"error-json"===d.type||void 0,cache_control:u})}break;default:throw Error(`Unsupported role: ${o}`)}}P.push({role:"user",content:e});break}case"assistant":{let e=[],a=new Set;for(let s=0;s<o.messages.length;s++){let l=o.messages[s],u=s===o.messages.length-1,{content:p}=l;for(let o=0;o<p.length;o++){let s=p[o],h=o===p.length-1,m=null!=(f=M.getCacheControl(s.providerOptions,{type:"assistant message part",canCache:!0}))?f:h?M.getCacheControl(l.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(s.type){case"text":{let t=null==(y=s.providerOptions)?void 0:y.anthropic;(null==t?void 0:t.type)==="compaction"?e.push({type:"compaction",content:s.text,cache_control:m}):e.push({type:"text",text:c&&u&&h?s.text.trim():s.text,cache_control:m});break}case"reasoning":if(t){let t=await (0,n.c1)({provider:"anthropic",providerOptions:s.providerOptions,schema:d});null!=t?null!=t.signature?(M.getCacheControl(s.providerOptions,{type:"thinking block",canCache:!1}),e.push({type:"thinking",thinking:s.text,signature:t.signature})):null!=t.redactedData?(M.getCacheControl(s.providerOptions,{type:"redacted thinking block",canCache:!1}),e.push({type:"redacted_thinking",data:t.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":{if(s.providerExecuted){let t=i.toProviderToolName(s.toolName);if((null==(g=null==(_=s.providerOptions)?void 0:_.anthropic)?void 0:g.type)==="mcp-tool-use"){a.add(s.toolCallId);let t=null==(b=null==(v=s.providerOptions)?void 0:v.anthropic)?void 0:b.serverName;if(null==t||"string"!=typeof t){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}e.push({type:"mcp_tool_use",id:s.toolCallId,name:s.toolName,input:s.input,server_name:t,cache_control:m})}else if("code_execution"===t&&null!=s.input&&"object"==typeof s.input&&"type"in s.input&&"string"==typeof s.input.type&&("bash_code_execution"===s.input.type||"text_editor_code_execution"===s.input.type))e.push({type:"server_tool_use",id:s.toolCallId,name:s.input.type,input:s.input,cache_control:m});else if("code_execution"===t&&null!=s.input&&"object"==typeof s.input&&"type"in s.input&&"programmatic-tool-call"===s.input.type){let{type:t,...r}=s.input;e.push({type:"server_tool_use",id:s.toolCallId,name:"code_execution",input:r,cache_control:m})}else"code_execution"===t||"web_fetch"===t||"web_search"===t?e.push({type:"server_tool_use",id:s.toolCallId,name:t,input:s.input,cache_control:m}):"tool_search_tool_regex"===t||"tool_search_tool_bm25"===t?e.push({type:"server_tool_use",id:s.toolCallId,name:t,input:s.input,cache_control:m}):r.push({type:"other",message:`provider executed tool call for tool ${s.toolName} is not supported`});break}let t=null==(w=s.providerOptions)?void 0:w.anthropic,n=(null==t?void 0:t.caller)?("code_execution_20250825"===t.caller.type||"code_execution_20260120"===t.caller.type)&&t.caller.toolId?{type:t.caller.type,tool_id:t.caller.toolId}:"direct"===t.caller.type?{type:"direct"}:void 0:void 0;e.push({type:"tool_use",id:s.toolCallId,name:s.toolName,input:s.input,...n&&{caller:n},cache_control:m});break}case"tool-result":{let t=i.toProviderToolName(s.toolName);if(a.has(s.toolCallId)){let t=s.output;if("json"!==t.type&&"error-json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId,is_error:"error-json"===t.type,content:t.value,cache_control:m})}else if("code_execution"===t){let t=s.output;if("error-text"===t.type||"error-json"===t.type){let r={};try{"string"==typeof t.value?r=JSON.parse(t.value):"object"==typeof t.value&&null!==t.value&&(r=t.value)}catch(e){}"code_execution_tool_result_error"===r.type?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:"code_execution_tool_result_error",error_code:null!=(k=r.errorCode)?k:"unknown"},cache_control:m}):e.push({type:"bash_code_execution_tool_result",tool_use_id:s.toolCallId,cache_control:m,content:{type:"bash_code_execution_tool_result_error",error_code:null!=(I=r.errorCode)?I:"unknown"}});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}if(null==t.value||"object"!=typeof t.value||!("type"in t.value)||"string"!=typeof t.value.type){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${s.toolName}`});break}if("code_execution_result"===t.value.type){let r=await (0,n.rJ)({value:t.value,schema:$});e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code,content:null!=(T=r.content)?T:[]},cache_control:m})}else if("encrypted_code_execution_result"===t.value.type){let r=await (0,n.rJ)({value:t.value,schema:q});"encrypted_code_execution_result"===r.type&&e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:r.type,encrypted_stdout:r.encrypted_stdout,stderr:r.stderr,return_code:r.return_code,content:null!=(R=r.content)?R:[]},cache_control:m})}else{let r=await (0,n.rJ)({value:t.value,schema:F});"code_execution_result"===r.type?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code,content:null!=(S=r.content)?S:[]},cache_control:m}):"bash_code_execution_result"===r.type||"bash_code_execution_tool_result_error"===r.type?e.push({type:"bash_code_execution_tool_result",tool_use_id:s.toolCallId,cache_control:m,content:r}):e.push({type:"text_editor_code_execution_tool_result",tool_use_id:s.toolCallId,cache_control:m,content:r})}break}if("web_fetch"===t){let t=s.output;if("error-json"===t.type){let r={};try{"string"==typeof t.value?r=JSON.parse(t.value):"object"==typeof t.value&&null!==t.value&&(r=t.value)}catch(a){let e=null==(Z=t.value)?void 0:Z.errorCode;r={errorCode:"string"==typeof e?e:"unknown"}}e.push({type:"web_fetch_tool_result",tool_use_id:s.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:null!=(C=r.errorCode)?C:"unknown"},cache_control:m});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let a=await (0,n.rJ)({value:t.value,schema:E});e.push({type:"web_fetch_tool_result",tool_use_id:s.toolCallId,content:{type:"web_fetch_result",url:a.url,retrieved_at:a.retrievedAt,content:{type:"document",title:a.content.title,citations:a.content.citations,source:{type:a.content.source.type,media_type:a.content.source.mediaType,data:a.content.source.data}}},cache_control:m});break}if("web_search"===t){let t=s.output;if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let a=await (0,n.rJ)({value:t.value,schema:x});e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId,content:a.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:m});break}if("tool_search_tool_regex"===t||"tool_search_tool_bm25"===t){let t=s.output;if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let a=(await (0,n.rJ)({value:t.value,schema:V})).map(e=>({type:"tool_reference",tool_name:e.toolName}));e.push({type:"tool_search_tool_result",tool_use_id:s.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:a},cache_control:m});break}r.push({type:"other",message:`provider executed tool result for tool ${s.toolName} is not supported`})}}}}P.push({role:"assistant",content:e});break}default:throw Error(`content type: ${h}`)}}return{prompt:{system:O,messages:P},betas:A}}function J({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":case"model_context_window_exceeded":return"length";default:return"other"}}function H(e,t,r){var a;if("web_search_result_location"===e.type)return{type:"source",sourceType:"url",id:r(),url:e.url,title:e.title,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if("page_location"!==e.type&&"char_location"!==e.type)return;let n=t[e.document_index];if(n)return{type:"source",sourceType:"document",id:r(),mediaType:n.mediaType,title:null!=(a=e.document_title)?a:n.title,filename:n.filename,providerMetadata:{anthropic:"page_location"===e.type?{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 Y=class{constructor(e,t){var r;this.specificationVersion="v3",this.modelId=e,this.config=t,this.generateId=null!=(r=t.generateId)?r:n.Ox}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return -1===t?e:e.substring(0,t)}get supportedUrls(){var e,t,r;return null!=(r=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?r:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:r,temperature:a,topP:o,topK:i,frequencyPenalty:s,presencePenalty:l,stopSequences:u,responseFormat:d,seed:c,tools:m,toolChoice:f,providerOptions:y,stream:_}){var g,v,b,w,x,k,I,T;let R=[];null!=s&&R.push({type:"unsupported",feature:"frequencyPenalty"}),null!=l&&R.push({type:"unsupported",feature:"presencePenalty"}),null!=c&&R.push({type:"unsupported",feature:"seed"}),null!=a&&a>1?(R.push({type:"unsupported",feature:"temperature",details:`${a} exceeds anthropic maximum of 1.0. clamped to 1.0`}),a=1):null!=a&&a<0&&(R.push({type:"unsupported",feature:"temperature",details:`${a} is below anthropic minimum of 0. clamped to 0`}),a=0),(null==d?void 0:d.type)==="json"&&null==d.schema&&R.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let S=this.providerOptionsName,Z=await (0,n.c1)({provider:"anthropic",providerOptions:y,schema:p}),C="anthropic"!==S?await (0,n.c1)({provider:S,providerOptions:y,schema:p}):null,E=null!=C,O=Object.assign({},null!=Z?Z:{},null!=C?C:{}),{maxOutputTokens:A,supportsStructuredOutput:M,isKnownModel:$}=(T=this.modelId).includes("claude-sonnet-4-6")||T.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,isKnownModel:!0}:T.includes("claude-sonnet-4-5")||T.includes("claude-opus-4-5")||T.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:T.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:T.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:T.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:T.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1},P=(null==(g=this.config.supportsNativeStructuredOutput)||g)&&M,j=null!=(v=null==O?void 0:O.structuredOutputMode)?v:"auto",F="outputFormat"===j||"auto"===j&&P,z=(null==d?void 0:d.type)!=="json"||null==d.schema||F?void 0:{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:d.schema},D=null==O?void 0:O.contextManagement,q=new h,U=(0,n.U_)({tools:m,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:L,betas:V}=await K({prompt:t,sendReasoning:null==(b=null==O?void 0:O.sendReasoning)||b,warnings:R,cacheControlValidator:q,toolNameMapping:U}),G=null==(w=null==O?void 0:O.thinking)?void 0:w.type,W="enabled"===G||"adaptive"===G,X="enabled"===G?null==(x=null==O?void 0:O.thinking)?void 0:x.budgetTokens:void 0,B=null!=r?r:A,J={model:this.modelId,max_tokens:B,temperature:a,top_k:i,top_p:o,stop_sequences:u,...W&&{thinking:{type:G,...null!=X&&{budget_tokens:X}}},...((null==O?void 0:O.effort)||F&&(null==d?void 0:d.type)==="json"&&null!=d.schema)&&{output_config:{...(null==O?void 0:O.effort)&&{effort:O.effort},...F&&(null==d?void 0:d.type)==="json"&&null!=d.schema&&{format:{type:"json_schema",schema:d.schema}}}},...(null==O?void 0:O.speed)&&{speed:O.speed},...(null==O?void 0:O.cacheControl)&&{cache_control:O.cacheControl},...(null==O?void 0:O.mcpServers)&&O.mcpServers.length>0&&{mcp_servers:O.mcpServers.map(e=>({type:e.type,name:e.name,url:e.url,authorization_token:e.authorizationToken,tool_configuration:e.toolConfiguration?{allowed_tools:e.toolConfiguration.allowedTools,enabled:e.toolConfiguration.enabled}:void 0}))},...(null==O?void 0:O.container)&&{container:O.container.skills&&O.container.skills.length>0?{id:O.container.id,skills:O.container.skills.map(e=>({type:e.type,skill_id:e.skillId,version:e.version}))}:O.container.id},system:L.system,messages:L.messages,...D&&{context_management:{edits:D.edits.map(e=>{let t=e.type;switch(t){case"clear_tool_uses_20250919":return{type:e.type,...void 0!==e.trigger&&{trigger:e.trigger},...void 0!==e.keep&&{keep:e.keep},...void 0!==e.clearAtLeast&&{clear_at_least:e.clearAtLeast},...void 0!==e.clearToolInputs&&{clear_tool_inputs:e.clearToolInputs},...void 0!==e.excludeTools&&{exclude_tools:e.excludeTools}};case"clear_thinking_20251015":return{type:e.type,...void 0!==e.keep&&{keep:e.keep}};case"compact_20260112":return{type:e.type,...void 0!==e.trigger&&{trigger:e.trigger},...void 0!==e.pauseAfterCompaction&&{pause_after_compaction:e.pauseAfterCompaction},...void 0!==e.instructions&&{instructions:e.instructions}};default:R.push({type:"other",message:`Unknown context management strategy: ${t}`});return}}).filter(e=>void 0!==e)}}};W?("enabled"===G&&null==X&&(R.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),J.thinking={type:"enabled",budget_tokens:1024},X=1024),null!=J.temperature&&(J.temperature=void 0,R.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(J.top_k=void 0,R.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),null!=o&&(J.top_p=void 0,R.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),J.max_tokens=B+(null!=X?X:0)):null!=o&&null!=a&&(R.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),J.top_p=void 0),$&&J.max_tokens>A&&(null!=r&&R.push({type:"unsupported",feature:"maxOutputTokens",details:`${J.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${A} max output tokens. The max output tokens have been limited to ${A}.`}),J.max_tokens=A),(null==O?void 0:O.mcpServers)&&O.mcpServers.length>0&&V.add("mcp-client-2025-04-04"),D&&(V.add("context-management-2025-06-27"),D.edits.some(e=>"compact_20260112"===e.type)&&V.add("compact-2026-01-12")),(null==O?void 0:O.container)&&O.container.skills&&O.container.skills.length>0&&(V.add("code-execution-2025-08-25"),V.add("skills-2025-10-02"),V.add("files-api-2025-04-14"),(null==m?void 0:m.some(e=>"provider"===e.type&&("anthropic.code_execution_20250825"===e.id||"anthropic.code_execution_20260120"===e.id)))||R.push({type:"other",message:"code execution tool is required when using skills"})),(null==O?void 0:O.effort)&&V.add("effort-2025-11-24"),(null==O?void 0:O.speed)==="fast"&&V.add("fast-mode-2026-02-01"),_&&(null==(k=null==O?void 0:O.toolStreaming)||k)&&V.add("fine-grained-tool-streaming-2025-05-14");let{tools:H,toolChoice:Y,toolWarnings:Q,betas:ee}=await N(null!=z?{tools:[...null!=m?m:[],z],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:q,supportsStructuredOutput:!1}:{tools:null!=m?m:[],toolChoice:f,disableParallelToolUse:null==O?void 0:O.disableParallelToolUse,cacheControlValidator:q,supportsStructuredOutput:P}),et=q.getWarnings();return{args:{...J,tools:H,tool_choice:Y,stream:!0===_||void 0},warnings:[...R,...Q,...et],betas:new Set([...V,...ee,...e,...null!=(I=null==O?void 0:O.anthropicBeta)?I:[]]),usesJsonResponseTool:null!=z,toolNameMapping:U,providerOptionsName:S,usedCustomProviderKey:E}}async getHeaders({betas:e,headers:t}){return(0,n.NF)(await (0,n.DB)(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,r;let a=null!=(t=(await (0,n.DB)(this.config.headers))["anthropic-beta"])?t:"",o=null!=(r=null==e?void 0:e["anthropic-beta"])?r:"";return new Set([...a.toLowerCase().split(","),...o.toLowerCase().split(",")].map(e=>e.trim()).filter(e=>""!==e))}buildRequestUrl(e){var t,r,a;return null!=(a=null==(r=(t=this.config).buildRequestUrl)?void 0:r.call(t,this.config.baseURL,e))?a:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var r,a,n;return null!=(n=null==(a=(r=this.config).transformRequestBody)?void 0:a.call(r,e,t))?n:e}extractCitationDocuments(e){return e.filter(e=>"user"===e.role).flatMap(e=>e.content).filter(e=>{var t,r;if("file"!==e.type||"application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;let a=null==(t=e.providerOptions)?void 0:t.anthropic,n=null==a?void 0:a.citations;return null!=(r=null==n?void 0:n.enabled)&&r}).map(e=>{var t;return{title:null!=(t=e.filename)?t:"Untitled Document",filename:e.filename,mediaType:e.mediaType}})}async doGenerate(e){var t,r,a,o,i,u,d;let{args:c,warnings:p,betas:h,usesJsonResponseTool:m,toolNameMapping:f,providerOptionsName:y,usedCustomProviderKey:_}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),g=[...this.extractCitationDocuments(e.prompt)],v=Q(c.tools),{responseHeaders:b,value:w,rawValue:x}=await (0,n.A8)({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:h,headers:e.headers}),body:this.transformRequestBody(c,h),failedResponseHandler:s,successfulResponseHandler:(0,n.tc)(l),abortSignal:e.abortSignal,fetch:this.config.fetch}),k=[],I={},T={},R=!1;for(let e of w.content)switch(e.type){case"text":if(!m&&(k.push({type:"text",text:e.text}),e.citations))for(let t of e.citations){let e=H(t,g,this.generateId);e&&k.push(e)}break;case"thinking":k.push({type:"reasoning",text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case"redacted_thinking":k.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:e.data}}});break;case"compaction":k.push({type:"text",text:e.content,providerMetadata:{anthropic:{type:"compaction"}}});break;case"tool_use":if(m&&"json"===e.name)R=!0,k.push({type:"text",text:JSON.stringify(e.input)});else{let t=e.caller,r=t?{type:t.type,toolId:"tool_id"in t?t.tool_id:void 0}:void 0;k.push({type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),...r&&{providerMetadata:{anthropic:{caller:r}}}})}break;case"server_tool_use":if("text_editor_code_execution"===e.name||"bash_code_execution"===e.name)k.push({type:"tool-call",toolCallId:e.id,toolName:f.toCustomToolName("code_execution"),input:JSON.stringify({type:e.name,...e.input}),providerExecuted:!0});else if("web_search"===e.name||"code_execution"===e.name||"web_fetch"===e.name){let t="code_execution"===e.name&&null!=e.input&&"object"==typeof e.input&&"code"in e.input&&!("type"in e.input)?{type:"programmatic-tool-call",...e.input}:e.input;k.push({type:"tool-call",toolCallId:e.id,toolName:f.toCustomToolName(e.name),input:JSON.stringify(t),providerExecuted:!0,...v&&"code_execution"===e.name?{dynamic:!0}:{}})}else("tool_search_tool_regex"===e.name||"tool_search_tool_bm25"===e.name)&&(T[e.id]=e.name,k.push({type:"tool-call",toolCallId:e.id,toolName:f.toCustomToolName(e.name),input:JSON.stringify(e.input),providerExecuted:!0}));break;case"mcp_tool_use":I[e.id]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:e.server_name}}},k.push(I[e.id]);break;case"mcp_tool_result":k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:I[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:I[e.tool_use_id].providerMetadata});break;case"web_fetch_tool_result":"web_fetch_result"===e.content.type?(g.push({title:null!=(t=e.content.content.title)?t:e.content.url,mediaType:e.content.content.source.media_type}),k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}})):"web_fetch_tool_result_error"===e.content.type&&k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:e.content.error_code}});break;case"web_search_tool_result":if(Array.isArray(e.content))for(let t of(k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_search"),result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})}),e.content))k.push({type:"source",sourceType:"url",id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}});else k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code}});break;case"code_execution_tool_result":"code_execution_result"===e.content.type?k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(a=e.content.content)?a:[]}}):"encrypted_code_execution_result"===e.content.type?k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:e.content.type,encrypted_stdout:e.content.encrypted_stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(o=e.content.content)?o:[]}}):"code_execution_tool_result_error"===e.content.type&&k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:e.content});break;case"tool_search_tool_result":{let t=T[e.tool_use_id];if(null==t){let e=f.toCustomToolName("tool_search_tool_bm25");f.toCustomToolName("tool_search_tool_regex"),t="tool_search_tool_bm25"!==e?"tool_search_tool_bm25":"tool_search_tool_regex"}"tool_search_tool_search_result"===e.content.type?k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName(t),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:e.content.error_code}})}}return{content:k,finishReason:{unified:J({finishReason:w.stop_reason,isJsonResponseFromTool:R}),raw:null!=(i=w.stop_reason)?i:void 0},usage:M({usage:w.usage}),request:{body:c},response:{id:null!=(u=w.id)?u:void 0,modelId:null!=(d=w.model)?d:void 0,headers:b,body:x},warnings:p,providerMetadata:(()=>{var e,t,r,a,n;let o={usage:w.usage,cacheCreationInputTokens:null!=(e=w.usage.cache_creation_input_tokens)?e:null,stopSequence:null!=(t=w.stop_sequence)?t:null,iterations:w.usage.iterations?w.usage.iterations.map(e=>({type:e.type,inputTokens:e.input_tokens,outputTokens:e.output_tokens})):null,container:w.container?{expiresAt:w.container.expires_at,id:w.container.id,skills:null!=(a=null==(r=w.container.skills)?void 0:r.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?a:null}:null,contextManagement:null!=(n=ee(w.context_management))?n:null},i={anthropic:o};return _&&"anthropic"!==y&&(i[y]=o),i})()}}async doStream(e){var t,r;let o,i;let{args:l,warnings:d,betas:c,usesJsonResponseTool:p,toolNameMapping:h,providerOptionsName:m,usedCustomProviderKey:f}=await this.getArgs({...e,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),y=[...this.extractCitationDocuments(e.prompt)],_=Q(l.tools),g=this.buildRequestUrl(!0),{responseHeaders:v,value:b}=await (0,n.A8)({url:g,headers:await this.getHeaders({betas:c,headers:e.headers}),body:this.transformRequestBody(l,c),failedResponseHandler:s,successfulResponseHandler:(0,n.cP)(u),abortSignal:e.abortSignal,fetch:this.config.fetch}),w={unified:"other",raw:void 0},x={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},k={},I={},T={},R=null,S=null,Z=null,C=null,E=!1,O=this.generateId,[A,N]=b.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:d})},transform(t,r){var a,n,s,l,u,d,c,g,v,b,A,N,$,P;if(e.includeRawChunks&&r.enqueue({type:"raw",rawValue:t.rawValue}),!t.success){r.enqueue({type:"error",error:t.error});return}let j=t.value;switch(j.type){case"ping":return;case"content_block_start":{let e=j.content_block,t=e.type;switch(i=t,t){case"text":if(p)return;k[j.index]={type:"text"},r.enqueue({type:"text-start",id:String(j.index)});return;case"thinking":k[j.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(j.index)});return;case"redacted_thinking":k[j.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(j.index),providerMetadata:{anthropic:{redactedData:e.data}}});return;case"compaction":k[j.index]={type:"text"},r.enqueue({type:"text-start",id:String(j.index),providerMetadata:{anthropic:{type:"compaction"}}});return;case"tool_use":if(p&&"json"===e.name)E=!0,k[j.index]={type:"text"},r.enqueue({type:"text-start",id:String(j.index)});else{let t=e.caller,a=t?{type:t.type,toolId:"tool_id"in t?t.tool_id:void 0}:void 0,n=e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):"";k[j.index]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:n,firstDelta:0===n.length,...a&&{caller:a}},r.enqueue({type:"tool-input-start",id:e.id,toolName:e.name})}return;case"server_tool_use":if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(e.name)){let t="text_editor_code_execution"===e.name||"bash_code_execution"===e.name?"code_execution":e.name,a=h.toCustomToolName(t),n=null!=e.input&&"object"==typeof e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):"";k[j.index]={type:"tool-call",toolCallId:e.id,toolName:a,input:n,providerExecuted:!0,..._&&"code_execution"===t?{dynamic:!0}:{},firstDelta:!0,providerToolName:e.name},r.enqueue({type:"tool-input-start",id:e.id,toolName:a,providerExecuted:!0,..._&&"code_execution"===t?{dynamic:!0}:{}})}else if("tool_search_tool_regex"===e.name||"tool_search_tool_bm25"===e.name){T[e.id]=e.name;let t=h.toCustomToolName(e.name);k[j.index]={type:"tool-call",toolCallId:e.id,toolName:t,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:e.name},r.enqueue({type:"tool-input-start",id:e.id,toolName:t,providerExecuted:!0})}return;case"web_fetch_tool_result":"web_fetch_result"===e.content.type?(y.push({title:null!=(a=e.content.content.title)?a:e.content.url,mediaType:e.content.content.source.media_type}),r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}})):"web_fetch_tool_result_error"===e.content.type&&r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:e.content.error_code}});return;case"web_search_tool_result":if(Array.isArray(e.content))for(let t of(r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_search"),result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})}),e.content))r.enqueue({type:"source",sourceType:"url",id:O(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(n=t.page_age)?n:null}}});else r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code}});return;case"code_execution_tool_result":"code_execution_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(s=e.content.content)?s:[]}}):"encrypted_code_execution_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),result:{type:e.content.type,encrypted_stdout:e.content.encrypted_stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(l=e.content.content)?l:[]}}):"code_execution_tool_result_error"===e.content.type&&r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code}});return;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),result:e.content});return;case"tool_search_tool_result":{let t=T[e.tool_use_id];if(null==t){let e=h.toCustomToolName("tool_search_tool_bm25");h.toCustomToolName("tool_search_tool_regex"),t="tool_search_tool_bm25"!==e?"tool_search_tool_bm25":"tool_search_tool_regex"}"tool_search_tool_search_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName(t),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:e.content.error_code}});return}case"mcp_tool_use":I[e.id]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:e.server_name}}},r.enqueue(I[e.id]);return;case"mcp_tool_result":r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:I[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:I[e.tool_use_id].providerMetadata});return;default:throw Error(`Unsupported content block type: ${t}`)}}case"content_block_stop":if(null!=k[j.index]){let e=k[j.index];switch(e.type){case"text":r.enqueue({type:"text-end",id:String(j.index)});break;case"reasoning":r.enqueue({type:"reasoning-end",id:String(j.index)});break;case"tool-call":if(!(p&&"json"===e.toolName)){r.enqueue({type:"tool-input-end",id:e.toolCallId});let t=""===e.input?"{}":e.input;if("code_execution"===e.providerToolName)try{let e=JSON.parse(t);null!=e&&"object"==typeof e&&"code"in e&&!("type"in e)&&(t=JSON.stringify({type:"programmatic-tool-call",...e}))}catch(e){}r.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t,providerExecuted:e.providerExecuted,..._&&"code_execution"===e.providerToolName?{dynamic:!0}:{},...e.caller&&{providerMetadata:{anthropic:{caller:e.caller}}}})}}delete k[j.index]}i=void 0;return;case"content_block_delta":{let e=j.delta.type;switch(e){case"text_delta":if(p)return;r.enqueue({type:"text-delta",id:String(j.index),delta:j.delta.text});return;case"thinking_delta":r.enqueue({type:"reasoning-delta",id:String(j.index),delta:j.delta.thinking});return;case"signature_delta":"thinking"===i&&r.enqueue({type:"reasoning-delta",id:String(j.index),delta:"",providerMetadata:{anthropic:{signature:j.delta.signature}}});return;case"compaction_delta":null!=j.delta.content&&r.enqueue({type:"text-delta",id:String(j.index),delta:j.delta.content});return;case"input_json_delta":{let e=k[j.index],t=j.delta.partial_json;if(0===t.length)return;if(E){if((null==e?void 0:e.type)!=="text")return;r.enqueue({type:"text-delta",id:String(j.index),delta:t})}else{if((null==e?void 0:e.type)!=="tool-call")return;e.firstDelta&&("bash_code_execution"===e.providerToolName||"text_editor_code_execution"===e.providerToolName)&&(t=`{"type": "${e.providerToolName}",${t.substring(1)}`),r.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t,e.firstDelta=!1}return}case"citations_delta":{let e=H(j.delta.citation,y,O);e&&r.enqueue(e);return}default:throw Error(`Unsupported delta type: ${e}`)}}case"message_start":if(x.input_tokens=j.message.usage.input_tokens,x.cache_read_input_tokens=null!=(u=j.message.usage.cache_read_input_tokens)?u:0,x.cache_creation_input_tokens=null!=(d=j.message.usage.cache_creation_input_tokens)?d:0,o={...j.message.usage},S=null!=(c=j.message.usage.cache_creation_input_tokens)?c:null,null!=j.message.container&&(C={expiresAt:j.message.container.expires_at,id:j.message.container.id,skills:null}),null!=j.message.stop_reason&&(w={unified:J({finishReason:j.message.stop_reason,isJsonResponseFromTool:E}),raw:j.message.stop_reason}),r.enqueue({type:"response-metadata",id:null!=(g=j.message.id)?g:void 0,modelId:null!=(v=j.message.model)?v:void 0}),null!=j.message.content)for(let e=0;e<j.message.content.length;e++){let t=j.message.content[e];if("tool_use"===t.type){let e=t.caller,a=e?{type:e.type,toolId:"tool_id"in e?e.tool_id:void 0}:void 0;r.enqueue({type:"tool-input-start",id:t.id,toolName:t.name});let n=JSON.stringify(null!=(b=t.input)?b:{});r.enqueue({type:"tool-input-delta",id:t.id,delta:n}),r.enqueue({type:"tool-input-end",id:t.id}),r.enqueue({type:"tool-call",toolCallId:t.id,toolName:t.name,input:n,...a&&{providerMetadata:{anthropic:{caller:a}}}})}}return;case"message_delta":null!=j.usage.input_tokens&&x.input_tokens!==j.usage.input_tokens&&(x.input_tokens=j.usage.input_tokens),x.output_tokens=j.usage.output_tokens,null!=j.usage.cache_read_input_tokens&&(x.cache_read_input_tokens=j.usage.cache_read_input_tokens),null!=j.usage.cache_creation_input_tokens&&(x.cache_creation_input_tokens=j.usage.cache_creation_input_tokens,S=j.usage.cache_creation_input_tokens),null!=j.usage.iterations&&(x.iterations=j.usage.iterations),w={unified:J({finishReason:j.delta.stop_reason,isJsonResponseFromTool:E}),raw:null!=(A=j.delta.stop_reason)?A:void 0},Z=null!=(N=j.delta.stop_sequence)?N:null,C=null!=j.delta.container?{expiresAt:j.delta.container.expires_at,id:j.delta.container.id,skills:null!=(P=null==($=j.delta.container.skills)?void 0:$.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?P:null}:null,j.context_management&&(R=ee(j.context_management)),o={...o,...j.usage};return;case"message_stop":{let e={usage:null!=o?o:null,cacheCreationInputTokens:S,stopSequence:Z,iterations:x.iterations?x.iterations.map(e=>({type:e.type,inputTokens:e.input_tokens,outputTokens:e.output_tokens})):null,container:C,contextManagement:R},t={anthropic:e};f&&"anthropic"!==m&&(t[m]=e),r.enqueue({type:"finish",finishReason:w,usage:M({usage:x,rawUsage:o}),providerMetadata:t});return}case"error":r.enqueue({type:"error",error:j.error});return;default:throw Error(`Unsupported chunk type: ${j}`)}}})).tee(),$=A.getReader();try{await $.read();let e=await $.read();if((null==(t=e.value)?void 0:t.type)==="raw"&&(e=await $.read()),(null==(r=e.value)?void 0:r.type)==="error"){let t=e.value.error;throw new a.w({message:t.message,url:g,requestBodyValues:l,statusCode:"overloaded_error"===t.type?529:500,responseHeaders:v,responseBody:JSON.stringify(t),isRetryable:"overloaded_error"===t.type})}}finally{$.cancel().catch(()=>{}),$.releaseLock()}return{stream:N,request:{body:l},response:{headers:v}}}};function Q(e){if(!e)return!1;let t=!1,r=!1;for(let a of e){if("type"in a&&("web_fetch_20260209"===a.type||"web_search_20260209"===a.type)){t=!0;continue}if("code_execution"===a.name){r=!0;break}}return t&&!r}function ee(e){return e?{appliedEdits:e.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens};case"compact_20260112":return{type:e.type}}}).filter(e=>void 0!==e)}:null}var et=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Z_(),restart:o.O7().optional()}))),er=(0,n.W0)({id:"anthropic.bash_20241022",inputSchema:et}),ea=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Z_(),restart:o.O7().optional()}))),en=(0,n.W0)({id:"anthropic.bash_20250124",inputSchema:ea}),eo=(0,n.DG)(()=>(0,n.r0)(o.Ry({action:o.Km(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:o.IX(o.Rx().int()).optional(),text:o.Z_().optional()}))),ei=(0,n.W0)({id:"anthropic.computer_20241022",inputSchema:eo}),es=(0,n.DG)(()=>(0,n.r0)(o.Ry({action:o.Km(["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:o.bc([o.Rx().int(),o.Rx().int()]).optional(),duration:o.Rx().optional(),scroll_amount:o.Rx().optional(),scroll_direction:o.Km(["up","down","left","right"]).optional(),start_coordinate:o.bc([o.Rx().int(),o.Rx().int()]).optional(),text:o.Z_().optional()}))),el=(0,n.W0)({id:"anthropic.computer_20250124",inputSchema:es}),eu=(0,n.DG)(()=>(0,n.r0)(o.Ry({action:o.Km(["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","zoom"]),coordinate:o.bc([o.Rx().int(),o.Rx().int()]).optional(),duration:o.Rx().optional(),region:o.bc([o.Rx().int(),o.Rx().int(),o.Rx().int(),o.Rx().int()]).optional(),scroll_amount:o.Rx().optional(),scroll_direction:o.Km(["up","down","left","right"]).optional(),start_coordinate:o.bc([o.Rx().int(),o.Rx().int()]).optional(),text:o.Z_().optional()}))),ed=(0,n.W0)({id:"anthropic.computer_20251124",inputSchema:eu}),ec=(0,n.DG)(()=>(0,n.r0)(o.VK("command",[o.Ry({command:o.i0("view"),path:o.Z_(),view_range:o.bc([o.Rx(),o.Rx()]).optional()}),o.Ry({command:o.i0("create"),path:o.Z_(),file_text:o.Z_()}),o.Ry({command:o.i0("str_replace"),path:o.Z_(),old_str:o.Z_(),new_str:o.Z_()}),o.Ry({command:o.i0("insert"),path:o.Z_(),insert_line:o.Rx(),insert_text:o.Z_()}),o.Ry({command:o.i0("delete"),path:o.Z_()}),o.Ry({command:o.i0("rename"),old_path:o.Z_(),new_path:o.Z_()})]))),ep=(0,n.W0)({id:"anthropic.memory_20250818",inputSchema:ec}),eh=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert","undo_edit"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),em=(0,n.W0)({id:"anthropic.text_editor_20241022",inputSchema:eh}),ef=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert","undo_edit"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),ey=(0,n.W0)({id:"anthropic.text_editor_20250124",inputSchema:ef}),e_=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),eg=(0,n.W0)({id:"anthropic.text_editor_20250429",inputSchema:e_}),ev=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({type:o.i0("tool_reference"),toolName:o.Z_()})))),eb=(0,n.DG)(()=>(0,n.r0)(o.Ry({query:o.Z_(),limit:o.Rx().optional()}))),ew=(0,n.ql)({id:"anthropic.tool_search_bm25_20251119",inputSchema:eb,outputSchema:ev,supportsDeferredResults:!0}),ex={bash_20241022:er,bash_20250124:en,codeExecution_20250522:(e={})=>j(e),codeExecution_20250825:(e={})=>D(e),codeExecution_20260120:(e={})=>L(e),computer_20241022:ei,computer_20250124:el,computer_20251124:ed,memory_20250818:ep,textEditor_20241022:em,textEditor_20250124:ey,textEditor_20250429:eg,textEditor_20250728:(e={})=>y(e),webFetch_20250910:(e={})=>A(e),webFetch_20260209:(e={})=>Z(e),webSearch_20250305:(e={})=>I(e),webSearch_20260209:(e={})=>b(e),toolSearchRegex_20251119:(e={})=>W(e),toolSearchBm25_20251119:(e={})=>ew(e)};function ek(e={}){var t,r;let o=null!=(t=(0,n.QT)((0,n.P6)({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))?t:"https://api.anthropic.com/v1",i=null!=(r=e.name)?r:"anthropic.messages";if(e.apiKey&&e.authToken)throw new a.RU({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let s=()=>{let t=e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":(0,n.pd)({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return(0,n.CR)({"anthropic-version":"2023-06-01",...t,...e.headers},"ai-sdk/anthropic/3.0.58")},l=t=>{var r;return new Y(t,{provider:i,baseURL:o,headers:s,fetch:e.fetch,generateId:null!=(r=e.generateId)?r:n.Ox,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},u=function(e){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return l(e)};return u.specificationVersion="v3",u.languageModel=l,u.chat=l,u.messages=l,u.embeddingModel=e=>{throw new a.JJ({modelId:e,modelType:"embeddingModel"})},u.textEmbeddingModel=u.embeddingModel,u.imageModel=e=>{throw new a.JJ({modelId:e,modelType:"imageModel"})},u.tools=ex,u}ek()},6365:(e,t,r)=>{r.d(t,{N$:()=>C,eh:()=>g,Bx:()=>Z,C3:()=>eM,NF:()=>m,MS:()=>x,QF:()=>I,k0:()=>k,cP:()=>eJ,bF:()=>M,Sq:()=>eK,tc:()=>eH,W0:()=>eW,ql:()=>eX,U_:()=>f,gw:()=>y,aN:()=>eQ,Ox:()=>$,e$:()=>P,hb:()=>W,gJ:()=>q,D_:()=>j,C_:()=>X,MT:()=>B,fB:()=>eN,DG:()=>eA,pd:()=>K,P6:()=>J,kh:()=>U,RF:()=>eD,c1:()=>eq,A8:()=>eL,SN:()=>E,DB:()=>eB,NX:()=>ez,pW:()=>ej,w3:()=>eG,SA:()=>O,rJ:()=>eP,CR:()=>L,QT:()=>eY,r0:()=>e$});var a,n,o=r(9519),i=r(6496),s=r(8510);class l{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??i.$Z,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;let a=e._zod.def,n=this.seen.get(e);if(n)return n.count++,t.schemaPath.includes(e)&&(n.cycle=t.path),n.schema;let o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);let i=e._zod.toJSONSchema?.();if(i)o.schema=i;else{let r={...t,schemaPath:[...t.schemaPath,e],path:t.path},n=e._zod.parent;if(n)o.ref=n,this.process(n,r),this.seen.get(n).isParent=!0;else{let t=o.schema;switch(a.type){case"string":{t.type="string";let{minimum:r,maximum:a,format:n,patterns:i,contentEncoding:s}=e._zod.bag;if("number"==typeof r&&(t.minLength=r),"number"==typeof a&&(t.maxLength=a),n&&(t.format=({guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""})[n]??n,""===t.format&&delete t.format),s&&(t.contentEncoding=s),i&&i.size>0){let e=[...i];1===e.length?t.pattern=e[0].source:e.length>1&&(o.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{let{minimum:r,maximum:a,format:n,multipleOf:o,exclusiveMaximum:i,exclusiveMinimum:s}=e._zod.bag;"string"==typeof n&&n.includes("int")?t.type="integer":t.type="number","number"==typeof s&&(t.exclusiveMinimum=s),"number"==typeof r&&(t.minimum=r,"number"==typeof s&&(s>=r?delete t.minimum:delete t.exclusiveMinimum)),"number"==typeof i&&(t.exclusiveMaximum=i),"number"==typeof a&&(t.maximum=a,"number"==typeof i&&(i<=a?delete t.maximum:delete t.exclusiveMaximum)),"number"==typeof o&&(t.multipleOf=o);break}case"boolean":case"success":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw Error("Date cannot be represented in JSON Schema");break;case"array":{let{minimum:n,maximum:o}=e._zod.bag;"number"==typeof n&&(t.minItems=n),"number"==typeof o&&(t.maxItems=o),t.type="array",t.items=this.process(a.element,{...r,path:[...r.path,"items"]});break}case"object":{t.type="object",t.properties={};let e=a.shape;for(let a in e)t.properties[a]=this.process(e[a],{...r,path:[...r.path,"properties",a]});let n=new Set([...new Set(Object.keys(e))].filter(e=>{let t=a.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));n.size>0&&(t.required=Array.from(n)),a.catchall?._zod.def.type==="never"?t.additionalProperties=!1:a.catchall?a.catchall&&(t.additionalProperties=this.process(a.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(t.additionalProperties=!1);break}case"union":t.anyOf=a.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{let e=this.process(a.left,{...r,path:[...r.path,"allOf",0]}),n=this.process(a.right,{...r,path:[...r.path,"allOf",1]}),o=[..."allOf"in e&&1===Object.keys(e).length?e.allOf:[e],..."allOf"in n&&1===Object.keys(n).length?n.allOf:[n]];t.allOf=o;break}case"tuple":{t.type="array";let n=a.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?t.prefixItems=n:t.items=n,a.rest){let e=this.process(a.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?t.items=e:t.additionalItems=e}a.rest&&(t.items=this.process(a.rest,{...r,path:[...r.path,"items"]}));let{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(t.minItems=o),"number"==typeof i&&(t.maxItems=i);break}case"record":t.type="object",t.propertyNames=this.process(a.keyType,{...r,path:[...r.path,"propertyNames"]}),t.additionalProperties=this.process(a.valueType,{...r,path:[...r.path,"additionalProperties"]});break;case"map":if("throw"===this.unrepresentable)throw Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw Error("Set cannot be represented in JSON Schema");break;case"enum":{let e=(0,s.B8)(a.entries);e.every(e=>"number"==typeof e)&&(t.type="number"),e.every(e=>"string"==typeof e)&&(t.type="string"),t.enum=e;break}case"literal":{let e=[];for(let t of a.values)if(void 0===t){if("throw"===this.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t){if("throw"===this.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");e.push(Number(t))}else e.push(t);if(0===e.length);else if(1===e.length){let r=e[0];t.type=null===r?"null":typeof r,t.const=r}else e.every(e=>"number"==typeof e)&&(t.type="number"),e.every(e=>"string"==typeof e)&&(t.type="string"),e.every(e=>"boolean"==typeof e)&&(t.type="string"),e.every(e=>null===e)&&(t.type="null"),t.enum=e;break}case"file":{let r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:n,mime:o}=e._zod.bag;void 0!==a&&(r.minLength=a),void 0!==n&&(r.maxLength=n),o?1===o.length?(r.contentMediaType=o[0],Object.assign(t,r)):t.anyOf=o.map(e=>({...r,contentMediaType:e})):Object.assign(t,r);break}case"transform":if("throw"===this.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{let e=this.process(a.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(a.innerType,r),o.ref=a.innerType;break;case"default":this.process(a.innerType,r),o.ref=a.innerType,t.default=JSON.parse(JSON.stringify(a.defaultValue));break;case"prefault":this.process(a.innerType,r),o.ref=a.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break;case"catch":{let e;this.process(a.innerType,r),o.ref=a.innerType;try{e=a.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{let r=e._zod.pattern;if(!r)throw Error("Pattern not found in template literal");t.type="string",t.pattern=r.source;break}case"pipe":{let e="input"===this.io?"transform"===a.in._zod.def.type?a.out:a.in:a.out;this.process(e,r),o.ref=e;break}case"readonly":this.process(a.innerType,r),o.ref=a.innerType,t.readOnly=!0;break;case"lazy":{let t=e._zod.innerType;this.process(t,r),o.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(o.schema,l),"input"===this.io&&function e(t,r){let a=r??{seen:new Set};if(a.seen.has(t))return!1;a.seen.add(t);let n=t._zod.def;switch(n.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":case"custom":case"success":case"catch":return!1;case"array":return e(n.element,a);case"object":for(let t in n.shape)if(e(n.shape[t],a))return!0;return!1;case"union":for(let t of n.options)if(e(t,a))return!0;return!1;case"intersection":return e(n.left,a)||e(n.right,a);case"tuple":for(let t of n.items)if(e(t,a))return!0;if(n.rest&&e(n.rest,a))return!0;return!1;case"record":case"map":return e(n.keyType,a)||e(n.valueType,a);case"set":return e(n.valueType,a);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return e(n.innerType,a);case"lazy":return e(n.getter(),a);case"transform":return!0;case"pipe":return e(n.in,a)||e(n.out,a)}throw Error(`Unknown schema type: ${n.type}`)}(e)&&(delete o.schema.examples,delete o.schema.default),"input"===this.io&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){let r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},a=this.seen.get(e);if(!a)throw Error("Unprocessed schema. This is a bug in Zod.");let n=e=>{let t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){let a=r.external.registry.get(e[0])?.id,n=r.external.uri??(e=>e);if(a)return{ref:n(a)};let o=e[1].defId??e[1].schema.id??`schema${this.counter++}`;return e[1].defId=o,{defId:o,ref:`${n("__shared")}#/${t}/${o}`}}if(e[1]===a)return{ref:"#"};let n=`#/${t}/`,o=e[1].schema.id??`__schema${this.counter++}`;return{defId:o,ref:n+o}},o=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:r,defId:a}=n(e);t.def={...t.schema},a&&(t.defId=a);let o=t.schema;for(let e in o)delete o[e];o.$ref=r};if("throw"===r.cycles)for(let e of this.seen.entries()){let t=e[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>
1
+ "use strict";exports.id=124,exports.ids=[124],exports.modules={6939:e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,r)=>{for(var a in r)t(e,a,{get:r[a],enumerable:!0})})(o,{SYMBOL_FOR_REQ_CONTEXT:()=>i,getContext:()=>s}),e.exports=((e,o,i,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let l of a(o))n.call(e,l)||l===i||t(e,l,{get:()=>o[l],enumerable:!(s=r(o,l))||s.enumerable});return e})(t({},"__esModule",{value:!0}),o);let i=Symbol.for("@vercel/request-context");function s(){let e=globalThis;return e[i]?.get?.()??{}}},6485:(e,t,r)=>{Object.create;var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,i=(Object.getPrototypeOf,Object.prototype.hasOwnProperty),s={};((e,t)=>{for(var r in t)a(e,r,{get:t[r],enumerable:!0})})(s,{getVercelOidcToken:()=>d,getVercelOidcTokenSync:()=>c}),e.exports=((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of o(t))i.call(e,l)||l===r||a(e,l,{get:()=>t[l],enumerable:!(s=n(t,l))||s.enumerable});return e})(a({},"__esModule",{value:!0}),s);var l=r(6939),u=r(1403);async function d(){let e,t="";try{t=c()}catch(t){e=t}try{let[{getTokenPayload:e,isExpired:a},{refreshToken:n}]=await Promise.all([await r.e(361).then(r.t.bind(r,1934,23)),await r.e(136).then(r.t.bind(r,9136,23))]);(!t||a(e(t)))&&(await n(),t=c())}catch(r){let t=e instanceof Error?e.message:"";if(r instanceof Error&&(t=`${t}
2
+ ${r.message}`),t)throw new u.VercelOidcTokenError(t);throw r}return t}function c(){let e=l.getContext().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return e}},489:(e,t,r)=>{var a=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,s={};((e,t)=>{for(var r in t)a(e,r,{get:t[r],enumerable:!0})})(s,{getContext:()=>u.getContext,getVercelOidcToken:()=>l.getVercelOidcToken,getVercelOidcTokenSync:()=>l.getVercelOidcTokenSync}),e.exports=((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of o(t))i.call(e,l)||l===r||a(e,l,{get:()=>t[l],enumerable:!(s=n(t,l))||s.enumerable});return e})(a({},"__esModule",{value:!0}),s);var l=r(6485),u=r(6939)},1403:e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,r)=>{for(var a in r)t(e,a,{get:r[a],enumerable:!0})})(o,{VercelOidcTokenError:()=>i}),e.exports=((e,o,i,s)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let l of a(o))n.call(e,l)||l===i||t(e,l,{get:()=>o[l],enumerable:!(s=r(o,l))||s.enumerable});return e})(t({},"__esModule",{value:!0}),o);class i extends Error{constructor(e,t){super(e),this.name="VercelOidcTokenError",this.cause=t}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}}},3036:(e,t,r)=>{e.exports=r(517)},4523:(e,t,r)=>{r.d(t,{D3:()=>ek});var a=r(9519),n=r(6365),o=r(2943),i=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("error"),error:o.Ry({type:o.Z_(),message:o.Z_()})}))),s=(0,n.Sq)({errorSchema:i,errorToMessage:e=>e.error.message}),l=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("message"),id:o.Z_().nullish(),model:o.Z_().nullish(),content:o.IX(o.VK("type",[o.Ry({type:o.i0("text"),text:o.Z_(),citations:o.IX(o.VK("type",[o.Ry({type:o.i0("web_search_result_location"),cited_text:o.Z_(),url:o.Z_(),title:o.Z_(),encrypted_index:o.Z_()}),o.Ry({type:o.i0("page_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_page_number:o.Rx(),end_page_number:o.Rx()}),o.Ry({type:o.i0("char_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_char_index:o.Rx(),end_char_index:o.Rx()})])).optional()}),o.Ry({type:o.i0("thinking"),thinking:o.Z_(),signature:o.Z_()}),o.Ry({type:o.i0("redacted_thinking"),data:o.Z_()}),o.Ry({type:o.i0("compaction"),content:o.Z_()}),o.Ry({type:o.i0("tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),caller:o.G0([o.Ry({type:o.i0("code_execution_20250825"),tool_id:o.Z_()}),o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("server_tool_use"),id:o.Z_(),name:o.Z_(),input:o.IM(o.Z_(),o._4()).nullish(),caller:o.G0([o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("mcp_tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),server_name:o.Z_()}),o.Ry({type:o.i0("mcp_tool_result"),tool_use_id:o.Z_(),is_error:o.O7(),content:o.IX(o.G0([o.Z_(),o.Ry({type:o.i0("text"),text:o.Z_()})]))}),o.Ry({type:o.i0("web_fetch_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),retrieved_at:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),media_type:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),media_type:o.i0("text/plain"),data:o.Z_()})])})}),o.Ry({type:o.i0("web_fetch_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("web_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.IX(o.Ry({type:o.i0("web_search_result"),url:o.Z_(),title:o.Z_(),encrypted_content:o.Z_(),page_age:o.Z_().nullish()})),o.Ry({type:o.i0("web_search_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("code_execution_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("encrypted_code_execution_result"),encrypted_stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("bash_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("text_editor_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})])}),o.Ry({type:o.i0("tool_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("tool_search_tool_search_result"),tool_references:o.IX(o.Ry({type:o.i0("tool_reference"),tool_name:o.Z_()}))}),o.Ry({type:o.i0("tool_search_tool_result_error"),error_code:o.Z_()})])})])),stop_reason:o.Z_().nullish(),stop_sequence:o.Z_().nullish(),usage:o.d7({input_tokens:o.Rx(),output_tokens:o.Rx(),cache_creation_input_tokens:o.Rx().nullish(),cache_read_input_tokens:o.Rx().nullish(),iterations:o.IX(o.Ry({type:o.G0([o.i0("compaction"),o.i0("message")]),input_tokens:o.Rx(),output_tokens:o.Rx()})).nullish()}),container:o.Ry({expires_at:o.Z_(),id:o.Z_(),skills:o.IX(o.Ry({type:o.G0([o.i0("anthropic"),o.i0("custom")]),skill_id:o.Z_(),version:o.Z_()})).nullish()}).nullish(),context_management:o.Ry({applied_edits:o.IX(o.G0([o.Ry({type:o.i0("clear_tool_uses_20250919"),cleared_tool_uses:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("clear_thinking_20251015"),cleared_thinking_turns:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("compact_20260112")})]))}).nullish()}))),u=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("message_start"),message:o.Ry({id:o.Z_().nullish(),model:o.Z_().nullish(),role:o.Z_().nullish(),usage:o.d7({input_tokens:o.Rx(),cache_creation_input_tokens:o.Rx().nullish(),cache_read_input_tokens:o.Rx().nullish()}),content:o.IX(o.VK("type",[o.Ry({type:o.i0("tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),caller:o.G0([o.Ry({type:o.i0("code_execution_20250825"),tool_id:o.Z_()}),o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()})])).nullish(),stop_reason:o.Z_().nullish(),container:o.Ry({expires_at:o.Z_(),id:o.Z_()}).nullish()})}),o.Ry({type:o.i0("content_block_start"),index:o.Rx(),content_block:o.VK("type",[o.Ry({type:o.i0("text"),text:o.Z_()}),o.Ry({type:o.i0("thinking"),thinking:o.Z_()}),o.Ry({type:o.i0("tool_use"),id:o.Z_(),name:o.Z_(),input:o.IM(o.Z_(),o._4()).optional(),caller:o.G0([o.Ry({type:o.i0("code_execution_20250825"),tool_id:o.Z_()}),o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("redacted_thinking"),data:o.Z_()}),o.Ry({type:o.i0("compaction"),content:o.Z_().nullish()}),o.Ry({type:o.i0("server_tool_use"),id:o.Z_(),name:o.Z_(),input:o.IM(o.Z_(),o._4()).nullish(),caller:o.G0([o.Ry({type:o.i0("code_execution_20260120"),tool_id:o.Z_()}),o.Ry({type:o.i0("direct")})]).optional()}),o.Ry({type:o.i0("mcp_tool_use"),id:o.Z_(),name:o.Z_(),input:o._4(),server_name:o.Z_()}),o.Ry({type:o.i0("mcp_tool_result"),tool_use_id:o.Z_(),is_error:o.O7(),content:o.IX(o.G0([o.Z_(),o.Ry({type:o.i0("text"),text:o.Z_()})]))}),o.Ry({type:o.i0("web_fetch_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),retrieved_at:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),media_type:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),media_type:o.i0("text/plain"),data:o.Z_()})])})}),o.Ry({type:o.i0("web_fetch_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("web_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.IX(o.Ry({type:o.i0("web_search_result"),url:o.Z_(),title:o.Z_(),encrypted_content:o.Z_(),page_age:o.Z_().nullish()})),o.Ry({type:o.i0("web_search_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("code_execution_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("encrypted_code_execution_result"),encrypted_stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("bash_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()})])}),o.Ry({type:o.i0("text_editor_code_execution_tool_result"),tool_use_id:o.Z_(),content:o.VK("type",[o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})])}),o.Ry({type:o.i0("tool_search_tool_result"),tool_use_id:o.Z_(),content:o.G0([o.Ry({type:o.i0("tool_search_tool_search_result"),tool_references:o.IX(o.Ry({type:o.i0("tool_reference"),tool_name:o.Z_()}))}),o.Ry({type:o.i0("tool_search_tool_result_error"),error_code:o.Z_()})])})])}),o.Ry({type:o.i0("content_block_delta"),index:o.Rx(),delta:o.VK("type",[o.Ry({type:o.i0("input_json_delta"),partial_json:o.Z_()}),o.Ry({type:o.i0("text_delta"),text:o.Z_()}),o.Ry({type:o.i0("thinking_delta"),thinking:o.Z_()}),o.Ry({type:o.i0("signature_delta"),signature:o.Z_()}),o.Ry({type:o.i0("compaction_delta"),content:o.Z_().nullish()}),o.Ry({type:o.i0("citations_delta"),citation:o.VK("type",[o.Ry({type:o.i0("web_search_result_location"),cited_text:o.Z_(),url:o.Z_(),title:o.Z_(),encrypted_index:o.Z_()}),o.Ry({type:o.i0("page_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_page_number:o.Rx(),end_page_number:o.Rx()}),o.Ry({type:o.i0("char_location"),cited_text:o.Z_(),document_index:o.Rx(),document_title:o.Z_().nullable(),start_char_index:o.Rx(),end_char_index:o.Rx()})])})])}),o.Ry({type:o.i0("content_block_stop"),index:o.Rx()}),o.Ry({type:o.i0("error"),error:o.Ry({type:o.Z_(),message:o.Z_()})}),o.Ry({type:o.i0("message_delta"),delta:o.Ry({stop_reason:o.Z_().nullish(),stop_sequence:o.Z_().nullish(),container:o.Ry({expires_at:o.Z_(),id:o.Z_(),skills:o.IX(o.Ry({type:o.G0([o.i0("anthropic"),o.i0("custom")]),skill_id:o.Z_(),version:o.Z_()})).nullish()}).nullish()}),usage:o.d7({input_tokens:o.Rx().nullish(),output_tokens:o.Rx(),cache_creation_input_tokens:o.Rx().nullish(),cache_read_input_tokens:o.Rx().nullish(),iterations:o.IX(o.Ry({type:o.G0([o.i0("compaction"),o.i0("message")]),input_tokens:o.Rx(),output_tokens:o.Rx()})).nullish()}),context_management:o.Ry({applied_edits:o.IX(o.G0([o.Ry({type:o.i0("clear_tool_uses_20250919"),cleared_tool_uses:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("clear_thinking_20251015"),cleared_thinking_turns:o.Rx(),cleared_input_tokens:o.Rx()}),o.Ry({type:o.i0("compact_20260112")})]))}).nullish()}),o.Ry({type:o.i0("message_stop")}),o.Ry({type:o.i0("ping")})]))),d=(0,n.DG)(()=>(0,n.r0)(o.Ry({signature:o.Z_().optional(),redactedData:o.Z_().optional()}))),c=o.Ry({citations:o.Ry({enabled:o.O7()}).optional(),title:o.Z_().optional(),context:o.Z_().optional()}),p=o.Ry({sendReasoning:o.O7().optional(),structuredOutputMode:o.Km(["outputFormat","jsonTool","auto"]).optional(),thinking:o.VK("type",[o.Ry({type:o.i0("adaptive")}),o.Ry({type:o.i0("enabled"),budgetTokens:o.Rx().optional()}),o.Ry({type:o.i0("disabled")})]).optional(),disableParallelToolUse:o.O7().optional(),cacheControl:o.Ry({type:o.i0("ephemeral"),ttl:o.G0([o.i0("5m"),o.i0("1h")]).optional()}).optional(),mcpServers:o.IX(o.Ry({type:o.i0("url"),name:o.Z_(),url:o.Z_(),authorizationToken:o.Z_().nullish(),toolConfiguration:o.Ry({enabled:o.O7().nullish(),allowedTools:o.IX(o.Z_()).nullish()}).nullish()})).optional(),container:o.Ry({id:o.Z_().optional(),skills:o.IX(o.Ry({type:o.G0([o.i0("anthropic"),o.i0("custom")]),skillId:o.Z_(),version:o.Z_().optional()})).optional()}).optional(),toolStreaming:o.O7().optional(),effort:o.Km(["low","medium","high","max"]).optional(),speed:o.Km(["fast","standard"]).optional(),anthropicBeta:o.IX(o.Z_()).optional(),contextManagement:o.Ry({edits:o.IX(o.VK("type",[o.Ry({type:o.i0("clear_tool_uses_20250919"),trigger:o.VK("type",[o.Ry({type:o.i0("input_tokens"),value:o.Rx()}),o.Ry({type:o.i0("tool_uses"),value:o.Rx()})]).optional(),keep:o.Ry({type:o.i0("tool_uses"),value:o.Rx()}).optional(),clearAtLeast:o.Ry({type:o.i0("input_tokens"),value:o.Rx()}).optional(),clearToolInputs:o.O7().optional(),excludeTools:o.IX(o.Z_()).optional()}),o.Ry({type:o.i0("clear_thinking_20251015"),keep:o.G0([o.i0("all"),o.Ry({type:o.i0("thinking_turns"),value:o.Rx()})]).optional()}),o.Ry({type:o.i0("compact_20260112"),trigger:o.Ry({type:o.i0("input_tokens"),value:o.Rx()}).optional(),pauseAfterCompaction:o.O7().optional(),instructions:o.Z_().optional()})]))}).optional()}),h=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let r=function(e){var t;let r=null==e?void 0:e.anthropic;return null!=(t=null==r?void 0:r.cacheControl)?t:null==r?void 0:r.cache_control}(e);if(r){if(!t.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>4){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum 4 cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return r}}getWarnings(){return this.warnings}},m=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxCharacters:o.Rx().optional()}))),f=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),y=(0,n.W0)({id:"anthropic.text_editor_20250728",inputSchema:f}),_=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),userLocation:o.Ry({type:o.i0("approximate"),city:o.Z_().optional(),region:o.Z_().optional(),country:o.Z_().optional(),timezone:o.Z_().optional()}).optional()}))),g=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({url:o.Z_(),title:o.Z_().nullable(),pageAge:o.Z_().nullable(),encryptedContent:o.Z_(),type:o.i0("web_search_result")})))),v=(0,n.DG)(()=>(0,n.r0)(o.Ry({query:o.Z_()}))),b=(0,n.ql)({id:"anthropic.web_search_20260209",inputSchema:v,outputSchema:g,supportsDeferredResults:!0}),w=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),userLocation:o.Ry({type:o.i0("approximate"),city:o.Z_().optional(),region:o.Z_().optional(),country:o.Z_().optional(),timezone:o.Z_().optional()}).optional()}))),x=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({url:o.Z_(),title:o.Z_().nullable(),pageAge:o.Z_().nullable(),encryptedContent:o.Z_(),type:o.i0("web_search_result")})))),k=(0,n.DG)(()=>(0,n.r0)(o.Ry({query:o.Z_()}))),I=(0,n.ql)({id:"anthropic.web_search_20250305",inputSchema:k,outputSchema:x,supportsDeferredResults:!0}),T=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),citations:o.Ry({enabled:o.O7()}).optional(),maxContentTokens:o.Rx().optional()}))),R=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),mediaType:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),mediaType:o.i0("text/plain"),data:o.Z_()})])}),retrievedAt:o.Z_().nullable()}))),S=(0,n.DG)(()=>(0,n.r0)(o.Ry({url:o.Z_()}))),Z=(0,n.ql)({id:"anthropic.web_fetch_20260209",inputSchema:S,outputSchema:R,supportsDeferredResults:!0}),C=(0,n.DG)(()=>(0,n.r0)(o.Ry({maxUses:o.Rx().optional(),allowedDomains:o.IX(o.Z_()).optional(),blockedDomains:o.IX(o.Z_()).optional(),citations:o.Ry({enabled:o.O7()}).optional(),maxContentTokens:o.Rx().optional()}))),E=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("web_fetch_result"),url:o.Z_(),content:o.Ry({type:o.i0("document"),title:o.Z_().nullable(),citations:o.Ry({enabled:o.O7()}).optional(),source:o.G0([o.Ry({type:o.i0("base64"),mediaType:o.i0("application/pdf"),data:o.Z_()}),o.Ry({type:o.i0("text"),mediaType:o.i0("text/plain"),data:o.Z_()})])}),retrievedAt:o.Z_().nullable()}))),O=(0,n.DG)(()=>(0,n.r0)(o.Ry({url:o.Z_()}))),A=(0,n.ql)({id:"anthropic.web_fetch_20250910",inputSchema:O,outputSchema:E,supportsDeferredResults:!0});async function N({tools:e,toolChoice:t,disableParallelToolUse:r,cacheControlValidator:o,supportsStructuredOutput:i}){var s;e=(null==e?void 0:e.length)?e:void 0;let l=[],u=new Set,d=o||new h;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:l,betas:u};let c=[];for(let t of e)switch(t.type){case"function":{let e=d.getCacheControl(t.providerOptions,{type:"tool definition",canCache:!0}),r=null==(s=t.providerOptions)?void 0:s.anthropic,a=null==r?void 0:r.eagerInputStreaming,n=null==r?void 0:r.deferLoading,o=null==r?void 0:r.allowedCallers;c.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...a?{eager_input_streaming:!0}:{},...!0===i&&null!=t.strict?{strict:t.strict}:{},...null!=n?{defer_loading:n}:{},...null!=o?{allowed_callers:o}:{},...null!=t.inputExamples?{input_examples:t.inputExamples.map(e=>e.input)}:{}}),!0===i&&u.add("structured-outputs-2025-11-13"),(null!=t.inputExamples||null!=o)&&u.add("advanced-tool-use-2025-11-20");break}case"provider":switch(t.id){case"anthropic.code_execution_20250522":u.add("code-execution-2025-05-22"),c.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break;case"anthropic.code_execution_20250825":u.add("code-execution-2025-08-25"),c.push({type:"code_execution_20250825",name:"code_execution"});break;case"anthropic.code_execution_20260120":c.push({type:"code_execution_20260120",name:"code_execution"});break;case"anthropic.computer_20250124":u.add("computer-use-2025-01-24"),c.push({name:"computer",type:"computer_20250124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.computer_20251124":u.add("computer-use-2025-11-24"),c.push({name:"computer",type:"computer_20251124",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,enable_zoom:t.args.enableZoom,cache_control:void 0});break;case"anthropic.computer_20241022":u.add("computer-use-2024-10-22"),c.push({name:"computer",type:"computer_20241022",display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case"anthropic.text_editor_20250124":u.add("computer-use-2025-01-24"),c.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break;case"anthropic.text_editor_20241022":u.add("computer-use-2024-10-22"),c.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break;case"anthropic.text_editor_20250429":u.add("computer-use-2025-01-24"),c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break;case"anthropic.text_editor_20250728":{let e=await (0,n.rJ)({value:t.args,schema:m});c.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:e.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":u.add("computer-use-2025-01-24"),c.push({name:"bash",type:"bash_20250124",cache_control:void 0});break;case"anthropic.bash_20241022":u.add("computer-use-2024-10-22"),c.push({name:"bash",type:"bash_20241022",cache_control:void 0});break;case"anthropic.memory_20250818":u.add("context-management-2025-06-27"),c.push({name:"memory",type:"memory_20250818"});break;case"anthropic.web_fetch_20250910":{u.add("web-fetch-2025-09-10");let e=await (0,n.rJ)({value:t.args,schema:C});c.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{u.add("code-execution-web-tools-2026-02-09");let e=await (0,n.rJ)({value:t.args,schema:T});c.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let e=await (0,n.rJ)({value:t.args,schema:w});c.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{u.add("code-execution-web-tools-2026-02-09");let e=await (0,n.rJ)({value:t.args,schema:_});c.push({type:"web_search_20260209",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":u.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break;case"anthropic.tool_search_bm25_20251119":u.add("advanced-tool-use-2025-11-20"),c.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break;default:l.push({type:"unsupported",feature:`provider-defined tool ${t.id}`})}break;default:l.push({type:"unsupported",feature:`tool ${t}`})}if(null==t)return{tools:c,toolChoice:r?{type:"auto",disable_parallel_tool_use:r}:void 0,toolWarnings:l,betas:u};let p=t.type;switch(p){case"auto":return{tools:c,toolChoice:{type:"auto",disable_parallel_tool_use:r},toolWarnings:l,betas:u};case"required":return{tools:c,toolChoice:{type:"any",disable_parallel_tool_use:r},toolWarnings:l,betas:u};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:l,betas:u};case"tool":return{tools:c,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:r},toolWarnings:l,betas:u};default:throw new a.A_({functionality:`tool choice type: ${p}`})}}function M({usage:e,rawUsage:t}){var r,a;let n,o;let i=null!=(r=e.cache_creation_input_tokens)?r:0,s=null!=(a=e.cache_read_input_tokens)?a:0;if(e.iterations&&e.iterations.length>0){let t=e.iterations.reduce((e,t)=>({input:e.input+t.input_tokens,output:e.output+t.output_tokens}),{input:0,output:0});n=t.input,o=t.output}else n=e.input_tokens,o=e.output_tokens;return{inputTokens:{total:n+i+s,noCache:n,cacheRead:s,cacheWrite:i},outputTokens:{total:o,text:void 0,reasoning:void 0},raw:null!=t?t:e}}var $=(0,n.DG)(()=>(0,n.r0)(o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}))),P=(0,n.DG)(()=>(0,n.r0)(o.Ry({code:o.Z_()}))),j=(0,n.ql)({id:"anthropic.code_execution_20250522",inputSchema:P,outputSchema:$}),F=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})]))),z=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("programmatic-tool-call"),code:o.Z_()}),o.Ry({type:o.i0("bash_code_execution"),command:o.Z_()}),o.VK("command",[o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("view"),path:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("create"),path:o.Z_(),file_text:o.Z_().nullish()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("str_replace"),path:o.Z_(),old_str:o.Z_(),new_str:o.Z_()})])]))),D=(0,n.ql)({id:"anthropic.code_execution_20250825",inputSchema:z,outputSchema:F,supportsDeferredResults:!0}),q=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("code_execution_result"),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("encrypted_code_execution_result"),encrypted_stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx(),content:o.IX(o.Ry({type:o.i0("code_execution_output"),file_id:o.Z_()})).optional().default([])}),o.Ry({type:o.i0("bash_code_execution_result"),content:o.IX(o.Ry({type:o.i0("bash_code_execution_output"),file_id:o.Z_()})),stdout:o.Z_(),stderr:o.Z_(),return_code:o.Rx()}),o.Ry({type:o.i0("bash_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_tool_result_error"),error_code:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution_view_result"),content:o.Z_(),file_type:o.Z_(),num_lines:o.Rx().nullable(),start_line:o.Rx().nullable(),total_lines:o.Rx().nullable()}),o.Ry({type:o.i0("text_editor_code_execution_create_result"),is_file_update:o.O7()}),o.Ry({type:o.i0("text_editor_code_execution_str_replace_result"),lines:o.IX(o.Z_()).nullable(),new_lines:o.Rx().nullable(),new_start:o.Rx().nullable(),old_lines:o.Rx().nullable(),old_start:o.Rx().nullable()})]))),U=(0,n.DG)(()=>(0,n.r0)(o.VK("type",[o.Ry({type:o.i0("programmatic-tool-call"),code:o.Z_()}),o.Ry({type:o.i0("bash_code_execution"),command:o.Z_()}),o.VK("command",[o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("view"),path:o.Z_()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("create"),path:o.Z_(),file_text:o.Z_().nullish()}),o.Ry({type:o.i0("text_editor_code_execution"),command:o.i0("str_replace"),path:o.Z_(),old_str:o.Z_(),new_str:o.Z_()})])]))),L=(0,n.ql)({id:"anthropic.code_execution_20260120",inputSchema:U,outputSchema:q,supportsDeferredResults:!0}),V=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({type:o.i0("tool_reference"),toolName:o.Z_()})))),G=(0,n.DG)(()=>(0,n.r0)(o.Ry({pattern:o.Z_(),limit:o.Rx().optional()}))),W=(0,n.ql)({id:"anthropic.tool_search_regex_20251119",inputSchema:G,outputSchema:V,supportsDeferredResults:!0});function X(e){return e instanceof URL||"string"==typeof e&&/^https?:\/\//i.test(e)}function B(e){return e instanceof URL?e.toString():e}async function K({prompt:e,sendReasoning:t,warnings:r,cacheControlValidator:o,toolNameMapping:i}){var s,l,u,p,m,f,y,_,g,v,b,w,k,I,T,R,S,Z,C;let O;let A=new Set,N=function(e){let t;let r=[];for(let a of e){let{role:e}=a;switch(e){case"system":(null==t?void 0:t.type)!=="system"&&(t={type:"system",messages:[]},r.push(t)),t.messages.push(a);break;case"assistant":(null==t?void 0:t.type)!=="assistant"&&(t={type:"assistant",messages:[]},r.push(t)),t.messages.push(a);break;case"user":case"tool":(null==t?void 0:t.type)!=="user"&&(t={type:"user",messages:[]},r.push(t)),t.messages.push(a);break;default:throw Error(`Unsupported role: ${e}`)}}return r}(e),M=o||new h,P=[];async function j(e){var t,r;let a=await (0,n.c1)({provider:"anthropic",providerOptions:e,schema:c});return null!=(r=null==(t=null==a?void 0:a.citations)?void 0:t.enabled)&&r}async function z(e){let t=await (0,n.c1)({provider:"anthropic",providerOptions:e,schema:c});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let e=0;e<N.length;e++){let o=N[e],c=e===N.length-1,h=o.type;switch(h){case"system":if(null!=O)throw new a.A_({functionality:"Multiple system messages that are separated by user/assistant messages"});O=o.messages.map(({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:M.getCacheControl(t,{type:"system message",canCache:!0})}));break;case"user":{let e=[];for(let t of o.messages){let{role:o,content:i}=t;switch(o){case"user":for(let r=0;r<i.length;r++){let o=i[r],d=r===i.length-1,c=null!=(s=M.getCacheControl(o.providerOptions,{type:"user message part",canCache:!0}))?s:d?M.getCacheControl(t.providerOptions,{type:"user message",canCache:!0}):void 0;switch(o.type){case"text":e.push({type:"text",text:o.text,cache_control:c});break;case"file":if(o.mediaType.startsWith("image/"))e.push({type:"image",source:X(o.data)?{type:"url",url:B(o.data)}:{type:"base64",media_type:"image/*"===o.mediaType?"image/jpeg":o.mediaType,data:(0,n.QF)(o.data)},cache_control:c});else if("application/pdf"===o.mediaType){A.add("pdfs-2024-09-25");let t=await j(o.providerOptions),r=await z(o.providerOptions);e.push({type:"document",source:X(o.data)?{type:"url",url:B(o.data)}:{type:"base64",media_type:"application/pdf",data:(0,n.QF)(o.data)},title:null!=(l=r.title)?l:o.filename,...r.context&&{context:r.context},...t&&{citations:{enabled:!0}},cache_control:c})}else if("text/plain"===o.mediaType){let t=await j(o.providerOptions),r=await z(o.providerOptions);e.push({type:"document",source:X(o.data)?{type:"url",url:B(o.data)}:{type:"text",media_type:"text/plain",data:function(e){if("string"==typeof e)return new TextDecoder().decode((0,n.MS)(e));if(e instanceof Uint8Array)return new TextDecoder().decode(e);if(e instanceof URL)throw new a.A_({functionality:"URL-based text documents are not supported for citations"});throw new a.A_({functionality:`unsupported data type for text documents: ${typeof e}`})}(o.data)},title:null!=(u=r.title)?u:o.filename,...r.context&&{context:r.context},...t&&{citations:{enabled:!0}},cache_control:c})}else throw new a.A_({functionality:`media type: ${o.mediaType}`})}}break;case"tool":for(let a=0;a<i.length;a++){let o;let s=i[a];if("tool-approval-response"===s.type)continue;let l=a===i.length-1,u=null!=(p=M.getCacheControl(s.providerOptions,{type:"tool result part",canCache:!0}))?p:l?M.getCacheControl(t.providerOptions,{type:"tool result message",canCache:!0}):void 0,d=s.output;switch(d.type){case"content":o=d.value.map(e=>{var t;switch(e.type){case"text":return{type:"text",text:e.text};case"image-data":return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data}};case"image-url":return{type:"image",source:{type:"url",url:e.url}};case"file-url":return{type:"document",source:{type:"url",url:e.url}};case"file-data":if("application/pdf"===e.mediaType)return A.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:e.mediaType,data:e.data}};r.push({type:"other",message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return;case"custom":{let a=null==(t=e.providerOptions)?void 0:t.anthropic;if((null==a?void 0:a.type)==="tool-reference")return{type:"tool_reference",tool_name:a.toolName};r.push({type:"other",message:"unsupported custom tool content part"});return}default:r.push({type:"other",message:`unsupported tool content part type: ${e.type}`});return}}).filter(n.C_);break;case"text":case"error-text":o=d.value;break;case"execution-denied":o=null!=(m=d.reason)?m:"Tool execution denied.";break;default:o=JSON.stringify(d.value)}e.push({type:"tool_result",tool_use_id:s.toolCallId,content:o,is_error:"error-text"===d.type||"error-json"===d.type||void 0,cache_control:u})}break;default:throw Error(`Unsupported role: ${o}`)}}P.push({role:"user",content:e});break}case"assistant":{let e=[],a=new Set;for(let s=0;s<o.messages.length;s++){let l=o.messages[s],u=s===o.messages.length-1,{content:p}=l;for(let o=0;o<p.length;o++){let s=p[o],h=o===p.length-1,m=null!=(f=M.getCacheControl(s.providerOptions,{type:"assistant message part",canCache:!0}))?f:h?M.getCacheControl(l.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(s.type){case"text":{let t=null==(y=s.providerOptions)?void 0:y.anthropic;(null==t?void 0:t.type)==="compaction"?e.push({type:"compaction",content:s.text,cache_control:m}):e.push({type:"text",text:c&&u&&h?s.text.trim():s.text,cache_control:m});break}case"reasoning":if(t){let t=await (0,n.c1)({provider:"anthropic",providerOptions:s.providerOptions,schema:d});null!=t?null!=t.signature?(M.getCacheControl(s.providerOptions,{type:"thinking block",canCache:!1}),e.push({type:"thinking",thinking:s.text,signature:t.signature})):null!=t.redactedData?(M.getCacheControl(s.providerOptions,{type:"redacted thinking block",canCache:!1}),e.push({type:"redacted_thinking",data:t.redactedData})):r.push({type:"other",message:"unsupported reasoning metadata"}):r.push({type:"other",message:"unsupported reasoning metadata"})}else r.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":{if(s.providerExecuted){let t=i.toProviderToolName(s.toolName);if((null==(g=null==(_=s.providerOptions)?void 0:_.anthropic)?void 0:g.type)==="mcp-tool-use"){a.add(s.toolCallId);let t=null==(b=null==(v=s.providerOptions)?void 0:v.anthropic)?void 0:b.serverName;if(null==t||"string"!=typeof t){r.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}e.push({type:"mcp_tool_use",id:s.toolCallId,name:s.toolName,input:s.input,server_name:t,cache_control:m})}else if("code_execution"===t&&null!=s.input&&"object"==typeof s.input&&"type"in s.input&&"string"==typeof s.input.type&&("bash_code_execution"===s.input.type||"text_editor_code_execution"===s.input.type))e.push({type:"server_tool_use",id:s.toolCallId,name:s.input.type,input:s.input,cache_control:m});else if("code_execution"===t&&null!=s.input&&"object"==typeof s.input&&"type"in s.input&&"programmatic-tool-call"===s.input.type){let{type:t,...r}=s.input;e.push({type:"server_tool_use",id:s.toolCallId,name:"code_execution",input:r,cache_control:m})}else"code_execution"===t||"web_fetch"===t||"web_search"===t?e.push({type:"server_tool_use",id:s.toolCallId,name:t,input:s.input,cache_control:m}):"tool_search_tool_regex"===t||"tool_search_tool_bm25"===t?e.push({type:"server_tool_use",id:s.toolCallId,name:t,input:s.input,cache_control:m}):r.push({type:"other",message:`provider executed tool call for tool ${s.toolName} is not supported`});break}let t=null==(w=s.providerOptions)?void 0:w.anthropic,n=(null==t?void 0:t.caller)?("code_execution_20250825"===t.caller.type||"code_execution_20260120"===t.caller.type)&&t.caller.toolId?{type:t.caller.type,tool_id:t.caller.toolId}:"direct"===t.caller.type?{type:"direct"}:void 0:void 0;e.push({type:"tool_use",id:s.toolCallId,name:s.toolName,input:s.input,...n&&{caller:n},cache_control:m});break}case"tool-result":{let t=i.toProviderToolName(s.toolName);if(a.has(s.toolCallId)){let t=s.output;if("json"!==t.type&&"error-json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId,is_error:"error-json"===t.type,content:t.value,cache_control:m})}else if("code_execution"===t){let t=s.output;if("error-text"===t.type||"error-json"===t.type){let r={};try{"string"==typeof t.value?r=JSON.parse(t.value):"object"==typeof t.value&&null!==t.value&&(r=t.value)}catch(e){}"code_execution_tool_result_error"===r.type?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:"code_execution_tool_result_error",error_code:null!=(k=r.errorCode)?k:"unknown"},cache_control:m}):e.push({type:"bash_code_execution_tool_result",tool_use_id:s.toolCallId,cache_control:m,content:{type:"bash_code_execution_tool_result_error",error_code:null!=(I=r.errorCode)?I:"unknown"}});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}if(null==t.value||"object"!=typeof t.value||!("type"in t.value)||"string"!=typeof t.value.type){r.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${s.toolName}`});break}if("code_execution_result"===t.value.type){let r=await (0,n.rJ)({value:t.value,schema:$});e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code,content:null!=(T=r.content)?T:[]},cache_control:m})}else if("encrypted_code_execution_result"===t.value.type){let r=await (0,n.rJ)({value:t.value,schema:q});"encrypted_code_execution_result"===r.type&&e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:r.type,encrypted_stdout:r.encrypted_stdout,stderr:r.stderr,return_code:r.return_code,content:null!=(R=r.content)?R:[]},cache_control:m})}else{let r=await (0,n.rJ)({value:t.value,schema:F});"code_execution_result"===r.type?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code,content:null!=(S=r.content)?S:[]},cache_control:m}):"bash_code_execution_result"===r.type||"bash_code_execution_tool_result_error"===r.type?e.push({type:"bash_code_execution_tool_result",tool_use_id:s.toolCallId,cache_control:m,content:r}):e.push({type:"text_editor_code_execution_tool_result",tool_use_id:s.toolCallId,cache_control:m,content:r})}break}if("web_fetch"===t){let t=s.output;if("error-json"===t.type){let r={};try{"string"==typeof t.value?r=JSON.parse(t.value):"object"==typeof t.value&&null!==t.value&&(r=t.value)}catch(a){let e=null==(Z=t.value)?void 0:Z.errorCode;r={errorCode:"string"==typeof e?e:"unknown"}}e.push({type:"web_fetch_tool_result",tool_use_id:s.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:null!=(C=r.errorCode)?C:"unknown"},cache_control:m});break}if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let a=await (0,n.rJ)({value:t.value,schema:E});e.push({type:"web_fetch_tool_result",tool_use_id:s.toolCallId,content:{type:"web_fetch_result",url:a.url,retrieved_at:a.retrievedAt,content:{type:"document",title:a.content.title,citations:a.content.citations,source:{type:a.content.source.type,media_type:a.content.source.mediaType,data:a.content.source.data}}},cache_control:m});break}if("web_search"===t){let t=s.output;if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let a=await (0,n.rJ)({value:t.value,schema:x});e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId,content:a.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:m});break}if("tool_search_tool_regex"===t||"tool_search_tool_bm25"===t){let t=s.output;if("json"!==t.type){r.push({type:"other",message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let a=(await (0,n.rJ)({value:t.value,schema:V})).map(e=>({type:"tool_reference",tool_name:e.toolName}));e.push({type:"tool_search_tool_result",tool_use_id:s.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:a},cache_control:m});break}r.push({type:"other",message:`provider executed tool result for tool ${s.toolName} is not supported`})}}}}P.push({role:"assistant",content:e});break}default:throw Error(`content type: ${h}`)}}return{prompt:{system:O,messages:P},betas:A}}function J({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":case"model_context_window_exceeded":return"length";default:return"other"}}function H(e,t,r){var a;if("web_search_result_location"===e.type)return{type:"source",sourceType:"url",id:r(),url:e.url,title:e.title,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if("page_location"!==e.type&&"char_location"!==e.type)return;let n=t[e.document_index];if(n)return{type:"source",sourceType:"document",id:r(),mediaType:n.mediaType,title:null!=(a=e.document_title)?a:n.title,filename:n.filename,providerMetadata:{anthropic:"page_location"===e.type?{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 Y=class{constructor(e,t){var r;this.specificationVersion="v3",this.modelId=e,this.config=t,this.generateId=null!=(r=t.generateId)?r:n.Ox}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(".");return -1===t?e:e.substring(0,t)}get supportedUrls(){var e,t,r;return null!=(r=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?r:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:r,temperature:a,topP:o,topK:i,frequencyPenalty:s,presencePenalty:l,stopSequences:u,responseFormat:d,seed:c,tools:m,toolChoice:f,providerOptions:y,stream:_}){var g,v,b,w,x,k,I,T;let R=[];null!=s&&R.push({type:"unsupported",feature:"frequencyPenalty"}),null!=l&&R.push({type:"unsupported",feature:"presencePenalty"}),null!=c&&R.push({type:"unsupported",feature:"seed"}),null!=a&&a>1?(R.push({type:"unsupported",feature:"temperature",details:`${a} exceeds anthropic maximum of 1.0. clamped to 1.0`}),a=1):null!=a&&a<0&&(R.push({type:"unsupported",feature:"temperature",details:`${a} is below anthropic minimum of 0. clamped to 0`}),a=0),(null==d?void 0:d.type)==="json"&&null==d.schema&&R.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let S=this.providerOptionsName,Z=await (0,n.c1)({provider:"anthropic",providerOptions:y,schema:p}),C="anthropic"!==S?await (0,n.c1)({provider:S,providerOptions:y,schema:p}):null,E=null!=C,O=Object.assign({},null!=Z?Z:{},null!=C?C:{}),{maxOutputTokens:A,supportsStructuredOutput:M,isKnownModel:$}=(T=this.modelId).includes("claude-sonnet-4-6")||T.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,isKnownModel:!0}:T.includes("claude-sonnet-4-5")||T.includes("claude-opus-4-5")||T.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:T.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:T.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:T.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:T.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1},P=(null==(g=this.config.supportsNativeStructuredOutput)||g)&&M,j=null!=(v=null==O?void 0:O.structuredOutputMode)?v:"auto",F="outputFormat"===j||"auto"===j&&P,z=(null==d?void 0:d.type)!=="json"||null==d.schema||F?void 0:{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:d.schema},D=null==O?void 0:O.contextManagement,q=new h,U=(0,n.U_)({tools:m,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:L,betas:V}=await K({prompt:t,sendReasoning:null==(b=null==O?void 0:O.sendReasoning)||b,warnings:R,cacheControlValidator:q,toolNameMapping:U}),G=null==(w=null==O?void 0:O.thinking)?void 0:w.type,W="enabled"===G||"adaptive"===G,X="enabled"===G?null==(x=null==O?void 0:O.thinking)?void 0:x.budgetTokens:void 0,B=null!=r?r:A,J={model:this.modelId,max_tokens:B,temperature:a,top_k:i,top_p:o,stop_sequences:u,...W&&{thinking:{type:G,...null!=X&&{budget_tokens:X}}},...((null==O?void 0:O.effort)||F&&(null==d?void 0:d.type)==="json"&&null!=d.schema)&&{output_config:{...(null==O?void 0:O.effort)&&{effort:O.effort},...F&&(null==d?void 0:d.type)==="json"&&null!=d.schema&&{format:{type:"json_schema",schema:d.schema}}}},...(null==O?void 0:O.speed)&&{speed:O.speed},...(null==O?void 0:O.cacheControl)&&{cache_control:O.cacheControl},...(null==O?void 0:O.mcpServers)&&O.mcpServers.length>0&&{mcp_servers:O.mcpServers.map(e=>({type:e.type,name:e.name,url:e.url,authorization_token:e.authorizationToken,tool_configuration:e.toolConfiguration?{allowed_tools:e.toolConfiguration.allowedTools,enabled:e.toolConfiguration.enabled}:void 0}))},...(null==O?void 0:O.container)&&{container:O.container.skills&&O.container.skills.length>0?{id:O.container.id,skills:O.container.skills.map(e=>({type:e.type,skill_id:e.skillId,version:e.version}))}:O.container.id},system:L.system,messages:L.messages,...D&&{context_management:{edits:D.edits.map(e=>{let t=e.type;switch(t){case"clear_tool_uses_20250919":return{type:e.type,...void 0!==e.trigger&&{trigger:e.trigger},...void 0!==e.keep&&{keep:e.keep},...void 0!==e.clearAtLeast&&{clear_at_least:e.clearAtLeast},...void 0!==e.clearToolInputs&&{clear_tool_inputs:e.clearToolInputs},...void 0!==e.excludeTools&&{exclude_tools:e.excludeTools}};case"clear_thinking_20251015":return{type:e.type,...void 0!==e.keep&&{keep:e.keep}};case"compact_20260112":return{type:e.type,...void 0!==e.trigger&&{trigger:e.trigger},...void 0!==e.pauseAfterCompaction&&{pause_after_compaction:e.pauseAfterCompaction},...void 0!==e.instructions&&{instructions:e.instructions}};default:R.push({type:"other",message:`Unknown context management strategy: ${t}`});return}}).filter(e=>void 0!==e)}}};W?("enabled"===G&&null==X&&(R.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),J.thinking={type:"enabled",budget_tokens:1024},X=1024),null!=J.temperature&&(J.temperature=void 0,R.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(J.top_k=void 0,R.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),null!=o&&(J.top_p=void 0,R.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),J.max_tokens=B+(null!=X?X:0)):null!=o&&null!=a&&(R.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),J.top_p=void 0),$&&J.max_tokens>A&&(null!=r&&R.push({type:"unsupported",feature:"maxOutputTokens",details:`${J.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${A} max output tokens. The max output tokens have been limited to ${A}.`}),J.max_tokens=A),(null==O?void 0:O.mcpServers)&&O.mcpServers.length>0&&V.add("mcp-client-2025-04-04"),D&&(V.add("context-management-2025-06-27"),D.edits.some(e=>"compact_20260112"===e.type)&&V.add("compact-2026-01-12")),(null==O?void 0:O.container)&&O.container.skills&&O.container.skills.length>0&&(V.add("code-execution-2025-08-25"),V.add("skills-2025-10-02"),V.add("files-api-2025-04-14"),(null==m?void 0:m.some(e=>"provider"===e.type&&("anthropic.code_execution_20250825"===e.id||"anthropic.code_execution_20260120"===e.id)))||R.push({type:"other",message:"code execution tool is required when using skills"})),(null==O?void 0:O.effort)&&V.add("effort-2025-11-24"),(null==O?void 0:O.speed)==="fast"&&V.add("fast-mode-2026-02-01"),_&&(null==(k=null==O?void 0:O.toolStreaming)||k)&&V.add("fine-grained-tool-streaming-2025-05-14");let{tools:H,toolChoice:Y,toolWarnings:Q,betas:ee}=await N(null!=z?{tools:[...null!=m?m:[],z],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:q,supportsStructuredOutput:!1}:{tools:null!=m?m:[],toolChoice:f,disableParallelToolUse:null==O?void 0:O.disableParallelToolUse,cacheControlValidator:q,supportsStructuredOutput:P}),et=q.getWarnings();return{args:{...J,tools:H,tool_choice:Y,stream:!0===_||void 0},warnings:[...R,...Q,...et],betas:new Set([...V,...ee,...e,...null!=(I=null==O?void 0:O.anthropicBeta)?I:[]]),usesJsonResponseTool:null!=z,toolNameMapping:U,providerOptionsName:S,usedCustomProviderKey:E}}async getHeaders({betas:e,headers:t}){return(0,n.NF)(await (0,n.DB)(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,r;let a=null!=(t=(await (0,n.DB)(this.config.headers))["anthropic-beta"])?t:"",o=null!=(r=null==e?void 0:e["anthropic-beta"])?r:"";return new Set([...a.toLowerCase().split(","),...o.toLowerCase().split(",")].map(e=>e.trim()).filter(e=>""!==e))}buildRequestUrl(e){var t,r,a;return null!=(a=null==(r=(t=this.config).buildRequestUrl)?void 0:r.call(t,this.config.baseURL,e))?a:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var r,a,n;return null!=(n=null==(a=(r=this.config).transformRequestBody)?void 0:a.call(r,e,t))?n:e}extractCitationDocuments(e){return e.filter(e=>"user"===e.role).flatMap(e=>e.content).filter(e=>{var t,r;if("file"!==e.type||"application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;let a=null==(t=e.providerOptions)?void 0:t.anthropic,n=null==a?void 0:a.citations;return null!=(r=null==n?void 0:n.enabled)&&r}).map(e=>{var t;return{title:null!=(t=e.filename)?t:"Untitled Document",filename:e.filename,mediaType:e.mediaType}})}async doGenerate(e){var t,r,a,o,i,u,d;let{args:c,warnings:p,betas:h,usesJsonResponseTool:m,toolNameMapping:f,providerOptionsName:y,usedCustomProviderKey:_}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),g=[...this.extractCitationDocuments(e.prompt)],v=Q(c.tools),{responseHeaders:b,value:w,rawValue:x}=await (0,n.A8)({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:h,headers:e.headers}),body:this.transformRequestBody(c,h),failedResponseHandler:s,successfulResponseHandler:(0,n.tc)(l),abortSignal:e.abortSignal,fetch:this.config.fetch}),k=[],I={},T={},R=!1;for(let e of w.content)switch(e.type){case"text":if(!m&&(k.push({type:"text",text:e.text}),e.citations))for(let t of e.citations){let e=H(t,g,this.generateId);e&&k.push(e)}break;case"thinking":k.push({type:"reasoning",text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case"redacted_thinking":k.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:e.data}}});break;case"compaction":k.push({type:"text",text:e.content,providerMetadata:{anthropic:{type:"compaction"}}});break;case"tool_use":if(m&&"json"===e.name)R=!0,k.push({type:"text",text:JSON.stringify(e.input)});else{let t=e.caller,r=t?{type:t.type,toolId:"tool_id"in t?t.tool_id:void 0}:void 0;k.push({type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),...r&&{providerMetadata:{anthropic:{caller:r}}}})}break;case"server_tool_use":if("text_editor_code_execution"===e.name||"bash_code_execution"===e.name)k.push({type:"tool-call",toolCallId:e.id,toolName:f.toCustomToolName("code_execution"),input:JSON.stringify({type:e.name,...e.input}),providerExecuted:!0});else if("web_search"===e.name||"code_execution"===e.name||"web_fetch"===e.name){let t="code_execution"===e.name&&null!=e.input&&"object"==typeof e.input&&"code"in e.input&&!("type"in e.input)?{type:"programmatic-tool-call",...e.input}:e.input;k.push({type:"tool-call",toolCallId:e.id,toolName:f.toCustomToolName(e.name),input:JSON.stringify(t),providerExecuted:!0,...v&&"code_execution"===e.name?{dynamic:!0}:{}})}else("tool_search_tool_regex"===e.name||"tool_search_tool_bm25"===e.name)&&(T[e.id]=e.name,k.push({type:"tool-call",toolCallId:e.id,toolName:f.toCustomToolName(e.name),input:JSON.stringify(e.input),providerExecuted:!0}));break;case"mcp_tool_use":I[e.id]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:e.server_name}}},k.push(I[e.id]);break;case"mcp_tool_result":k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:I[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:I[e.tool_use_id].providerMetadata});break;case"web_fetch_tool_result":"web_fetch_result"===e.content.type?(g.push({title:null!=(t=e.content.content.title)?t:e.content.url,mediaType:e.content.content.source.media_type}),k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}})):"web_fetch_tool_result_error"===e.content.type&&k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:e.content.error_code}});break;case"web_search_tool_result":if(Array.isArray(e.content))for(let t of(k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_search"),result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})}),e.content))k.push({type:"source",sourceType:"url",id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}});else k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code}});break;case"code_execution_tool_result":"code_execution_result"===e.content.type?k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(a=e.content.content)?a:[]}}):"encrypted_code_execution_result"===e.content.type?k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:{type:e.content.type,encrypted_stdout:e.content.encrypted_stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(o=e.content.content)?o:[]}}):"code_execution_tool_result_error"===e.content.type&&k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code}});break;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName("code_execution"),result:e.content});break;case"tool_search_tool_result":{let t=T[e.tool_use_id];if(null==t){let e=f.toCustomToolName("tool_search_tool_bm25");f.toCustomToolName("tool_search_tool_regex"),t="tool_search_tool_bm25"!==e?"tool_search_tool_bm25":"tool_search_tool_regex"}"tool_search_tool_search_result"===e.content.type?k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):k.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:f.toCustomToolName(t),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:e.content.error_code}})}}return{content:k,finishReason:{unified:J({finishReason:w.stop_reason,isJsonResponseFromTool:R}),raw:null!=(i=w.stop_reason)?i:void 0},usage:M({usage:w.usage}),request:{body:c},response:{id:null!=(u=w.id)?u:void 0,modelId:null!=(d=w.model)?d:void 0,headers:b,body:x},warnings:p,providerMetadata:(()=>{var e,t,r,a,n;let o={usage:w.usage,cacheCreationInputTokens:null!=(e=w.usage.cache_creation_input_tokens)?e:null,stopSequence:null!=(t=w.stop_sequence)?t:null,iterations:w.usage.iterations?w.usage.iterations.map(e=>({type:e.type,inputTokens:e.input_tokens,outputTokens:e.output_tokens})):null,container:w.container?{expiresAt:w.container.expires_at,id:w.container.id,skills:null!=(a=null==(r=w.container.skills)?void 0:r.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?a:null}:null,contextManagement:null!=(n=ee(w.context_management))?n:null},i={anthropic:o};return _&&"anthropic"!==y&&(i[y]=o),i})()}}async doStream(e){var t,r;let o,i;let{args:l,warnings:d,betas:c,usesJsonResponseTool:p,toolNameMapping:h,providerOptionsName:m,usedCustomProviderKey:f}=await this.getArgs({...e,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),y=[...this.extractCitationDocuments(e.prompt)],_=Q(l.tools),g=this.buildRequestUrl(!0),{responseHeaders:v,value:b}=await (0,n.A8)({url:g,headers:await this.getHeaders({betas:c,headers:e.headers}),body:this.transformRequestBody(l,c),failedResponseHandler:s,successfulResponseHandler:(0,n.cP)(u),abortSignal:e.abortSignal,fetch:this.config.fetch}),w={unified:"other",raw:void 0},x={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},k={},I={},T={},R=null,S=null,Z=null,C=null,E=!1,O=this.generateId,[A,N]=b.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:d})},transform(t,r){var a,n,s,l,u,d,c,g,v,b,A,N,$,P;if(e.includeRawChunks&&r.enqueue({type:"raw",rawValue:t.rawValue}),!t.success){r.enqueue({type:"error",error:t.error});return}let j=t.value;switch(j.type){case"ping":return;case"content_block_start":{let e=j.content_block,t=e.type;switch(i=t,t){case"text":if(p)return;k[j.index]={type:"text"},r.enqueue({type:"text-start",id:String(j.index)});return;case"thinking":k[j.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(j.index)});return;case"redacted_thinking":k[j.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(j.index),providerMetadata:{anthropic:{redactedData:e.data}}});return;case"compaction":k[j.index]={type:"text"},r.enqueue({type:"text-start",id:String(j.index),providerMetadata:{anthropic:{type:"compaction"}}});return;case"tool_use":if(p&&"json"===e.name)E=!0,k[j.index]={type:"text"},r.enqueue({type:"text-start",id:String(j.index)});else{let t=e.caller,a=t?{type:t.type,toolId:"tool_id"in t?t.tool_id:void 0}:void 0,n=e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):"";k[j.index]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:n,firstDelta:0===n.length,...a&&{caller:a}},r.enqueue({type:"tool-input-start",id:e.id,toolName:e.name})}return;case"server_tool_use":if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(e.name)){let t="text_editor_code_execution"===e.name||"bash_code_execution"===e.name?"code_execution":e.name,a=h.toCustomToolName(t),n=null!=e.input&&"object"==typeof e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):"";k[j.index]={type:"tool-call",toolCallId:e.id,toolName:a,input:n,providerExecuted:!0,..._&&"code_execution"===t?{dynamic:!0}:{},firstDelta:!0,providerToolName:e.name},r.enqueue({type:"tool-input-start",id:e.id,toolName:a,providerExecuted:!0,..._&&"code_execution"===t?{dynamic:!0}:{}})}else if("tool_search_tool_regex"===e.name||"tool_search_tool_bm25"===e.name){T[e.id]=e.name;let t=h.toCustomToolName(e.name);k[j.index]={type:"tool-call",toolCallId:e.id,toolName:t,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:e.name},r.enqueue({type:"tool-input-start",id:e.id,toolName:t,providerExecuted:!0})}return;case"web_fetch_tool_result":"web_fetch_result"===e.content.type?(y.push({title:null!=(a=e.content.content.title)?a:e.content.url,mediaType:e.content.content.source.media_type}),r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}})):"web_fetch_tool_result_error"===e.content.type&&r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:e.content.error_code}});return;case"web_search_tool_result":if(Array.isArray(e.content))for(let t of(r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_search"),result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}})}),e.content))r.enqueue({type:"source",sourceType:"url",id:O(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(n=t.page_age)?n:null}}});else r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code}});return;case"code_execution_tool_result":"code_execution_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(s=e.content.content)?s:[]}}):"encrypted_code_execution_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),result:{type:e.content.type,encrypted_stdout:e.content.encrypted_stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:null!=(l=e.content.content)?l:[]}}):"code_execution_tool_result_error"===e.content.type&&r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code}});return;case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName("code_execution"),result:e.content});return;case"tool_search_tool_result":{let t=T[e.tool_use_id];if(null==t){let e=h.toCustomToolName("tool_search_tool_bm25");h.toCustomToolName("tool_search_tool_regex"),t="tool_search_tool_bm25"!==e?"tool_search_tool_bm25":"tool_search_tool_regex"}"tool_search_tool_search_result"===e.content.type?r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:h.toCustomToolName(t),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:e.content.error_code}});return}case"mcp_tool_use":I[e.id]={type:"tool-call",toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:e.server_name}}},r.enqueue(I[e.id]);return;case"mcp_tool_result":r.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:I[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:I[e.tool_use_id].providerMetadata});return;default:throw Error(`Unsupported content block type: ${t}`)}}case"content_block_stop":if(null!=k[j.index]){let e=k[j.index];switch(e.type){case"text":r.enqueue({type:"text-end",id:String(j.index)});break;case"reasoning":r.enqueue({type:"reasoning-end",id:String(j.index)});break;case"tool-call":if(!(p&&"json"===e.toolName)){r.enqueue({type:"tool-input-end",id:e.toolCallId});let t=""===e.input?"{}":e.input;if("code_execution"===e.providerToolName)try{let e=JSON.parse(t);null!=e&&"object"==typeof e&&"code"in e&&!("type"in e)&&(t=JSON.stringify({type:"programmatic-tool-call",...e}))}catch(e){}r.enqueue({type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t,providerExecuted:e.providerExecuted,..._&&"code_execution"===e.providerToolName?{dynamic:!0}:{},...e.caller&&{providerMetadata:{anthropic:{caller:e.caller}}}})}}delete k[j.index]}i=void 0;return;case"content_block_delta":{let e=j.delta.type;switch(e){case"text_delta":if(p)return;r.enqueue({type:"text-delta",id:String(j.index),delta:j.delta.text});return;case"thinking_delta":r.enqueue({type:"reasoning-delta",id:String(j.index),delta:j.delta.thinking});return;case"signature_delta":"thinking"===i&&r.enqueue({type:"reasoning-delta",id:String(j.index),delta:"",providerMetadata:{anthropic:{signature:j.delta.signature}}});return;case"compaction_delta":null!=j.delta.content&&r.enqueue({type:"text-delta",id:String(j.index),delta:j.delta.content});return;case"input_json_delta":{let e=k[j.index],t=j.delta.partial_json;if(0===t.length)return;if(E){if((null==e?void 0:e.type)!=="text")return;r.enqueue({type:"text-delta",id:String(j.index),delta:t})}else{if((null==e?void 0:e.type)!=="tool-call")return;e.firstDelta&&("bash_code_execution"===e.providerToolName||"text_editor_code_execution"===e.providerToolName)&&(t=`{"type": "${e.providerToolName}",${t.substring(1)}`),r.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t,e.firstDelta=!1}return}case"citations_delta":{let e=H(j.delta.citation,y,O);e&&r.enqueue(e);return}default:throw Error(`Unsupported delta type: ${e}`)}}case"message_start":if(x.input_tokens=j.message.usage.input_tokens,x.cache_read_input_tokens=null!=(u=j.message.usage.cache_read_input_tokens)?u:0,x.cache_creation_input_tokens=null!=(d=j.message.usage.cache_creation_input_tokens)?d:0,o={...j.message.usage},S=null!=(c=j.message.usage.cache_creation_input_tokens)?c:null,null!=j.message.container&&(C={expiresAt:j.message.container.expires_at,id:j.message.container.id,skills:null}),null!=j.message.stop_reason&&(w={unified:J({finishReason:j.message.stop_reason,isJsonResponseFromTool:E}),raw:j.message.stop_reason}),r.enqueue({type:"response-metadata",id:null!=(g=j.message.id)?g:void 0,modelId:null!=(v=j.message.model)?v:void 0}),null!=j.message.content)for(let e=0;e<j.message.content.length;e++){let t=j.message.content[e];if("tool_use"===t.type){let e=t.caller,a=e?{type:e.type,toolId:"tool_id"in e?e.tool_id:void 0}:void 0;r.enqueue({type:"tool-input-start",id:t.id,toolName:t.name});let n=JSON.stringify(null!=(b=t.input)?b:{});r.enqueue({type:"tool-input-delta",id:t.id,delta:n}),r.enqueue({type:"tool-input-end",id:t.id}),r.enqueue({type:"tool-call",toolCallId:t.id,toolName:t.name,input:n,...a&&{providerMetadata:{anthropic:{caller:a}}}})}}return;case"message_delta":null!=j.usage.input_tokens&&x.input_tokens!==j.usage.input_tokens&&(x.input_tokens=j.usage.input_tokens),x.output_tokens=j.usage.output_tokens,null!=j.usage.cache_read_input_tokens&&(x.cache_read_input_tokens=j.usage.cache_read_input_tokens),null!=j.usage.cache_creation_input_tokens&&(x.cache_creation_input_tokens=j.usage.cache_creation_input_tokens,S=j.usage.cache_creation_input_tokens),null!=j.usage.iterations&&(x.iterations=j.usage.iterations),w={unified:J({finishReason:j.delta.stop_reason,isJsonResponseFromTool:E}),raw:null!=(A=j.delta.stop_reason)?A:void 0},Z=null!=(N=j.delta.stop_sequence)?N:null,C=null!=j.delta.container?{expiresAt:j.delta.container.expires_at,id:j.delta.container.id,skills:null!=(P=null==($=j.delta.container.skills)?void 0:$.map(e=>({type:e.type,skillId:e.skill_id,version:e.version})))?P:null}:null,j.context_management&&(R=ee(j.context_management)),o={...o,...j.usage};return;case"message_stop":{let e={usage:null!=o?o:null,cacheCreationInputTokens:S,stopSequence:Z,iterations:x.iterations?x.iterations.map(e=>({type:e.type,inputTokens:e.input_tokens,outputTokens:e.output_tokens})):null,container:C,contextManagement:R},t={anthropic:e};f&&"anthropic"!==m&&(t[m]=e),r.enqueue({type:"finish",finishReason:w,usage:M({usage:x,rawUsage:o}),providerMetadata:t});return}case"error":r.enqueue({type:"error",error:j.error});return;default:throw Error(`Unsupported chunk type: ${j}`)}}})).tee(),$=A.getReader();try{await $.read();let e=await $.read();if((null==(t=e.value)?void 0:t.type)==="raw"&&(e=await $.read()),(null==(r=e.value)?void 0:r.type)==="error"){let t=e.value.error;throw new a.w({message:t.message,url:g,requestBodyValues:l,statusCode:"overloaded_error"===t.type?529:500,responseHeaders:v,responseBody:JSON.stringify(t),isRetryable:"overloaded_error"===t.type})}}finally{$.cancel().catch(()=>{}),$.releaseLock()}return{stream:N,request:{body:l},response:{headers:v}}}};function Q(e){if(!e)return!1;let t=!1,r=!1;for(let a of e){if("type"in a&&("web_fetch_20260209"===a.type||"web_search_20260209"===a.type)){t=!0;continue}if("code_execution"===a.name){r=!0;break}}return t&&!r}function ee(e){return e?{appliedEdits:e.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens};case"compact_20260112":return{type:e.type}}}).filter(e=>void 0!==e)}:null}var et=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Z_(),restart:o.O7().optional()}))),er=(0,n.W0)({id:"anthropic.bash_20241022",inputSchema:et}),ea=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Z_(),restart:o.O7().optional()}))),en=(0,n.W0)({id:"anthropic.bash_20250124",inputSchema:ea}),eo=(0,n.DG)(()=>(0,n.r0)(o.Ry({action:o.Km(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:o.IX(o.Rx().int()).optional(),text:o.Z_().optional()}))),ei=(0,n.W0)({id:"anthropic.computer_20241022",inputSchema:eo}),es=(0,n.DG)(()=>(0,n.r0)(o.Ry({action:o.Km(["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:o.bc([o.Rx().int(),o.Rx().int()]).optional(),duration:o.Rx().optional(),scroll_amount:o.Rx().optional(),scroll_direction:o.Km(["up","down","left","right"]).optional(),start_coordinate:o.bc([o.Rx().int(),o.Rx().int()]).optional(),text:o.Z_().optional()}))),el=(0,n.W0)({id:"anthropic.computer_20250124",inputSchema:es}),eu=(0,n.DG)(()=>(0,n.r0)(o.Ry({action:o.Km(["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","zoom"]),coordinate:o.bc([o.Rx().int(),o.Rx().int()]).optional(),duration:o.Rx().optional(),region:o.bc([o.Rx().int(),o.Rx().int(),o.Rx().int(),o.Rx().int()]).optional(),scroll_amount:o.Rx().optional(),scroll_direction:o.Km(["up","down","left","right"]).optional(),start_coordinate:o.bc([o.Rx().int(),o.Rx().int()]).optional(),text:o.Z_().optional()}))),ed=(0,n.W0)({id:"anthropic.computer_20251124",inputSchema:eu}),ec=(0,n.DG)(()=>(0,n.r0)(o.VK("command",[o.Ry({command:o.i0("view"),path:o.Z_(),view_range:o.bc([o.Rx(),o.Rx()]).optional()}),o.Ry({command:o.i0("create"),path:o.Z_(),file_text:o.Z_()}),o.Ry({command:o.i0("str_replace"),path:o.Z_(),old_str:o.Z_(),new_str:o.Z_()}),o.Ry({command:o.i0("insert"),path:o.Z_(),insert_line:o.Rx(),insert_text:o.Z_()}),o.Ry({command:o.i0("delete"),path:o.Z_()}),o.Ry({command:o.i0("rename"),old_path:o.Z_(),new_path:o.Z_()})]))),ep=(0,n.W0)({id:"anthropic.memory_20250818",inputSchema:ec}),eh=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert","undo_edit"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),em=(0,n.W0)({id:"anthropic.text_editor_20241022",inputSchema:eh}),ef=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert","undo_edit"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),ey=(0,n.W0)({id:"anthropic.text_editor_20250124",inputSchema:ef}),e_=(0,n.DG)(()=>(0,n.r0)(o.Ry({command:o.Km(["view","create","str_replace","insert"]),path:o.Z_(),file_text:o.Z_().optional(),insert_line:o.Rx().int().optional(),new_str:o.Z_().optional(),insert_text:o.Z_().optional(),old_str:o.Z_().optional(),view_range:o.IX(o.Rx().int()).optional()}))),eg=(0,n.W0)({id:"anthropic.text_editor_20250429",inputSchema:e_}),ev=(0,n.DG)(()=>(0,n.r0)(o.IX(o.Ry({type:o.i0("tool_reference"),toolName:o.Z_()})))),eb=(0,n.DG)(()=>(0,n.r0)(o.Ry({query:o.Z_(),limit:o.Rx().optional()}))),ew=(0,n.ql)({id:"anthropic.tool_search_bm25_20251119",inputSchema:eb,outputSchema:ev,supportsDeferredResults:!0}),ex={bash_20241022:er,bash_20250124:en,codeExecution_20250522:(e={})=>j(e),codeExecution_20250825:(e={})=>D(e),codeExecution_20260120:(e={})=>L(e),computer_20241022:ei,computer_20250124:el,computer_20251124:ed,memory_20250818:ep,textEditor_20241022:em,textEditor_20250124:ey,textEditor_20250429:eg,textEditor_20250728:(e={})=>y(e),webFetch_20250910:(e={})=>A(e),webFetch_20260209:(e={})=>Z(e),webSearch_20250305:(e={})=>I(e),webSearch_20260209:(e={})=>b(e),toolSearchRegex_20251119:(e={})=>W(e),toolSearchBm25_20251119:(e={})=>ew(e)};function ek(e={}){var t,r;let o=null!=(t=(0,n.QT)((0,n.P6)({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))?t:"https://api.anthropic.com/v1",i=null!=(r=e.name)?r:"anthropic.messages";if(e.apiKey&&e.authToken)throw new a.RU({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let s=()=>{let t=e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":(0,n.pd)({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return(0,n.CR)({"anthropic-version":"2023-06-01",...t,...e.headers},"ai-sdk/anthropic/3.0.58")},l=t=>{var r;return new Y(t,{provider:i,baseURL:o,headers:s,fetch:e.fetch,generateId:null!=(r=e.generateId)?r:n.Ox,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},u=function(e){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return l(e)};return u.specificationVersion="v3",u.languageModel=l,u.chat=l,u.messages=l,u.embeddingModel=e=>{throw new a.JJ({modelId:e,modelType:"embeddingModel"})},u.textEmbeddingModel=u.embeddingModel,u.imageModel=e=>{throw new a.JJ({modelId:e,modelType:"imageModel"})},u.tools=ex,u}ek()},6365:(e,t,r)=>{r.d(t,{N$:()=>C,eh:()=>g,Bx:()=>Z,C3:()=>eM,NF:()=>m,MS:()=>x,QF:()=>I,k0:()=>k,cP:()=>eJ,bF:()=>M,Sq:()=>eK,tc:()=>eH,W0:()=>eW,ql:()=>eX,U_:()=>f,gw:()=>y,aN:()=>eQ,Ox:()=>$,e$:()=>P,hb:()=>W,gJ:()=>q,D_:()=>j,C_:()=>X,MT:()=>B,fB:()=>eN,DG:()=>eA,pd:()=>K,P6:()=>J,kh:()=>U,RF:()=>eD,c1:()=>eq,A8:()=>eL,SN:()=>E,DB:()=>eB,NX:()=>ez,pW:()=>ej,w3:()=>eG,SA:()=>O,rJ:()=>eP,CR:()=>L,QT:()=>eY,r0:()=>e$});var a,n,o=r(9519),i=r(6496),s=r(8510);class l{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??i.$Z,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;let a=e._zod.def,n=this.seen.get(e);if(n)return n.count++,t.schemaPath.includes(e)&&(n.cycle=t.path),n.schema;let o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);let i=e._zod.toJSONSchema?.();if(i)o.schema=i;else{let r={...t,schemaPath:[...t.schemaPath,e],path:t.path},n=e._zod.parent;if(n)o.ref=n,this.process(n,r),this.seen.get(n).isParent=!0;else{let t=o.schema;switch(a.type){case"string":{t.type="string";let{minimum:r,maximum:a,format:n,patterns:i,contentEncoding:s}=e._zod.bag;if("number"==typeof r&&(t.minLength=r),"number"==typeof a&&(t.maxLength=a),n&&(t.format=({guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""})[n]??n,""===t.format&&delete t.format),s&&(t.contentEncoding=s),i&&i.size>0){let e=[...i];1===e.length?t.pattern=e[0].source:e.length>1&&(o.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{let{minimum:r,maximum:a,format:n,multipleOf:o,exclusiveMaximum:i,exclusiveMinimum:s}=e._zod.bag;"string"==typeof n&&n.includes("int")?t.type="integer":t.type="number","number"==typeof s&&(t.exclusiveMinimum=s),"number"==typeof r&&(t.minimum=r,"number"==typeof s&&(s>=r?delete t.minimum:delete t.exclusiveMinimum)),"number"==typeof i&&(t.exclusiveMaximum=i),"number"==typeof a&&(t.maximum=a,"number"==typeof i&&(i<=a?delete t.maximum:delete t.exclusiveMaximum)),"number"==typeof o&&(t.multipleOf=o);break}case"boolean":case"success":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw Error("Date cannot be represented in JSON Schema");break;case"array":{let{minimum:n,maximum:o}=e._zod.bag;"number"==typeof n&&(t.minItems=n),"number"==typeof o&&(t.maxItems=o),t.type="array",t.items=this.process(a.element,{...r,path:[...r.path,"items"]});break}case"object":{t.type="object",t.properties={};let e=a.shape;for(let a in e)t.properties[a]=this.process(e[a],{...r,path:[...r.path,"properties",a]});let n=new Set([...new Set(Object.keys(e))].filter(e=>{let t=a.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));n.size>0&&(t.required=Array.from(n)),a.catchall?._zod.def.type==="never"?t.additionalProperties=!1:a.catchall?a.catchall&&(t.additionalProperties=this.process(a.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(t.additionalProperties=!1);break}case"union":t.anyOf=a.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{let e=this.process(a.left,{...r,path:[...r.path,"allOf",0]}),n=this.process(a.right,{...r,path:[...r.path,"allOf",1]}),o=[..."allOf"in e&&1===Object.keys(e).length?e.allOf:[e],..."allOf"in n&&1===Object.keys(n).length?n.allOf:[n]];t.allOf=o;break}case"tuple":{t.type="array";let n=a.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?t.prefixItems=n:t.items=n,a.rest){let e=this.process(a.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?t.items=e:t.additionalItems=e}a.rest&&(t.items=this.process(a.rest,{...r,path:[...r.path,"items"]}));let{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(t.minItems=o),"number"==typeof i&&(t.maxItems=i);break}case"record":t.type="object",t.propertyNames=this.process(a.keyType,{...r,path:[...r.path,"propertyNames"]}),t.additionalProperties=this.process(a.valueType,{...r,path:[...r.path,"additionalProperties"]});break;case"map":if("throw"===this.unrepresentable)throw Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw Error("Set cannot be represented in JSON Schema");break;case"enum":{let e=(0,s.B8)(a.entries);e.every(e=>"number"==typeof e)&&(t.type="number"),e.every(e=>"string"==typeof e)&&(t.type="string"),t.enum=e;break}case"literal":{let e=[];for(let t of a.values)if(void 0===t){if("throw"===this.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t){if("throw"===this.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");e.push(Number(t))}else e.push(t);if(0===e.length);else if(1===e.length){let r=e[0];t.type=null===r?"null":typeof r,t.const=r}else e.every(e=>"number"==typeof e)&&(t.type="number"),e.every(e=>"string"==typeof e)&&(t.type="string"),e.every(e=>"boolean"==typeof e)&&(t.type="string"),e.every(e=>null===e)&&(t.type="null"),t.enum=e;break}case"file":{let r={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:n,mime:o}=e._zod.bag;void 0!==a&&(r.minLength=a),void 0!==n&&(r.maxLength=n),o?1===o.length?(r.contentMediaType=o[0],Object.assign(t,r)):t.anyOf=o.map(e=>({...r,contentMediaType:e})):Object.assign(t,r);break}case"transform":if("throw"===this.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{let e=this.process(a.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(a.innerType,r),o.ref=a.innerType;break;case"default":this.process(a.innerType,r),o.ref=a.innerType,t.default=JSON.parse(JSON.stringify(a.defaultValue));break;case"prefault":this.process(a.innerType,r),o.ref=a.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(a.defaultValue)));break;case"catch":{let e;this.process(a.innerType,r),o.ref=a.innerType;try{e=a.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{let r=e._zod.pattern;if(!r)throw Error("Pattern not found in template literal");t.type="string",t.pattern=r.source;break}case"pipe":{let e="input"===this.io?"transform"===a.in._zod.def.type?a.out:a.in:a.out;this.process(e,r),o.ref=e;break}case"readonly":this.process(a.innerType,r),o.ref=a.innerType,t.readOnly=!0;break;case"lazy":{let t=e._zod.innerType;this.process(t,r),o.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(o.schema,l),"input"===this.io&&function e(t,r){let a=r??{seen:new Set};if(a.seen.has(t))return!1;a.seen.add(t);let n=t._zod.def;switch(n.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":case"custom":case"success":case"catch":return!1;case"array":return e(n.element,a);case"object":for(let t in n.shape)if(e(n.shape[t],a))return!0;return!1;case"union":for(let t of n.options)if(e(t,a))return!0;return!1;case"intersection":return e(n.left,a)||e(n.right,a);case"tuple":for(let t of n.items)if(e(t,a))return!0;if(n.rest&&e(n.rest,a))return!0;return!1;case"record":case"map":return e(n.keyType,a)||e(n.valueType,a);case"set":return e(n.valueType,a);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return e(n.innerType,a);case"lazy":return e(n.getter(),a);case"transform":return!0;case"pipe":return e(n.in,a)||e(n.out,a)}throw Error(`Unknown schema type: ${n.type}`)}(e)&&(delete o.schema.examples,delete o.schema.default),"input"===this.io&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){let r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},a=this.seen.get(e);if(!a)throw Error("Unprocessed schema. This is a bug in Zod.");let n=e=>{let t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){let a=r.external.registry.get(e[0])?.id,n=r.external.uri??(e=>e);if(a)return{ref:n(a)};let o=e[1].defId??e[1].schema.id??`schema${this.counter++}`;return e[1].defId=o,{defId:o,ref:`${n("__shared")}#/${t}/${o}`}}if(e[1]===a)return{ref:"#"};let n=`#/${t}/`,o=e[1].schema.id??`__schema${this.counter++}`;return{defId:o,ref:n+o}},o=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:r,defId:a}=n(e);t.def={...t.schema},a&&(t.defId=a);let o=t.schema;for(let e in o)delete o[e];o.$ref=r};if("throw"===r.cycles)for(let e of this.seen.entries()){let t=e[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>
3
3
 
4
4
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let t of this.seen.entries()){let a=t[1];if(e===t[0]){o(t);continue}if(r.external){let a=r.external.registry.get(t[0])?.id;if(e!==t[0]&&a){o(t);continue}}if(this.metadataRegistry.get(t[0])?.id||a.cycle||a.count>1&&"ref"===r.reused){o(t);continue}}let i=(e,t)=>{let r=this.seen.get(e),a=r.def??r.schema,n={...a};if(null===r.ref)return;let o=r.ref;if(r.ref=null,o){i(o,t);let e=this.seen.get(o).schema;e.$ref&&"draft-7"===t.target?(a.allOf=a.allOf??[],a.allOf.push(e)):(Object.assign(a,e),Object.assign(a,n))}r.isParent||this.override({zodSchema:e,jsonSchema:a,path:r.path??[]})};for(let e of[...this.seen.entries()].reverse())i(e[0],{target:this.target});let s={};if("draft-2020-12"===this.target?s.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?s.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let t=r.external.registry.get(e)?.id;if(!t)throw Error("Schema is missing an `id` property");s.$id=r.external.uri(t)}Object.assign(s,a.def);let l=r.external?.defs??{};for(let e of this.seen.entries()){let t=e[1];t.def&&t.defId&&(l[t.defId]=t.def)}r.external||Object.keys(l).length>0&&("draft-2020-12"===this.target?s.$defs=l:s.definitions=l);try{return JSON.parse(JSON.stringify(s))}catch(e){throw Error("Error converting schema to JSON.")}}}var u=r(3947),d=r(9763);class c extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function p(e){}class h extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let a;super({start(n){a=function(e){if("function"==typeof e)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=p,onError:r=p,onRetry:a=p,onComment:n}=e,o="",i=!0,s,l="",u="";function d(e){if(""===e){l.length>0&&t({id:s,event:u||void 0,data:l.endsWith(`
5
5
  `)?l.slice(0,-1):l}),s=void 0,l="",u="";return}if(e.startsWith(":")){n&&n(e.slice(e.startsWith(": ")?2:1));return}let r=e.indexOf(":");if(-1!==r){let t=e.slice(0,r),a=" "===e[r+1]?2:1;h(t,e.slice(r+a),e);return}h(e,"",e)}function h(e,t,n){switch(e){case"event":u=t;break;case"data":l=`${l}${t}
@@ -11,7 +11,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11
11
  `:`[${n[e]}\r
12
12
  ]`;continue}o+=n[e],"\\"===n[e]?i=!0:s&&"]"===n[e]?s=!1:s||"["!==n[e]||(s=!0)}try{new RegExp(o)}catch(r){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 o}function eg(e,t){var r,a,n,o,i,s;let l={type:"object",additionalProperties:null!=(r=eR(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))?r:t.allowedAdditionalProperties};if((null==(a=e.keyType)?void 0:a._def.typeName)===d.pA.ZodString&&(null==(n=e.keyType._def.checks)?void 0:n.length)){let{type:r,...a}=ep(e.keyType._def,t);return{...l,propertyNames:a}}if((null==(o=e.keyType)?void 0:o._def.typeName)===d.pA.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if((null==(i=e.keyType)?void 0:i._def.typeName)===d.pA.ZodBranded&&e.keyType._def.type._def.typeName===d.pA.ZodString&&(null==(s=e.keyType._def.type._def.checks)?void 0:s.length)){let{type:r,...a}=ei(e.keyType._def,t);return{...l,propertyNames:a}}return l}var ev={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},eb=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>eR(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0},ew=(e,t)=>{var r;if(t.currentPath.toString()===(null==(r=t.propertyPath)?void 0:r.toString()))return eR(e.innerType._def,t);let a=eR(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return a?{anyOf:[{not:{}},a]}:{}},ex=(e,t)=>{if("input"===t.pipeStrategy)return eR(e.in._def,t);if("output"===t.pipeStrategy)return eR(e.out._def,t);let r=eR(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=eR(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(e=>void 0!==e)}},ek=(e,t)=>eR(e.innerType._def,t),eI=(e,t,r)=>{switch(t){case d.pA.ZodString:return ep(e,r);case d.pA.ZodNumber:return function(e){let t={type:"number"};if(!e.checks)return t;for(let r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value}return t}(e);case d.pA.ZodObject:return function(e,t){let r={type:"object",properties:{}},a=[],n=e.shape();for(let e in n){let o=n[e];if(void 0===o||void 0===o._def)continue;let i=function(e){try{return e.isOptional()}catch(e){return!0}}(o),s=eR(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==s&&(r.properties[e]=s,i||a.push(e))}a.length&&(r.required=a);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return eR(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(r.additionalProperties=o),r}(e,r);case d.pA.ZodBigInt:return function(e){let t={type:"integer",format:"int64"};if(!e.checks)return t;for(let r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value}return t}(e);case d.pA.ZodBoolean:return{type:"boolean"};case d.pA.ZodDate:return function e(t,r,a){let n=null!=a?a:r.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((a,n)=>e(t,r,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return el(t)}}(e,r);case d.pA.ZodUndefined:return{not:{}};case d.pA.ZodNull:return{type:"null"};case d.pA.ZodArray:return function(e,t){var r,a,n;let o={type:"array"};return(null==(r=e.type)?void 0:r._def)&&(null==(n=null==(a=e.type)?void 0:a._def)?void 0:n.typeName)!==d.pA.ZodAny&&(o.items=eR(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(o.minItems=e.minLength.value),e.maxLength&&(o.maxItems=e.maxLength.value),e.exactLength&&(o.minItems=e.exactLength.value,o.maxItems=e.exactLength.value),o}(e,r);case d.pA.ZodUnion:case d.pA.ZodDiscriminatedUnion:return function(e,t){let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in ev&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=ev[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return eb(e,t)}(e,r);case d.pA.ZodIntersection:return function(e,t){let r=[eR(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),eR(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),a=[];return r.forEach(e=>{if(eu(e))a.push(...e.allOf);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}a.push(t)}}),a.length?{allOf:a}:void 0}(e,r);case d.pA.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>eR(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:eR(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>eR(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case d.pA.ZodRecord:return eg(e,r);case d.pA.ZodLiteral:return function(e){let t=typeof e.value;return"bigint"!==t&&"number"!==t&&"boolean"!==t&&"string"!==t?{type:Array.isArray(e.value)?"array":"object"}:{type:"bigint"===t?"integer":t,const:e.value}}(e);case d.pA.ZodEnum:return{type:"string",enum:Array.from(e.values)};case d.pA.ZodNativeEnum:return function(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),a=Array.from(new Set(r.map(e=>typeof e)));return{type:1===a.length?"string"===a[0]?"string":"number":["string","number"],enum:r}}(e);case d.pA.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ev[e.innerType._def.typeName],"null"]};let r=eR(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case d.pA.ZodOptional:return ew(e,r);case d.pA.ZodMap:return function(e,t){return"record"===t.mapStrategy?eg(e,t):{type:"array",maxItems:125,items:{type:"array",items:[eR(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},eR(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case d.pA.ZodSet:return function(e,t){let r={type:"array",uniqueItems:!0,items:eR(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}(e,r);case d.pA.ZodLazy:return()=>e.getter()._def;case d.pA.ZodPromise:return eR(e.type._def,r);case d.pA.ZodNaN:case d.pA.ZodNever:return{not:{}};case d.pA.ZodEffects:return function(e,t){return"input"===t.effectStrategy?eR(e.schema._def,t):{}}(e,r);case d.pA.ZodAny:case d.pA.ZodUnknown:return{};case d.pA.ZodDefault:return function(e,t){return{...eR(e.innerType._def,t),default:e.defaultValue()}}(e,r);case d.pA.ZodBranded:return ei(e,r);case d.pA.ZodReadonly:return ek(e,r);case d.pA.ZodCatch:return es(e,r);case d.pA.ZodPipeline:return ex(e,r);case d.pA.ZodFunction:case d.pA.ZodVoid:case d.pA.ZodSymbol:default:return}},eT=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function eR(e,t,r=!1){var a;let n=t.seen.get(e);if(t.override){let o=null==(a=t.override)?void 0:a.call(t,e,t,n,r);if(o!==ea)return o}if(n&&!r){let e=eS(n,t);if(void 0!==e)return e}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=eI(e,e.typeName,t),s="function"==typeof i?eR(i(),t):i;if(s&&eZ(e,t,s),t.postProcess){let r=t.postProcess(s,e,t);return o.jsonSchema=s,r}return o.jsonSchema=s,s}var eS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:eT(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{};return"seen"===t.$refStrategy?{}:void 0}},eZ=(e,t,r)=>(e.description&&(r.description=e.description),r),eC=e=>{let t=eo(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},eE=(e,t)=>{var r;let a=eC(t),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>{var n;return{...e,[t]:null!=(n=eR(r._def,{...a,currentPath:[...a.basePath,a.definitionPath,t]},!0))?n:{}}},{}):void 0,o="string"==typeof t?t:(null==t?void 0:t.nameStrategy)==="title"?void 0:null==t?void 0:t.name,i=null!=(r=eR(e._def,void 0===o?a:{...a,currentPath:[...a.basePath,a.definitionPath,o]},!1))?r:{},s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(i.title=s);let l=void 0===o?n?{...i,[a.definitionPath]:n}:i:{$ref:[..."relative"===a.$refStrategy?[]:a.basePath,a.definitionPath,o].join("/"),[a.definitionPath]:{...n,[o]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},eO=Symbol.for("vercel.ai.schema");function eA(e){let t;return()=>(null==t&&(t=e()),t)}function eN(e,{validate:t}={}){return{[eO]:!0,_type:void 0,get jsonSchema(){return"function"==typeof e&&(e=e()),e},validate:t}}function eM(e){return null==e?eN({properties:{},additionalProperties:!1}):"object"==typeof e&&null!==e&&eO in e&&!0===e[eO]&&"jsonSchema"in e&&"validate"in e?e:"~standard"in e?"zod"===e["~standard"].vendor?e$(e):eN(()=>et(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{let r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new o.Gz({value:t,cause:r.issues})}}}):e()}function e$(e,t){return"_zod"in e?function(e,t){var r;let a=null!=(r=null==t?void 0:t.useReferences)&&r;return eN(()=>et(function(e,t){if(e instanceof i.EC){let r=new l(t),a={};for(let t of e._idmap.entries()){let[e,a]=t;r.process(a)}let n={},o={registry:e,uri:t?.uri,defs:a};for(let a of e._idmap.entries()){let[e,i]=a;n[e]=r.emit(i,{...t,external:o})}if(Object.keys(a).length>0){let e="draft-2020-12"===r.target?"$defs":"definitions";n.__shared={[e]:a}}return{schemas:n}}let r=new l(t);return r.process(e),r.emit(e,t)}(e,{target:"draft-7",io:"input",reused:a?"ref":"inline"})),{validate:async t=>{let r=await u.X9(e,t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}(e,t):function(e,t){var r;let a=null!=(r=null==t?void 0:t.useReferences)&&r;return eN(()=>eE(e,{$refStrategy:a?"root":"none"}),{validate:async t=>{let r=await e.safeParseAsync(t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}(e,t)}async function eP({value:e,schema:t,context:r}){let a=await ej({value:e,schema:t,context:r});if(!a.success)throw o.Gz.wrap({value:e,cause:a.error,context:r});return a.value}async function ej({value:e,schema:t,context:r}){let a=eM(t);try{if(null==a.validate)return{success:!0,value:e,rawValue:e};let t=await a.validate(e);if(t.success)return{success:!0,value:t.value,rawValue:e};return{success:!1,error:o.Gz.wrap({value:e,cause:t.error,context:r}),rawValue:e}}catch(t){return{success:!1,error:o.Gz.wrap({value:e,cause:t,context:r}),rawValue:e}}}async function eF({text:e,schema:t}){try{let r=ee(e);if(null==t)return r;return eP({value:r,schema:t})}catch(t){if(o.xU.isInstance(t)||o.Gz.isInstance(t))throw t;throw new o.xU({text:e,cause:t})}}async function ez({text:e,schema:t}){try{let r=ee(e);if(null==t)return{success:!0,value:r,rawValue:r};return await ej({value:r,schema:t})}catch(t){return{success:!1,error:o.xU.isInstance(t)?t:new o.xU({text:e,cause:t}),rawValue:void 0}}}function eD({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new h).pipeThrough(new TransformStream({async transform({data:e},r){"[DONE]"!==e&&r.enqueue(await ez({text:e,schema:t}))}}))}async function eq({provider:e,providerOptions:t,schema:r}){if((null==t?void 0:t[e])==null)return;let a=await ej({value:t[e],schema:r});if(!a.success)throw new o.RU({argument:"providerOptions",message:`invalid ${e} provider options`,cause:a.error});return a.value}var eU=()=>globalThis.fetch,eL=async({url:e,headers:t,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:o,fetch:i})=>eV({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:o,fetch:i}),eV=async({url:e,headers:t={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:i,fetch:s=eU()})=>{try{let l=await s(e,{method:"POST",headers:L(t,`ai-sdk/provider-utils/${V}`,q()),body:r.content,signal:i}),u=v(l);if(!l.ok){let t;try{t=await n({response:l,url:e,requestBodyValues:r.values})}catch(t){if(j(t)||o.w.isInstance(t))throw t;throw new o.w({message:"Failed to process error response",cause:t,statusCode:l.status,url:e,responseHeaders:u,requestBodyValues:r.values})}throw t.value}try{return await a({response:l,url:e,requestBodyValues:r.values})}catch(t){if(t instanceof Error&&(j(t)||o.w.isInstance(t)))throw t;throw new o.w({message:"Failed to process successful response",cause:t,statusCode:l.status,url:e,responseHeaders:u,requestBodyValues:r.values})}}catch(t){throw D({error:t,url:e,requestBodyValues:r.values})}};function eG(e){return e}function eW({id:e,inputSchema:t}){return({execute:r,outputSchema:a,needsApproval:n,toModelOutput:o,onInputStart:i,onInputDelta:s,onInputAvailable:l,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:a,execute:r,needsApproval:n,toModelOutput:o,onInputStart:i,onInputDelta:s,onInputAvailable:l})}function eX({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:a}){return({execute:n,needsApproval:o,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:u,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:r,execute:n,needsApproval:o,toModelOutput:i,onInputStart:s,onInputDelta:l,onInputAvailable:u,supportsDeferredResults:a})}async function eB(e){return"function"==typeof e&&(e=e()),Promise.resolve(e)}var eK=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:a,url:n,requestBodyValues:i})=>{let s=await a.text(),l=v(a);if(""===s.trim())return{responseHeaders:l,value:new o.w({message:a.statusText,url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:l,responseBody:s,isRetryable:null==r?void 0:r(a)})};try{let u=await eF({text:s,schema:e});return{responseHeaders:l,value:new o.w({message:t(u),url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:l,responseBody:s,data:u,isRetryable:null==r?void 0:r(a,u)})}}catch(e){return{responseHeaders:l,value:new o.w({message:a.statusText,url:n,requestBodyValues:i,statusCode:a.status,responseHeaders:l,responseBody:s,isRetryable:null==r?void 0:r(a)})}}},eJ=e=>async({response:t})=>{let r=v(t);if(null==t.body)throw new o.g8({});return{responseHeaders:r,value:eD({stream:t.body,schema:e})}},eH=e=>async({response:t,url:r,requestBodyValues:a})=>{let n=await t.text(),i=await ez({text:n,schema:e}),s=v(t);if(!i.success)throw new o.w({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:s,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:s,value:i.value,rawValue:i.rawValue}};function eY(e){return null==e?void 0:e.replace(/\/$/,"")}async function*eQ({execute:e,input:t,options:r}){let a=e(t,r);if(null!=a&&"function"==typeof a[Symbol.asyncIterator]){let e;for await(let t of a)e=t,yield{type:"preliminary",output:t};yield{type:"final",output:e}}else yield{type:"final",output:await a}}},9519:(e,t,r)=>{r.d(t,{AX:()=>T,A_:()=>el,Gz:()=>en,JJ:()=>ee,Mt:()=>U,RU:()=>F,e$:()=>M,g8:()=>N,tZ:()=>J,w:()=>C,xU:()=>W});var a,n,o,i,s,l,u,d,c,p,h,m,f,y,_,g,v,b,w,x,k="vercel.ai.error",I=Symbol.for(k),T=class e extends(n=Error,a=I,n){constructor({name:e,message:t,cause:r}){super(t),this[a]=!0,this.name=e,this.cause=r}static isInstance(t){return e.hasMarker(t,k)}static hasMarker(e,t){let r=Symbol.for(t);return null!=e&&"object"==typeof e&&r in e&&"boolean"==typeof e[r]&&!0===e[r]}},R="AI_APICallError",S=`vercel.ai.error.${R}`,Z=Symbol.for(S),C=class extends(i=T,o=Z,i){constructor({message:e,url:t,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:i,cause:s,isRetryable:l=null!=a&&(408===a||409===a||429===a||a>=500),data:u}){super({name:R,message:e,cause:s}),this[o]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=i,this.isRetryable=l,this.data=u}static isInstance(e){return T.hasMarker(e,S)}},E="AI_EmptyResponseBodyError",O=`vercel.ai.error.${E}`,A=Symbol.for(O),N=class extends(l=T,s=A,l){constructor({message:e="Empty response body"}={}){super({name:E,message:e}),this[s]=!0}static isInstance(e){return T.hasMarker(e,O)}};function M(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}var $="AI_InvalidArgumentError",P=`vercel.ai.error.${$}`,j=Symbol.for(P),F=class extends(d=T,u=j,d){constructor({message:e,cause:t,argument:r}){super({name:$,message:e,cause:t}),this[u]=!0,this.argument=r}static isInstance(e){return T.hasMarker(e,P)}},z="AI_InvalidPromptError",D=`vercel.ai.error.${z}`,q=Symbol.for(D),U=class extends(p=T,c=q,p){constructor({prompt:e,message:t,cause:r}){super({name:z,message:`Invalid prompt: ${t}`,cause:r}),this[c]=!0,this.prompt=e}static isInstance(e){return T.hasMarker(e,D)}},L=(Symbol.for("vercel.ai.error.AI_InvalidResponseDataError"),"AI_JSONParseError"),V=`vercel.ai.error.${L}`,G=Symbol.for(V),W=class extends(m=T,h=G,m){constructor({text:e,cause:t}){super({name:L,message:`JSON parsing failed: Text: ${e}.
13
13
  Error message: ${M(t)}`,cause:t}),this[h]=!0,this.text=e}static isInstance(e){return T.hasMarker(e,V)}},X="AI_LoadAPIKeyError",B=`vercel.ai.error.${X}`,K=Symbol.for(B),J=class extends(y=T,f=K,y){constructor({message:e}){super({name:X,message:e}),this[f]=!0}static isInstance(e){return T.hasMarker(e,B)}},H=(Symbol.for("vercel.ai.error.AI_LoadSettingError"),Symbol.for("vercel.ai.error.AI_NoContentGeneratedError"),"AI_NoSuchModelError"),Y=`vercel.ai.error.${H}`,Q=Symbol.for(Y),ee=class extends(g=T,_=Q,g){constructor({errorName:e=H,modelId:t,modelType:r,message:a=`No such ${r}: ${t}`}){super({name:e,message:a}),this[_]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return T.hasMarker(e,Y)}},et=(Symbol.for("vercel.ai.error.AI_TooManyEmbeddingValuesForCallError"),"AI_TypeValidationError"),er=`vercel.ai.error.${et}`,ea=Symbol.for(er),en=class e extends(b=T,v=ea,b){constructor({value:e,cause:t,context:r}){let a="Type validation failed";if((null==r?void 0:r.field)&&(a+=` for ${r.field}`),(null==r?void 0:r.entityName)||(null==r?void 0:r.entityId)){a+=" (";let e=[];r.entityName&&e.push(r.entityName),r.entityId&&e.push(`id: "${r.entityId}"`),a+=e.join(", ")+")"}super({name:et,message:`${a}: Value: ${JSON.stringify(e)}.
14
- Error message: ${M(t)}`,cause:t}),this[v]=!0,this.value=e,this.context=r}static isInstance(e){return T.hasMarker(e,er)}static wrap({value:t,cause:r,context:a}){var n,o,i;return e.isInstance(r)&&r.value===t&&(null==(n=r.context)?void 0:n.field)===(null==a?void 0:a.field)&&(null==(o=r.context)?void 0:o.entityName)===(null==a?void 0:a.entityName)&&(null==(i=r.context)?void 0:i.entityId)===(null==a?void 0:a.entityId)?r:new e({value:t,cause:r,context:a})}},eo="AI_UnsupportedFunctionalityError",ei=`vercel.ai.error.${eo}`,es=Symbol.for(ei),el=class extends(x=T,w=es,x){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:eo,message:t}),this[w]=!0,this.functionality=e}static isInstance(e){return T.hasMarker(e,ei)}};function eu(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||(Array.isArray(e)?e.every(eu):"object"==typeof e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&(void 0===t||eu(t))))}},1379:(e,t,r)=>{var a,n,o,i,s,l,u,d,c,p,h,m,f,y,_,g,v,b,w,x,k,I,T,R,S,Z,C,E,O,A,N,M,$,P,j,F,z,D,q,U,L,V,G,W,X,B,K,J,H,Y,Q,ee,et,er,ea,en,eo,ei,es,el,eu,ed,ec,ep,eh,em,ef,ey;let e_,eg,ev;function eb(e,t,r,a,n){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!n)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?n.call(e,r):n?n.value=r:t.set(e,r),r}function ew(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)}r.d(t,{ZP:()=>rv});let ex=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ex=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^r()&15>>+e/4).toString(16))};function ek(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let eI=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class eT extends Error{}class eR extends eT{constructor(e,t,r,a){super(`${eR.makeMessage(e,t,r)}`),this.status=e,this.headers=a,this.requestID=a?.get("request-id"),this.error=t}static makeMessage(e,t,r){let a=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,t,r,a){return e&&a?400===e?new eE(e,t,r,a):401===e?new eO(e,t,r,a):403===e?new eA(e,t,r,a):404===e?new eN(e,t,r,a):409===e?new eM(e,t,r,a):422===e?new e$(e,t,r,a):429===e?new eP(e,t,r,a):e>=500?new ej(e,t,r,a):new eR(e,t,r,a):new eZ({message:r,cause:eI(t)})}}class eS extends eR{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class eZ extends eR{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class eC extends eZ{constructor({message:e}={}){super({message:e??"Request timed out."})}}class eE extends eR{}class eO extends eR{}class eA extends eR{}class eN extends eR{}class eM extends eR{}class e$ extends eR{}class eP extends eR{}class ej extends eR{}let eF=/^[a-z][a-z0-9+.-]*:/i,ez=e=>eF.test(e),eD=e=>(eD=Array.isArray)(e),eq=eD;function eU(e){return"object"!=typeof e?{}:e??{}}let eL=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new eT(`${e} must be an integer`);if(t<0)throw new eT(`${e} must be a positive integer`);return t},eV=e=>{try{return JSON.parse(e)}catch(e){return}},eG=e=>new Promise(t=>setTimeout(t,e)),eW="0.78.0",eX=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator,eB=()=>{let e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":eJ(Deno.build.os),"X-Stainless-Arch":eK(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":eJ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":eK(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=function(){if("undefined"==typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,a=r[2]||0,n=r[3]||0;return{browser:e,version:`${t}.${a}.${n}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},eK=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",eJ=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",eH=()=>e_??(e_=eB());function eY(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function eQ(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return eY({start(){},async pull(e){let{done:r,value:a}=await t.next();r?e.close():e.enqueue(a)},async cancel(){await t.return?.()}})}function e0(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function e1(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}let e2=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function e4(e){let t;return(eg??(eg=(t=new globalThis.TextEncoder).encode.bind(t)))(e)}function e9(e){let t;return(ev??(ev=(t=new globalThis.TextDecoder).decode.bind(t)))(e)}class e5{constructor(){a.set(this,void 0),n.set(this,void 0),eb(this,a,new Uint8Array,"f"),eb(this,n,null,"f")}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?e4(e):e;eb(this,a,function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),a=0;for(let t of e)r.set(t,a),a+=t.length;return r}([ew(this,a,"f"),r]),"f");let o=[];for(;null!=(t=function(e,t){for(let r=t??0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}(ew(this,a,"f"),ew(this,n,"f")));){if(t.carriage&&null==ew(this,n,"f")){eb(this,n,t.index,"f");continue}if(null!=ew(this,n,"f")&&(t.index!==ew(this,n,"f")+1||t.carriage)){o.push(e9(ew(this,a,"f").subarray(0,ew(this,n,"f")-1))),eb(this,a,ew(this,a,"f").subarray(ew(this,n,"f")),"f"),eb(this,n,null,"f");continue}let e=null!==ew(this,n,"f")?t.preceding-1:t.preceding,r=e9(ew(this,a,"f").subarray(0,e));o.push(r),eb(this,a,ew(this,a,"f").subarray(t.index),"f"),eb(this,n,null,"f")}return o}flush(){return ew(this,a,"f").length?this.decode("\n"):[]}}a=new WeakMap,n=new WeakMap,e5.NEWLINE_CHARS=new Set(["\n","\r"]),e5.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let e6={off:0,error:200,warn:300,info:400,debug:500},e3=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(e6,e))return e;tr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(e6))}`)}};function e7(){}function e8(e,t,r){return!t||e6[e]>e6[r]?e7:t[e].bind(t)}let te={error:e7,warn:e7,info:e7,debug:e7},tt=new WeakMap;function tr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return te;let a=tt.get(t);if(a&&a[0]===r)return a[1];let n={error:e8("error",t,r),warn:e8("warn",t,r),info:e8("info",t,r),debug:e8("debug",t,r)};return tt.set(t,[r,n]),n}let ta=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class tn{constructor(e,t,r){this.iterator=e,o.set(this,void 0),this.controller=t,eb(this,o,r,"f")}static fromSSEResponse(e,t,r){let a=!1,n=r?tr(r):console;return new tn(async function*(){if(a)throw new eT("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let r=!1;try{for await(let r of to(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw n.error("Could not parse message into JSON:",r.data),n.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw n.error("Could not parse message into JSON:",r.data),n.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw new eR(void 0,eV(r.data)??r.data,void 0,e.headers)}r=!0}catch(e){if(ek(e))return;throw e}finally{r||t.abort()}},t,r)}static fromReadableStream(e,t,r){let a=!1;async function*n(){let t=new e5;for await(let r of e0(e))for(let e of t.decode(r))yield e;for(let e of t.flush())yield e}return new tn(async function*(){if(a)throw new eT("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let t of n())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(ek(e))return;throw e}finally{e||t.abort()}},t,r)}[(o=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),a=a=>({next:()=>{if(0===a.length){let a=r.next();e.push(a),t.push(a)}return a.shift()}});return[new tn(()=>a(e),this.controller,ew(this,o,"f")),new tn(()=>a(t),this.controller,ew(this,o,"f"))]}toReadableStream(){let e;let t=this;return eY({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:a}=await e.next();if(a)return t.close();let n=e4(JSON.stringify(r)+"\n");t.enqueue(n)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*to(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new eT("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new eT("Attempted to iterate over a response with no body")}let r=new ts,a=new e5;for await(let t of ti(e0(e.body)))for(let e of a.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of a.flush()){let t=r.decode(e);t&&(yield t)}}async function*ti(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let a=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?e4(r):r,n=new Uint8Array(t.length+a.length);for(n.set(t),n.set(a,t.length),t=n;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class ts{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,a]=function(e,t){let r=e.indexOf(":");return -1!==r?[e.substring(0,r),":",e.substring(r+t.length)]:[e,"",""]}(e,":");return a.startsWith(" ")&&(a=a.substring(1)),"event"===t?this.event=a:"data"===t&&this.data.push(a),null}}async function tl(e,t){let{response:r,requestLogID:a,retryOfRequestLogID:n,startTime:o}=t,i=await (async()=>{if(t.options.stream)return(tr(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller):tn.fromSSEResponse(r,t.controller);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let a=r.headers.get("content-type"),n=a?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){if("0"===r.headers.get("content-length"))return;return tu(await r.json(),r)}return await r.text()})();return tr(e).debug(`[${a}] response parsed`,ta({retryOfRequestLogID:n,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function tu(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class td extends Promise{constructor(e,t,r=tl){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,i.set(this,void 0),eb(this,i,e,"f")}_thenUnwrap(e){return new td(ew(this,i,"f"),this.responsePromise,async(t,r)=>tu(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ew(this,i,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}i=new WeakMap;class tc{constructor(e,t,r,a){s.set(this,void 0),eb(this,s,e,"f"),this.options=a,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new eT("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ew(this,s,"f").requestAPIList(this.constructor,e)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(s=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class tp extends td{constructor(e,t,r){super(e,t,async(e,t)=>new r(e,t.response,await tl(e,t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}class th extends tc{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...eU(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...eU(this.options.query),after_id:e}}:null}}class tm extends tc{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.has_more=r.has_more||!1,this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...eU(this.options.query),page:e}}:null}}let tf=()=>{if("undefined"==typeof File){let{process:e}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof e?.versions?.node&&20>parseInt(e.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ty(e,t,r){return tf(),new File(e,t??"unknown_file",r)}function t_(e,t){let r="object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"";return t?r.split(/[\\/]/).pop()||void 0:r}let tg=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],tv=async(e,t,r=!0)=>({...e,body:await tw(e.body,t,r)}),tb=new WeakMap,tw=async(e,t,r=!0)=>{if(!await function(e){let t="function"==typeof e?e:e.fetch,r=tb.get(t);if(r)return r;let a=(async()=>{try{let e="Response"in t?t.Response:(await t("data:,")).constructor,r=new FormData;if(r.toString()===await new e(r).text())return!1;return!0}catch{return!0}})();return tb.set(t,a),a}(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let a=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>tT(a,e,t,r))),a},tx=e=>e instanceof Blob&&"name"in e,tk=e=>"object"==typeof e&&null!==e&&(e instanceof Response||tg(e)||tx(e)),tI=e=>{if(tk(e))return!0;if(Array.isArray(e))return e.some(tI);if(e&&"object"==typeof e){for(let t in e)if(tI(e[t]))return!0}return!1},tT=async(e,t,r,a)=>{if(void 0!==r){if(null==r)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(r instanceof Response){let n={},o=r.headers.get("Content-Type");o&&(n={type:o}),e.append(t,ty([await r.blob()],t_(r,a),n))}else if(tg(r))e.append(t,ty([await new Response(eQ(r)).blob()],t_(r,a)));else if(tx(r))e.append(t,ty([r],t_(r,a),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(r=>tT(e,t+"[]",r,a)));else if("object"==typeof r)await Promise.all(Object.entries(r).map(([r,n])=>tT(e,`${t}[${r}]`,n,a)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}},tR=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,tS=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&tR(e),tZ=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob;async function tC(e,t,r){if(tf(),e=await e,t||(t=t_(e,!0)),tS(e))return e instanceof File&&null==t&&null==r?e:ty([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...r});if(tZ(e)){let a=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),ty(await tE(a),t,r)}let a=await tE(e);if(!r?.type){let e=a.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r={...r,type:e})}return ty(a,t,r)}async function tE(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(tR(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(tg(e))for await(let r of e)t.push(...await tE(r));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class tO{constructor(e){this._client=e}}let tA=Symbol.for("brand.privateNullableHeaders"),tN=e=>{let t=new Headers,r=new Set;for(let a of e){let e=new Set;for(let[n,o]of function*(e){let t;if(!e)return;if(tA in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let a of(e instanceof Headers?t=e.entries():eq(e)?t=e:(r=!0,t=Object.entries(e??{})),t)){let e=a[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=eq(a[1])?a[1]:[a[1]],n=!1;for(let a of t)void 0!==a&&(r&&!n&&(n=!0,yield[e,null]),yield[e,a])}}(a)){let a=n.toLowerCase();e.has(a)||(t.delete(n),e.add(a)),null===o?(t.delete(n),r.add(a)):(t.append(n,o),r.delete(a))}}return{[tA]:!0,values:t,nulls:r}},tM=Symbol("anthropic.sdk.stainlessHelper");function t$(e){return"object"==typeof e&&null!==e&&tM in e}function tP(e,t){let r=new Set;if(e)for(let t of e)t$(t)&&r.add(t[tM]);if(t){for(let e of t)if(t$(e)&&r.add(e[tM]),Array.isArray(e.content))for(let t of e.content)t$(t)&&r.add(t[tM])}return Array.from(r)}function tj(e,t){let r=tP(e,t);return 0===r.length?{}:{"x-stainless-helper":r.join(", ")}}function tF(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}let tz=Object.freeze(Object.create(null)),tD=((e=tF)=>function(t,...r){let a;if(1===t.length)return t[0];let n=!1,o=[],i=t.reduce((t,a,i)=>{/[?#]/.test(a)&&(n=!0);let s=r[i],l=(n?encodeURIComponent:e)(""+s);return i!==r.length&&(null==s||"object"==typeof s&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??tz)??tz)?.toString)&&(l=s+"",o.push({start:t.length+a.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(i===r.length?"":l)},""),s=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(a=l.exec(s));)o.push({start:a.index,length:a[0].length,error:`Value "${a[0]}" can't be safely passed as a path parameter`});if(o.sort((e,t)=>e.start-t.start),o.length>0){let e=0,t=o.reduce((t,r)=>{let a=" ".repeat(r.start-e),n="^".repeat(r.length);return e=r.start+r.length,t+a+n},"");throw new eT(`Path parameters result in path with invalid segments:
14
+ Error message: ${M(t)}`,cause:t}),this[v]=!0,this.value=e,this.context=r}static isInstance(e){return T.hasMarker(e,er)}static wrap({value:t,cause:r,context:a}){var n,o,i;return e.isInstance(r)&&r.value===t&&(null==(n=r.context)?void 0:n.field)===(null==a?void 0:a.field)&&(null==(o=r.context)?void 0:o.entityName)===(null==a?void 0:a.entityName)&&(null==(i=r.context)?void 0:i.entityId)===(null==a?void 0:a.entityId)?r:new e({value:t,cause:r,context:a})}},eo="AI_UnsupportedFunctionalityError",ei=`vercel.ai.error.${eo}`,es=Symbol.for(ei),el=class extends(x=T,w=es,x){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:eo,message:t}),this[w]=!0,this.functionality=e}static isInstance(e){return T.hasMarker(e,ei)}};function eu(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e||(Array.isArray(e)?e.every(eu):"object"==typeof e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&(void 0===t||eu(t))))}},1379:(e,t,r)=>{var a,n,o,i,s,l,u,d,c,p,h,m,f,y,_,g,v,b,w,x,k,I,T,R,S,Z,C,E,O,A,N,M,$,P,j,F,z,D,q,U,L,V,G,W,X,B,K,J,H,Y,Q,ee,et,er,ea,en,eo,ei,es,el,eu,ed,ec,ep,eh,em,ef,ey;let e_,eg,ev;function eb(e,t,r,a,n){if("m"===a)throw TypeError("Private method is not writable");if("a"===a&&!n)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===a?n.call(e,r):n?n.value=r:t.set(e,r),r}function ew(e,t,r,a){if("a"===r&&!a)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!a:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(e):a?a.value:t.get(e)}r.d(t,{ZP:()=>rv});let ex=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ex=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^r()&15>>+e/4).toString(16))};function ek(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let eI=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class eT extends Error{}class eR extends eT{constructor(e,t,r,a){super(`${eR.makeMessage(e,t,r)}`),this.status=e,this.headers=a,this.requestID=a?.get("request-id"),this.error=t}static makeMessage(e,t,r){let a=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,t,r,a){return e&&a?400===e?new eE(e,t,r,a):401===e?new eO(e,t,r,a):403===e?new eA(e,t,r,a):404===e?new eN(e,t,r,a):409===e?new eM(e,t,r,a):422===e?new e$(e,t,r,a):429===e?new eP(e,t,r,a):e>=500?new ej(e,t,r,a):new eR(e,t,r,a):new eZ({message:r,cause:eI(t)})}}class eS extends eR{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class eZ extends eR{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class eC extends eZ{constructor({message:e}={}){super({message:e??"Request timed out."})}}class eE extends eR{}class eO extends eR{}class eA extends eR{}class eN extends eR{}class eM extends eR{}class e$ extends eR{}class eP extends eR{}class ej extends eR{}let eF=/^[a-z][a-z0-9+.-]*:/i,ez=e=>eF.test(e),eD=e=>(eD=Array.isArray)(e),eq=eD;function eU(e){return"object"!=typeof e?{}:e??{}}let eL=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new eT(`${e} must be an integer`);if(t<0)throw new eT(`${e} must be a positive integer`);return t},eV=e=>{try{return JSON.parse(e)}catch(e){return}},eG=e=>new Promise(t=>setTimeout(t,e)),eW="0.78.0",eX=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator,eB=()=>{let e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":eJ(Deno.build.os),"X-Stainless-Arch":eK(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":eJ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":eK(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=function(){if("undefined"==typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,a=r[2]||0,n=r[3]||0;return{browser:e,version:`${t}.${a}.${n}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":eW,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},eK=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",eJ=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",eH=()=>e_??(e_=eB());function eY(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function eQ(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return eY({start(){},async pull(e){let{done:r,value:a}=await t.next();r?e.close():e.enqueue(a)},async cancel(){await t.return?.()}})}function e0(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function e1(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}let e2=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});function e4(e){let t;return(eg??(eg=(t=new globalThis.TextEncoder).encode.bind(t)))(e)}function e9(e){let t;return(ev??(ev=(t=new globalThis.TextDecoder).decode.bind(t)))(e)}class e5{constructor(){a.set(this,void 0),n.set(this,void 0),eb(this,a,new Uint8Array,"f"),eb(this,n,null,"f")}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?e4(e):e;eb(this,a,function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),a=0;for(let t of e)r.set(t,a),a+=t.length;return r}([ew(this,a,"f"),r]),"f");let o=[];for(;null!=(t=function(e,t){for(let r=t??0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}(ew(this,a,"f"),ew(this,n,"f")));){if(t.carriage&&null==ew(this,n,"f")){eb(this,n,t.index,"f");continue}if(null!=ew(this,n,"f")&&(t.index!==ew(this,n,"f")+1||t.carriage)){o.push(e9(ew(this,a,"f").subarray(0,ew(this,n,"f")-1))),eb(this,a,ew(this,a,"f").subarray(ew(this,n,"f")),"f"),eb(this,n,null,"f");continue}let e=null!==ew(this,n,"f")?t.preceding-1:t.preceding,r=e9(ew(this,a,"f").subarray(0,e));o.push(r),eb(this,a,ew(this,a,"f").subarray(t.index),"f"),eb(this,n,null,"f")}return o}flush(){return ew(this,a,"f").length?this.decode("\n"):[]}}a=new WeakMap,n=new WeakMap,e5.NEWLINE_CHARS=new Set(["\n","\r"]),e5.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let e6={off:0,error:200,warn:300,info:400,debug:500},e3=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(e6,e))return e;tr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(e6))}`)}};function e8(){}function e7(e,t,r){return!t||e6[e]>e6[r]?e8:t[e].bind(t)}let te={error:e8,warn:e8,info:e8,debug:e8},tt=new WeakMap;function tr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return te;let a=tt.get(t);if(a&&a[0]===r)return a[1];let n={error:e7("error",t,r),warn:e7("warn",t,r),info:e7("info",t,r),debug:e7("debug",t,r)};return tt.set(t,[r,n]),n}let ta=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class tn{constructor(e,t,r){this.iterator=e,o.set(this,void 0),this.controller=t,eb(this,o,r,"f")}static fromSSEResponse(e,t,r){let a=!1,n=r?tr(r):console;return new tn(async function*(){if(a)throw new eT("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let r=!1;try{for await(let r of to(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw n.error("Could not parse message into JSON:",r.data),n.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw n.error("Could not parse message into JSON:",r.data),n.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw new eR(void 0,eV(r.data)??r.data,void 0,e.headers)}r=!0}catch(e){if(ek(e))return;throw e}finally{r||t.abort()}},t,r)}static fromReadableStream(e,t,r){let a=!1;async function*n(){let t=new e5;for await(let r of e0(e))for(let e of t.decode(r))yield e;for(let e of t.flush())yield e}return new tn(async function*(){if(a)throw new eT("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let t of n())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(ek(e))return;throw e}finally{e||t.abort()}},t,r)}[(o=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),a=a=>({next:()=>{if(0===a.length){let a=r.next();e.push(a),t.push(a)}return a.shift()}});return[new tn(()=>a(e),this.controller,ew(this,o,"f")),new tn(()=>a(t),this.controller,ew(this,o,"f"))]}toReadableStream(){let e;let t=this;return eY({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:a}=await e.next();if(a)return t.close();let n=e4(JSON.stringify(r)+"\n");t.enqueue(n)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*to(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new eT("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new eT("Attempted to iterate over a response with no body")}let r=new ts,a=new e5;for await(let t of ti(e0(e.body)))for(let e of a.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of a.flush()){let t=r.decode(e);t&&(yield t)}}async function*ti(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let a=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?e4(r):r,n=new Uint8Array(t.length+a.length);for(n.set(t),n.set(a,t.length),t=n;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class ts{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,a]=function(e,t){let r=e.indexOf(":");return -1!==r?[e.substring(0,r),":",e.substring(r+t.length)]:[e,"",""]}(e,":");return a.startsWith(" ")&&(a=a.substring(1)),"event"===t?this.event=a:"data"===t&&this.data.push(a),null}}async function tl(e,t){let{response:r,requestLogID:a,retryOfRequestLogID:n,startTime:o}=t,i=await (async()=>{if(t.options.stream)return(tr(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller):tn.fromSSEResponse(r,t.controller);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let a=r.headers.get("content-type"),n=a?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){if("0"===r.headers.get("content-length"))return;return tu(await r.json(),r)}return await r.text()})();return tr(e).debug(`[${a}] response parsed`,ta({retryOfRequestLogID:n,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function tu(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}class td extends Promise{constructor(e,t,r=tl){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,i.set(this,void 0),eb(this,i,e,"f")}_thenUnwrap(e){return new td(ew(this,i,"f"),this.responsePromise,async(t,r)=>tu(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ew(this,i,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}i=new WeakMap;class tc{constructor(e,t,r,a){s.set(this,void 0),eb(this,s,e,"f"),this.options=a,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new eT("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ew(this,s,"f").requestAPIList(this.constructor,e)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(s=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class tp extends td{constructor(e,t,r){super(e,t,async(e,t)=>new r(e,t.response,await tl(e,t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}class th extends tc{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...eU(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...eU(this.options.query),after_id:e}}:null}}class tm extends tc{constructor(e,t,r,a){super(e,t,r,a),this.data=r.data||[],this.has_more=r.has_more||!1,this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...eU(this.options.query),page:e}}:null}}let tf=()=>{if("undefined"==typeof File){let{process:e}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof e?.versions?.node&&20>parseInt(e.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ty(e,t,r){return tf(),new File(e,t??"unknown_file",r)}function t_(e,t){let r="object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"";return t?r.split(/[\\/]/).pop()||void 0:r}let tg=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],tv=async(e,t,r=!0)=>({...e,body:await tw(e.body,t,r)}),tb=new WeakMap,tw=async(e,t,r=!0)=>{if(!await function(e){let t="function"==typeof e?e:e.fetch,r=tb.get(t);if(r)return r;let a=(async()=>{try{let e="Response"in t?t.Response:(await t("data:,")).constructor,r=new FormData;if(r.toString()===await new e(r).text())return!1;return!0}catch{return!0}})();return tb.set(t,a),a}(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let a=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>tT(a,e,t,r))),a},tx=e=>e instanceof Blob&&"name"in e,tk=e=>"object"==typeof e&&null!==e&&(e instanceof Response||tg(e)||tx(e)),tI=e=>{if(tk(e))return!0;if(Array.isArray(e))return e.some(tI);if(e&&"object"==typeof e){for(let t in e)if(tI(e[t]))return!0}return!1},tT=async(e,t,r,a)=>{if(void 0!==r){if(null==r)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(r instanceof Response){let n={},o=r.headers.get("Content-Type");o&&(n={type:o}),e.append(t,ty([await r.blob()],t_(r,a),n))}else if(tg(r))e.append(t,ty([await new Response(eQ(r)).blob()],t_(r,a)));else if(tx(r))e.append(t,ty([r],t_(r,a),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(r=>tT(e,t+"[]",r,a)));else if("object"==typeof r)await Promise.all(Object.entries(r).map(([r,n])=>tT(e,`${t}[${r}]`,n,a)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}},tR=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,tS=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&tR(e),tZ=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob;async function tC(e,t,r){if(tf(),e=await e,t||(t=t_(e,!0)),tS(e))return e instanceof File&&null==t&&null==r?e:ty([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...r});if(tZ(e)){let a=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),ty(await tE(a),t,r)}let a=await tE(e);if(!r?.type){let e=a.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r={...r,type:e})}return ty(a,t,r)}async function tE(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(tR(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(tg(e))for await(let r of e)t.push(...await tE(r));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class tO{constructor(e){this._client=e}}let tA=Symbol.for("brand.privateNullableHeaders"),tN=e=>{let t=new Headers,r=new Set;for(let a of e){let e=new Set;for(let[n,o]of function*(e){let t;if(!e)return;if(tA in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let a of(e instanceof Headers?t=e.entries():eq(e)?t=e:(r=!0,t=Object.entries(e??{})),t)){let e=a[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=eq(a[1])?a[1]:[a[1]],n=!1;for(let a of t)void 0!==a&&(r&&!n&&(n=!0,yield[e,null]),yield[e,a])}}(a)){let a=n.toLowerCase();e.has(a)||(t.delete(n),e.add(a)),null===o?(t.delete(n),r.add(a)):(t.append(n,o),r.delete(a))}}return{[tA]:!0,values:t,nulls:r}},tM=Symbol("anthropic.sdk.stainlessHelper");function t$(e){return"object"==typeof e&&null!==e&&tM in e}function tP(e,t){let r=new Set;if(e)for(let t of e)t$(t)&&r.add(t[tM]);if(t){for(let e of t)if(t$(e)&&r.add(e[tM]),Array.isArray(e.content))for(let t of e.content)t$(t)&&r.add(t[tM])}return Array.from(r)}function tj(e,t){let r=tP(e,t);return 0===r.length?{}:{"x-stainless-helper":r.join(", ")}}function tF(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}let tz=Object.freeze(Object.create(null)),tD=((e=tF)=>function(t,...r){let a;if(1===t.length)return t[0];let n=!1,o=[],i=t.reduce((t,a,i)=>{/[?#]/.test(a)&&(n=!0);let s=r[i],l=(n?encodeURIComponent:e)(""+s);return i!==r.length&&(null==s||"object"==typeof s&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??tz)??tz)?.toString)&&(l=s+"",o.push({start:t.length+a.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(i===r.length?"":l)},""),s=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(a=l.exec(s));)o.push({start:a.index,length:a[0].length,error:`Value "${a[0]}" can't be safely passed as a path parameter`});if(o.sort((e,t)=>e.start-t.start),o.length>0){let e=0,t=o.reduce((t,r)=>{let a=" ".repeat(r.start-e),n="^".repeat(r.length);return e=r.start+r.length,t+a+n},"");throw new eT(`Path parameters result in path with invalid segments:
15
15
  ${o.map(e=>e.error).join("\n")}
16
16
  ${i}
17
17
  ${t}`)}return i})(tF);class tq extends tO{list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/files",th,{query:a,...t,headers:tN([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){let{betas:a}=t??{};return this._client.delete(tD`/v1/files/${e}`,{...r,headers:tN([{"anthropic-beta":[...a??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/files/${e}/content`,{...r,headers:tN([{"anthropic-beta":[...a??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/files/${e}`,{...r,headers:tN([{"anthropic-beta":[...a??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){var r;let{betas:a,...n}=e;return this._client.post("/v1/files",tv({body:n,...t,headers:tN([{"anthropic-beta":[...a??[],"files-api-2025-04-14"].toString()},t$(r=n.file)?{"x-stainless-helper":r[tM]}:{},t?.headers])},this._client))}}class tU extends tO{retrieve(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/models/${e}?beta=true`,{...r,headers:tN([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/models?beta=true",th,{query:a,...t,headers:tN([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}let tL={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function tV(e){return e?.output_format??e?.output_config?.format}function tG(e,t,r){let a=tV(t);return t&&"parse"in(a??{})?tW(e,t,r):{...e,content:e.content.map(e=>"text"===e.type?Object.defineProperty(Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}),"parsed",{get:()=>(r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null),enumerable:!1}):e),parsed_output:null}}function tW(e,t,r){let a=null,n=e.content.map(e=>{if("text"===e.type){let n=function(e,t){let r=tV(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(e){throw new eT(`Failed to parse structured output: ${e}`)}}(t,e.text);return null===a&&(a=n),Object.defineProperty(Object.defineProperty({...e},"parsed_output",{value:n,enumerable:!1}),"parsed",{get:()=>(r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),n),enumerable:!1})}return e});return{...e,content:n,parsed_output:a}}let tX=e=>{let t=0,r=[];for(;t<e.length;){let a=e[t];if("\\"===a){t++;continue}if("{"===a){r.push({type:"brace",value:"{"}),t++;continue}if("}"===a){r.push({type:"brace",value:"}"}),t++;continue}if("["===a){r.push({type:"paren",value:"["}),t++;continue}if("]"===a){r.push({type:"paren",value:"]"}),t++;continue}if(":"===a){r.push({type:"separator",value:":"}),t++;continue}if(","===a){r.push({type:"delimiter",value:","}),t++;continue}if('"'===a){let n="",o=!1;for(a=e[++t];'"'!==a;){if(t===e.length){o=!0;break}if("\\"===a){if(++t===e.length){o=!0;break}n+=a+e[t],a=e[++t]}else n+=a,a=e[++t]}a=e[++t],o||r.push({type:"string",value:n});continue}let n=/\s/;if(a&&n.test(a)){t++;continue}let o=/[0-9]/;if(a&&o.test(a)||"-"===a||"."===a){let n="";for("-"===a&&(n+=a,a=e[++t]);a&&o.test(a)||"."===a;)n+=a,a=e[++t];r.push({type:"number",value:n});continue}let i=/[a-z]/i;if(a&&i.test(a)){let n="";for(;a&&i.test(a)&&t!==e.length;)n+=a,a=e[++t];"true"==n||"false"==n||"null"===n?r.push({type:"name",value:n}):t++;continue}t++}return r},tB=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return tB(e=e.slice(0,e.length-1));case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return tB(e=e.slice(0,e.length-1));case"string":let a=e[e.length-2];if(a?.type==="delimiter"||a?.type==="brace"&&"{"===a.value)return tB(e=e.slice(0,e.length-1));break;case"delimiter":return tB(e=e.slice(0,e.length-1))}return e},tK=e=>{let t=[];return e.map(e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})}),e},tJ=e=>{let t="";return e.map(e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value}),t},tH=e=>JSON.parse(tJ(tK(tB(tX(e))))),tY="__json_buf";function tQ(e){return"tool_use"===e.type||"server_tool_use"===e.type||"mcp_tool_use"===e.type}class t0{constructor(e,t){l.add(this),this.messages=[],this.receivedMessages=[],u.set(this,void 0),d.set(this,null),this.controller=new AbortController,c.set(this,void 0),p.set(this,()=>{}),h.set(this,()=>{}),m.set(this,void 0),f.set(this,()=>{}),y.set(this,()=>{}),_.set(this,{}),g.set(this,!1),v.set(this,!1),b.set(this,!1),w.set(this,!1),x.set(this,void 0),k.set(this,void 0),I.set(this,void 0),S.set(this,e=>{if(eb(this,v,!0,"f"),ek(e)&&(e=new eS),e instanceof eS)return eb(this,b,!0,"f"),this._emit("abort",e);if(e instanceof eT)return this._emit("error",e);if(e instanceof Error){let t=new eT(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eT(String(e)))}),eb(this,c,new Promise((e,t)=>{eb(this,p,e,"f"),eb(this,h,t,"f")}),"f"),eb(this,m,new Promise((e,t)=>{eb(this,f,e,"f"),eb(this,y,t,"f")}),"f"),ew(this,c,"f").catch(()=>{}),ew(this,m,"f").catch(()=>{}),eb(this,d,e,"f"),eb(this,I,t?.logger??console,"f")}get response(){return ew(this,x,"f")}get request_id(){return ew(this,k,"f")}async withResponse(){eb(this,w,!0,"f");let e=await ew(this,c,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new t0(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:a}={}){let n=new t0(t,{logger:a});for(let e of t.messages)n._addMessageParam(e);return eb(n,d,{...t,stream:!0},"f"),n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ew(this,S,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let a;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),n.addEventListener("abort",a));try{ew(this,l,"m",Z).call(this);let{response:a,data:n}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();for await(let e of(this._connected(a),n))ew(this,l,"m",C).call(this,e);if(n.controller.signal?.aborted)throw new eS;ew(this,l,"m",E).call(this)}finally{n&&a&&n.removeEventListener("abort",a)}}_connected(e){this.ended||(eb(this,x,e,"f"),eb(this,k,e?.headers.get("request-id"),"f"),ew(this,p,"f").call(this,e),this._emit("connect"))}get ended(){return ew(this,g,"f")}get errored(){return ew(this,v,"f")}get aborted(){return ew(this,b,"f")}abort(){this.controller.abort()}on(e,t){return(ew(this,_,"f")[e]||(ew(this,_,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=ew(this,_,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(ew(this,_,"f")[e]||(ew(this,_,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{eb(this,w,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){eb(this,w,!0,"f"),await ew(this,m,"f")}get currentMessage(){return ew(this,u,"f")}async finalMessage(){return await this.done(),ew(this,l,"m",T).call(this)}async finalText(){return await this.done(),ew(this,l,"m",R).call(this)}_emit(e,...t){if(ew(this,g,"f"))return;"end"===e&&(eb(this,g,!0,"f"),ew(this,f,"f").call(this));let r=ew(this,_,"f")[e];if(r&&(ew(this,_,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];ew(this,w,"f")||r?.length||Promise.reject(e),ew(this,h,"f").call(this,e),ew(this,y,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];ew(this,w,"f")||r?.length||Promise.reject(e),ew(this,h,"f").call(this,e),ew(this,y,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ew(this,l,"m",T).call(this))}async _fromReadableStream(e,t){let r;let a=t?.signal;a&&(a.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),a.addEventListener("abort",r));try{ew(this,l,"m",Z).call(this),this._connected(null);let t=tn.fromReadableStream(e,this.controller);for await(let e of t)ew(this,l,"m",C).call(this,e);if(t.controller.signal?.aborted)throw new eS;ew(this,l,"m",E).call(this)}finally{a&&r&&a.removeEventListener("abort",r)}}[(u=new WeakMap,d=new WeakMap,c=new WeakMap,p=new WeakMap,h=new WeakMap,m=new WeakMap,f=new WeakMap,y=new WeakMap,_=new WeakMap,g=new WeakMap,v=new WeakMap,b=new WeakMap,w=new WeakMap,x=new WeakMap,k=new WeakMap,I=new WeakMap,S=new WeakMap,l=new WeakSet,T=function(){if(0===this.receivedMessages.length)throw new eT("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},R=function(){if(0===this.receivedMessages.length)throw new eT("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new eT("stream ended without producing a content block with type=text");return e.join(" ")},Z=function(){this.ended||eb(this,u,void 0,"f")},C=function(e){if(this.ended)return;let t=ew(this,l,"m",O).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":tQ(r)&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;case"compaction_delta":"compaction"===r.type&&r.content&&this._emit("compaction",r.content);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(tG(t,ew(this,d,"f"),{logger:ew(this,I,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":eb(this,u,t,"f")}},E=function(){if(this.ended)throw new eT("stream has ended, this shouldn't happen");let e=ew(this,u,"f");if(!e)throw new eT("request ended without sending any chunks");return eb(this,u,void 0,"f"),tG(e,ew(this,d,"f"),{logger:ew(this,I,"f")})},O=function(e){let t=ew(this,u,"f");if("message_start"===e.type){if(t)throw new eT(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new eT(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),null!=e.usage.iterations&&(t.usage.iterations=e.usage.iterations),t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{let r=t.content.at(e.index);switch(e.delta.type){case"text_delta":r?.type==="text"&&(t.content[e.index]={...r,text:(r.text||"")+e.delta.text});break;case"citations_delta":r?.type==="text"&&(t.content[e.index]={...r,citations:[...r.citations??[],e.delta.citation]});break;case"input_json_delta":if(r&&tQ(r)){let a=r[tY]||"";a+=e.delta.partial_json;let n={...r};if(Object.defineProperty(n,tY,{value:a,enumerable:!1,writable:!0}),a)try{n.input=tH(a)}catch(t){let e=new eT(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${t}. JSON: ${a}`);ew(this,S,"f").call(this,e)}t.content[e.index]=n}break;case"thinking_delta":r?.type==="thinking"&&(t.content[e.index]={...r,thinking:r.thinking+e.delta.thinking});break;case"signature_delta":r?.type==="thinking"&&(t.content[e.index]={...r,signature:e.delta.signature});break;case"compaction_delta":r?.type==="compaction"&&(t.content[e.index]={...r,content:(r.content||"")+e.delta.content});break;default:e.delta}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class t1 extends Error{constructor(e){super("string"==typeof e?e:e.map(e=>"text"===e.type?e.text:`[${e.type}]`).join(" ")),this.name="ToolError",this.content=e}}let t2=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
@@ -36,8 +36,8 @@ User preferences or style requirements
36
36
  Domain-specific details that aren't obvious
37
37
  Any promises made to the user
38
38
  Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
39
- Wrap your summary in <summary></summary> tags.`;function t4(){let e,t;return{promise:new Promise((r,a)=>{e=r,t=a}),resolve:e,reject:t}}class t9{constructor(e,t,r){A.add(this),this.client=e,N.set(this,!1),M.set(this,!1),$.set(this,void 0),P.set(this,void 0),j.set(this,void 0),F.set(this,void 0),z.set(this,void 0),D.set(this,0),eb(this,$,{params:{...t,messages:structuredClone(t.messages)}},"f");let a=["BetaToolRunner",...tP(t.tools,t.messages)].join(", ");eb(this,P,{...r,headers:tN([{"x-stainless-helper":a},r?.headers])},"f"),eb(this,z,t4(),"f")}async *[(N=new WeakMap,M=new WeakMap,$=new WeakMap,P=new WeakMap,j=new WeakMap,F=new WeakMap,z=new WeakMap,D=new WeakMap,A=new WeakSet,q=async function(){let e=ew(this,$,"f").params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(void 0!==ew(this,j,"f"))try{let e=await ew(this,j,"f");t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}if(t<(e.contextTokenThreshold??1e5))return!1;let r=e.model??ew(this,$,"f").params.model,a=e.summaryPrompt??t2,n=ew(this,$,"f").params.messages;if("assistant"===n[n.length-1].role){let e=n[n.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>"tool_use"!==e.type);0===t.length?n.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...n,{role:"user",content:[{type:"text",text:a}]}],max_tokens:ew(this,$,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(o.content[0]?.type!=="text")throw new eT("Expected text response for compaction");return ew(this,$,"f").params.messages=[{role:"user",content:o.content}],!0},Symbol.asyncIterator)](){var e;if(ew(this,N,"f"))throw new eT("Cannot iterate over a consumed stream");eb(this,N,!0,"f"),eb(this,M,!0,"f"),eb(this,F,void 0,"f");try{for(;;){let t;try{if(ew(this,$,"f").params.max_iterations&&ew(this,D,"f")>=ew(this,$,"f").params.max_iterations)break;eb(this,M,!1,"f"),eb(this,F,void 0,"f"),eb(this,D,(e=ew(this,D,"f"),++e),"f"),eb(this,j,void 0,"f");let{max_iterations:r,compactionControl:a,...n}=ew(this,$,"f").params;if(n.stream?(t=this.client.beta.messages.stream({...n},ew(this,P,"f")),eb(this,j,t.finalMessage(),"f"),ew(this,j,"f").catch(()=>{}),yield t):(eb(this,j,this.client.beta.messages.create({...n,stream:!1},ew(this,P,"f")),"f"),yield ew(this,j,"f")),!await ew(this,A,"m",q).call(this)){if(!ew(this,M,"f")){let{role:e,content:t}=await ew(this,j,"f");ew(this,$,"f").params.messages.push({role:e,content:t})}let e=await ew(this,A,"m",U).call(this,ew(this,$,"f").params.messages.at(-1));if(e)ew(this,$,"f").params.messages.push(e);else if(!ew(this,M,"f"))break}}finally{t&&t.abort()}}if(!ew(this,j,"f"))throw new eT("ToolRunner concluded without a message from the server");ew(this,z,"f").resolve(await ew(this,j,"f"))}catch(e){throw eb(this,N,!1,"f"),ew(this,z,"f").promise.catch(()=>{}),ew(this,z,"f").reject(e),eb(this,z,t4(),"f"),e}}setMessagesParams(e){"function"==typeof e?ew(this,$,"f").params=e(ew(this,$,"f").params):ew(this,$,"f").params=e,eb(this,M,!0,"f"),eb(this,F,void 0,"f")}async generateToolResponse(){let e=await ew(this,j,"f")??this.params.messages.at(-1);return e?ew(this,A,"m",U).call(this,e):null}done(){return ew(this,z,"f").promise}async runUntilDone(){if(!ew(this,N,"f"))for await(let e of this);return this.done()}get params(){return ew(this,$,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}async function t5(e,t=e.messages.at(-1)){if(!t||"assistant"!==t.role||!t.content||"string"==typeof t.content)return null;let r=t.content.filter(e=>"tool_use"===e.type);return 0===r.length?null:{role:"user",content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>("name"in e?e.name:e.mcp_server_name)===t.name);if(!r||!("run"in r))return{type:"tool_result",tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;"parse"in r&&r.parse&&(e=r.parse(e));let a=await r.run(e);return{type:"tool_result",tool_use_id:t.id,content:a}}catch(e){return{type:"tool_result",tool_use_id:t.id,content:e instanceof t1?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}U=async function(e){return void 0!==ew(this,F,"f")||eb(this,F,t5(ew(this,$,"f").params,e),"f"),ew(this,F,"f")};class t6{constructor(e,t){this.iterator=e,this.controller=t}async *decoder(){let e=new e5;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new eT("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new eT("Attempted to iterate over a response with no body")}return new t6(e0(e.body),t)}}class t3 extends tO{create(e,t){let{betas:r,...a}=e;return this._client.post("/v1/messages/batches?beta=true",{body:a,...t,headers:tN([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/messages/batches/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",th,{query:a,...t,headers:tN([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:a}=t??{};return this._client.delete(tD`/v1/messages/batches/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:a}=t??{};return this._client.post(tD`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let a=await this.retrieve(e);if(!a.results_url)throw new eT(`No batch \`results_url\`; Has it finished processing? ${a.processing_status} - ${a.id}`);let{betas:n}=t??{};return this._client.get(a.results_url,{...r,headers:tN([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>t6.fromResponse(t.response,t.controller))}}let t7={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},t8=["claude-opus-4-6"];class re extends tO{constructor(){super(...arguments),this.batches=new t3(this._client)}create(e,t){let r=rt(e),{betas:a,...n}=r;n.model in t7&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${t7[n.model]}
40
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),n.model in t8&&n.thinking&&"enabled"===n.thinking.type&&console.warn(`Using Claude with ${n.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let o=this._client._options.timeout;if(!n.stream&&null==o){let e=tL[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,e)}let i=tj(n.tools,n.messages);return this._client.post("/v1/messages?beta=true",{body:n,timeout:o??6e5,...t,headers:tN([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},i,t?.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:tN([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(t=>tW(t,e,{logger:this._client.logger??console}))}stream(e,t){return t0.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...a}=rt(e);return this._client.post("/v1/messages/count_tokens?beta=true",{body:a,...t,headers:tN([{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new t9(this._client,e,t)}}function rt(e){if(!e.output_format)return e;if(e.output_config?.format)throw new eT("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:t,...r}=e;return{...r,output_config:{...e.output_config,format:t}}}re.Batches=t3,re.BetaToolRunner=t9,re.ToolError=t1;class rr extends tO{create(e,t={},r){let{betas:a,...n}=t??{};return this._client.post(tD`/v1/skills/${e}/versions?beta=true`,tv({body:n,...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,t,r){let{skill_id:a,betas:n}=t;return this._client.get(tD`/v1/skills/${a}/versions/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){let{betas:a,...n}=t??{};return this._client.getAPIList(tD`/v1/skills/${e}/versions?beta=true`,tm,{query:n,...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){let{skill_id:a,betas:n}=t;return this._client.delete(tD`/v1/skills/${a}/versions/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}}class ra extends tO{constructor(){super(...arguments),this.versions=new rr(this._client)}create(e={},t){let{betas:r,...a}=e??{};return this._client.post("/v1/skills?beta=true",tv({body:a,...t,headers:tN([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/skills/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/skills?beta=true",tm,{query:a,...t,headers:tN([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){let{betas:a}=t??{};return this._client.delete(tD`/v1/skills/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])})}}ra.Versions=rr;class rn extends tO{constructor(){super(...arguments),this.models=new tU(this._client),this.messages=new re(this._client),this.files=new tq(this._client),this.skills=new ra(this._client)}}rn.Models=tU,rn.Messages=re,rn.Files=tq,rn.Skills=ra;class ro extends tO{create(e,t){let{betas:r,...a}=e;return this._client.post("/v1/complete",{body:a,timeout:this._client._options.timeout??6e5,...t,headers:tN([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}function ri(e){return e?.output_config?.format}function rs(e,t,r){let a=ri(t);return t&&"parse"in(a??{})?rl(e,t,r):{...e,content:e.content.map(e=>"text"===e.type?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}}function rl(e,t,r){let a=null,n=e.content.map(e=>{if("text"===e.type){let r=function(e,t){let r=ri(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(e){throw new eT(`Failed to parse structured output: ${e}`)}}(t,e.text);return null===a&&(a=r),Object.defineProperty({...e},"parsed_output",{value:r,enumerable:!1})}return e});return{...e,content:n,parsed_output:a}}let ru="__json_buf";function rd(e){return"tool_use"===e.type||"server_tool_use"===e.type}class rc{constructor(e,t){L.add(this),this.messages=[],this.receivedMessages=[],V.set(this,void 0),G.set(this,null),this.controller=new AbortController,W.set(this,void 0),X.set(this,()=>{}),B.set(this,()=>{}),K.set(this,void 0),J.set(this,()=>{}),H.set(this,()=>{}),Y.set(this,{}),Q.set(this,!1),ee.set(this,!1),et.set(this,!1),er.set(this,!1),ea.set(this,void 0),en.set(this,void 0),eo.set(this,void 0),el.set(this,e=>{if(eb(this,ee,!0,"f"),ek(e)&&(e=new eS),e instanceof eS)return eb(this,et,!0,"f"),this._emit("abort",e);if(e instanceof eT)return this._emit("error",e);if(e instanceof Error){let t=new eT(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eT(String(e)))}),eb(this,W,new Promise((e,t)=>{eb(this,X,e,"f"),eb(this,B,t,"f")}),"f"),eb(this,K,new Promise((e,t)=>{eb(this,J,e,"f"),eb(this,H,t,"f")}),"f"),ew(this,W,"f").catch(()=>{}),ew(this,K,"f").catch(()=>{}),eb(this,G,e,"f"),eb(this,eo,t?.logger??console,"f")}get response(){return ew(this,ea,"f")}get request_id(){return ew(this,en,"f")}async withResponse(){eb(this,er,!0,"f");let e=await ew(this,W,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new rc(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:a}={}){let n=new rc(t,{logger:a});for(let e of t.messages)n._addMessageParam(e);return eb(n,G,{...t,stream:!0},"f"),n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ew(this,el,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let a;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),n.addEventListener("abort",a));try{ew(this,L,"m",eu).call(this);let{response:a,data:n}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();for await(let e of(this._connected(a),n))ew(this,L,"m",ed).call(this,e);if(n.controller.signal?.aborted)throw new eS;ew(this,L,"m",ec).call(this)}finally{n&&a&&n.removeEventListener("abort",a)}}_connected(e){this.ended||(eb(this,ea,e,"f"),eb(this,en,e?.headers.get("request-id"),"f"),ew(this,X,"f").call(this,e),this._emit("connect"))}get ended(){return ew(this,Q,"f")}get errored(){return ew(this,ee,"f")}get aborted(){return ew(this,et,"f")}abort(){this.controller.abort()}on(e,t){return(ew(this,Y,"f")[e]||(ew(this,Y,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=ew(this,Y,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(ew(this,Y,"f")[e]||(ew(this,Y,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{eb(this,er,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){eb(this,er,!0,"f"),await ew(this,K,"f")}get currentMessage(){return ew(this,V,"f")}async finalMessage(){return await this.done(),ew(this,L,"m",ei).call(this)}async finalText(){return await this.done(),ew(this,L,"m",es).call(this)}_emit(e,...t){if(ew(this,Q,"f"))return;"end"===e&&(eb(this,Q,!0,"f"),ew(this,J,"f").call(this));let r=ew(this,Y,"f")[e];if(r&&(ew(this,Y,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];ew(this,er,"f")||r?.length||Promise.reject(e),ew(this,B,"f").call(this,e),ew(this,H,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];ew(this,er,"f")||r?.length||Promise.reject(e),ew(this,B,"f").call(this,e),ew(this,H,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ew(this,L,"m",ei).call(this))}async _fromReadableStream(e,t){let r;let a=t?.signal;a&&(a.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),a.addEventListener("abort",r));try{ew(this,L,"m",eu).call(this),this._connected(null);let t=tn.fromReadableStream(e,this.controller);for await(let e of t)ew(this,L,"m",ed).call(this,e);if(t.controller.signal?.aborted)throw new eS;ew(this,L,"m",ec).call(this)}finally{a&&r&&a.removeEventListener("abort",r)}}[(V=new WeakMap,G=new WeakMap,W=new WeakMap,X=new WeakMap,B=new WeakMap,K=new WeakMap,J=new WeakMap,H=new WeakMap,Y=new WeakMap,Q=new WeakMap,ee=new WeakMap,et=new WeakMap,er=new WeakMap,ea=new WeakMap,en=new WeakMap,eo=new WeakMap,el=new WeakMap,L=new WeakSet,ei=function(){if(0===this.receivedMessages.length)throw new eT("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},es=function(){if(0===this.receivedMessages.length)throw new eT("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new eT("stream ended without producing a content block with type=text");return e.join(" ")},eu=function(){this.ended||eb(this,V,void 0,"f")},ed=function(e){if(this.ended)return;let t=ew(this,L,"m",ep).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":rd(r)&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(rs(t,ew(this,G,"f"),{logger:ew(this,eo,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":eb(this,V,t,"f")}},ec=function(){if(this.ended)throw new eT("stream has ended, this shouldn't happen");let e=ew(this,V,"f");if(!e)throw new eT("request ended without sending any chunks");return eb(this,V,void 0,"f"),rs(e,ew(this,G,"f"),{logger:ew(this,eo,"f")})},ep=function(e){let t=ew(this,V,"f");if("message_start"===e.type){if(t)throw new eT(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new eT(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push({...e.content_block}),t;case"content_block_delta":{let r=t.content.at(e.index);switch(e.delta.type){case"text_delta":r?.type==="text"&&(t.content[e.index]={...r,text:(r.text||"")+e.delta.text});break;case"citations_delta":r?.type==="text"&&(t.content[e.index]={...r,citations:[...r.citations??[],e.delta.citation]});break;case"input_json_delta":if(r&&rd(r)){let a=r[ru]||"";a+=e.delta.partial_json;let n={...r};Object.defineProperty(n,ru,{value:a,enumerable:!1,writable:!0}),a&&(n.input=tH(a)),t.content[e.index]=n}break;case"thinking_delta":r?.type==="thinking"&&(t.content[e.index]={...r,thinking:r.thinking+e.delta.thinking});break;case"signature_delta":r?.type==="thinking"&&(t.content[e.index]={...r,signature:e.delta.signature});break;default:e.delta}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class rp extends tO{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(tD`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",th,{query:e,...t})}delete(e,t){return this._client.delete(tD`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(tD`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new eT(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:tN([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>t6.fromResponse(t.response,t.controller))}}class rh extends tO{constructor(){super(...arguments),this.batches=new rp(this._client)}create(e,t){e.model in rm&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${rm[e.model]}
39
+ Wrap your summary in <summary></summary> tags.`;function t4(){let e,t;return{promise:new Promise((r,a)=>{e=r,t=a}),resolve:e,reject:t}}class t9{constructor(e,t,r){A.add(this),this.client=e,N.set(this,!1),M.set(this,!1),$.set(this,void 0),P.set(this,void 0),j.set(this,void 0),F.set(this,void 0),z.set(this,void 0),D.set(this,0),eb(this,$,{params:{...t,messages:structuredClone(t.messages)}},"f");let a=["BetaToolRunner",...tP(t.tools,t.messages)].join(", ");eb(this,P,{...r,headers:tN([{"x-stainless-helper":a},r?.headers])},"f"),eb(this,z,t4(),"f")}async *[(N=new WeakMap,M=new WeakMap,$=new WeakMap,P=new WeakMap,j=new WeakMap,F=new WeakMap,z=new WeakMap,D=new WeakMap,A=new WeakSet,q=async function(){let e=ew(this,$,"f").params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(void 0!==ew(this,j,"f"))try{let e=await ew(this,j,"f");t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}if(t<(e.contextTokenThreshold??1e5))return!1;let r=e.model??ew(this,$,"f").params.model,a=e.summaryPrompt??t2,n=ew(this,$,"f").params.messages;if("assistant"===n[n.length-1].role){let e=n[n.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>"tool_use"!==e.type);0===t.length?n.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...n,{role:"user",content:[{type:"text",text:a}]}],max_tokens:ew(this,$,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(o.content[0]?.type!=="text")throw new eT("Expected text response for compaction");return ew(this,$,"f").params.messages=[{role:"user",content:o.content}],!0},Symbol.asyncIterator)](){var e;if(ew(this,N,"f"))throw new eT("Cannot iterate over a consumed stream");eb(this,N,!0,"f"),eb(this,M,!0,"f"),eb(this,F,void 0,"f");try{for(;;){let t;try{if(ew(this,$,"f").params.max_iterations&&ew(this,D,"f")>=ew(this,$,"f").params.max_iterations)break;eb(this,M,!1,"f"),eb(this,F,void 0,"f"),eb(this,D,(e=ew(this,D,"f"),++e),"f"),eb(this,j,void 0,"f");let{max_iterations:r,compactionControl:a,...n}=ew(this,$,"f").params;if(n.stream?(t=this.client.beta.messages.stream({...n},ew(this,P,"f")),eb(this,j,t.finalMessage(),"f"),ew(this,j,"f").catch(()=>{}),yield t):(eb(this,j,this.client.beta.messages.create({...n,stream:!1},ew(this,P,"f")),"f"),yield ew(this,j,"f")),!await ew(this,A,"m",q).call(this)){if(!ew(this,M,"f")){let{role:e,content:t}=await ew(this,j,"f");ew(this,$,"f").params.messages.push({role:e,content:t})}let e=await ew(this,A,"m",U).call(this,ew(this,$,"f").params.messages.at(-1));if(e)ew(this,$,"f").params.messages.push(e);else if(!ew(this,M,"f"))break}}finally{t&&t.abort()}}if(!ew(this,j,"f"))throw new eT("ToolRunner concluded without a message from the server");ew(this,z,"f").resolve(await ew(this,j,"f"))}catch(e){throw eb(this,N,!1,"f"),ew(this,z,"f").promise.catch(()=>{}),ew(this,z,"f").reject(e),eb(this,z,t4(),"f"),e}}setMessagesParams(e){"function"==typeof e?ew(this,$,"f").params=e(ew(this,$,"f").params):ew(this,$,"f").params=e,eb(this,M,!0,"f"),eb(this,F,void 0,"f")}async generateToolResponse(){let e=await ew(this,j,"f")??this.params.messages.at(-1);return e?ew(this,A,"m",U).call(this,e):null}done(){return ew(this,z,"f").promise}async runUntilDone(){if(!ew(this,N,"f"))for await(let e of this);return this.done()}get params(){return ew(this,$,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}async function t5(e,t=e.messages.at(-1)){if(!t||"assistant"!==t.role||!t.content||"string"==typeof t.content)return null;let r=t.content.filter(e=>"tool_use"===e.type);return 0===r.length?null:{role:"user",content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>("name"in e?e.name:e.mcp_server_name)===t.name);if(!r||!("run"in r))return{type:"tool_result",tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;"parse"in r&&r.parse&&(e=r.parse(e));let a=await r.run(e);return{type:"tool_result",tool_use_id:t.id,content:a}}catch(e){return{type:"tool_result",tool_use_id:t.id,content:e instanceof t1?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}U=async function(e){return void 0!==ew(this,F,"f")||eb(this,F,t5(ew(this,$,"f").params,e),"f"),ew(this,F,"f")};class t6{constructor(e,t){this.iterator=e,this.controller=t}async *decoder(){let e=new e5;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new eT("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new eT("Attempted to iterate over a response with no body")}return new t6(e0(e.body),t)}}class t3 extends tO{create(e,t){let{betas:r,...a}=e;return this._client.post("/v1/messages/batches?beta=true",{body:a,...t,headers:tN([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/messages/batches/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",th,{query:a,...t,headers:tN([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){let{betas:a}=t??{};return this._client.delete(tD`/v1/messages/batches/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){let{betas:a}=t??{};return this._client.post(tD`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){let a=await this.retrieve(e);if(!a.results_url)throw new eT(`No batch \`results_url\`; Has it finished processing? ${a.processing_status} - ${a.id}`);let{betas:n}=t??{};return this._client.get(a.results_url,{...r,headers:tN([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>t6.fromResponse(t.response,t.controller))}}let t8={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},t7=["claude-opus-4-6"];class re extends tO{constructor(){super(...arguments),this.batches=new t3(this._client)}create(e,t){let r=rt(e),{betas:a,...n}=r;n.model in t8&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${t8[n.model]}
40
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),n.model in t7&&n.thinking&&"enabled"===n.thinking.type&&console.warn(`Using Claude with ${n.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let o=this._client._options.timeout;if(!n.stream&&null==o){let e=tL[n.model]??void 0;o=this._client.calculateNonstreamingTimeout(n.max_tokens,e)}let i=tj(n.tools,n.messages);return this._client.post("/v1/messages?beta=true",{body:n,timeout:o??6e5,...t,headers:tN([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},i,t?.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:tN([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(t=>tW(t,e,{logger:this._client.logger??console}))}stream(e,t){return t0.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...a}=rt(e);return this._client.post("/v1/messages/count_tokens?beta=true",{body:a,...t,headers:tN([{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new t9(this._client,e,t)}}function rt(e){if(!e.output_format)return e;if(e.output_config?.format)throw new eT("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:t,...r}=e;return{...r,output_config:{...e.output_config,format:t}}}re.Batches=t3,re.BetaToolRunner=t9,re.ToolError=t1;class rr extends tO{create(e,t={},r){let{betas:a,...n}=t??{};return this._client.post(tD`/v1/skills/${e}/versions?beta=true`,tv({body:n,...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,t,r){let{skill_id:a,betas:n}=t;return this._client.get(tD`/v1/skills/${a}/versions/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){let{betas:a,...n}=t??{};return this._client.getAPIList(tD`/v1/skills/${e}/versions?beta=true`,tm,{query:n,...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){let{skill_id:a,betas:n}=t;return this._client.delete(tD`/v1/skills/${a}/versions/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}}class ra extends tO{constructor(){super(...arguments),this.versions=new rr(this._client)}create(e={},t){let{betas:r,...a}=e??{};return this._client.post("/v1/skills?beta=true",tv({body:a,...t,headers:tN([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/skills/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/skills?beta=true",tm,{query:a,...t,headers:tN([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){let{betas:a}=t??{};return this._client.delete(tD`/v1/skills/${e}?beta=true`,{...r,headers:tN([{"anthropic-beta":[...a??[],"skills-2025-10-02"].toString()},r?.headers])})}}ra.Versions=rr;class rn extends tO{constructor(){super(...arguments),this.models=new tU(this._client),this.messages=new re(this._client),this.files=new tq(this._client),this.skills=new ra(this._client)}}rn.Models=tU,rn.Messages=re,rn.Files=tq,rn.Skills=ra;class ro extends tO{create(e,t){let{betas:r,...a}=e;return this._client.post("/v1/complete",{body:a,timeout:this._client._options.timeout??6e5,...t,headers:tN([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}function ri(e){return e?.output_config?.format}function rs(e,t,r){let a=ri(t);return t&&"parse"in(a??{})?rl(e,t,r):{...e,content:e.content.map(e=>"text"===e.type?Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1}):e),parsed_output:null}}function rl(e,t,r){let a=null,n=e.content.map(e=>{if("text"===e.type){let r=function(e,t){let r=ri(e);if(r?.type!=="json_schema")return null;try{if("parse"in r)return r.parse(t);return JSON.parse(t)}catch(e){throw new eT(`Failed to parse structured output: ${e}`)}}(t,e.text);return null===a&&(a=r),Object.defineProperty({...e},"parsed_output",{value:r,enumerable:!1})}return e});return{...e,content:n,parsed_output:a}}let ru="__json_buf";function rd(e){return"tool_use"===e.type||"server_tool_use"===e.type}class rc{constructor(e,t){L.add(this),this.messages=[],this.receivedMessages=[],V.set(this,void 0),G.set(this,null),this.controller=new AbortController,W.set(this,void 0),X.set(this,()=>{}),B.set(this,()=>{}),K.set(this,void 0),J.set(this,()=>{}),H.set(this,()=>{}),Y.set(this,{}),Q.set(this,!1),ee.set(this,!1),et.set(this,!1),er.set(this,!1),ea.set(this,void 0),en.set(this,void 0),eo.set(this,void 0),el.set(this,e=>{if(eb(this,ee,!0,"f"),ek(e)&&(e=new eS),e instanceof eS)return eb(this,et,!0,"f"),this._emit("abort",e);if(e instanceof eT)return this._emit("error",e);if(e instanceof Error){let t=new eT(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eT(String(e)))}),eb(this,W,new Promise((e,t)=>{eb(this,X,e,"f"),eb(this,B,t,"f")}),"f"),eb(this,K,new Promise((e,t)=>{eb(this,J,e,"f"),eb(this,H,t,"f")}),"f"),ew(this,W,"f").catch(()=>{}),ew(this,K,"f").catch(()=>{}),eb(this,G,e,"f"),eb(this,eo,t?.logger??console,"f")}get response(){return ew(this,ea,"f")}get request_id(){return ew(this,en,"f")}async withResponse(){eb(this,er,!0,"f");let e=await ew(this,W,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new rc(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:a}={}){let n=new rc(t,{logger:a});for(let e of t.messages)n._addMessageParam(e);return eb(n,G,{...t,stream:!0},"f"),n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ew(this,el,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let a;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),a=this.controller.abort.bind(this.controller),n.addEventListener("abort",a));try{ew(this,L,"m",eu).call(this);let{response:a,data:n}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();for await(let e of(this._connected(a),n))ew(this,L,"m",ed).call(this,e);if(n.controller.signal?.aborted)throw new eS;ew(this,L,"m",ec).call(this)}finally{n&&a&&n.removeEventListener("abort",a)}}_connected(e){this.ended||(eb(this,ea,e,"f"),eb(this,en,e?.headers.get("request-id"),"f"),ew(this,X,"f").call(this,e),this._emit("connect"))}get ended(){return ew(this,Q,"f")}get errored(){return ew(this,ee,"f")}get aborted(){return ew(this,et,"f")}abort(){this.controller.abort()}on(e,t){return(ew(this,Y,"f")[e]||(ew(this,Y,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=ew(this,Y,"f")[e];if(!r)return this;let a=r.findIndex(e=>e.listener===t);return a>=0&&r.splice(a,1),this}once(e,t){return(ew(this,Y,"f")[e]||(ew(this,Y,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{eb(this,er,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){eb(this,er,!0,"f"),await ew(this,K,"f")}get currentMessage(){return ew(this,V,"f")}async finalMessage(){return await this.done(),ew(this,L,"m",ei).call(this)}async finalText(){return await this.done(),ew(this,L,"m",es).call(this)}_emit(e,...t){if(ew(this,Q,"f"))return;"end"===e&&(eb(this,Q,!0,"f"),ew(this,J,"f").call(this));let r=ew(this,Y,"f")[e];if(r&&(ew(this,Y,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];ew(this,er,"f")||r?.length||Promise.reject(e),ew(this,B,"f").call(this,e),ew(this,H,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];ew(this,er,"f")||r?.length||Promise.reject(e),ew(this,B,"f").call(this,e),ew(this,H,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ew(this,L,"m",ei).call(this))}async _fromReadableStream(e,t){let r;let a=t?.signal;a&&(a.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),a.addEventListener("abort",r));try{ew(this,L,"m",eu).call(this),this._connected(null);let t=tn.fromReadableStream(e,this.controller);for await(let e of t)ew(this,L,"m",ed).call(this,e);if(t.controller.signal?.aborted)throw new eS;ew(this,L,"m",ec).call(this)}finally{a&&r&&a.removeEventListener("abort",r)}}[(V=new WeakMap,G=new WeakMap,W=new WeakMap,X=new WeakMap,B=new WeakMap,K=new WeakMap,J=new WeakMap,H=new WeakMap,Y=new WeakMap,Q=new WeakMap,ee=new WeakMap,et=new WeakMap,er=new WeakMap,ea=new WeakMap,en=new WeakMap,eo=new WeakMap,el=new WeakMap,L=new WeakSet,ei=function(){if(0===this.receivedMessages.length)throw new eT("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},es=function(){if(0===this.receivedMessages.length)throw new eT("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new eT("stream ended without producing a content block with type=text");return e.join(" ")},eu=function(){this.ended||eb(this,V,void 0,"f")},ed=function(e){if(this.ended)return;let t=ew(this,L,"m",ep).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);switch(e.delta.type){case"text_delta":"text"===r.type&&this._emit("text",e.delta.text,r.text||"");break;case"citations_delta":"text"===r.type&&this._emit("citation",e.delta.citation,r.citations??[]);break;case"input_json_delta":rd(r)&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break;case"thinking_delta":"thinking"===r.type&&this._emit("thinking",e.delta.thinking,r.thinking);break;case"signature_delta":"thinking"===r.type&&this._emit("signature",r.signature);break;default:e.delta}break}case"message_stop":this._addMessageParam(t),this._addMessage(rs(t,ew(this,G,"f"),{logger:ew(this,eo,"f")}),!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":eb(this,V,t,"f")}},ec=function(){if(this.ended)throw new eT("stream has ended, this shouldn't happen");let e=ew(this,V,"f");if(!e)throw new eT("request ended without sending any chunks");return eb(this,V,void 0,"f"),rs(e,ew(this,G,"f"),{logger:ew(this,eo,"f")})},ep=function(e){let t=ew(this,V,"f");if("message_start"===e.type){if(t)throw new eT(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new eT(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,null!=e.usage.input_tokens&&(t.usage.input_tokens=e.usage.input_tokens),null!=e.usage.cache_creation_input_tokens&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),null!=e.usage.cache_read_input_tokens&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),null!=e.usage.server_tool_use&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case"content_block_start":return t.content.push({...e.content_block}),t;case"content_block_delta":{let r=t.content.at(e.index);switch(e.delta.type){case"text_delta":r?.type==="text"&&(t.content[e.index]={...r,text:(r.text||"")+e.delta.text});break;case"citations_delta":r?.type==="text"&&(t.content[e.index]={...r,citations:[...r.citations??[],e.delta.citation]});break;case"input_json_delta":if(r&&rd(r)){let a=r[ru]||"";a+=e.delta.partial_json;let n={...r};Object.defineProperty(n,ru,{value:a,enumerable:!1,writable:!0}),a&&(n.input=tH(a)),t.content[e.index]=n}break;case"thinking_delta":r?.type==="thinking"&&(t.content[e.index]={...r,thinking:r.thinking+e.delta.thinking});break;case"signature_delta":r?.type==="thinking"&&(t.content[e.index]={...r,signature:e.delta.signature});break;default:e.delta}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),this.on("error",e=>{for(let a of(r=!0,t))a.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new tn(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class rp extends tO{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(tD`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",th,{query:e,...t})}delete(e,t){return this._client.delete(tD`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(tD`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let r=await this.retrieve(e);if(!r.results_url)throw new eT(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:tN([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>t6.fromResponse(t.response,t.controller))}}class rh extends tO{constructor(){super(...arguments),this.batches=new rp(this._client)}create(e,t){e.model in rm&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${rm[e.model]}
41
41
  Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),e.model in rf&&e.thinking&&"enabled"===e.thinking.type&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&null==r){let t=tL[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let a=tj(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...t,headers:tN([a,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>rl(t,e,{logger:this._client.logger??console}))}stream(e,t){return rc.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}let rm={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026"},rf=["claude-opus-4-6"];rh.Batches=rp;class ry extends tO{retrieve(e,t={},r){let{betas:a}=t??{};return this._client.get(tD`/v1/models/${e}`,{...r,headers:tN([{...a?.toString()!=null?{"anthropic-beta":a?.toString()}:void 0},r?.headers])})}list(e={},t){let{betas:r,...a}=e??{};return this._client.getAPIList("/v1/models",th,{query:a,...t,headers:tN([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}}let r_=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;class rg{constructor({baseURL:e=r_("ANTHROPIC_BASE_URL"),apiKey:t=r_("ANTHROPIC_API_KEY")??null,authToken:r=r_("ANTHROPIC_AUTH_TOKEN")??null,...a}={}){eh.add(this),ef.set(this,void 0);let n={apiKey:t,authToken:r,...a,baseURL:e||"https://api.anthropic.com"};if(!n.dangerouslyAllowBrowser&&eX())throw new eT("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");this.baseURL=n.baseURL,this.timeout=n.timeout??em.DEFAULT_TIMEOUT,this.logger=n.logger??console;let o="warn";this.logLevel=o,this.logLevel=e3(n.logLevel,"ClientOptions.logLevel",this)??e3(r_("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=n.fetchOptions,this.maxRetries=n.maxRetries??2,this.fetch=n.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),eb(this,ef,e2,"f"),this._options=n,this.apiKey="string"==typeof t?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization")||this.apiKey&&e.get("x-api-key")||t.has("x-api-key")||this.authToken&&e.get("authorization")||t.has("authorization")))throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return tN([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(null!=this.apiKey)return tN([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(null!=this.authToken)return tN([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new eT(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${eW}`}defaultIdempotencyKey(){return`stainless-node-retry-${ex()}`}makeStatusError(e,t,r,a){return eR.generate(e,t,r,a)}buildURL(e,t,r){let a=!ew(this,eh,"m",ey).call(this)&&r||this.baseURL,n=new URL(ez(e)?e:a+(a.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(o)&&(t={...o,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new eT("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 6e5}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new td(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let a=await e,n=a.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(a);let{req:o,url:i,timeout:s}=await this.buildRequest(a,{retryCount:n-t});await this.prepareRequest(o,{url:i,options:a});let l="log_"+(16777216*Math.random()|0).toString(16).padStart(6,"0"),u=void 0===r?"":`, retryOf: ${r}`,d=Date.now();if(tr(this).debug(`[${l}] sending request`,ta({retryOfRequestLogID:r,method:a.method,url:i,options:a,headers:o.headers})),a.signal?.aborted)throw new eS;let c=new AbortController,p=await this.fetchWithTimeout(i,o,s,c).catch(eI),h=Date.now();if(p instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(a.signal?.aborted)throw new eS;let n=ek(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return tr(this).info(`[${l}] connection ${n?"timed out":"failed"} - ${e}`),tr(this).debug(`[${l}] connection ${n?"timed out":"failed"} (${e})`,ta({retryOfRequestLogID:r,url:i,durationMs:h-d,message:p.message})),this.retryRequest(a,t,r??l);if(tr(this).info(`[${l}] connection ${n?"timed out":"failed"} - error; no more retries left`),tr(this).debug(`[${l}] connection ${n?"timed out":"failed"} (error; no more retries left)`,ta({retryOfRequestLogID:r,url:i,durationMs:h-d,message:p.message})),n)throw new eC;throw new eZ({cause:p})}let m=[...p.headers.entries()].filter(([e])=>"request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join(""),f=`[${l}${u}${m}] ${o.method} ${i} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let e=await this.shouldRetry(p);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await e1(p.body),tr(this).info(`${f} - ${e}`),tr(this).debug(`[${l}] response error (${e})`,ta({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(a,t,r??l,p.headers)}let n=e?"error; no more retries left":"error; not retryable";tr(this).info(`${f} - ${n}`);let o=await p.text().catch(e=>eI(e).message),i=eV(o),s=i?void 0:o;throw tr(this).debug(`[${l}] response error (${n})`,ta({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:s,durationMs:Date.now()-d})),this.makeStatusError(p.status,i,s,p.headers)}return tr(this).info(f),tr(this).debug(`[${l}] response start`,ta({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:a,controller:c,requestLogID:l,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(t=>({method:"get",path:e,...t})):{method:"get",path:e,...r})}requestAPIList(e,t){return new tp(this,this.makeRequest(t,null,void 0),e)}async fetchWithTimeout(e,t,r,a){let{signal:n,method:o,...i}=t||{},s=this._makeAbort(a);n&&n.addEventListener("abort",s,{once:!0});let l=setTimeout(s,r),u=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,d={signal:a.signal,...u?{duplex:"half"}:{},method:"GET",...i};o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,r,a){let n;let o=a?.get("retry-after-ms");if(o){let e=parseFloat(o);Number.isNaN(e)||(n=e)}let i=a?.get("retry-after");if(i&&!n){let e=parseFloat(i);n=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){let r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await eG(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||null!=t&&e>t)throw new eT("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:a,path:n,query:o,defaultBaseURL:i}=r,s=this.buildURL(n,o,i);"timeout"in r&&eL("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:a,bodyHeaders:l,retryCount:t});return{req:{method:a,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:s,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:a}){let n={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),n[this.idempotencyHeader]=e.idempotencyKey);let o=tN([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(a),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...eH(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=tN([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:eQ(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:ew(this,ef,"f").call(this,{body:e,headers:r})}}em=rg,ef=new WeakMap,eh=new WeakSet,ey=function(){return"https://api.anthropic.com"!==this.baseURL},rg.Anthropic=em,rg.HUMAN_PROMPT="\\n\\nHuman:",rg.AI_PROMPT="\\n\\nAssistant:",rg.DEFAULT_TIMEOUT=6e5,rg.AnthropicError=eT,rg.APIError=eR,rg.APIConnectionError=eZ,rg.APIConnectionTimeoutError=eC,rg.APIUserAbortError=eS,rg.NotFoundError=eN,rg.ConflictError=eM,rg.RateLimitError=eP,rg.BadRequestError=eE,rg.AuthenticationError=eO,rg.InternalServerError=ej,rg.PermissionDeniedError=eA,rg.UnprocessableEntityError=e$,rg.toFile=tC;class rv extends rg{constructor(){super(...arguments),this.completions=new ro(this),this.messages=new rh(this),this.models=new ry(this),this.beta=new rn(this)}}rv.Completions=ro,rv.Messages=rh,rv.Models=ry,rv.Beta=rn},1041:(e,t,r)=>{r.d(t,{bS:()=>aa,vk:()=>rG,kP:()=>at});var a,n,o,i,s,l,u,d,c,p,h,m,f,y,_,g,v,b,w,x,k,I,T,R,S,Z,C,E,O,A,N,M=r(6365),$=r(9519),P=r(2943),j=r(9763),F=r(489),z=Symbol.for("vercel.ai.gateway.error"),D=class e extends(n=Error,a=z,n){constructor({message:e,statusCode:t=500,cause:r,generationId:n}){super(n?`${e} [${n}]`:e),this[a]=!0,this.statusCode=t,this.cause=r,this.generationId=n}static isInstance(t){return e.hasMarker(t)}static hasMarker(e){return"object"==typeof e&&null!==e&&z in e&&!0===e[z]}},q="GatewayAuthenticationError",U=Symbol.for(`vercel.ai.gateway.error.${q}`),L=class e extends(i=D,o=U,i){constructor({message:e="Authentication failed",statusCode:t=401,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[o]=!0,this.name=q,this.type="authentication_error"}static isInstance(e){return D.hasMarker(e)&&U in e}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:o,generationId:i}){return new e({message:t?`AI Gateway authentication failed: Invalid API key.
42
42
 
43
43
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
@@ -55,9 +55,9 @@ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
55
55
  Option 2 - OIDC token:
56
56
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,statusCode:n,cause:o,generationId:i})}},V="GatewayInvalidRequestError",G=Symbol.for(`vercel.ai.gateway.error.${V}`),W=class extends(l=D,s=G,l){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[s]=!0,this.name=V,this.type="invalid_request_error"}static isInstance(e){return D.hasMarker(e)&&G in e}},X="GatewayRateLimitError",B=Symbol.for(`vercel.ai.gateway.error.${X}`),K=class extends(d=D,u=B,d){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[u]=!0,this.name=X,this.type="rate_limit_exceeded"}static isInstance(e){return D.hasMarker(e)&&B in e}},J="GatewayModelNotFoundError",H=Symbol.for(`vercel.ai.gateway.error.${J}`),Y=(0,M.DG)(()=>(0,M.r0)(P.Ry({modelId:P.Z_()}))),Q=class extends(p=D,c=H,p){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:a,generationId:n}={}){super({message:e,statusCode:t,cause:a,generationId:n}),this[c]=!0,this.name=J,this.type="model_not_found",this.modelId=r}static isInstance(e){return D.hasMarker(e)&&H in e}},ee="GatewayInternalServerError",et=Symbol.for(`vercel.ai.gateway.error.${ee}`),er=class extends(m=D,h=et,m){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[h]=!0,this.name=ee,this.type="internal_server_error"}static isInstance(e){return D.hasMarker(e)&&et in e}},ea="GatewayResponseError",en=Symbol.for(`vercel.ai.gateway.error.${ea}`),eo=class extends(y=D,f=en,y){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:a,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[f]=!0,this.name=ea,this.type="response_error",this.response=r,this.validationError=a}static isInstance(e){return D.hasMarker(e)&&en in e}};async function ei({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){var o;let i=await (0,M.pW)({value:e,schema:es});if(!i.success){let n="object"==typeof e&&null!==e&&"generationId"in e?e.generationId:void 0;return new eo({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:a,generationId:n})}let s=i.value,l=s.error.type,u=s.error.message,d=null!=(o=s.generationId)?o:void 0;switch(l){case"authentication_error":return L.createContextualError({apiKeyProvided:"api-key"===n,oidcTokenProvided:"oidc"===n,statusCode:t,cause:a,generationId:d});case"invalid_request_error":return new W({message:u,statusCode:t,cause:a,generationId:d});case"rate_limit_exceeded":return new K({message:u,statusCode:t,cause:a,generationId:d});case"model_not_found":{let e=await (0,M.pW)({value:s.error.param,schema:Y});return new Q({message:u,statusCode:t,modelId:e.success?e.value.modelId:void 0,cause:a,generationId:d})}default:return new er({message:u,statusCode:t,cause:a,generationId:d})}}var es=(0,M.DG)(()=>(0,M.r0)(P.Ry({error:P.Ry({message:P.Z_(),type:P.Z_().nullish(),param:P._4().nullish(),code:P.G0([P.Z_(),P.Rx()]).nullish()}),generationId:P.Z_().nullish()}))),el="GatewayTimeoutError",eu=Symbol.for(`vercel.ai.gateway.error.${el}`),ed=class e extends(g=D,_=eu,g){constructor({message:e="Request timed out",statusCode:t=408,cause:r,generationId:a}={}){super({message:e,statusCode:t,cause:r,generationId:a}),this[_]=!0,this.name=el,this.type="timeout_error"}static isInstance(e){return D.hasMarker(e)&&eu in e}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:a,generationId:n}){return new e({message:`Gateway request timed out: ${t}
57
57
 
58
- 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`,statusCode:r,cause:a,generationId:n})}};function ec(e){if(!(e instanceof Error))return!1;let t=e.code;return"string"==typeof t&&["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t)}async function ep(e,t){var r;return D.isInstance(e)?e:ec(e)?ed.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):$.w.isInstance(e)?e.cause&&ec(e.cause)?ed.createTimeoutError({originalMessage:e.message,cause:e}):await ei({response:function(e){if(void 0!==e.data)return e.data;if(null!=e.responseBody)try{return JSON.parse(e.responseBody)}catch(t){return e.responseBody}return{}}(e),statusCode:null!=(r=e.statusCode)?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await ei({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var eh="ai-gateway-auth-method";async function em(e){let t=await (0,M.pW)({value:e[eh],schema:ef});return t.success?t.value:void 0}var ef=(0,M.DG)(()=>(0,M.r0)(P.G0([P.i0("api-key"),P.i0("oidc")]))),ey=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await (0,M.hb)({url:`${this.config.baseURL}/config`,headers:await (0,M.DB)(this.config.headers()),successfulResponseHandler:(0,M.tc)(e_),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),fetch:this.config.fetch});return e}catch(e){throw await ep(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await (0,M.hb)({url:`${e.origin}/v1/credits`,headers:await (0,M.DB)(this.config.headers()),successfulResponseHandler:(0,M.tc)(eg),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(e){throw await ep(e)}}},e_=(0,M.DG)(()=>(0,M.r0)(P.Ry({models:P.IX(P.Ry({id:P.Z_(),name:P.Z_(),description:P.Z_().nullish(),pricing:P.Ry({input:P.Z_(),output:P.Z_(),input_cache_read:P.Z_().nullish(),input_cache_write:P.Z_().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:a})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:P.Ry({specificationVersion:P.i0("v3"),provider:P.Z_(),modelId:P.Z_()}),modelType:P.Km(["embedding","image","language","video"]).nullish()}))}))),eg=(0,M.DG)(()=>(0,M.r0)(P.Ry({balance:P.Z_(),total_used:P.Z_()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),ev=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:a}=e,n=await (0,M.DB)(this.config.headers());try{let{responseHeaders:o,value:i,rawValue:s}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(n,e.headers,this.getModelConfigHeaders(this.modelId,!1),await (0,M.DB)(this.config.o11yHeaders)),body:t,successfulResponseHandler:(0,M.tc)(P.Yj()),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:o,body:s},warnings:r}}catch(e){throw await ep(e,await em(n))}}async doStream(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:a}=e,n=await (0,M.DB)(this.config.headers());try{let{value:o,responseHeaders:i}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(n,e.headers,this.getModelConfigHeaders(this.modelId,!0),await (0,M.DB)(this.config.o11yHeaders)),body:t,successfulResponseHandler:(0,M.cP)(P.Yj()),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(e){r.length>0&&e.enqueue({type:"stream-start",warnings:r})},transform(t,r){if(t.success){let a=t.value;("raw"!==a.type||e.includeRawChunks)&&("response-metadata"===a.type&&a.timestamp&&"string"==typeof a.timestamp&&(a.timestamp=new Date(a.timestamp)),r.enqueue(a))}else r.error(t.error)}})),request:{body:t},response:{headers:i}}}catch(e){throw await ep(e,await em(n))}}isFilePart(e){return e&&"object"==typeof e&&"type"in e&&"file"===e.type}maybeEncodeFileParts(e){for(let t of e.prompt)for(let e of t.content)if(this.isFilePart(e)&&e.data instanceof Uint8Array){let t=Uint8Array.from(e.data),r=Buffer.from(t).toString("base64");e.data=new URL(`data:${e.mediaType||"application/octet-stream"};base64,${r}`)}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},eb=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:a}){var n;let o=await (0,M.DB)(this.config.headers());try{let{responseHeaders:i,value:s,rawValue:l}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(o,null!=t?t:{},this.getModelConfigHeaders(),await (0,M.DB)(this.config.o11yHeaders)),body:{values:e,...a?{providerOptions:a}:{}},successfulResponseHandler:(0,M.tc)(ew),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:null!=(n=s.usage)?n:void 0,providerMetadata:s.providerMetadata,response:{headers:i,body:l},warnings:[]}}catch(e){throw await ep(e,await em(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},ew=(0,M.DG)(()=>(0,M.r0)(P.Ry({embeddings:P.IX(P.IX(P.Rx())),usage:P.Ry({tokens:P.Rx()}).nullish(),providerMetadata:P.IM(P.Z_(),P.IM(P.Z_(),P._4())).optional()}))),ex=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:a,seed:n,files:o,mask:i,providerOptions:s,headers:l,abortSignal:u}){var d,c,p,h;let m=await (0,M.DB)(this.config.headers());try{let{responseHeaders:f,value:y,rawValue:_}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(m,null!=l?l:{},this.getModelConfigHeaders(),await (0,M.DB)(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...a&&{aspectRatio:a},...n&&{seed:n},...s&&{providerOptions:s},...o&&{files:o.map(e=>ek(e))},...i&&{mask:ek(i)}},successfulResponseHandler:(0,M.tc)(eS),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...u&&{abortSignal:u},fetch:this.config.fetch});return{images:y.images,warnings:null!=(d=y.warnings)?d:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f},...null!=y.usage&&{usage:{inputTokens:null!=(c=y.usage.inputTokens)?c:void 0,outputTokens:null!=(p=y.usage.outputTokens)?p:void 0,totalTokens:null!=(h=y.usage.totalTokens)?h:void 0}}}}catch(e){throw await ep(e,await em(m))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function ek(e){return"file"===e.type&&e.data instanceof Uint8Array?{...e,data:(0,M.k0)(e.data)}:e}var eI=P.Ry({images:P.IX(P._4()).optional()}).catchall(P._4()),eT=P.VK("type",[P.Ry({type:P.i0("unsupported"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("compatibility"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("other"),message:P.Z_()})]),eR=P.Ry({inputTokens:P.Rx().nullish(),outputTokens:P.Rx().nullish(),totalTokens:P.Rx().nullish()}),eS=P.Ry({images:P.IX(P.Z_()),warnings:P.IX(eT).optional(),providerMetadata:P.IM(P.Z_(),eI).optional(),usage:eR.optional()}),eZ=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:a,duration:n,fps:o,seed:i,image:s,providerOptions:l,headers:u,abortSignal:d}){var c;let p=await (0,M.DB)(this.config.headers());try{let{responseHeaders:h,value:m}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(p,null!=u?u:{},this.getModelConfigHeaders(),await (0,M.DB)(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...a&&{resolution:a},...n&&{duration:n},...o&&{fps:o},...i&&{seed:i},...l&&{providerOptions:l},...s&&{image:"file"===s.type&&s.data instanceof Uint8Array?{...s,data:(0,M.k0)(s.data)}:s}},successfulResponseHandler:async({response:e,url:t,requestBodyValues:r})=>{if(null==e.body)throw new $.w({message:"SSE response body is empty",url:t,requestBodyValues:r,statusCode:e.status});let a=(0,M.RF)({stream:e.body,schema:eA}).getReader(),{done:n,value:o}=await a.read();if(a.releaseLock(),n||!o)throw new $.w({message:"SSE stream ended without a data event",url:t,requestBodyValues:r,statusCode:e.status});if(!o.success)throw new $.w({message:"Failed to parse video SSE event",cause:o.error,url:t,requestBodyValues:r,statusCode:e.status});let i=o.value;if("error"===i.type)throw new $.w({message:i.message,statusCode:i.statusCode,url:t,requestBodyValues:r,responseHeaders:Object.fromEntries([...e.headers]),responseBody:JSON.stringify(i),data:{error:{message:i.message,type:i.errorType,param:i.param}}});return{value:{videos:i.videos,warnings:i.warnings,providerMetadata:i.providerMetadata},responseHeaders:Object.fromEntries([...e.headers])}},failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...d&&{abortSignal:d},fetch:this.config.fetch});return{videos:m.videos,warnings:null!=(c=m.warnings)?c:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(e){throw await ep(e,await em(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}},eC=P.Ry({videos:P.IX(P._4()).optional()}).catchall(P._4()),eE=P.G0([P.Ry({type:P.i0("url"),url:P.Z_(),mediaType:P.Z_()}),P.Ry({type:P.i0("base64"),data:P.Z_(),mediaType:P.Z_()})]),eO=P.VK("type",[P.Ry({type:P.i0("unsupported"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("compatibility"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("other"),message:P.Z_()})]),eA=P.VK("type",[P.Ry({type:P.i0("result"),videos:P.IX(eE),warnings:P.IX(eO).optional(),providerMetadata:P.IM(P.Z_(),eC).optional()}),P.Ry({type:P.i0("error"),message:P.Z_(),errorType:P.Z_(),statusCode:P.Rx(),param:P._4().nullable()})]),eN=(0,M.DG)(()=>(0,M.r0)(j.Ry({objective:j.Z_().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:j.IX(j.Z_()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:j.Km(["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:j.Rx().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:j.Ry({include_domains:j.IX(j.Z_()).optional().describe("List of domains to include in search results."),exclude_domains:j.IX(j.Z_()).optional().describe("List of domains to exclude from search results."),after_date:j.Z_().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:j.Ry({max_chars_per_result:j.Rx().optional().describe("Maximum characters per result."),max_chars_total:j.Rx().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:j.Ry({max_age_seconds:j.Rx().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.")}))),eM=(0,M.DG)(()=>(0,M.r0)(j.G0([j.Ry({searchId:j.Z_(),results:j.IX(j.Ry({url:j.Z_(),title:j.Z_(),excerpt:j.Z_(),publishDate:j.Z_().nullable().optional(),relevanceScore:j.Rx().optional()}))}),j.Ry({error:j.Km(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:j.Rx().optional(),message:j.Z_()})]))),e$=(0,M.ql)({id:"gateway.parallel_search",inputSchema:eN,outputSchema:eM}),eP=(0,M.DG)(()=>(0,M.r0)(j.Ry({query:j.G0([j.Z_(),j.IX(j.Z_())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:j.Rx().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:j.Rx().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:j.Rx().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:j.Z_().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:j.IX(j.Z_()).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:j.IX(j.Z_()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:j.Z_().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:j.Z_().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:j.Z_().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:j.Z_().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:j.Km(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),ej=(0,M.DG)(()=>(0,M.r0)(j.G0([j.Ry({results:j.IX(j.Ry({title:j.Z_(),url:j.Z_(),snippet:j.Z_(),date:j.Z_().optional(),lastUpdated:j.Z_().optional()})),id:j.Z_()}),j.Ry({error:j.Km(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:j.Rx().optional(),message:j.Z_()})]))),eF=(0,M.ql)({id:"gateway.perplexity_search",inputSchema:eP,outputSchema:ej}),ez={parallelSearch:(e={})=>e$(e),perplexitySearch:(e={})=>eF(e)};async function eD(){var e;return null==(e=(0,F.getContext)().headers)?void 0:e["x-vercel-id"]}var eq=function(e={}){var t,r;let a=null,n=null,o=null!=(t=e.metadataCacheRefreshMillis)?t:3e5,i=0,s=null!=(r=(0,M.QT)(e.baseURL))?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{let t=await eU(e);return(0,M.CR)({Authorization:`Bearer ${t.token}`,"ai-gateway-protocol-version":"0.0.1",[eh]:t.authMethod,...e.headers},"ai-sdk/gateway/3.0.66")}catch(e){throw L.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:e})}},u=()=>{let e=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),t=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),r=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),a=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let n=await eD();return{...e&&{"ai-o11y-deployment-id":e},...t&&{"ai-o11y-environment":t},...r&&{"ai-o11y-region":r},...n&&{"ai-o11y-request-id":n},...a&&{"ai-o11y-project-id":a}}}},d=t=>new ev(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),c=async()=>{var t,r,u;let d=null!=(u=null==(r=null==(t=e._internal)?void 0:t.currentDate)?void 0:r.call(t).getTime())?u:Date.now();return(!a||d-i>o)&&(i=d,a=new ey({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then(e=>(n=e,e)).catch(async e=>{throw await ep(e,await em(await l()))})),n?Promise.resolve(n):a},p=async()=>new ey({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async e=>{throw await ep(e,await em(await l()))}),h=function(e){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return d(e)};h.specificationVersion="v3",h.getAvailableModels=c,h.getCredits=p,h.imageModel=t=>new ex(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),h.languageModel=d;let m=t=>new eb(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()});return h.embeddingModel=m,h.textEmbeddingModel=m,h.videoModel=t=>new eZ(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),h.chat=h.languageModel,h.embedding=h.embeddingModel,h.image=h.imageModel,h.video=h.videoModel,h.tools=ez,h}();async function eU(e){let t=(0,M.P6)({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await (0,F.getVercelOidcToken)(),authMethod:"oidc"}}var eL=r(3998),eV=r(3924),eG=r(8997),eW=Object.defineProperty,eX="AI_InvalidArgumentError",eB=`vercel.ai.error.${eX}`,eK=Symbol.for(eB),eJ=class extends $.AX{constructor({parameter:e,value:t,message:r}){super({name:eX,message:`Invalid argument for parameter ${e}: ${r}`}),this[v]=!0,this.parameter=e,this.value=t}static isInstance(e){return $.AX.hasMarker(e,eB)}};v=eK,Symbol.for("vercel.ai.error.AI_InvalidStreamPartError"),$.AX;var eH="AI_InvalidToolApprovalError",eY=`vercel.ai.error.${eH}`,eQ=Symbol.for(eY),e0=class extends $.AX{constructor({approvalId:e}){super({name:eH,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[b]=!0,this.approvalId=e}static isInstance(e){return $.AX.hasMarker(e,eY)}};b=eQ;var e1="AI_InvalidToolInputError",e2=`vercel.ai.error.${e1}`,e4=Symbol.for(e2),e9=class extends $.AX{constructor({toolInput:e,toolName:t,cause:r,message:a=`Invalid input for tool ${t}: ${(0,$.e$)(r)}`}){super({name:e1,message:a,cause:r}),this[w]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return $.AX.hasMarker(e,e2)}};w=e4;var e5="AI_ToolCallNotFoundForApprovalError",e6=`vercel.ai.error.${e5}`,e3=Symbol.for(e6),e7=class extends $.AX{constructor({toolCallId:e,approvalId:t}){super({name:e5,message:`Tool call "${e}" not found for approval request "${t}".`}),this[x]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return $.AX.hasMarker(e,e6)}};x=e3;var e8="AI_MissingToolResultsError",te=`vercel.ai.error.${e8}`,tt=Symbol.for(te),tr=class extends $.AX{constructor({toolCallIds:e}){super({name:e8,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[k]=!0,this.toolCallIds=e}static isInstance(e){return $.AX.hasMarker(e,te)}};k=tt;var ta=Symbol.for("vercel.ai.error.AI_NoImageGeneratedError");$.AX;var tn="AI_NoObjectGeneratedError",to=`vercel.ai.error.${tn}`,ti=Symbol.for(to),ts=class extends $.AX{constructor({message:e="No object generated.",cause:t,text:r,response:a,usage:n,finishReason:o}){super({name:tn,message:e,cause:t}),this[I]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=o}static isInstance(e){return $.AX.hasMarker(e,to)}};I=ti;var tl="AI_NoOutputGeneratedError",tu=`vercel.ai.error.${tl}`,td=Symbol.for(tu),tc=class extends $.AX{constructor({message:e="No output generated.",cause:t}={}){super({name:tl,message:e,cause:t}),this[T]=!0}static isInstance(e){return $.AX.hasMarker(e,tu)}};T=td;var tp=Symbol.for("vercel.ai.error.AI_NoSpeechGeneratedError");$.AX;var th=Symbol.for("vercel.ai.error.AI_NoTranscriptGeneratedError");$.AX;var tm=Symbol.for("vercel.ai.error.AI_NoVideoGeneratedError");$.AX;var tf="AI_NoSuchToolError",ty=`vercel.ai.error.${tf}`,t_=Symbol.for(ty),tg=class extends $.AX{constructor({toolName:e,availableTools:t,message:r=`Model tried to call unavailable tool '${e}'. ${void 0===t?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:tf,message:r}),this[R]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return $.AX.hasMarker(e,ty)}};R=t_;var tv="AI_ToolCallRepairError",tb=`vercel.ai.error.${tv}`,tw=Symbol.for(tb),tx=class extends $.AX{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${(0,$.e$)(e)}`}){super({name:tv,message:r,cause:e}),this[S]=!0,this.originalError=t}static isInstance(e){return $.AX.hasMarker(e,tb)}};S=tw;var tk=class extends $.AX{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}},tI="AI_UIMessageStreamError",tT=`vercel.ai.error.${tI}`,tR=Symbol.for(tT),tS=class extends $.AX{constructor({chunkType:e,chunkId:t,message:r}){super({name:tI,message:r}),this[Z]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return $.AX.hasMarker(e,tT)}};Z=tR;var tZ="AI_InvalidDataContentError",tC=`vercel.ai.error.${tZ}`,tE=Symbol.for(tC);$.AX,C=tE;var tO="AI_InvalidMessageRoleError",tA=`vercel.ai.error.${tO}`,tN=Symbol.for(tA),tM=class extends $.AX{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:tO,message:t}),this[E]=!0,this.role=e}static isInstance(e){return $.AX.hasMarker(e,tA)}};E=tN;var t$="AI_MessageConversionError",tP=`vercel.ai.error.${t$}`,tj=Symbol.for(tP),tF=class extends $.AX{constructor({originalMessage:e,message:t}){super({name:t$,message:t}),this[O]=!0,this.originalMessage=e}static isInstance(e){return $.AX.hasMarker(e,tP)}};O=tj;var tz="AI_RetryError",tD=`vercel.ai.error.${tz}`,tq=Symbol.for(tD),tU=class extends $.AX{constructor({message:e,reason:t,errors:r}){super({name:tz,message:e}),this[A]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return $.AX.hasMarker(e,tD)}};function tL(e){return void 0===e?[]:Array.isArray(e)?e:[e]}async function tV(e){for(let t of tL(e.callbacks))if(null!=t)try{await t(e.event)}catch(e){}}A=tq;var tG=!1,tW=e=>{if(0===e.warnings.length)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(!1!==t){if("function"==typeof t){t(e);return}for(let t of(tG||(tG=!0,console.info("AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.")),e.warnings))console.warn(function({warning:e,provider:t,model:r}){let a=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let t=`${a} The feature "${e.feature}" is not supported.`;return e.details&&(t+=` ${e.details}`),t}case"compatibility":{let t=`${a} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(t+=` ${e.details}`),t}case"other":return`${a} ${e.message}`;default:return`${a} ${JSON.stringify(e,null,2)}`}}({warning:t,provider:e.provider,model:e.model}))}};function tX({provider:e,modelId:t}){tW({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function tB(e){return{unified:"unknown"===e?"other":e,raw:void 0}}function tK(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function tJ(e){if("string"!=typeof e){var t;if("v3"!==e.specificationVersion&&"v2"!==e.specificationVersion)throw new tk({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return"v3"===(t=e).specificationVersion?t:(tX({provider:t.provider,modelId:t.modelId}),new Proxy(t,{get(e,t){switch(t){case"specificationVersion":return"v3";case"doGenerate":return async(...t)=>{let r=await e.doGenerate(...t);return{...r,finishReason:tB(r.finishReason),usage:tK(r.usage)}};case"doStream":return async(...t)=>{let r=await e.doStream(...t);return{...r,stream:r.stream.pipeThrough(new TransformStream({transform(e,t){"finish"===e.type?t.enqueue({...e,finishReason:tB(e.finishReason),usage:tK(e.usage)}):t.enqueue(e)}}))}};default:return e[t]}}}))}return(function(){var e;return null!=(e=globalThis.AI_SDK_DEFAULT_PROVIDER)?e:eq})().languageModel(e)}function tH(e){return null==e?void 0:"number"==typeof e?e:e.totalMs}var tY=[{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]}],tQ=e=>{let t="string"==typeof e?(0,M.MS)(e):e,r=(127&t[6])<<21|(127&t[7])<<14|(127&t[8])<<7|127&t[9];return t.slice(r+10)},t0="6.0.116",t1=async({url:e,maxBytes:t,abortSignal:r})=>{var a;let n=e.toString();(0,M.SA)(n);try{let e=await fetch(n,{headers:(0,M.CR)({},`ai-sdk/${t0}`,(0,M.gJ)()),signal:r});if(!e.ok)throw new M.Bx({url:n,statusCode:e.status,statusText:e.statusText});return{data:await (0,M.SN)({response:e,url:n,maxBytes:null!=t?t:M.N$}),mediaType:null!=(a=e.headers.get("content-type"))?a:void 0}}catch(e){if(M.Bx.isInstance(e))throw e;throw new M.Bx({url:n,cause:e})}},t2=(e=t1)=>t=>Promise.all(t.map(async t=>t.isUrlSupportedByModel?null:e(t))),t4=P.G0([P.Z_(),P.Pp(Uint8Array),P.Pp(ArrayBuffer),P.PG(e=>{var t,r;return null!=(r=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&r},{message:"Must be a Buffer"})]);function t9(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if("string"==typeof e)try{e=new URL(e)}catch(e){}if(e instanceof URL&&"data:"===e.protocol){let{mediaType:t,base64Content:r}=function(e){try{let[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch(e){return{mediaType:void 0,base64Content:void 0}}}(e.toString());if(null==t||null==r)throw new $.AX({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}async function t5({prompt:e,supportedUrls:t,download:r=t2()}){let a=await t6(e.messages,r,t),n=new Map;for(let t of e.messages)if("assistant"===t.role&&Array.isArray(t.content))for(let e of t.content)"tool-approval-request"===e.type&&"approvalId"in e&&"toolCallId"in e&&n.set(e.approvalId,e.toolCallId);let o=new Set;for(let t of e.messages)if("tool"===t.role){for(let e of t.content)if("tool-approval-response"===e.type){let t=n.get(e.approvalId);t&&o.add(t)}}let i=[...null!=e.system?"string"==typeof e.system?[{role:"system",content:e.system}]:tL(e.system).map(e=>({role:"system",content:e.content,providerOptions:e.providerOptions})):[],...e.messages.map(e=>(function({message:e,downloadedAssets:t}){let r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":if("string"==typeof e.content)return{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};return{role:"user",content:e.content.map(e=>(function(e,t){var r;let a;if("text"===e.type)return{type:"text",text:e.text,providerOptions:e.providerOptions};let n=e.type;switch(n){case"image":a=e.image;break;case"file":a=e.data;break;default:throw Error(`Unsupported part type: ${n}`)}let{data:o,mediaType:i}=t9(a),s=null!=i?i:e.mediaType,l=o;if(l instanceof URL){let e=t[l.toString()];e&&(l=e.data,null!=s||(s=e.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||"string"==typeof l)&&(s=null!=(r=function({data:e,signatures:t}){let r="string"==typeof e&&e.startsWith("SUQz")||"string"!=typeof e&&e.length>10&&73===e[0]&&68===e[1]&&51===e[2]?tQ(e):e,a="string"==typeof r?(0,M.MS)(r.substring(0,Math.min(r.length,24))):r;for(let e of t)if(a.length>=e.bytesPrefix.length&&e.bytesPrefix.every((e,t)=>null===e||a[t]===e))return e.mediaType}({data:l,signatures:tY}))?r:s),{type:"file",mediaType:null!=s?s:"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":if(null==s)throw Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}})(e,t)).filter(e=>"text"!==e.type||""!==e.text),providerOptions:e.providerOptions};case"assistant":if("string"==typeof e.content)return{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};return{role:"assistant",content:e.content.filter(e=>"text"!==e.type||""!==e.text||null!=e.providerOptions).filter(e=>"tool-approval-request"!==e.type).map(e=>{let t=e.providerOptions;switch(e.type){case"file":{let{data:r,mediaType:a}=t9(e.data);return{type:"file",data:r,filename:e.filename,mediaType:null!=a?a:e.mediaType,providerOptions:t}}case"reasoning":return{type:"reasoning",text:e.text,providerOptions:t};case"text":return{type:"text",text:e.text,providerOptions:t};case"tool-call":return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:t};case"tool-result":return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:t3(e.output),providerOptions:t}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(e=>"tool-approval-response"!==e.type||e.providerExecuted).map(e=>{switch(e.type){case"tool-result":return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:t3(e.output),providerOptions:e.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:e.approvalId,approved:e.approved,reason:e.reason}}}),providerOptions:e.providerOptions};default:throw new tM({role:r})}})({message:e,downloadedAssets:a}))],s=[];for(let e of i){if("tool"!==e.role){s.push(e);continue}let t=s.at(-1);(null==t?void 0:t.role)==="tool"?t.content.push(...e.content):s.push(e)}let l=new Set;for(let e of s)switch(e.role){case"assistant":for(let t of e.content)"tool-call"!==t.type||t.providerExecuted||l.add(t.toolCallId);break;case"tool":for(let t of e.content)"tool-result"===t.type&&l.delete(t.toolCallId);break;case"user":case"system":for(let e of o)l.delete(e);if(l.size>0)throw new tr({toolCallIds:Array.from(l)})}for(let e of o)l.delete(e);if(l.size>0)throw new tr({toolCallIds:Array.from(l)});return s.filter(e=>"tool"!==e.role||e.content.length>0)}async function t6(e,t,r){let a=e.filter(e=>"user"===e.role).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>"image"===e.type||"file"===e.type).map(e=>{var t;let r=null!=(t=e.mediaType)?t:"image"===e.type?"image/*":void 0,a="image"===e.type?e.image:e.data;if("string"==typeof a)try{a=new URL(a)}catch(e){}return{mediaType:r,data:a}}).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:null!=e.mediaType&&(0,M.MT)({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:r})}));return Object.fromEntries((await t(a)).map((e,t)=>null==e?null:[a[t].url.toString(),{data:e.data,mediaType:e.mediaType}]).filter(e=>null!=e))}function t3(e){return"content"!==e.type?e:{type:"content",value:e.value.map(e=>"media"!==e.type?e:e.mediaType.startsWith("image/")?{type:"image-data",data:e.data,mediaType:e.mediaType}:{type:"file-data",data:e.data,mediaType:e.mediaType})}}async function t7({toolCallId:e,input:t,output:r,tool:a,errorMode:n}){return"text"===n?{type:"error-text",value:(0,$.e$)(r)}:"json"===n?{type:"error-json",value:t8(r)}:(null==a?void 0:a.toModelOutput)?await a.toModelOutput({toolCallId:e,input:t,output:r}):"string"==typeof r?{type:"text",value:r}:{type:"json",value:t8(r)}}function t8(e){return void 0===e?null:e}async function re({tools:e,toolChoice:t,activeTools:r}){if(!(null!=e&&Object.keys(e).length>0))return{tools:void 0,toolChoice:void 0};let a=null!=r?Object.entries(e).filter(([e])=>r.includes(e)):Object.entries(e),n=[];for(let[e,t]of a){let r=t.type;switch(r){case void 0:case"dynamic":case"function":n.push({type:"function",name:e,description:t.description,inputSchema:await (0,M.C3)(t.inputSchema).jsonSchema,...null!=t.inputExamples?{inputExamples:t.inputExamples}:{},providerOptions:t.providerOptions,...null!=t.strict?{strict:t.strict}:{}});break;case"provider":n.push({type:"provider",name:e,id:t.id,args:t.args});break;default:throw Error(`Unsupported tool type: ${r}`)}}return{tools:n,toolChoice:null==t?{type:"auto"}:"string"==typeof t?{type:t}:{type:"tool",toolName:t.toolName}}}var rt=P.Vo(()=>P.G0([P.lB(),P.Z_(),P.Rx(),P.O7(),P.IM(P.Z_(),rt.optional()),P.IX(rt)])),rr=P.IM(P.Z_(),P.IM(P.Z_(),rt.optional())),ra=P.Ry({type:P.i0("text"),text:P.Z_(),providerOptions:rr.optional()}),rn=P.Ry({type:P.i0("image"),image:P.G0([t4,P.Pp(URL)]),mediaType:P.Z_().optional(),providerOptions:rr.optional()}),ro=P.Ry({type:P.i0("file"),data:P.G0([t4,P.Pp(URL)]),filename:P.Z_().optional(),mediaType:P.Z_(),providerOptions:rr.optional()}),ri=P.Ry({type:P.i0("reasoning"),text:P.Z_(),providerOptions:rr.optional()}),rs=P.Ry({type:P.i0("tool-call"),toolCallId:P.Z_(),toolName:P.Z_(),input:P._4(),providerOptions:rr.optional(),providerExecuted:P.O7().optional()}),rl=P.VK("type",[P.Ry({type:P.i0("text"),value:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("json"),value:rt,providerOptions:rr.optional()}),P.Ry({type:P.i0("execution-denied"),reason:P.Z_().optional(),providerOptions:rr.optional()}),P.Ry({type:P.i0("error-text"),value:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("error-json"),value:rt,providerOptions:rr.optional()}),P.Ry({type:P.i0("content"),value:P.IX(P.G0([P.Ry({type:P.i0("text"),text:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("media"),data:P.Z_(),mediaType:P.Z_()}),P.Ry({type:P.i0("file-data"),data:P.Z_(),mediaType:P.Z_(),filename:P.Z_().optional(),providerOptions:rr.optional()}),P.Ry({type:P.i0("file-url"),url:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("file-id"),fileId:P.G0([P.Z_(),P.IM(P.Z_(),P.Z_())]),providerOptions:rr.optional()}),P.Ry({type:P.i0("image-data"),data:P.Z_(),mediaType:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("image-url"),url:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("image-file-id"),fileId:P.G0([P.Z_(),P.IM(P.Z_(),P.Z_())]),providerOptions:rr.optional()}),P.Ry({type:P.i0("custom"),providerOptions:rr.optional()})]))})]),ru=P.Ry({type:P.i0("tool-result"),toolCallId:P.Z_(),toolName:P.Z_(),output:rl,providerOptions:rr.optional()}),rd=P.Ry({type:P.i0("tool-approval-request"),approvalId:P.Z_(),toolCallId:P.Z_()}),rc=P.Ry({type:P.i0("tool-approval-response"),approvalId:P.Z_(),approved:P.O7(),reason:P.Z_().optional()}),rp=P.Ry({role:P.i0("system"),content:P.Z_(),providerOptions:rr.optional()}),rh=P.Ry({role:P.i0("user"),content:P.G0([P.Z_(),P.IX(P.G0([ra,rn,ro]))]),providerOptions:rr.optional()}),rm=P.Ry({role:P.i0("assistant"),content:P.G0([P.Z_(),P.IX(P.G0([ra,ro,ri,rs,ru,rd]))]),providerOptions:rr.optional()}),rf=P.Ry({role:P.i0("tool"),content:P.IX(P.G0([ru,rc])),providerOptions:rr.optional()}),ry=P.G0([rp,rh,rm,rf]);async function r_(e){let t;if(null==e.prompt&&null==e.messages)throw new $.Mt({prompt:e,message:"prompt or messages must be defined"});if(null!=e.prompt&&null!=e.messages)throw new $.Mt({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(null!=e.system&&"string"!=typeof e.system&&!tL(e.system).every(e=>"object"==typeof e&&null!==e&&"role"in e&&"system"===e.role))throw new $.Mt({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(null!=e.prompt&&"string"==typeof e.prompt)t=[{role:"user",content:e.prompt}];else if(null!=e.prompt&&Array.isArray(e.prompt))t=e.prompt;else if(null!=e.messages)t=e.messages;else throw new $.Mt({prompt:e,message:"prompt or messages must be defined"});if(0===t.length)throw new $.Mt({prompt:e,message:"messages must not be empty"});let r=await (0,M.pW)({value:t,schema:P.IX(ry)});if(!r.success)throw new $.Mt({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function rg({operationId:e,telemetry:t}){return{"operation.name":`${e}${(null==t?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":null==t?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":null==t?void 0:t.functionId}}var rv={startSpan:()=>rb,startActiveSpan:(e,t,r,a)=>"function"==typeof t?t(rb):"function"==typeof r?r(rb):"function"==typeof a?a(rb):void 0},rb={spanContext:()=>rw,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:()=>!1,recordException(){return this}},rw={traceId:"",spanId:"",traceFlags:0};async function rx({name:e,tracer:t,attributes:r,fn:a,endWhenDone:n=!0}){return t.startActiveSpan(e,{attributes:await r},async e=>{let t=eV.D.active();try{let r=await eV.D.with(t,()=>a(e));return n&&e.end(),r}catch(t){try{rk(e,t)}finally{e.end()}throw t}})}function rk(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:eG.Q.ERROR,message:t.message})):e.setStatus({code:eG.Q.ERROR})}async function rI({telemetry:e,attributes:t}){if((null==e?void 0:e.isEnabled)!==!0)return{};let r={};for(let[a,n]of Object.entries(t))if(null!=n){if("object"==typeof n&&"input"in n&&"function"==typeof n.input){if((null==e?void 0:e.recordInputs)===!1)continue;let t=await n.input();null!=t&&(r[a]=t);continue}if("object"==typeof n&&"output"in n&&"function"==typeof n.output){if((null==e?void 0:e.recordOutputs)===!1)continue;let t=await n.output();null!=t&&(r[a]=t);continue}r[a]=n}return r}function rT(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function rR(e,t){return null==e&&null==t?void 0:(null!=e?e:0)+(null!=t?t:0)}function rS(e,t){if(void 0===e&&void 0===t)return;if(void 0===e)return t;if(void 0===t)return e;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let n=t[a];if(void 0===n)continue;let o=a in e?e[a]:void 0,i=null!==n&&"object"==typeof n&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),s=null!=o&&"object"==typeof o&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&s?r[a]=rS(o,n):r[a]=n}return r}var rZ=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>rC(n,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:a});async function rC(e,{maxRetries:t,delayInMs:r,backoffFactor:a,abortSignal:n},o=[]){try{return await e()}catch(u){if((0,M.D_)(u)||0===t)throw u;let i=(0,M.e$)(u),s=[...o,u],l=s.length;if(l>t)throw new tU({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:s});if(u instanceof Error&&$.w.isInstance(u)&&!0===u.isRetryable&&l<=t)return await (0,M.gw)(function({error:e,exponentialBackoffDelay:t}){let r;let a=e.responseHeaders;if(!a)return t;let n=a["retry-after-ms"];if(n){let e=parseFloat(n);Number.isNaN(e)||(r=e)}let o=a["retry-after"];if(o&&void 0===r){let e=parseFloat(o);r=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}return null!=r&&!Number.isNaN(r)&&0<=r&&(r<6e4||r<t)?r:t}({error:u,exponentialBackoffDelay:r}),{abortSignal:n}),rC(e,{maxRetries:t,delayInMs:a*r,backoffFactor:a,abortSignal:n},s);if(1===l)throw u;throw new tU({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:s})}}function rE(){var e,t;return null!=(t=null==(e=null==globalThis?void 0:globalThis.performance)?void 0:e.now())?t:Date.now()}async function rO({toolCall:e,tools:t,tracer:r,telemetry:a,messages:n,abortSignal:o,experimental_context:i,stepNumber:s,model:l,onPreliminaryToolResult:u,onToolCallStart:d,onToolCallFinish:c}){let{toolName:p,toolCallId:h,input:m}=e,f=null==t?void 0:t[p];if((null==f?void 0:f.execute)==null)return;let y={stepNumber:s,model:l,toolCall:e,messages:n,abortSignal:o,functionId:null==a?void 0:a.functionId,metadata:null==a?void 0:a.metadata,experimental_context:i};return rx({name:"ai.toolCall",attributes:rI({telemetry:a,attributes:{...rg({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(m)}}}),tracer:r,fn:async t=>{let r;await tV({event:y,callbacks:d});let s=rE();try{for await(let t of(0,M.aN)({execute:f.execute.bind(f),input:m,options:{toolCallId:h,messages:n,abortSignal:o,experimental_context:i}}))"preliminary"===t.type?null==u||u({...e,type:"tool-result",output:t.output,preliminary:!0}):r=t.output}catch(a){let r=rE()-s;return await tV({event:{...y,success:!1,error:a,durationMs:r},callbacks:c}),rk(t,a),{type:"tool-error",toolCallId:h,toolName:p,input:m,error:a,dynamic:"dynamic"===f.type,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}}let l=rE()-s;await tV({event:{...y,success:!0,output:r,durationMs:l},callbacks:c});try{t.setAttributes(await rI({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(r)}}}))}catch(e){}return{type:"tool-result",toolCallId:h,toolName:p,input:m,output:r,dynamic:"dynamic"===f.type,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}}})}var rA=class{constructor({data:e,mediaType:t}){let r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return null==this.base64Data&&(this.base64Data=(0,M.k0)(this.uint8ArrayData)),this.base64Data}get uint8Array(){return null==this.uint8ArrayData&&(this.uint8ArrayData=(0,M.MS)(this.base64Data)),this.uint8ArrayData}},rN=class extends rA{constructor(e){super(e),this.type="file"}};async function rM({tool:e,toolCall:t,messages:r,experimental_context:a}){return null!=e.needsApproval&&("boolean"==typeof e.needsApproval?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:a}))}async function r$(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await (0,M.NX)({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await (0,M.NX)({text:function(e){let t=["ROOT"],r=-1,a=null;function n(e,n,o){switch(e){case'"':r=n,t.pop(),t.push(o),t.push("INSIDE_STRING");break;case"f":case"t":case"n":r=n,a=n,t.pop(),t.push(o),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(o),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":r=n,t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"{":r=n,t.pop(),t.push(o),t.push("INSIDE_OBJECT_START");break;case"[":r=n,t.pop(),t.push(o),t.push("INSIDE_ARRAY_START")}}function o(e,a){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":r=a,t.pop()}}function i(e,a){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":r=a,t.pop()}}for(let s=0;s<e.length;s++){let l=e[s];switch(t[t.length-1]){case"ROOT":n(l,s,"FINISH");break;case"INSIDE_OBJECT_START":switch(l){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":r=s,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":'"'===l&&(t.pop(),t.push("INSIDE_OBJECT_KEY"));break;case"INSIDE_OBJECT_KEY":'"'===l&&(t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY"));break;case"INSIDE_OBJECT_AFTER_KEY":":"===l&&(t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE"));break;case"INSIDE_OBJECT_BEFORE_VALUE":n(l,s,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(l,s);break;case"INSIDE_STRING":switch(l){case'"':t.pop(),r=s;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:r=s}break;case"INSIDE_ARRAY_START":"]"===l?(r=s,t.pop()):(r=s,n(l,s,"INSIDE_ARRAY_AFTER_VALUE"));break;case"INSIDE_ARRAY_AFTER_VALUE":switch(l){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":r=s,t.pop();break;default:r=s}break;case"INSIDE_ARRAY_AFTER_COMMA":n(l,s,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),r=s;break;case"INSIDE_NUMBER":switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":r=s;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&i(l,s),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(l,s);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(l,s);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&i(l,s);break;default:t.pop()}break;case"INSIDE_LITERAL":{let n=e.substring(a,s+1);"false".startsWith(n)||"true".startsWith(n)||"null".startsWith(n)?r=s:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(l,s):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&i(l,s))}}}let s=e.slice(0,r+1);for(let r=t.length-1;r>=0;r--)switch(t[r]){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":{let t=e.substring(a,e.length);"true".startsWith(t)?s+="true".slice(t.length):"false".startsWith(t)?s+="false".slice(t.length):"null".startsWith(t)&&(s+="null".slice(t.length))}}return s}(e)})).success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"}}((e,t)=>{for(var r in t)eW(e,r,{get:t[r],enumerable:!0})})({},{array:()=>rF,choice:()=>rz,json:()=>rD,object:()=>rj,text:()=>rP});var rP=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),parseCompleteOutput:async({text:e})=>e,parsePartialOutput:async({text:e})=>({partial:e}),createElementStreamTransform(){}}),rj=({schema:e,name:t,description:r})=>{let a=(0,M.C3)(e);return{name:"object",responseFormat:(0,M.DB)(a.jsonSchema).then(e=>({type:"json",schema:e,...null!=t&&{name:t},...null!=r&&{description:r}})),async parseCompleteOutput({text:e},t){let r=await (0,M.NX)({text:e});if(!r.success)throw new ts({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let n=await (0,M.pW)({value:r.value,schema:a});if(!n.success)throw new ts({message:"No object generated: response did not match schema.",cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await r$(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value}}},createElementStreamTransform(){}}},rF=({element:e,name:t,description:r})=>{let a=(0,M.C3)(e);return{name:"array",responseFormat:(0,M.DB)(a.jsonSchema).then(e=>{let{$schema:a,...n}=e;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:n}},required:["elements"],additionalProperties:!1},...null!=t&&{name:t},...null!=r&&{description:r}}}),async parseCompleteOutput({text:e},t){let r=await (0,M.NX)({text:e});if(!r.success)throw new ts({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let n=r.value;if(null==n||"object"!=typeof n||!("elements"in n)||!Array.isArray(n.elements))throw new ts({message:"No object generated: response did not match schema.",cause:new $.Gz({value:n,cause:"response must be an object with an elements array"}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});for(let r of n.elements){let n=await (0,M.pW)({value:r,schema:a});if(!n.success)throw new ts({message:"No object generated: response did not match schema.",cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason})}return n.elements},async parsePartialOutput({text:e}){let t=await r$(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let e=t.value;if(null==e||"object"!=typeof e||!("elements"in e)||!Array.isArray(e.elements))return;let r="repaired-parse"===t.state&&e.elements.length>0?e.elements.slice(0,-1):e.elements,n=[];for(let e of r){let t=await (0,M.pW)({value:e,schema:a});t.success&&n.push(t.value)}return{partial:n}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},r){if(null!=t)for(;e<t.length;e++)r.enqueue(t[e])}})}}},rz=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...null!=t&&{name:t},...null!=r&&{description:r}}),async parseCompleteOutput({text:t},r){let a=await (0,M.NX)({text:t});if(!a.success)throw new ts({message:"No object generated: could not parse the response.",cause:a.error,text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});let n=a.value;if(null==n||"object"!=typeof n||!("result"in n)||"string"!=typeof n.result||!e.includes(n.result))throw new ts({message:"No object generated: response did not match schema.",cause:new $.Gz({value:n,cause:"response must be an object that contains a choice value."}),text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});return n.result},async parsePartialOutput({text:t}){let r=await r$(t);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let t=r.value;if(null==t||"object"!=typeof t||!("result"in t)||"string"!=typeof t.result)return;let a=e.filter(e=>e.startsWith(t.result));if("successful-parse"===r.state)return a.includes(t.result)?{partial:t.result}:void 0;return 1===a.length?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),rD=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...null!=e&&{name:e},...null!=t&&{description:t}}),async parseCompleteOutput({text:e},t){let r=await (0,M.NX)({text:e});if(!r.success)throw new ts({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return r.value},async parsePartialOutput({text:e}){let t=await r$(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return void 0===t.value?void 0:{partial:t.value}}},createElementStreamTransform(){}});async function rq({toolCall:e,tools:t,repairToolCall:r,system:a,messages:n}){var o;try{if(null==t){if(e.providerExecuted&&e.dynamic)return await rU(e);throw new tg({toolName:e.toolName})}try{return await rL({toolCall:e,tools:t})}catch(i){if(null==r||!(tg.isInstance(i)||e9.isInstance(i)))throw i;let o=null;try{o=await r({toolCall:e,tools:t,inputSchema:async({toolName:e})=>{let{inputSchema:r}=t[e];return await (0,M.C3)(r).jsonSchema},system:a,messages:n,error:i})}catch(e){throw new tx({cause:e,originalError:i})}if(null==o)throw i;return await rL({toolCall:o,tools:t})}}catch(n){let r=await (0,M.NX)({text:e.input}),a=r.success?r.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a,dynamic:!0,invalid:!0,error:n,title:null==(o=null==t?void 0:t[e.toolName])?void 0:o.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function rU(e){let t=""===e.input.trim()?{success:!0,value:{}}:await (0,M.NX)({text:e.input});if(!1===t.success)throw new e9({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function rL({toolCall:e,tools:t}){let r=e.toolName,a=t[r];if(null==a){if(e.providerExecuted&&e.dynamic)return await rU(e);throw new tg({toolName:e.toolName,availableTools:Object.keys(t)})}let n=(0,M.C3)(a.inputSchema),o=""===e.input.trim()?await (0,M.pW)({value:{},schema:n}):await (0,M.NX)({text:e.input,schema:n});if(!1===o.success)throw new e9({toolName:r,toolInput:e.input,cause:o.error});return"dynamic"===a.type?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:a.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:a.title}}var rV=class{constructor({stepNumber:e,model:t,functionId:r,metadata:a,experimental_context:n,content:o,finishReason:i,rawFinishReason:s,usage:l,warnings:u,request:d,response:c,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=a,this.experimental_context=n,this.content=o,this.finishReason=i,this.rawFinishReason=s,this.usage=l,this.warnings=u,this.request=d,this.response=c,this.providerMetadata=p}get text(){return this.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>"reasoning"===e.type)}get reasoningText(){return 0===this.reasoning.length?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>"file"===e.type).map(e=>e.file)}get sources(){return this.content.filter(e=>"source"===e.type)}get toolCalls(){return this.content.filter(e=>"tool-call"===e.type)}get staticToolCalls(){return this.toolCalls.filter(e=>!0!==e.dynamic)}get dynamicToolCalls(){return this.toolCalls.filter(e=>!0===e.dynamic)}get toolResults(){return this.content.filter(e=>"tool-result"===e.type)}get staticToolResults(){return this.toolResults.filter(e=>!0!==e.dynamic)}get dynamicToolResults(){return this.toolResults.filter(e=>!0===e.dynamic)}};function rG(e){return({steps:t})=>t.length===e}async function rW({stopConditions:e,steps:t}){return(await Promise.all(e.map(e=>e({steps:t})))).some(e=>e)}async function rX({content:e,tools:t}){let r=[],a=[];for(let r of e)if("source"!==r.type&&("tool-result"!==r.type&&"tool-error"!==r.type||r.providerExecuted)&&("text"!==r.type||0!==r.text.length))switch(r.type){case"text":a.push({type:"text",text:r.text,providerOptions:r.providerMetadata});break;case"reasoning":a.push({type:"reasoning",text:r.text,providerOptions:r.providerMetadata});break;case"file":a.push({type:"file",data:r.file.base64,mediaType:r.file.mediaType,providerOptions:r.providerMetadata});break;case"tool-call":a.push({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:r.providerMetadata});break;case"tool-result":{let e=await t7({toolCallId:r.toolCallId,input:r.input,tool:null==t?void 0:t[r.toolName],output:r.output,errorMode:"none"});a.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:e,providerOptions:r.providerMetadata});break}case"tool-error":{let e=await t7({toolCallId:r.toolCallId,input:r.input,tool:null==t?void 0:t[r.toolName],output:r.error,errorMode:"json"});a.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:e,providerOptions:r.providerMetadata});break}case"tool-approval-request":a.push({type:"tool-approval-request",approvalId:r.approvalId,toolCallId:r.toolCall.toolCallId})}a.length>0&&r.push({role:"assistant",content:a});let n=[];for(let r of e){if(!("tool-result"===r.type||"tool-error"===r.type)||r.providerExecuted)continue;let e=await t7({toolCallId:r.toolCallId,input:r.input,tool:null==t?void 0:t[r.toolName],output:"tool-result"===r.type?r.output:r.error,errorMode:"tool-error"===r.type?"text":"none"});n.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:e,...null!=r.providerMetadata?{providerOptions:r.providerMetadata}:{}})}return n.length>0&&r.push({role:"tool",content:n}),r}(0,M.bF)({prefix:"aitxt",size:24});function rB(e,t){let r=new Headers(null!=e?e:{});for(let[e,a]of Object.entries(t))r.has(e)||r.set(e,a);return r}function rK({response:e,status:t,statusText:r,headers:a,stream:n}){let o=null!=t?t:200;void 0!==r?e.writeHead(o,r,a):e.writeHead(o,a);let i=n.getReader();(async()=>{try{for(;;){let{done:t,value:r}=await i.read();if(t)break;e.write(r)||await new Promise(t=>{e.once("drain",t)})}}catch(e){throw e}finally{e.end()}})()}var rJ=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
58
+ 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`,statusCode:r,cause:a,generationId:n})}};function ec(e){if(!(e instanceof Error))return!1;let t=e.code;return"string"==typeof t&&["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t)}async function ep(e,t){var r;return D.isInstance(e)?e:ec(e)?ed.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):$.w.isInstance(e)?e.cause&&ec(e.cause)?ed.createTimeoutError({originalMessage:e.message,cause:e}):await ei({response:function(e){if(void 0!==e.data)return e.data;if(null!=e.responseBody)try{return JSON.parse(e.responseBody)}catch(t){return e.responseBody}return{}}(e),statusCode:null!=(r=e.statusCode)?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await ei({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var eh="ai-gateway-auth-method";async function em(e){let t=await (0,M.pW)({value:e[eh],schema:ef});return t.success?t.value:void 0}var ef=(0,M.DG)(()=>(0,M.r0)(P.G0([P.i0("api-key"),P.i0("oidc")]))),ey=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await (0,M.hb)({url:`${this.config.baseURL}/config`,headers:await (0,M.DB)(this.config.headers()),successfulResponseHandler:(0,M.tc)(e_),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),fetch:this.config.fetch});return e}catch(e){throw await ep(e)}}async getCredits(){try{let e=new URL(this.config.baseURL),{value:t}=await (0,M.hb)({url:`${e.origin}/v1/credits`,headers:await (0,M.DB)(this.config.headers()),successfulResponseHandler:(0,M.tc)(eg),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(e){throw await ep(e)}}},e_=(0,M.DG)(()=>(0,M.r0)(P.Ry({models:P.IX(P.Ry({id:P.Z_(),name:P.Z_(),description:P.Z_().nullish(),pricing:P.Ry({input:P.Z_(),output:P.Z_(),input_cache_read:P.Z_().nullish(),input_cache_write:P.Z_().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:a})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:P.Ry({specificationVersion:P.i0("v3"),provider:P.Z_(),modelId:P.Z_()}),modelType:P.Km(["embedding","image","language","video"]).nullish()}))}))),eg=(0,M.DG)(()=>(0,M.r0)(P.Ry({balance:P.Z_(),total_used:P.Z_()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),ev=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:a}=e,n=await (0,M.DB)(this.config.headers());try{let{responseHeaders:o,value:i,rawValue:s}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(n,e.headers,this.getModelConfigHeaders(this.modelId,!1),await (0,M.DB)(this.config.o11yHeaders)),body:t,successfulResponseHandler:(0,M.tc)(P.Yj()),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:o,body:s},warnings:r}}catch(e){throw await ep(e,await em(n))}}async doStream(e){let{args:t,warnings:r}=await this.getArgs(e),{abortSignal:a}=e,n=await (0,M.DB)(this.config.headers());try{let{value:o,responseHeaders:i}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(n,e.headers,this.getModelConfigHeaders(this.modelId,!0),await (0,M.DB)(this.config.o11yHeaders)),body:t,successfulResponseHandler:(0,M.cP)(P.Yj()),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...a&&{abortSignal:a},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(e){r.length>0&&e.enqueue({type:"stream-start",warnings:r})},transform(t,r){if(t.success){let a=t.value;("raw"!==a.type||e.includeRawChunks)&&("response-metadata"===a.type&&a.timestamp&&"string"==typeof a.timestamp&&(a.timestamp=new Date(a.timestamp)),r.enqueue(a))}else r.error(t.error)}})),request:{body:t},response:{headers:i}}}catch(e){throw await ep(e,await em(n))}}isFilePart(e){return e&&"object"==typeof e&&"type"in e&&"file"===e.type}maybeEncodeFileParts(e){for(let t of e.prompt)for(let e of t.content)if(this.isFilePart(e)&&e.data instanceof Uint8Array){let t=Uint8Array.from(e.data),r=Buffer.from(t).toString("base64");e.data=new URL(`data:${e.mediaType||"application/octet-stream"};base64,${r}`)}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},eb=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:a}){var n;let o=await (0,M.DB)(this.config.headers());try{let{responseHeaders:i,value:s,rawValue:l}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(o,null!=t?t:{},this.getModelConfigHeaders(),await (0,M.DB)(this.config.o11yHeaders)),body:{values:e,...a?{providerOptions:a}:{}},successfulResponseHandler:(0,M.tc)(ew),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:null!=(n=s.usage)?n:void 0,providerMetadata:s.providerMetadata,response:{headers:i,body:l},warnings:[]}}catch(e){throw await ep(e,await em(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},ew=(0,M.DG)(()=>(0,M.r0)(P.Ry({embeddings:P.IX(P.IX(P.Rx())),usage:P.Ry({tokens:P.Rx()}).nullish(),providerMetadata:P.IM(P.Z_(),P.IM(P.Z_(),P._4())).optional()}))),ex=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:a,seed:n,files:o,mask:i,providerOptions:s,headers:l,abortSignal:u}){var d,c,p,h;let m=await (0,M.DB)(this.config.headers());try{let{responseHeaders:f,value:y,rawValue:_}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(m,null!=l?l:{},this.getModelConfigHeaders(),await (0,M.DB)(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...a&&{aspectRatio:a},...n&&{seed:n},...s&&{providerOptions:s},...o&&{files:o.map(e=>ek(e))},...i&&{mask:ek(i)}},successfulResponseHandler:(0,M.tc)(eS),failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...u&&{abortSignal:u},fetch:this.config.fetch});return{images:y.images,warnings:null!=(d=y.warnings)?d:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f},...null!=y.usage&&{usage:{inputTokens:null!=(c=y.usage.inputTokens)?c:void 0,outputTokens:null!=(p=y.usage.outputTokens)?p:void 0,totalTokens:null!=(h=y.usage.totalTokens)?h:void 0}}}}catch(e){throw await ep(e,await em(m))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function ek(e){return"file"===e.type&&e.data instanceof Uint8Array?{...e,data:(0,M.k0)(e.data)}:e}var eI=P.Ry({images:P.IX(P._4()).optional()}).catchall(P._4()),eT=P.VK("type",[P.Ry({type:P.i0("unsupported"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("compatibility"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("other"),message:P.Z_()})]),eR=P.Ry({inputTokens:P.Rx().nullish(),outputTokens:P.Rx().nullish(),totalTokens:P.Rx().nullish()}),eS=P.Ry({images:P.IX(P.Z_()),warnings:P.IX(eT).optional(),providerMetadata:P.IM(P.Z_(),eI).optional(),usage:eR.optional()}),eZ=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:a,duration:n,fps:o,seed:i,image:s,providerOptions:l,headers:u,abortSignal:d}){var c;let p=await (0,M.DB)(this.config.headers());try{let{responseHeaders:h,value:m}=await (0,M.A8)({url:this.getUrl(),headers:(0,M.NF)(p,null!=u?u:{},this.getModelConfigHeaders(),await (0,M.DB)(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...a&&{resolution:a},...n&&{duration:n},...o&&{fps:o},...i&&{seed:i},...l&&{providerOptions:l},...s&&{image:"file"===s.type&&s.data instanceof Uint8Array?{...s,data:(0,M.k0)(s.data)}:s}},successfulResponseHandler:async({response:e,url:t,requestBodyValues:r})=>{if(null==e.body)throw new $.w({message:"SSE response body is empty",url:t,requestBodyValues:r,statusCode:e.status});let a=(0,M.RF)({stream:e.body,schema:eA}).getReader(),{done:n,value:o}=await a.read();if(a.releaseLock(),n||!o)throw new $.w({message:"SSE stream ended without a data event",url:t,requestBodyValues:r,statusCode:e.status});if(!o.success)throw new $.w({message:"Failed to parse video SSE event",cause:o.error,url:t,requestBodyValues:r,statusCode:e.status});let i=o.value;if("error"===i.type)throw new $.w({message:i.message,statusCode:i.statusCode,url:t,requestBodyValues:r,responseHeaders:Object.fromEntries([...e.headers]),responseBody:JSON.stringify(i),data:{error:{message:i.message,type:i.errorType,param:i.param}}});return{value:{videos:i.videos,warnings:i.warnings,providerMetadata:i.providerMetadata},responseHeaders:Object.fromEntries([...e.headers])}},failedResponseHandler:(0,M.Sq)({errorSchema:P.Yj(),errorToMessage:e=>e}),...d&&{abortSignal:d},fetch:this.config.fetch});return{videos:m.videos,warnings:null!=(c=m.warnings)?c:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(e){throw await ep(e,await em(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}},eC=P.Ry({videos:P.IX(P._4()).optional()}).catchall(P._4()),eE=P.G0([P.Ry({type:P.i0("url"),url:P.Z_(),mediaType:P.Z_()}),P.Ry({type:P.i0("base64"),data:P.Z_(),mediaType:P.Z_()})]),eO=P.VK("type",[P.Ry({type:P.i0("unsupported"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("compatibility"),feature:P.Z_(),details:P.Z_().optional()}),P.Ry({type:P.i0("other"),message:P.Z_()})]),eA=P.VK("type",[P.Ry({type:P.i0("result"),videos:P.IX(eE),warnings:P.IX(eO).optional(),providerMetadata:P.IM(P.Z_(),eC).optional()}),P.Ry({type:P.i0("error"),message:P.Z_(),errorType:P.Z_(),statusCode:P.Rx(),param:P._4().nullable()})]),eN=(0,M.DG)(()=>(0,M.r0)(j.Ry({objective:j.Z_().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:j.IX(j.Z_()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:j.Km(["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:j.Rx().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:j.Ry({include_domains:j.IX(j.Z_()).optional().describe("List of domains to include in search results."),exclude_domains:j.IX(j.Z_()).optional().describe("List of domains to exclude from search results."),after_date:j.Z_().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:j.Ry({max_chars_per_result:j.Rx().optional().describe("Maximum characters per result."),max_chars_total:j.Rx().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:j.Ry({max_age_seconds:j.Rx().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.")}))),eM=(0,M.DG)(()=>(0,M.r0)(j.G0([j.Ry({searchId:j.Z_(),results:j.IX(j.Ry({url:j.Z_(),title:j.Z_(),excerpt:j.Z_(),publishDate:j.Z_().nullable().optional(),relevanceScore:j.Rx().optional()}))}),j.Ry({error:j.Km(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:j.Rx().optional(),message:j.Z_()})]))),e$=(0,M.ql)({id:"gateway.parallel_search",inputSchema:eN,outputSchema:eM}),eP=(0,M.DG)(()=>(0,M.r0)(j.Ry({query:j.G0([j.Z_(),j.IX(j.Z_())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:j.Rx().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:j.Rx().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:j.Rx().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:j.Z_().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:j.IX(j.Z_()).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:j.IX(j.Z_()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:j.Z_().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:j.Z_().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:j.Z_().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:j.Z_().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:j.Km(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),ej=(0,M.DG)(()=>(0,M.r0)(j.G0([j.Ry({results:j.IX(j.Ry({title:j.Z_(),url:j.Z_(),snippet:j.Z_(),date:j.Z_().optional(),lastUpdated:j.Z_().optional()})),id:j.Z_()}),j.Ry({error:j.Km(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:j.Rx().optional(),message:j.Z_()})]))),eF=(0,M.ql)({id:"gateway.perplexity_search",inputSchema:eP,outputSchema:ej}),ez={parallelSearch:(e={})=>e$(e),perplexitySearch:(e={})=>eF(e)};async function eD(){var e;return null==(e=(0,F.getContext)().headers)?void 0:e["x-vercel-id"]}var eq=function(e={}){var t,r;let a=null,n=null,o=null!=(t=e.metadataCacheRefreshMillis)?t:3e5,i=0,s=null!=(r=(0,M.QT)(e.baseURL))?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{let t=await eU(e);return(0,M.CR)({Authorization:`Bearer ${t.token}`,"ai-gateway-protocol-version":"0.0.1",[eh]:t.authMethod,...e.headers},"ai-sdk/gateway/3.0.66")}catch(e){throw L.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:e})}},u=()=>{let e=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),t=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),r=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),a=(0,M.P6)({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{let n=await eD();return{...e&&{"ai-o11y-deployment-id":e},...t&&{"ai-o11y-environment":t},...r&&{"ai-o11y-region":r},...n&&{"ai-o11y-request-id":n},...a&&{"ai-o11y-project-id":a}}}},d=t=>new ev(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),c=async()=>{var t,r,u;let d=null!=(u=null==(r=null==(t=e._internal)?void 0:t.currentDate)?void 0:r.call(t).getTime())?u:Date.now();return(!a||d-i>o)&&(i=d,a=new ey({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then(e=>(n=e,e)).catch(async e=>{throw await ep(e,await em(await l()))})),n?Promise.resolve(n):a},p=async()=>new ey({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async e=>{throw await ep(e,await em(await l()))}),h=function(e){if(new.target)throw Error("The Gateway Provider model function cannot be called with the new keyword.");return d(e)};h.specificationVersion="v3",h.getAvailableModels=c,h.getCredits=p,h.imageModel=t=>new ex(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),h.languageModel=d;let m=t=>new eb(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()});return h.embeddingModel=m,h.textEmbeddingModel=m,h.videoModel=t=>new eZ(t,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:u()}),h.chat=h.languageModel,h.embedding=h.embeddingModel,h.image=h.imageModel,h.video=h.videoModel,h.tools=ez,h}();async function eU(e){let t=(0,M.P6)({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await (0,F.getVercelOidcToken)(),authMethod:"oidc"}}var eL=r(3998),eV=r(3924),eG=r(8997),eW=Object.defineProperty,eX="AI_InvalidArgumentError",eB=`vercel.ai.error.${eX}`,eK=Symbol.for(eB),eJ=class extends $.AX{constructor({parameter:e,value:t,message:r}){super({name:eX,message:`Invalid argument for parameter ${e}: ${r}`}),this[v]=!0,this.parameter=e,this.value=t}static isInstance(e){return $.AX.hasMarker(e,eB)}};v=eK,Symbol.for("vercel.ai.error.AI_InvalidStreamPartError"),$.AX;var eH="AI_InvalidToolApprovalError",eY=`vercel.ai.error.${eH}`,eQ=Symbol.for(eY),e0=class extends $.AX{constructor({approvalId:e}){super({name:eH,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[b]=!0,this.approvalId=e}static isInstance(e){return $.AX.hasMarker(e,eY)}};b=eQ;var e1="AI_InvalidToolInputError",e2=`vercel.ai.error.${e1}`,e4=Symbol.for(e2),e9=class extends $.AX{constructor({toolInput:e,toolName:t,cause:r,message:a=`Invalid input for tool ${t}: ${(0,$.e$)(r)}`}){super({name:e1,message:a,cause:r}),this[w]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return $.AX.hasMarker(e,e2)}};w=e4;var e5="AI_ToolCallNotFoundForApprovalError",e6=`vercel.ai.error.${e5}`,e3=Symbol.for(e6),e8=class extends $.AX{constructor({toolCallId:e,approvalId:t}){super({name:e5,message:`Tool call "${e}" not found for approval request "${t}".`}),this[x]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return $.AX.hasMarker(e,e6)}};x=e3;var e7="AI_MissingToolResultsError",te=`vercel.ai.error.${e7}`,tt=Symbol.for(te),tr=class extends $.AX{constructor({toolCallIds:e}){super({name:e7,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[k]=!0,this.toolCallIds=e}static isInstance(e){return $.AX.hasMarker(e,te)}};k=tt;var ta=Symbol.for("vercel.ai.error.AI_NoImageGeneratedError");$.AX;var tn="AI_NoObjectGeneratedError",to=`vercel.ai.error.${tn}`,ti=Symbol.for(to),ts=class extends $.AX{constructor({message:e="No object generated.",cause:t,text:r,response:a,usage:n,finishReason:o}){super({name:tn,message:e,cause:t}),this[I]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=o}static isInstance(e){return $.AX.hasMarker(e,to)}};I=ti;var tl="AI_NoOutputGeneratedError",tu=`vercel.ai.error.${tl}`,td=Symbol.for(tu),tc=class extends $.AX{constructor({message:e="No output generated.",cause:t}={}){super({name:tl,message:e,cause:t}),this[T]=!0}static isInstance(e){return $.AX.hasMarker(e,tu)}};T=td;var tp=Symbol.for("vercel.ai.error.AI_NoSpeechGeneratedError");$.AX;var th=Symbol.for("vercel.ai.error.AI_NoTranscriptGeneratedError");$.AX;var tm=Symbol.for("vercel.ai.error.AI_NoVideoGeneratedError");$.AX;var tf="AI_NoSuchToolError",ty=`vercel.ai.error.${tf}`,t_=Symbol.for(ty),tg=class extends $.AX{constructor({toolName:e,availableTools:t,message:r=`Model tried to call unavailable tool '${e}'. ${void 0===t?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:tf,message:r}),this[R]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return $.AX.hasMarker(e,ty)}};R=t_;var tv="AI_ToolCallRepairError",tb=`vercel.ai.error.${tv}`,tw=Symbol.for(tb),tx=class extends $.AX{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${(0,$.e$)(e)}`}){super({name:tv,message:r,cause:e}),this[S]=!0,this.originalError=t}static isInstance(e){return $.AX.hasMarker(e,tb)}};S=tw;var tk=class extends $.AX{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}},tI="AI_UIMessageStreamError",tT=`vercel.ai.error.${tI}`,tR=Symbol.for(tT),tS=class extends $.AX{constructor({chunkType:e,chunkId:t,message:r}){super({name:tI,message:r}),this[Z]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return $.AX.hasMarker(e,tT)}};Z=tR;var tZ="AI_InvalidDataContentError",tC=`vercel.ai.error.${tZ}`,tE=Symbol.for(tC);$.AX,C=tE;var tO="AI_InvalidMessageRoleError",tA=`vercel.ai.error.${tO}`,tN=Symbol.for(tA),tM=class extends $.AX{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:tO,message:t}),this[E]=!0,this.role=e}static isInstance(e){return $.AX.hasMarker(e,tA)}};E=tN;var t$="AI_MessageConversionError",tP=`vercel.ai.error.${t$}`,tj=Symbol.for(tP),tF=class extends $.AX{constructor({originalMessage:e,message:t}){super({name:t$,message:t}),this[O]=!0,this.originalMessage=e}static isInstance(e){return $.AX.hasMarker(e,tP)}};O=tj;var tz="AI_RetryError",tD=`vercel.ai.error.${tz}`,tq=Symbol.for(tD),tU=class extends $.AX{constructor({message:e,reason:t,errors:r}){super({name:tz,message:e}),this[A]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return $.AX.hasMarker(e,tD)}};function tL(e){return void 0===e?[]:Array.isArray(e)?e:[e]}async function tV(e){for(let t of tL(e.callbacks))if(null!=t)try{await t(e.event)}catch(e){}}A=tq;var tG=!1,tW=e=>{if(0===e.warnings.length)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(!1!==t){if("function"==typeof t){t(e);return}for(let t of(tG||(tG=!0,console.info("AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.")),e.warnings))console.warn(function({warning:e,provider:t,model:r}){let a=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let t=`${a} The feature "${e.feature}" is not supported.`;return e.details&&(t+=` ${e.details}`),t}case"compatibility":{let t=`${a} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(t+=` ${e.details}`),t}case"other":return`${a} ${e.message}`;default:return`${a} ${JSON.stringify(e,null,2)}`}}({warning:t,provider:e.provider,model:e.model}))}};function tX({provider:e,modelId:t}){tW({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function tB(e){return{unified:"unknown"===e?"other":e,raw:void 0}}function tK(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function tJ(e){if("string"!=typeof e){var t;if("v3"!==e.specificationVersion&&"v2"!==e.specificationVersion)throw new tk({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return"v3"===(t=e).specificationVersion?t:(tX({provider:t.provider,modelId:t.modelId}),new Proxy(t,{get(e,t){switch(t){case"specificationVersion":return"v3";case"doGenerate":return async(...t)=>{let r=await e.doGenerate(...t);return{...r,finishReason:tB(r.finishReason),usage:tK(r.usage)}};case"doStream":return async(...t)=>{let r=await e.doStream(...t);return{...r,stream:r.stream.pipeThrough(new TransformStream({transform(e,t){"finish"===e.type?t.enqueue({...e,finishReason:tB(e.finishReason),usage:tK(e.usage)}):t.enqueue(e)}}))}};default:return e[t]}}}))}return(function(){var e;return null!=(e=globalThis.AI_SDK_DEFAULT_PROVIDER)?e:eq})().languageModel(e)}function tH(e){return null==e?void 0:"number"==typeof e?e:e.totalMs}var tY=[{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]}],tQ=e=>{let t="string"==typeof e?(0,M.MS)(e):e,r=(127&t[6])<<21|(127&t[7])<<14|(127&t[8])<<7|127&t[9];return t.slice(r+10)},t0="6.0.116",t1=async({url:e,maxBytes:t,abortSignal:r})=>{var a;let n=e.toString();(0,M.SA)(n);try{let e=await fetch(n,{headers:(0,M.CR)({},`ai-sdk/${t0}`,(0,M.gJ)()),signal:r});if(!e.ok)throw new M.Bx({url:n,statusCode:e.status,statusText:e.statusText});return{data:await (0,M.SN)({response:e,url:n,maxBytes:null!=t?t:M.N$}),mediaType:null!=(a=e.headers.get("content-type"))?a:void 0}}catch(e){if(M.Bx.isInstance(e))throw e;throw new M.Bx({url:n,cause:e})}},t2=(e=t1)=>t=>Promise.all(t.map(async t=>t.isUrlSupportedByModel?null:e(t))),t4=P.G0([P.Z_(),P.Pp(Uint8Array),P.Pp(ArrayBuffer),P.PG(e=>{var t,r;return null!=(r=null==(t=globalThis.Buffer)?void 0:t.isBuffer(e))&&r},{message:"Must be a Buffer"})]);function t9(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if("string"==typeof e)try{e=new URL(e)}catch(e){}if(e instanceof URL&&"data:"===e.protocol){let{mediaType:t,base64Content:r}=function(e){try{let[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch(e){return{mediaType:void 0,base64Content:void 0}}}(e.toString());if(null==t||null==r)throw new $.AX({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}async function t5({prompt:e,supportedUrls:t,download:r=t2()}){let a=await t6(e.messages,r,t),n=new Map;for(let t of e.messages)if("assistant"===t.role&&Array.isArray(t.content))for(let e of t.content)"tool-approval-request"===e.type&&"approvalId"in e&&"toolCallId"in e&&n.set(e.approvalId,e.toolCallId);let o=new Set;for(let t of e.messages)if("tool"===t.role){for(let e of t.content)if("tool-approval-response"===e.type){let t=n.get(e.approvalId);t&&o.add(t)}}let i=[...null!=e.system?"string"==typeof e.system?[{role:"system",content:e.system}]:tL(e.system).map(e=>({role:"system",content:e.content,providerOptions:e.providerOptions})):[],...e.messages.map(e=>(function({message:e,downloadedAssets:t}){let r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":if("string"==typeof e.content)return{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};return{role:"user",content:e.content.map(e=>(function(e,t){var r;let a;if("text"===e.type)return{type:"text",text:e.text,providerOptions:e.providerOptions};let n=e.type;switch(n){case"image":a=e.image;break;case"file":a=e.data;break;default:throw Error(`Unsupported part type: ${n}`)}let{data:o,mediaType:i}=t9(a),s=null!=i?i:e.mediaType,l=o;if(l instanceof URL){let e=t[l.toString()];e&&(l=e.data,null!=s||(s=e.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||"string"==typeof l)&&(s=null!=(r=function({data:e,signatures:t}){let r="string"==typeof e&&e.startsWith("SUQz")||"string"!=typeof e&&e.length>10&&73===e[0]&&68===e[1]&&51===e[2]?tQ(e):e,a="string"==typeof r?(0,M.MS)(r.substring(0,Math.min(r.length,24))):r;for(let e of t)if(a.length>=e.bytesPrefix.length&&e.bytesPrefix.every((e,t)=>null===e||a[t]===e))return e.mediaType}({data:l,signatures:tY}))?r:s),{type:"file",mediaType:null!=s?s:"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":if(null==s)throw Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}})(e,t)).filter(e=>"text"!==e.type||""!==e.text),providerOptions:e.providerOptions};case"assistant":if("string"==typeof e.content)return{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};return{role:"assistant",content:e.content.filter(e=>"text"!==e.type||""!==e.text||null!=e.providerOptions).filter(e=>"tool-approval-request"!==e.type).map(e=>{let t=e.providerOptions;switch(e.type){case"file":{let{data:r,mediaType:a}=t9(e.data);return{type:"file",data:r,filename:e.filename,mediaType:null!=a?a:e.mediaType,providerOptions:t}}case"reasoning":return{type:"reasoning",text:e.text,providerOptions:t};case"text":return{type:"text",text:e.text,providerOptions:t};case"tool-call":return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:t};case"tool-result":return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:t3(e.output),providerOptions:t}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(e=>"tool-approval-response"!==e.type||e.providerExecuted).map(e=>{switch(e.type){case"tool-result":return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:t3(e.output),providerOptions:e.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:e.approvalId,approved:e.approved,reason:e.reason}}}),providerOptions:e.providerOptions};default:throw new tM({role:r})}})({message:e,downloadedAssets:a}))],s=[];for(let e of i){if("tool"!==e.role){s.push(e);continue}let t=s.at(-1);(null==t?void 0:t.role)==="tool"?t.content.push(...e.content):s.push(e)}let l=new Set;for(let e of s)switch(e.role){case"assistant":for(let t of e.content)"tool-call"!==t.type||t.providerExecuted||l.add(t.toolCallId);break;case"tool":for(let t of e.content)"tool-result"===t.type&&l.delete(t.toolCallId);break;case"user":case"system":for(let e of o)l.delete(e);if(l.size>0)throw new tr({toolCallIds:Array.from(l)})}for(let e of o)l.delete(e);if(l.size>0)throw new tr({toolCallIds:Array.from(l)});return s.filter(e=>"tool"!==e.role||e.content.length>0)}async function t6(e,t,r){let a=e.filter(e=>"user"===e.role).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>"image"===e.type||"file"===e.type).map(e=>{var t;let r=null!=(t=e.mediaType)?t:"image"===e.type?"image/*":void 0,a="image"===e.type?e.image:e.data;if("string"==typeof a)try{a=new URL(a)}catch(e){}return{mediaType:r,data:a}}).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:null!=e.mediaType&&(0,M.MT)({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:r})}));return Object.fromEntries((await t(a)).map((e,t)=>null==e?null:[a[t].url.toString(),{data:e.data,mediaType:e.mediaType}]).filter(e=>null!=e))}function t3(e){return"content"!==e.type?e:{type:"content",value:e.value.map(e=>"media"!==e.type?e:e.mediaType.startsWith("image/")?{type:"image-data",data:e.data,mediaType:e.mediaType}:{type:"file-data",data:e.data,mediaType:e.mediaType})}}async function t8({toolCallId:e,input:t,output:r,tool:a,errorMode:n}){return"text"===n?{type:"error-text",value:(0,$.e$)(r)}:"json"===n?{type:"error-json",value:t7(r)}:(null==a?void 0:a.toModelOutput)?await a.toModelOutput({toolCallId:e,input:t,output:r}):"string"==typeof r?{type:"text",value:r}:{type:"json",value:t7(r)}}function t7(e){return void 0===e?null:e}async function re({tools:e,toolChoice:t,activeTools:r}){if(!(null!=e&&Object.keys(e).length>0))return{tools:void 0,toolChoice:void 0};let a=null!=r?Object.entries(e).filter(([e])=>r.includes(e)):Object.entries(e),n=[];for(let[e,t]of a){let r=t.type;switch(r){case void 0:case"dynamic":case"function":n.push({type:"function",name:e,description:t.description,inputSchema:await (0,M.C3)(t.inputSchema).jsonSchema,...null!=t.inputExamples?{inputExamples:t.inputExamples}:{},providerOptions:t.providerOptions,...null!=t.strict?{strict:t.strict}:{}});break;case"provider":n.push({type:"provider",name:e,id:t.id,args:t.args});break;default:throw Error(`Unsupported tool type: ${r}`)}}return{tools:n,toolChoice:null==t?{type:"auto"}:"string"==typeof t?{type:t}:{type:"tool",toolName:t.toolName}}}var rt=P.Vo(()=>P.G0([P.lB(),P.Z_(),P.Rx(),P.O7(),P.IM(P.Z_(),rt.optional()),P.IX(rt)])),rr=P.IM(P.Z_(),P.IM(P.Z_(),rt.optional())),ra=P.Ry({type:P.i0("text"),text:P.Z_(),providerOptions:rr.optional()}),rn=P.Ry({type:P.i0("image"),image:P.G0([t4,P.Pp(URL)]),mediaType:P.Z_().optional(),providerOptions:rr.optional()}),ro=P.Ry({type:P.i0("file"),data:P.G0([t4,P.Pp(URL)]),filename:P.Z_().optional(),mediaType:P.Z_(),providerOptions:rr.optional()}),ri=P.Ry({type:P.i0("reasoning"),text:P.Z_(),providerOptions:rr.optional()}),rs=P.Ry({type:P.i0("tool-call"),toolCallId:P.Z_(),toolName:P.Z_(),input:P._4(),providerOptions:rr.optional(),providerExecuted:P.O7().optional()}),rl=P.VK("type",[P.Ry({type:P.i0("text"),value:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("json"),value:rt,providerOptions:rr.optional()}),P.Ry({type:P.i0("execution-denied"),reason:P.Z_().optional(),providerOptions:rr.optional()}),P.Ry({type:P.i0("error-text"),value:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("error-json"),value:rt,providerOptions:rr.optional()}),P.Ry({type:P.i0("content"),value:P.IX(P.G0([P.Ry({type:P.i0("text"),text:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("media"),data:P.Z_(),mediaType:P.Z_()}),P.Ry({type:P.i0("file-data"),data:P.Z_(),mediaType:P.Z_(),filename:P.Z_().optional(),providerOptions:rr.optional()}),P.Ry({type:P.i0("file-url"),url:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("file-id"),fileId:P.G0([P.Z_(),P.IM(P.Z_(),P.Z_())]),providerOptions:rr.optional()}),P.Ry({type:P.i0("image-data"),data:P.Z_(),mediaType:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("image-url"),url:P.Z_(),providerOptions:rr.optional()}),P.Ry({type:P.i0("image-file-id"),fileId:P.G0([P.Z_(),P.IM(P.Z_(),P.Z_())]),providerOptions:rr.optional()}),P.Ry({type:P.i0("custom"),providerOptions:rr.optional()})]))})]),ru=P.Ry({type:P.i0("tool-result"),toolCallId:P.Z_(),toolName:P.Z_(),output:rl,providerOptions:rr.optional()}),rd=P.Ry({type:P.i0("tool-approval-request"),approvalId:P.Z_(),toolCallId:P.Z_()}),rc=P.Ry({type:P.i0("tool-approval-response"),approvalId:P.Z_(),approved:P.O7(),reason:P.Z_().optional()}),rp=P.Ry({role:P.i0("system"),content:P.Z_(),providerOptions:rr.optional()}),rh=P.Ry({role:P.i0("user"),content:P.G0([P.Z_(),P.IX(P.G0([ra,rn,ro]))]),providerOptions:rr.optional()}),rm=P.Ry({role:P.i0("assistant"),content:P.G0([P.Z_(),P.IX(P.G0([ra,ro,ri,rs,ru,rd]))]),providerOptions:rr.optional()}),rf=P.Ry({role:P.i0("tool"),content:P.IX(P.G0([ru,rc])),providerOptions:rr.optional()}),ry=P.G0([rp,rh,rm,rf]);async function r_(e){let t;if(null==e.prompt&&null==e.messages)throw new $.Mt({prompt:e,message:"prompt or messages must be defined"});if(null!=e.prompt&&null!=e.messages)throw new $.Mt({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(null!=e.system&&"string"!=typeof e.system&&!tL(e.system).every(e=>"object"==typeof e&&null!==e&&"role"in e&&"system"===e.role))throw new $.Mt({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(null!=e.prompt&&"string"==typeof e.prompt)t=[{role:"user",content:e.prompt}];else if(null!=e.prompt&&Array.isArray(e.prompt))t=e.prompt;else if(null!=e.messages)t=e.messages;else throw new $.Mt({prompt:e,message:"prompt or messages must be defined"});if(0===t.length)throw new $.Mt({prompt:e,message:"messages must not be empty"});let r=await (0,M.pW)({value:t,schema:P.IX(ry)});if(!r.success)throw new $.Mt({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function rg({operationId:e,telemetry:t}){return{"operation.name":`${e}${(null==t?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":null==t?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":null==t?void 0:t.functionId}}var rv={startSpan:()=>rb,startActiveSpan:(e,t,r,a)=>"function"==typeof t?t(rb):"function"==typeof r?r(rb):"function"==typeof a?a(rb):void 0},rb={spanContext:()=>rw,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:()=>!1,recordException(){return this}},rw={traceId:"",spanId:"",traceFlags:0};async function rx({name:e,tracer:t,attributes:r,fn:a,endWhenDone:n=!0}){return t.startActiveSpan(e,{attributes:await r},async e=>{let t=eV.D.active();try{let r=await eV.D.with(t,()=>a(e));return n&&e.end(),r}catch(t){try{rk(e,t)}finally{e.end()}throw t}})}function rk(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:eG.Q.ERROR,message:t.message})):e.setStatus({code:eG.Q.ERROR})}async function rI({telemetry:e,attributes:t}){if((null==e?void 0:e.isEnabled)!==!0)return{};let r={};for(let[a,n]of Object.entries(t))if(null!=n){if("object"==typeof n&&"input"in n&&"function"==typeof n.input){if((null==e?void 0:e.recordInputs)===!1)continue;let t=await n.input();null!=t&&(r[a]=t);continue}if("object"==typeof n&&"output"in n&&"function"==typeof n.output){if((null==e?void 0:e.recordOutputs)===!1)continue;let t=await n.output();null!=t&&(r[a]=t);continue}r[a]=n}return r}function rT(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function rR(e,t){return null==e&&null==t?void 0:(null!=e?e:0)+(null!=t?t:0)}function rS(e,t){if(void 0===e&&void 0===t)return;if(void 0===e)return t;if(void 0===t)return e;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let n=t[a];if(void 0===n)continue;let o=a in e?e[a]:void 0,i=null!==n&&"object"==typeof n&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),s=null!=o&&"object"==typeof o&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&s?r[a]=rS(o,n):r[a]=n}return r}var rZ=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>rC(n,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:a});async function rC(e,{maxRetries:t,delayInMs:r,backoffFactor:a,abortSignal:n},o=[]){try{return await e()}catch(u){if((0,M.D_)(u)||0===t)throw u;let i=(0,M.e$)(u),s=[...o,u],l=s.length;if(l>t)throw new tU({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:s});if(u instanceof Error&&$.w.isInstance(u)&&!0===u.isRetryable&&l<=t)return await (0,M.gw)(function({error:e,exponentialBackoffDelay:t}){let r;let a=e.responseHeaders;if(!a)return t;let n=a["retry-after-ms"];if(n){let e=parseFloat(n);Number.isNaN(e)||(r=e)}let o=a["retry-after"];if(o&&void 0===r){let e=parseFloat(o);r=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}return null!=r&&!Number.isNaN(r)&&0<=r&&(r<6e4||r<t)?r:t}({error:u,exponentialBackoffDelay:r}),{abortSignal:n}),rC(e,{maxRetries:t,delayInMs:a*r,backoffFactor:a,abortSignal:n},s);if(1===l)throw u;throw new tU({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:s})}}function rE(){var e,t;return null!=(t=null==(e=null==globalThis?void 0:globalThis.performance)?void 0:e.now())?t:Date.now()}async function rO({toolCall:e,tools:t,tracer:r,telemetry:a,messages:n,abortSignal:o,experimental_context:i,stepNumber:s,model:l,onPreliminaryToolResult:u,onToolCallStart:d,onToolCallFinish:c}){let{toolName:p,toolCallId:h,input:m}=e,f=null==t?void 0:t[p];if((null==f?void 0:f.execute)==null)return;let y={stepNumber:s,model:l,toolCall:e,messages:n,abortSignal:o,functionId:null==a?void 0:a.functionId,metadata:null==a?void 0:a.metadata,experimental_context:i};return rx({name:"ai.toolCall",attributes:rI({telemetry:a,attributes:{...rg({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(m)}}}),tracer:r,fn:async t=>{let r;await tV({event:y,callbacks:d});let s=rE();try{for await(let t of(0,M.aN)({execute:f.execute.bind(f),input:m,options:{toolCallId:h,messages:n,abortSignal:o,experimental_context:i}}))"preliminary"===t.type?null==u||u({...e,type:"tool-result",output:t.output,preliminary:!0}):r=t.output}catch(a){let r=rE()-s;return await tV({event:{...y,success:!1,error:a,durationMs:r},callbacks:c}),rk(t,a),{type:"tool-error",toolCallId:h,toolName:p,input:m,error:a,dynamic:"dynamic"===f.type,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}}let l=rE()-s;await tV({event:{...y,success:!0,output:r,durationMs:l},callbacks:c});try{t.setAttributes(await rI({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(r)}}}))}catch(e){}return{type:"tool-result",toolCallId:h,toolName:p,input:m,output:r,dynamic:"dynamic"===f.type,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}}})}var rA=class{constructor({data:e,mediaType:t}){let r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return null==this.base64Data&&(this.base64Data=(0,M.k0)(this.uint8ArrayData)),this.base64Data}get uint8Array(){return null==this.uint8ArrayData&&(this.uint8ArrayData=(0,M.MS)(this.base64Data)),this.uint8ArrayData}},rN=class extends rA{constructor(e){super(e),this.type="file"}};async function rM({tool:e,toolCall:t,messages:r,experimental_context:a}){return null!=e.needsApproval&&("boolean"==typeof e.needsApproval?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:a}))}async function r$(e){if(void 0===e)return{value:void 0,state:"undefined-input"};let t=await (0,M.NX)({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await (0,M.NX)({text:function(e){let t=["ROOT"],r=-1,a=null;function n(e,n,o){switch(e){case'"':r=n,t.pop(),t.push(o),t.push("INSIDE_STRING");break;case"f":case"t":case"n":r=n,a=n,t.pop(),t.push(o),t.push("INSIDE_LITERAL");break;case"-":t.pop(),t.push(o),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":r=n,t.pop(),t.push(o),t.push("INSIDE_NUMBER");break;case"{":r=n,t.pop(),t.push(o),t.push("INSIDE_OBJECT_START");break;case"[":r=n,t.pop(),t.push(o),t.push("INSIDE_ARRAY_START")}}function o(e,a){switch(e){case",":t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break;case"}":r=a,t.pop()}}function i(e,a){switch(e){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":r=a,t.pop()}}for(let s=0;s<e.length;s++){let l=e[s];switch(t[t.length-1]){case"ROOT":n(l,s,"FINISH");break;case"INSIDE_OBJECT_START":switch(l){case'"':t.pop(),t.push("INSIDE_OBJECT_KEY");break;case"}":r=s,t.pop()}break;case"INSIDE_OBJECT_AFTER_COMMA":'"'===l&&(t.pop(),t.push("INSIDE_OBJECT_KEY"));break;case"INSIDE_OBJECT_KEY":'"'===l&&(t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY"));break;case"INSIDE_OBJECT_AFTER_KEY":":"===l&&(t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE"));break;case"INSIDE_OBJECT_BEFORE_VALUE":n(l,s,"INSIDE_OBJECT_AFTER_VALUE");break;case"INSIDE_OBJECT_AFTER_VALUE":o(l,s);break;case"INSIDE_STRING":switch(l){case'"':t.pop(),r=s;break;case"\\":t.push("INSIDE_STRING_ESCAPE");break;default:r=s}break;case"INSIDE_ARRAY_START":"]"===l?(r=s,t.pop()):(r=s,n(l,s,"INSIDE_ARRAY_AFTER_VALUE"));break;case"INSIDE_ARRAY_AFTER_VALUE":switch(l){case",":t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break;case"]":r=s,t.pop();break;default:r=s}break;case"INSIDE_ARRAY_AFTER_COMMA":n(l,s,"INSIDE_ARRAY_AFTER_VALUE");break;case"INSIDE_STRING_ESCAPE":t.pop(),r=s;break;case"INSIDE_NUMBER":switch(l){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":r=s;break;case"e":case"E":case"-":case".":break;case",":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&i(l,s),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(l,s);break;case"}":t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]&&o(l,s);break;case"]":t.pop(),"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&i(l,s);break;default:t.pop()}break;case"INSIDE_LITERAL":{let n=e.substring(a,s+1);"false".startsWith(n)||"true".startsWith(n)||"null".startsWith(n)?r=s:(t.pop(),"INSIDE_OBJECT_AFTER_VALUE"===t[t.length-1]?o(l,s):"INSIDE_ARRAY_AFTER_VALUE"===t[t.length-1]&&i(l,s))}}}let s=e.slice(0,r+1);for(let r=t.length-1;r>=0;r--)switch(t[r]){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":{let t=e.substring(a,e.length);"true".startsWith(t)?s+="true".slice(t.length):"false".startsWith(t)?s+="false".slice(t.length):"null".startsWith(t)&&(s+="null".slice(t.length))}}return s}(e)})).success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"}}((e,t)=>{for(var r in t)eW(e,r,{get:t[r],enumerable:!0})})({},{array:()=>rF,choice:()=>rz,json:()=>rD,object:()=>rj,text:()=>rP});var rP=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),parseCompleteOutput:async({text:e})=>e,parsePartialOutput:async({text:e})=>({partial:e}),createElementStreamTransform(){}}),rj=({schema:e,name:t,description:r})=>{let a=(0,M.C3)(e);return{name:"object",responseFormat:(0,M.DB)(a.jsonSchema).then(e=>({type:"json",schema:e,...null!=t&&{name:t},...null!=r&&{description:r}})),async parseCompleteOutput({text:e},t){let r=await (0,M.NX)({text:e});if(!r.success)throw new ts({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let n=await (0,M.pW)({value:r.value,schema:a});if(!n.success)throw new ts({message:"No object generated: response did not match schema.",cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await r$(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:t.value}}},createElementStreamTransform(){}}},rF=({element:e,name:t,description:r})=>{let a=(0,M.C3)(e);return{name:"array",responseFormat:(0,M.DB)(a.jsonSchema).then(e=>{let{$schema:a,...n}=e;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:n}},required:["elements"],additionalProperties:!1},...null!=t&&{name:t},...null!=r&&{description:r}}}),async parseCompleteOutput({text:e},t){let r=await (0,M.NX)({text:e});if(!r.success)throw new ts({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let n=r.value;if(null==n||"object"!=typeof n||!("elements"in n)||!Array.isArray(n.elements))throw new ts({message:"No object generated: response did not match schema.",cause:new $.Gz({value:n,cause:"response must be an object with an elements array"}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});for(let r of n.elements){let n=await (0,M.pW)({value:r,schema:a});if(!n.success)throw new ts({message:"No object generated: response did not match schema.",cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason})}return n.elements},async parsePartialOutput({text:e}){let t=await r$(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let e=t.value;if(null==e||"object"!=typeof e||!("elements"in e)||!Array.isArray(e.elements))return;let r="repaired-parse"===t.state&&e.elements.length>0?e.elements.slice(0,-1):e.elements,n=[];for(let e of r){let t=await (0,M.pW)({value:e,schema:a});t.success&&n.push(t.value)}return{partial:n}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},r){if(null!=t)for(;e<t.length;e++)r.enqueue(t[e])}})}}},rz=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...null!=t&&{name:t},...null!=r&&{description:r}}),async parseCompleteOutput({text:t},r){let a=await (0,M.NX)({text:t});if(!a.success)throw new ts({message:"No object generated: could not parse the response.",cause:a.error,text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});let n=a.value;if(null==n||"object"!=typeof n||!("result"in n)||"string"!=typeof n.result||!e.includes(n.result))throw new ts({message:"No object generated: response did not match schema.",cause:new $.Gz({value:n,cause:"response must be an object that contains a choice value."}),text:t,response:r.response,usage:r.usage,finishReason:r.finishReason});return n.result},async parsePartialOutput({text:t}){let r=await r$(t);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{let t=r.value;if(null==t||"object"!=typeof t||!("result"in t)||"string"!=typeof t.result)return;let a=e.filter(e=>e.startsWith(t.result));if("successful-parse"===r.state)return a.includes(t.result)?{partial:t.result}:void 0;return 1===a.length?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),rD=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...null!=e&&{name:e},...null!=t&&{description:t}}),async parseCompleteOutput({text:e},t){let r=await (0,M.NX)({text:e});if(!r.success)throw new ts({message:"No object generated: could not parse the response.",cause:r.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return r.value},async parsePartialOutput({text:e}){let t=await r$(e);switch(t.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return void 0===t.value?void 0:{partial:t.value}}},createElementStreamTransform(){}});async function rq({toolCall:e,tools:t,repairToolCall:r,system:a,messages:n}){var o;try{if(null==t){if(e.providerExecuted&&e.dynamic)return await rU(e);throw new tg({toolName:e.toolName})}try{return await rL({toolCall:e,tools:t})}catch(i){if(null==r||!(tg.isInstance(i)||e9.isInstance(i)))throw i;let o=null;try{o=await r({toolCall:e,tools:t,inputSchema:async({toolName:e})=>{let{inputSchema:r}=t[e];return await (0,M.C3)(r).jsonSchema},system:a,messages:n,error:i})}catch(e){throw new tx({cause:e,originalError:i})}if(null==o)throw i;return await rL({toolCall:o,tools:t})}}catch(n){let r=await (0,M.NX)({text:e.input}),a=r.success?r.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a,dynamic:!0,invalid:!0,error:n,title:null==(o=null==t?void 0:t[e.toolName])?void 0:o.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function rU(e){let t=""===e.input.trim()?{success:!0,value:{}}:await (0,M.NX)({text:e.input});if(!1===t.success)throw new e9({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function rL({toolCall:e,tools:t}){let r=e.toolName,a=t[r];if(null==a){if(e.providerExecuted&&e.dynamic)return await rU(e);throw new tg({toolName:e.toolName,availableTools:Object.keys(t)})}let n=(0,M.C3)(a.inputSchema),o=""===e.input.trim()?await (0,M.pW)({value:{},schema:n}):await (0,M.NX)({text:e.input,schema:n});if(!1===o.success)throw new e9({toolName:r,toolInput:e.input,cause:o.error});return"dynamic"===a.type?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:a.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:o.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:a.title}}var rV=class{constructor({stepNumber:e,model:t,functionId:r,metadata:a,experimental_context:n,content:o,finishReason:i,rawFinishReason:s,usage:l,warnings:u,request:d,response:c,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=a,this.experimental_context=n,this.content=o,this.finishReason=i,this.rawFinishReason=s,this.usage=l,this.warnings=u,this.request=d,this.response=c,this.providerMetadata=p}get text(){return this.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>"reasoning"===e.type)}get reasoningText(){return 0===this.reasoning.length?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>"file"===e.type).map(e=>e.file)}get sources(){return this.content.filter(e=>"source"===e.type)}get toolCalls(){return this.content.filter(e=>"tool-call"===e.type)}get staticToolCalls(){return this.toolCalls.filter(e=>!0!==e.dynamic)}get dynamicToolCalls(){return this.toolCalls.filter(e=>!0===e.dynamic)}get toolResults(){return this.content.filter(e=>"tool-result"===e.type)}get staticToolResults(){return this.toolResults.filter(e=>!0!==e.dynamic)}get dynamicToolResults(){return this.toolResults.filter(e=>!0===e.dynamic)}};function rG(e){return({steps:t})=>t.length===e}async function rW({stopConditions:e,steps:t}){return(await Promise.all(e.map(e=>e({steps:t})))).some(e=>e)}async function rX({content:e,tools:t}){let r=[],a=[];for(let r of e)if("source"!==r.type&&("tool-result"!==r.type&&"tool-error"!==r.type||r.providerExecuted)&&("text"!==r.type||0!==r.text.length))switch(r.type){case"text":a.push({type:"text",text:r.text,providerOptions:r.providerMetadata});break;case"reasoning":a.push({type:"reasoning",text:r.text,providerOptions:r.providerMetadata});break;case"file":a.push({type:"file",data:r.file.base64,mediaType:r.file.mediaType,providerOptions:r.providerMetadata});break;case"tool-call":a.push({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:r.providerMetadata});break;case"tool-result":{let e=await t8({toolCallId:r.toolCallId,input:r.input,tool:null==t?void 0:t[r.toolName],output:r.output,errorMode:"none"});a.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:e,providerOptions:r.providerMetadata});break}case"tool-error":{let e=await t8({toolCallId:r.toolCallId,input:r.input,tool:null==t?void 0:t[r.toolName],output:r.error,errorMode:"json"});a.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:e,providerOptions:r.providerMetadata});break}case"tool-approval-request":a.push({type:"tool-approval-request",approvalId:r.approvalId,toolCallId:r.toolCall.toolCallId})}a.length>0&&r.push({role:"assistant",content:a});let n=[];for(let r of e){if(!("tool-result"===r.type||"tool-error"===r.type)||r.providerExecuted)continue;let e=await t8({toolCallId:r.toolCallId,input:r.input,tool:null==t?void 0:t[r.toolName],output:"tool-result"===r.type?r.output:r.error,errorMode:"tool-error"===r.type?"text":"none"});n.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:e,...null!=r.providerMetadata?{providerOptions:r.providerMetadata}:{}})}return n.length>0&&r.push({role:"tool",content:n}),r}(0,M.bF)({prefix:"aitxt",size:24});function rB(e,t){let r=new Headers(null!=e?e:{});for(let[e,a]of Object.entries(t))r.has(e)||r.set(e,a);return r}function rK({response:e,status:t,statusText:r,headers:a,stream:n}){let o=null!=t?t:200;void 0!==r?e.writeHead(o,r,a):e.writeHead(o,a);let i=n.getReader();(async()=>{try{for(;;){let{done:t,value:r}=await i.read();if(t)break;e.write(r)||await new Promise(t=>{e.once("drain",t)})}}catch(e){throw e}finally{e.end()}})()}var rJ=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
59
59
 
60
- `)},flush(e){e.enqueue("data: [DONE]\n\n")}})}},rH={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function rY(e){return e.type.startsWith("data-")}function rQ(e){return"text"===e.type}function r0(e){return"file"===e.type}function r1(e){return"reasoning"===e.type}function r2(e){return e.type.startsWith("tool-")}function r4(e){return"dynamic-tool"===e.type}function r9(e){return r2(e)||r4(e)}function r5(e){return e.type.split("-").slice(1).join("-")}function r6(e){return r4(e)?e.toolName:r5(e)}function r3(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function r(r){var a;if(!t){t=!0;try{r&&await (null==(a=e.cancel)?void 0:a.call(e))}finally{try{e.releaseLock()}catch(e){}}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:a,value:n}=await e.read();return a?(await r(!0),{done:!0,value:void 0}):{done:!1,value:n}},return:async()=>(await r(!0),{done:!0,value:void 0}),async throw(e){throw await r(!0),e}}},t}async function r7({stream:e,onError:t}){let r=e.getReader();try{for(;;){let{done:e}=await r.read();if(e)break}}catch(e){null==t||t(e)}finally{r.releaseLock()}}function r8(){let e,t;return{promise:new Promise((r,a)=>{e=r,t=a}),resolve:e,reject:t}}(0,M.DG)(()=>(0,M.r0)(P.G0([P.cf({type:P.i0("text-start"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("text-delta"),id:P.Z_(),delta:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("text-end"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("error"),errorText:P.Z_()}),P.cf({type:P.i0("tool-input-start"),toolCallId:P.Z_(),toolName:P.Z_(),providerExecuted:P.O7().optional(),providerMetadata:rr.optional(),dynamic:P.O7().optional(),title:P.Z_().optional()}),P.cf({type:P.i0("tool-input-delta"),toolCallId:P.Z_(),inputTextDelta:P.Z_()}),P.cf({type:P.i0("tool-input-available"),toolCallId:P.Z_(),toolName:P.Z_(),input:P._4(),providerExecuted:P.O7().optional(),providerMetadata:rr.optional(),dynamic:P.O7().optional(),title:P.Z_().optional()}),P.cf({type:P.i0("tool-input-error"),toolCallId:P.Z_(),toolName:P.Z_(),input:P._4(),providerExecuted:P.O7().optional(),providerMetadata:rr.optional(),dynamic:P.O7().optional(),errorText:P.Z_(),title:P.Z_().optional()}),P.cf({type:P.i0("tool-approval-request"),approvalId:P.Z_(),toolCallId:P.Z_()}),P.cf({type:P.i0("tool-output-available"),toolCallId:P.Z_(),output:P._4(),providerExecuted:P.O7().optional(),dynamic:P.O7().optional(),preliminary:P.O7().optional()}),P.cf({type:P.i0("tool-output-error"),toolCallId:P.Z_(),errorText:P.Z_(),providerExecuted:P.O7().optional(),dynamic:P.O7().optional()}),P.cf({type:P.i0("tool-output-denied"),toolCallId:P.Z_()}),P.cf({type:P.i0("reasoning-start"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("reasoning-delta"),id:P.Z_(),delta:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("reasoning-end"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("source-url"),sourceId:P.Z_(),url:P.Z_(),title:P.Z_().optional(),providerMetadata:rr.optional()}),P.cf({type:P.i0("source-document"),sourceId:P.Z_(),mediaType:P.Z_(),title:P.Z_(),filename:P.Z_().optional(),providerMetadata:rr.optional()}),P.cf({type:P.i0("file"),url:P.Z_(),mediaType:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.PG(e=>"string"==typeof e&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:P.Z_().optional(),data:P._4(),transient:P.O7().optional()}),P.cf({type:P.i0("start-step")}),P.cf({type:P.i0("finish-step")}),P.cf({type:P.i0("start"),messageId:P.Z_().optional(),messageMetadata:P._4().optional()}),P.cf({type:P.i0("finish"),finishReason:P.Km(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:P._4().optional()}),P.cf({type:P.i0("abort"),reason:P.Z_().optional()}),P.cf({type:P.i0("message-metadata"),messageMetadata:P._4()})])));var ae=(0,M.bF)({prefix:"aitxt",size:24});function at({model:e,tools:t,toolChoice:r,system:a,prompt:n,messages:o,maxRetries:i,abortSignal:s,timeout:l,headers:u,stopWhen:d=rG(1),experimental_output:c,output:p=c,experimental_telemetry:h,prepareStep:m,providerOptions:f,experimental_activeTools:y,activeTools:_=y,experimental_repairToolCall:g,experimental_transform:v,experimental_download:b,includeRawChunks:w=!1,onChunk:x,onError:k=({error:e})=>{console.error(e)},onFinish:I,onAbort:T,onStepFinish:R,experimental_onStart:S,experimental_onStepStart:Z,experimental_onToolCallStart:C,experimental_onToolCallFinish:E,experimental_context:O,experimental_include:A,_internal:{now:N=rE,generateId:M=ae}={},...$}){let P=tH(l),j=function(e){if(null!=e&&"number"!=typeof e)return e.stepMs}(l),F=function(e){if(null!=e&&"number"!=typeof e)return e.chunkMs}(l),z=null!=j?new AbortController:void 0,D=null!=F?new AbortController:void 0;return new ar({model:tJ(e),telemetry:h,headers:u,settings:$,maxRetries:i,abortSignal:function(...e){let t=e.filter(e=>null!=e);if(0===t.length)return;if(1===t.length)return t[0];let r=new AbortController;for(let e of t){if(e.aborted){r.abort(e.reason);break}e.addEventListener("abort",()=>{r.abort(e.reason)},{once:!0})}return r.signal}(s,null!=P?AbortSignal.timeout(P):void 0,null==z?void 0:z.signal,null==D?void 0:D.signal),stepTimeoutMs:j,stepAbortController:z,chunkTimeoutMs:F,chunkAbortController:D,system:a,prompt:n,messages:o,tools:t,toolChoice:r,transforms:tL(v),activeTools:_,repairToolCall:g,stopConditions:tL(d),output:p,providerOptions:f,prepareStep:m,includeRawChunks:w,timeout:l,stopWhen:d,originalAbortSignal:s,onChunk:x,onError:k,onFinish:I,onAbort:T,onStepFinish:R,onStart:S,onStepStart:Z,onToolCallStart:C,onToolCallFinish:E,now:N,generateId:M,experimental_context:O,download:b,include:A})}var ar=class{constructor({model:e,telemetry:t,headers:r,settings:a,maxRetries:n,abortSignal:o,stepTimeoutMs:i,stepAbortController:s,chunkTimeoutMs:l,chunkAbortController:u,system:d,prompt:c,messages:p,tools:h,toolChoice:m,transforms:f,activeTools:y,repairToolCall:_,stopConditions:g,output:v,providerOptions:b,prepareStep:w,includeRawChunks:x,now:k,generateId:I,timeout:T,stopWhen:R,originalAbortSignal:S,onChunk:Z,onError:C,onFinish:E,onAbort:O,onStepFinish:A,onStart:N,onStepStart:P,onToolCallStart:j,onToolCallFinish:F,experimental_context:z,download:D,include:q}){let U,V,G,W,X;this._totalUsage=new M.eh,this._finishReason=new M.eh,this._rawFinishReason=new M.eh,this._steps=new M.eh,this.outputSpecification=v,this.includeRawChunks=x,this.tools=h;let B=(function(){var e;let t=null!=(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)?e:[];return e=>{let r=[...t,...tL(e)];function a(e){let t=r.map(e).filter(Boolean);return async e=>{for(let r of t)try{await r(e)}catch(e){}}}return{onStart:a(e=>e.onStart),onStepStart:a(e=>e.onStepStart),onToolCallStart:a(e=>e.onToolCallStart),onToolCallFinish:a(e=>e.onToolCallFinish),onStepFinish:a(e=>e.onStepFinish),onFinish:a(e=>e.onFinish)}}})()(null==t?void 0:t.integrations),K=[],J=[],H={},Y=[],Q=[],ee=new Map,et={},er={},ea=new TransformStream({async transform(e,t){var r,a,n,o;t.enqueue(e);let{part:i}=e;if(("text-delta"===i.type||"reasoning-delta"===i.type||"source"===i.type||"tool-call"===i.type||"tool-result"===i.type||"tool-input-start"===i.type||"tool-input-delta"===i.type||"raw"===i.type)&&await (null==Z?void 0:Z({chunk:i})),"error"===i.type&&await C({error:function(e){if(!L.isInstance(e))return e;let t="https://ai-sdk.dev/unauthenticated-ai-gateway";return(null==process?void 0:"production")==="production"?new $.AX({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${t}`}):Object.assign(Error(`\x1b[1m\x1b[31mUnauthenticated request to AI Gateway.\x1b[0m
60
+ `)},flush(e){e.enqueue("data: [DONE]\n\n")}})}},rH={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function rY(e){return e.type.startsWith("data-")}function rQ(e){return"text"===e.type}function r0(e){return"file"===e.type}function r1(e){return"reasoning"===e.type}function r2(e){return e.type.startsWith("tool-")}function r4(e){return"dynamic-tool"===e.type}function r9(e){return r2(e)||r4(e)}function r5(e){return e.type.split("-").slice(1).join("-")}function r6(e){return r4(e)?e.toolName:r5(e)}function r3(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function r(r){var a;if(!t){t=!0;try{r&&await (null==(a=e.cancel)?void 0:a.call(e))}finally{try{e.releaseLock()}catch(e){}}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:a,value:n}=await e.read();return a?(await r(!0),{done:!0,value:void 0}):{done:!1,value:n}},return:async()=>(await r(!0),{done:!0,value:void 0}),async throw(e){throw await r(!0),e}}},t}async function r8({stream:e,onError:t}){let r=e.getReader();try{for(;;){let{done:e}=await r.read();if(e)break}}catch(e){null==t||t(e)}finally{r.releaseLock()}}function r7(){let e,t;return{promise:new Promise((r,a)=>{e=r,t=a}),resolve:e,reject:t}}(0,M.DG)(()=>(0,M.r0)(P.G0([P.cf({type:P.i0("text-start"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("text-delta"),id:P.Z_(),delta:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("text-end"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("error"),errorText:P.Z_()}),P.cf({type:P.i0("tool-input-start"),toolCallId:P.Z_(),toolName:P.Z_(),providerExecuted:P.O7().optional(),providerMetadata:rr.optional(),dynamic:P.O7().optional(),title:P.Z_().optional()}),P.cf({type:P.i0("tool-input-delta"),toolCallId:P.Z_(),inputTextDelta:P.Z_()}),P.cf({type:P.i0("tool-input-available"),toolCallId:P.Z_(),toolName:P.Z_(),input:P._4(),providerExecuted:P.O7().optional(),providerMetadata:rr.optional(),dynamic:P.O7().optional(),title:P.Z_().optional()}),P.cf({type:P.i0("tool-input-error"),toolCallId:P.Z_(),toolName:P.Z_(),input:P._4(),providerExecuted:P.O7().optional(),providerMetadata:rr.optional(),dynamic:P.O7().optional(),errorText:P.Z_(),title:P.Z_().optional()}),P.cf({type:P.i0("tool-approval-request"),approvalId:P.Z_(),toolCallId:P.Z_()}),P.cf({type:P.i0("tool-output-available"),toolCallId:P.Z_(),output:P._4(),providerExecuted:P.O7().optional(),dynamic:P.O7().optional(),preliminary:P.O7().optional()}),P.cf({type:P.i0("tool-output-error"),toolCallId:P.Z_(),errorText:P.Z_(),providerExecuted:P.O7().optional(),dynamic:P.O7().optional()}),P.cf({type:P.i0("tool-output-denied"),toolCallId:P.Z_()}),P.cf({type:P.i0("reasoning-start"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("reasoning-delta"),id:P.Z_(),delta:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("reasoning-end"),id:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.i0("source-url"),sourceId:P.Z_(),url:P.Z_(),title:P.Z_().optional(),providerMetadata:rr.optional()}),P.cf({type:P.i0("source-document"),sourceId:P.Z_(),mediaType:P.Z_(),title:P.Z_(),filename:P.Z_().optional(),providerMetadata:rr.optional()}),P.cf({type:P.i0("file"),url:P.Z_(),mediaType:P.Z_(),providerMetadata:rr.optional()}),P.cf({type:P.PG(e=>"string"==typeof e&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:P.Z_().optional(),data:P._4(),transient:P.O7().optional()}),P.cf({type:P.i0("start-step")}),P.cf({type:P.i0("finish-step")}),P.cf({type:P.i0("start"),messageId:P.Z_().optional(),messageMetadata:P._4().optional()}),P.cf({type:P.i0("finish"),finishReason:P.Km(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:P._4().optional()}),P.cf({type:P.i0("abort"),reason:P.Z_().optional()}),P.cf({type:P.i0("message-metadata"),messageMetadata:P._4()})])));var ae=(0,M.bF)({prefix:"aitxt",size:24});function at({model:e,tools:t,toolChoice:r,system:a,prompt:n,messages:o,maxRetries:i,abortSignal:s,timeout:l,headers:u,stopWhen:d=rG(1),experimental_output:c,output:p=c,experimental_telemetry:h,prepareStep:m,providerOptions:f,experimental_activeTools:y,activeTools:_=y,experimental_repairToolCall:g,experimental_transform:v,experimental_download:b,includeRawChunks:w=!1,onChunk:x,onError:k=({error:e})=>{console.error(e)},onFinish:I,onAbort:T,onStepFinish:R,experimental_onStart:S,experimental_onStepStart:Z,experimental_onToolCallStart:C,experimental_onToolCallFinish:E,experimental_context:O,experimental_include:A,_internal:{now:N=rE,generateId:M=ae}={},...$}){let P=tH(l),j=function(e){if(null!=e&&"number"!=typeof e)return e.stepMs}(l),F=function(e){if(null!=e&&"number"!=typeof e)return e.chunkMs}(l),z=null!=j?new AbortController:void 0,D=null!=F?new AbortController:void 0;return new ar({model:tJ(e),telemetry:h,headers:u,settings:$,maxRetries:i,abortSignal:function(...e){let t=e.filter(e=>null!=e);if(0===t.length)return;if(1===t.length)return t[0];let r=new AbortController;for(let e of t){if(e.aborted){r.abort(e.reason);break}e.addEventListener("abort",()=>{r.abort(e.reason)},{once:!0})}return r.signal}(s,null!=P?AbortSignal.timeout(P):void 0,null==z?void 0:z.signal,null==D?void 0:D.signal),stepTimeoutMs:j,stepAbortController:z,chunkTimeoutMs:F,chunkAbortController:D,system:a,prompt:n,messages:o,tools:t,toolChoice:r,transforms:tL(v),activeTools:_,repairToolCall:g,stopConditions:tL(d),output:p,providerOptions:f,prepareStep:m,includeRawChunks:w,timeout:l,stopWhen:d,originalAbortSignal:s,onChunk:x,onError:k,onFinish:I,onAbort:T,onStepFinish:R,onStart:S,onStepStart:Z,onToolCallStart:C,onToolCallFinish:E,now:N,generateId:M,experimental_context:O,download:b,include:A})}var ar=class{constructor({model:e,telemetry:t,headers:r,settings:a,maxRetries:n,abortSignal:o,stepTimeoutMs:i,stepAbortController:s,chunkTimeoutMs:l,chunkAbortController:u,system:d,prompt:c,messages:p,tools:h,toolChoice:m,transforms:f,activeTools:y,repairToolCall:_,stopConditions:g,output:v,providerOptions:b,prepareStep:w,includeRawChunks:x,now:k,generateId:I,timeout:T,stopWhen:R,originalAbortSignal:S,onChunk:Z,onError:C,onFinish:E,onAbort:O,onStepFinish:A,onStart:N,onStepStart:P,onToolCallStart:j,onToolCallFinish:F,experimental_context:z,download:D,include:q}){let U,V,G,W,X;this._totalUsage=new M.eh,this._finishReason=new M.eh,this._rawFinishReason=new M.eh,this._steps=new M.eh,this.outputSpecification=v,this.includeRawChunks=x,this.tools=h;let B=(function(){var e;let t=null!=(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)?e:[];return e=>{let r=[...t,...tL(e)];function a(e){let t=r.map(e).filter(Boolean);return async e=>{for(let r of t)try{await r(e)}catch(e){}}}return{onStart:a(e=>e.onStart),onStepStart:a(e=>e.onStepStart),onToolCallStart:a(e=>e.onToolCallStart),onToolCallFinish:a(e=>e.onToolCallFinish),onStepFinish:a(e=>e.onStepFinish),onFinish:a(e=>e.onFinish)}}})()(null==t?void 0:t.integrations),K=[],J=[],H={},Y=[],Q=[],ee=new Map,et={},er={},ea=new TransformStream({async transform(e,t){var r,a,n,o;t.enqueue(e);let{part:i}=e;if(("text-delta"===i.type||"reasoning-delta"===i.type||"source"===i.type||"tool-call"===i.type||"tool-result"===i.type||"tool-input-start"===i.type||"tool-input-delta"===i.type||"raw"===i.type)&&await (null==Z?void 0:Z({chunk:i})),"error"===i.type&&await C({error:function(e){if(!L.isInstance(e))return e;let t="https://ai-sdk.dev/unauthenticated-ai-gateway";return(null==process?void 0:"production")==="production"?new $.AX({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${t}`}):Object.assign(Error(`\x1b[1m\x1b[31mUnauthenticated request to AI Gateway.\x1b[0m
61
61
 
62
62
  To authenticate, set the \x1b[33mAI_GATEWAY_API_KEY\x1b[0m environment variable with your API key.
63
63
 
@@ -65,7 +65,7 @@ Alternatively, you can use a provider module instead of the AI Gateway.
65
65
 
66
66
  Learn more: \x1b[34m${t}\x1b[0m
67
67
 
68
- `),{name:"GatewayAuthenticationError"})}(i.error)}),"text-start"===i.type&&(et[i.id]={type:"text",text:"",providerMetadata:i.providerMetadata},K.push(et[i.id])),"text-delta"===i.type){let e=et[i.id];if(null==e){t.enqueue({part:{type:"error",error:`text part ${i.id} not found`},partialOutput:void 0});return}e.text+=i.text,e.providerMetadata=null!=(r=i.providerMetadata)?r:e.providerMetadata}if("text-end"===i.type){let e=et[i.id];if(null==e){t.enqueue({part:{type:"error",error:`text part ${i.id} not found`},partialOutput:void 0});return}e.providerMetadata=null!=(a=i.providerMetadata)?a:e.providerMetadata,delete et[i.id]}if("reasoning-start"===i.type&&(er[i.id]={type:"reasoning",text:"",providerMetadata:i.providerMetadata},K.push(er[i.id])),"reasoning-delta"===i.type){let e=er[i.id];if(null==e){t.enqueue({part:{type:"error",error:`reasoning part ${i.id} not found`},partialOutput:void 0});return}e.text+=i.text,e.providerMetadata=null!=(n=i.providerMetadata)?n:e.providerMetadata}if("reasoning-end"===i.type){let e=er[i.id];if(null==e){t.enqueue({part:{type:"error",error:`reasoning part ${i.id} not found`},partialOutput:void 0});return}e.providerMetadata=null!=(o=i.providerMetadata)?o:e.providerMetadata,delete er[i.id]}if("file"===i.type&&K.push({type:"file",file:i.file,...null!=i.providerMetadata?{providerMetadata:i.providerMetadata}:{}}),"source"===i.type&&K.push(i),"tool-call"===i.type&&K.push(i),"tool-result"!==i.type||i.preliminary||K.push(i),"tool-approval-request"===i.type&&K.push(i),"tool-error"===i.type&&K.push(i),"start-step"===i.type&&(K=[],er={},et={},H=i.request,Y=i.warnings),"finish-step"===i.type){let e=await rX({content:K,tools:h}),t=new rV({stepNumber:Q.length,model:eh,...em,experimental_context:z,content:K,finishReason:i.finishReason,rawFinishReason:i.rawFinishReason,usage:i.usage,warnings:Y,request:H,response:{...i.response,messages:[...J,...e]},providerMetadata:i.providerMetadata});await tV({event:t,callbacks:[A,B.onStepFinish]}),tW({warnings:Y,provider:eh.provider,model:eh.modelId}),Q.push(t),J.push(...e),U.resolve()}"finish"===i.type&&(X=i.totalUsage,G=i.finishReason,W=i.rawFinishReason)},async flush(e){try{if(0===Q.length){let e=(null==o?void 0:o.aborted)?o.reason:new tc({message:"No output generated. Check the stream for errors."});ep._finishReason.reject(e),ep._rawFinishReason.reject(e),ep._totalUsage.reject(e),ep._steps.reject(e);return}let e=null!=G?G:"other",r=null!=X?X:rT();ep._finishReason.resolve(e),ep._rawFinishReason.resolve(W),ep._totalUsage.resolve(r),ep._steps.resolve(Q);let a=Q[Q.length-1];await tV({event:{stepNumber:a.stepNumber,model:a.model,functionId:a.functionId,metadata:a.metadata,experimental_context:a.experimental_context,finishReason:a.finishReason,rawFinishReason:a.rawFinishReason,totalUsage:r,usage:a.usage,content:a.content,text:a.text,reasoningText:a.reasoningText,reasoning:a.reasoning,files:a.files,sources:a.sources,toolCalls:a.toolCalls,staticToolCalls:a.staticToolCalls,dynamicToolCalls:a.dynamicToolCalls,toolResults:a.toolResults,staticToolResults:a.staticToolResults,dynamicToolResults:a.dynamicToolResults,request:a.request,response:a.response,warnings:a.warnings,providerMetadata:a.providerMetadata,steps:Q},callbacks:[E,B.onFinish]}),V.setAttributes(await rI({telemetry:t,attributes:{"ai.response.finishReason":e,"ai.response.text":{output:()=>a.text},"ai.response.reasoning":{output:()=>a.reasoningText},"ai.response.toolCalls":{output:()=>{var e;return(null==(e=a.toolCalls)?void 0:e.length)?JSON.stringify(a.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(a.providerMetadata),"ai.usage.inputTokens":r.inputTokens,"ai.usage.outputTokens":r.outputTokens,"ai.usage.totalTokens":r.totalTokens,"ai.usage.reasoningTokens":r.reasoningTokens,"ai.usage.cachedInputTokens":r.cachedInputTokens}}))}catch(t){e.error(t)}finally{V.end()}}}),en=function(){let e=[],t=null,r=!1,a=r8(),n=()=>{r=!0,a.resolve(),e.forEach(e=>e.cancel()),e=[],null==t||t.close()},o=async()=>{if(r&&0===e.length){null==t||t.close();return}if(0===e.length)return a=r8(),await a.promise,o();try{let{value:a,done:n}=await e[0].read();n?(e.shift(),0===e.length&&r?null==t||t.close():await o()):null==t||t.enqueue(a)}catch(r){null==t||t.error(r),e.shift(),n()}};return{stream:new ReadableStream({start(e){t=e},pull:o,async cancel(){for(let t of e)await t.cancel();e=[],r=!0}}),addStream:t=>{if(r)throw Error("Cannot add inner stream: outer stream is closed");e.push(t.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),0===e.length&&(null==t||t.close())},terminate:n}}();this.addStream=en.addStream,this.closeStream=en.close;let eo=en.stream.getReader(),ei=new ReadableStream({async start(e){e.enqueue({type:"start"})},async pull(e){function t(){null==O||O({steps:Q}),e.enqueue({type:"abort",...(null==o?void 0:o.reason)!==void 0?{reason:(0,$.e$)(o.reason)}:{}}),e.close()}try{let{done:r,value:a}=await eo.read();if(r){e.close();return}if(null==o?void 0:o.aborted){t();return}e.enqueue(a)}catch(r){(0,M.D_)(r)&&(null==o?void 0:o.aborted)?t():e.error(r)}},cancel:e=>en.stream.cancel(e)});for(let e of f)ei=ei.pipeThrough(e({tools:h,stopStream(){en.terminate()}}));this.baseStream=ei.pipeThrough(function(e){let t,r;let a="",n="",o="";function i({controller:e,partialOutput:a}){e.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:r},partialOutput:a}),n=""}return new TransformStream({async transform(s,l){var u;if("finish-step"===s.type&&n.length>0&&i({controller:l}),"text-delta"!==s.type&&"text-start"!==s.type&&"text-end"!==s.type){l.enqueue({part:s,partialOutput:void 0});return}if(null==t)t=s.id;else if(s.id!==t){l.enqueue({part:s,partialOutput:void 0});return}if("text-start"===s.type){l.enqueue({part:s,partialOutput:void 0});return}if("text-end"===s.type){n.length>0&&i({controller:l}),l.enqueue({part:s,partialOutput:void 0});return}a+=s.text,n+=s.text,r=null!=(u=s.providerMetadata)?u:r;let d=await e.parsePartialOutput({text:a});if(void 0!==d){let e=JSON.stringify(d.partial);e!==o&&(i({controller:l,partialOutput:d.partial}),o=e)}}})}(null!=v?v:rP())).pipeThrough(ea);let{maxRetries:es,retry:el}=function({maxRetries:e,abortSignal:t}){if(null!=e){if(!Number.isInteger(e))throw new eJ({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new eJ({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}let r=null!=e?e:2;return{maxRetries:r,retry:rZ({maxRetries:r,abortSignal:t})}}({maxRetries:n,abortSignal:o}),eu=function({isEnabled:e=!1,tracer:t}={}){return e?t||eL.g.getTracer("ai"):rv}(t),ed=function({maxOutputTokens:e,temperature:t,topP:r,topK:a,presencePenalty:n,frequencyPenalty:o,seed:i,stopSequences:s}){if(null!=e){if(!Number.isInteger(e))throw new eJ({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new eJ({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(null!=t&&"number"!=typeof t)throw new eJ({parameter:"temperature",value:t,message:"temperature must be a number"});if(null!=r&&"number"!=typeof r)throw new eJ({parameter:"topP",value:r,message:"topP must be a number"});if(null!=a&&"number"!=typeof a)throw new eJ({parameter:"topK",value:a,message:"topK must be a number"});if(null!=n&&"number"!=typeof n)throw new eJ({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(null!=o&&"number"!=typeof o)throw new eJ({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(null!=i&&!Number.isInteger(i))throw new eJ({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:a,presencePenalty:n,frequencyPenalty:o,stopSequences:s,seed:i}}(a),ec=function({model:e,settings:t,telemetry:r,headers:a}){var n;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,r])=>{if("timeout"===t){let a=tH(r);null!=a&&(e[`ai.settings.${t}`]=a)}else e[`ai.settings.${t}`]=r;return e},{}),...Object.entries(null!=(n=null==r?void 0:r.metadata)?n:{}).reduce((e,[t,r])=>(e[`ai.telemetry.metadata.${t}`]=r,e),{}),...Object.entries(null!=a?a:{}).reduce((e,[t,r])=>(void 0!==r&&(e[`ai.request.headers.${t}`]=r),e),{})}}({model:e,telemetry:t,headers:r,settings:{...ed,maxRetries:es}}),ep=this,eh={provider:e.provider,modelId:e.modelId},em={functionId:null==t?void 0:t.functionId,metadata:null==t?void 0:t.metadata};rx({name:"ai.streamText",attributes:rI({telemetry:t,attributes:{...rg({operationId:"ai.streamText",telemetry:t}),...ec,"ai.prompt":{input:()=>JSON.stringify({system:d,prompt:c,messages:p})}}}),tracer:eu,endWhenDone:!1,fn:async a=>{V=a;let n=await r_({system:d,prompt:c,messages:p});await tV({event:{model:eh,system:d,prompt:c,messages:p,tools:h,toolChoice:m,activeTools:y,maxOutputTokens:ed.maxOutputTokens,temperature:ed.temperature,topP:ed.topP,topK:ed.topK,presencePenalty:ed.presencePenalty,frequencyPenalty:ed.frequencyPenalty,stopSequences:ed.stopSequences,seed:ed.seed,maxRetries:es,timeout:T,headers:r,providerOptions:b,stopWhen:R,output:v,abortSignal:S,include:q,...em,experimental_context:z},callbacks:[N,B.onStart]});let f=n.messages,x=[],{approvedToolApprovals:Z,deniedToolApprovals:C}=function({messages:e}){let t=e.at(-1);if((null==t?void 0:t.role)!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let r={};for(let t of e)if("assistant"===t.role&&"string"!=typeof t.content)for(let e of t.content)"tool-call"===e.type&&(r[e.toolCallId]=e);let a={};for(let t of e)if("assistant"===t.role&&"string"!=typeof t.content)for(let e of t.content)"tool-approval-request"===e.type&&(a[e.approvalId]=e);let n={};for(let e of t.content)"tool-result"===e.type&&(n[e.toolCallId]=e);let o=[],i=[];for(let e of t.content.filter(e=>"tool-approval-response"===e.type)){let t=a[e.approvalId];if(null==t)throw new e0({approvalId:e.approvalId});if(null!=n[t.toolCallId])continue;let s=r[t.toolCallId];if(null==s)throw new e7({toolCallId:t.toolCallId,approvalId:t.approvalId});let l={approvalRequest:t,approvalResponse:e,toolCall:s};e.approved?o.push(l):i.push(l)}return{approvedToolApprovals:o,deniedToolApprovals:i}}({messages:f});if(C.length>0||Z.length>0){let e;let r=[...Z,...C].filter(e=>e.toolCall.providerExecuted),a=Z.filter(e=>!e.toolCall.providerExecuted),n=C.filter(e=>!e.toolCall.providerExecuted),i=C.filter(e=>e.toolCall.providerExecuted),s=new ReadableStream({start(t){e=t}});ep.addStream(s);try{for(let t of[...n,...i])null==e||e.enqueue({type:"tool-output-denied",toolCallId:t.toolCall.toolCallId,toolName:t.toolCall.toolName});let s=[];if(await Promise.all(a.map(async r=>{let a=await rO({toolCall:r.toolCall,tools:h,tracer:eu,telemetry:t,messages:f,abortSignal:o,experimental_context:z,stepNumber:Q.length,model:eh,onToolCallStart:[j,B.onToolCallStart],onToolCallFinish:[F,B.onToolCallFinish],onPreliminaryToolResult:t=>{null==e||e.enqueue(t)}});null!=a&&(null==e||e.enqueue(a),s.push(a))})),r.length>0&&x.push({role:"tool",content:r.map(e=>({type:"tool-approval-response",approvalId:e.approvalResponse.approvalId,approved:e.approvalResponse.approved,reason:e.approvalResponse.reason,providerExecuted:!0}))}),s.length>0||n.length>0){let e=[];for(let t of s)e.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:await t7({toolCallId:t.toolCallId,input:t.input,tool:null==h?void 0:h[t.toolName],output:"tool-result"===t.type?t.output:t.error,errorMode:"tool-error"===t.type?"text":"none"})});for(let t of n)e.push({type:"tool-result",toolCallId:t.toolCall.toolCallId,toolName:t.toolCall.toolName,output:{type:"execution-denied",reason:t.approvalResponse.reason}});x.push({role:"tool",content:e})}}finally{null==e||e.close()}}async function E({currentStep:a,responseMessages:c,usage:p}){var x,Z,C,O,A,N,$,L,V;let G;let W=ep.includeRawChunks,X=null!=i?setTimeout(()=>s.abort(),i):void 0;function J(){null!=G&&(clearTimeout(G),G=void 0)}function H(){null!=X&&clearTimeout(X)}try{let i,s,X;U=new M.eh;let Y=[...f,...c],et=await (null==w?void 0:w({model:e,steps:Q,stepNumber:Q.length,messages:Y,experimental_context:z})),er=tJ(null!=(x=null==et?void 0:et.model)?x:e),ea={provider:er.provider,modelId:er.modelId},en=await t5({prompt:{system:null!=(Z=null==et?void 0:et.system)?Z:n.system,messages:null!=(C=null==et?void 0:et.messages)?C:Y},supportedUrls:await er.supportedUrls,download:D}),eo=null!=(O=null==et?void 0:et.activeTools)?O:y,{toolChoice:ei,tools:es}=await re({tools:h,toolChoice:null!=(A=null==et?void 0:et.toolChoice)?A:m,activeTools:eo});z=null!=(N=null==et?void 0:et.experimental_context)?N:z;let ef=null!=($=null==et?void 0:et.messages)?$:Y,ey=null!=(L=null==et?void 0:et.system)?L:n.system,e_=rS(b,null==et?void 0:et.providerOptions);await tV({event:{stepNumber:Q.length,model:ea,system:ey,messages:ef,tools:h,toolChoice:ei,activeTools:eo,steps:[...Q],providerOptions:e_,timeout:T,headers:r,stopWhen:R,output:v,abortSignal:S,include:q,...em,experimental_context:z},callbacks:[P,B.onStepStart]});let{result:{stream:eg,response:ev,request:eb},doStreamSpan:ew,startTimestampMs:ex}=await el(()=>rx({name:"ai.streamText.doStream",attributes:rI({telemetry:t,attributes:{...rg({operationId:"ai.streamText.doStream",telemetry:t}),...ec,"ai.model.provider":er.provider,"ai.model.id":er.modelId,"ai.prompt.messages":{input:()=>{var e;return e=en,JSON.stringify(e.map(e=>({...e,content:"string"==typeof e.content?e.content:e.content.map(e=>{var t;return"file"===e.type?{...e,data:e.data instanceof Uint8Array?"string"==typeof(t=e.data)?t:t instanceof ArrayBuffer?(0,M.k0)(new Uint8Array(t)):(0,M.k0)(t):e.data}:e})})))}},"ai.prompt.tools":{input:()=>null==es?void 0:es.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>null!=ei?JSON.stringify(ei):void 0},"gen_ai.system":er.provider,"gen_ai.request.model":er.modelId,"gen_ai.request.frequency_penalty":ed.frequencyPenalty,"gen_ai.request.max_tokens":ed.maxOutputTokens,"gen_ai.request.presence_penalty":ed.presencePenalty,"gen_ai.request.stop_sequences":ed.stopSequences,"gen_ai.request.temperature":ed.temperature,"gen_ai.request.top_k":ed.topK,"gen_ai.request.top_p":ed.topP}}),tracer:eu,endWhenDone:!1,fn:async e=>({startTimestampMs:k(),doStreamSpan:e,result:await er.doStream({...ed,tools:es,toolChoice:ei,responseFormat:await (null==v?void 0:v.responseFormat),prompt:en,providerOptions:e_,abortSignal:o,headers:r,includeRawChunks:W})})})),ek=function({tools:e,generatorStream:t,tracer:r,telemetry:a,system:n,messages:o,abortSignal:i,repairToolCall:s,experimental_context:l,generateId:u,stepNumber:d,model:c,onToolCallStart:p,onToolCallFinish:h}){let m,f=null,y=new ReadableStream({start(e){f=e}}),_=new Set,g=new Map,v=new Map,b=!1;function w(){b&&0===_.size&&(null!=m&&f.enqueue(m),f.close())}let x=new TransformStream({async transform(t,y){let b=t.type;switch(b){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":y.enqueue(t);break;case"file":y.enqueue({type:"file",file:new rN({data:t.data,mediaType:t.mediaType}),...null!=t.providerMetadata?{providerMetadata:t.providerMetadata}:{}});break;case"finish":var x;m={type:"finish",finishReason:t.finishReason.unified,rawFinishReason:t.finishReason.raw,usage:{inputTokens:(x=t.usage).inputTokens.total,inputTokenDetails:{noCacheTokens:x.inputTokens.noCache,cacheReadTokens:x.inputTokens.cacheRead,cacheWriteTokens:x.inputTokens.cacheWrite},outputTokens:x.outputTokens.total,outputTokenDetails:{textTokens:x.outputTokens.text,reasoningTokens:x.outputTokens.reasoning},totalTokens:rR(x.inputTokens.total,x.outputTokens.total),raw:x.raw,reasoningTokens:x.outputTokens.reasoning,cachedInputTokens:x.inputTokens.cacheRead},providerMetadata:t.providerMetadata};break;case"tool-approval-request":{let e=v.get(t.toolCallId);if(null==e){f.enqueue({type:"error",error:new e7({toolCallId:t.toolCallId,approvalId:t.approvalId})});break}y.enqueue({type:"tool-approval-request",approvalId:t.approvalId,toolCall:e});break}case"tool-call":try{let m=await rq({toolCall:t,tools:e,repairToolCall:s,system:n,messages:o});if(v.set(m.toolCallId,m),y.enqueue(m),m.invalid){f.enqueue({type:"tool-error",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,error:(0,M.e$)(m.error),dynamic:!0,title:m.title});break}let b=null==e?void 0:e[m.toolName];if(null==b)break;if(null!=b.onInputAvailable&&await b.onInputAvailable({input:m.input,toolCallId:m.toolCallId,messages:o,abortSignal:i,experimental_context:l}),await rM({tool:b,toolCall:m,messages:o,experimental_context:l})){f.enqueue({type:"tool-approval-request",approvalId:u(),toolCall:m});break}if(g.set(m.toolCallId,m.input),null!=b.execute&&!0!==m.providerExecuted){let t=u();_.add(t),rO({toolCall:m,tools:e,tracer:r,telemetry:a,messages:o,abortSignal:i,experimental_context:l,stepNumber:d,model:c,onToolCallStart:p,onToolCallFinish:h,onPreliminaryToolResult:e=>{f.enqueue(e)}}).then(e=>{f.enqueue(e)}).catch(e=>{f.enqueue({type:"error",error:e})}).finally(()=>{_.delete(t),w()})}}catch(e){f.enqueue({type:"error",error:e})}break;case"tool-result":{let e=t.toolName;t.isError?f.enqueue({type:"tool-error",toolCallId:t.toolCallId,toolName:e,input:g.get(t.toolCallId),providerExecuted:!0,error:t.result,dynamic:t.dynamic}):y.enqueue({type:"tool-result",toolCallId:t.toolCallId,toolName:e,input:g.get(t.toolCallId),output:t.result,providerExecuted:!0,dynamic:t.dynamic});break}default:throw Error(`Unhandled chunk type: ${b}`)}},flush(){b=!0,w()}});return new ReadableStream({start:async e=>Promise.all([t.pipeThrough(x).pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){}})),y.pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){e.close()}}))])})}({tools:h,generatorStream:eg,tracer:eu,telemetry:t,system:d,messages:Y,repairToolCall:_,abortSignal:o,experimental_context:z,generateId:I,stepNumber:Q.length,model:ea,onToolCallStart:[j,B.onToolCallStart],onToolCallFinish:[F,B.onToolCallFinish]}),eI=null==(V=null==q?void 0:q.requestBody)||V?null!=eb?eb:{}:{...eb,body:void 0},eT=[],eR=[],eS={},eZ="other",eC=rT(),eE=!0,eO={id:I(),timestamp:new Date,modelId:eh.modelId},eA="";ep.addStream(ek.pipeThrough(new TransformStream({async transform(e,t){var r,a,n,d,c;if(null!=l&&(null!=G&&clearTimeout(G),G=setTimeout(()=>u.abort(),l)),"stream-start"===e.type){i=e.warnings;return}if(eE){let e=k()-ex;eE=!1,ew.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":e}),ew.setAttributes({"ai.response.msToFirstChunk":e}),t.enqueue({type:"start-step",request:eI,warnings:null!=i?i:[]})}let p=e.type;switch(p){case"tool-approval-request":case"text-start":case"text-end":case"reasoning-start":case"reasoning-end":case"file":case"source":t.enqueue(e);break;case"text-delta":e.delta.length>0&&(t.enqueue({type:"text-delta",id:e.id,text:e.delta,providerMetadata:e.providerMetadata}),eA+=e.delta);break;case"reasoning-delta":t.enqueue({type:"reasoning-delta",id:e.id,text:e.delta,providerMetadata:e.providerMetadata});break;case"tool-call":t.enqueue(e),eT.push(e);break;case"tool-result":t.enqueue(e),e.preliminary||eR.push(e);break;case"tool-error":t.enqueue(e),eR.push(e);break;case"response-metadata":eO={id:null!=(r=e.id)?r:eO.id,timestamp:null!=(a=e.timestamp)?a:eO.timestamp,modelId:null!=(n=e.modelId)?n:eO.modelId};break;case"finish":{eC=e.usage,eZ=e.finishReason,X=e.rawFinishReason,s=e.providerMetadata;let t=k()-ex;ew.addEvent("ai.stream.finish"),ew.setAttributes({"ai.response.msToFinish":t,"ai.response.avgOutputTokensPerSecond":1e3*(null!=(d=eC.outputTokens)?d:0)/t});break}case"tool-input-start":{eS[e.id]=e.toolName;let r=null==h?void 0:h[e.toolName];(null==r?void 0:r.onInputStart)!=null&&await r.onInputStart({toolCallId:e.id,messages:Y,abortSignal:o,experimental_context:z}),t.enqueue({...e,dynamic:null!=(c=e.dynamic)?c:(null==r?void 0:r.type)==="dynamic",title:null==r?void 0:r.title});break}case"tool-input-end":delete eS[e.id],t.enqueue(e);break;case"tool-input-delta":{let r=eS[e.id],a=null==h?void 0:h[r];(null==a?void 0:a.onInputDelta)!=null&&await a.onInputDelta({inputTextDelta:e.delta,toolCallId:e.id,messages:Y,abortSignal:o,experimental_context:z}),t.enqueue(e);break}case"error":t.enqueue(e),eZ="error";break;case"raw":W&&t.enqueue(e);break;default:throw Error(`Unknown chunk type: ${p}`)}},async flush(e){var r,n,o,i,l,u,d,m,f,y,_,v;let b=eT.length>0?JSON.stringify(eT):void 0;try{ew.setAttributes(await rI({telemetry:t,attributes:{"ai.response.finishReason":eZ,"ai.response.text":{output:()=>eA},"ai.response.reasoning":{output:()=>{let e=K.filter(e=>"reasoning"===e.type);return e.length>0?e.map(e=>e.text).join("\n"):void 0}},"ai.response.toolCalls":{output:()=>b},"ai.response.id":eO.id,"ai.response.model":eO.modelId,"ai.response.timestamp":eO.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(s),"ai.usage.inputTokens":eC.inputTokens,"ai.usage.outputTokens":eC.outputTokens,"ai.usage.totalTokens":eC.totalTokens,"ai.usage.reasoningTokens":eC.reasoningTokens,"ai.usage.cachedInputTokens":eC.cachedInputTokens,"gen_ai.response.finish_reasons":[eZ],"gen_ai.response.id":eO.id,"gen_ai.response.model":eO.modelId,"gen_ai.usage.input_tokens":eC.inputTokens,"gen_ai.usage.output_tokens":eC.outputTokens}}))}catch(e){}finally{ew.end()}e.enqueue({type:"finish-step",finishReason:eZ,rawFinishReason:X,usage:eC,providerMetadata:s,response:{...eO,headers:null==ev?void 0:ev.headers}});let w=(r=p,n=eC,{inputTokens:rR(r.inputTokens,n.inputTokens),inputTokenDetails:{noCacheTokens:rR(null==(o=r.inputTokenDetails)?void 0:o.noCacheTokens,null==(i=n.inputTokenDetails)?void 0:i.noCacheTokens),cacheReadTokens:rR(null==(l=r.inputTokenDetails)?void 0:l.cacheReadTokens,null==(u=n.inputTokenDetails)?void 0:u.cacheReadTokens),cacheWriteTokens:rR(null==(d=r.inputTokenDetails)?void 0:d.cacheWriteTokens,null==(m=n.inputTokenDetails)?void 0:m.cacheWriteTokens)},outputTokens:rR(r.outputTokens,n.outputTokens),outputTokenDetails:{textTokens:rR(null==(f=r.outputTokenDetails)?void 0:f.textTokens,null==(y=n.outputTokenDetails)?void 0:y.textTokens),reasoningTokens:rR(null==(_=r.outputTokenDetails)?void 0:_.reasoningTokens,null==(v=n.outputTokenDetails)?void 0:v.reasoningTokens)},totalTokens:rR(r.totalTokens,n.totalTokens),reasoningTokens:rR(r.reasoningTokens,n.reasoningTokens),cachedInputTokens:rR(r.cachedInputTokens,n.cachedInputTokens)});await U.promise;let x=eT.filter(e=>!0!==e.providerExecuted),k=eR.filter(e=>!0!==e.providerExecuted);for(let e of eT){if(!0!==e.providerExecuted)continue;let t=null==h?void 0:h[e.toolName];(null==t?void 0:t.type)==="provider"&&t.supportsDeferredResults&&!eR.some(t=>("tool-result"===t.type||"tool-error"===t.type)&&t.toolCallId===e.toolCallId)&&ee.set(e.toolCallId,{toolName:e.toolName})}for(let e of eR)("tool-result"===e.type||"tool-error"===e.type)&&ee.delete(e.toolCallId);if(H(),J(),(x.length>0&&k.length===x.length||ee.size>0)&&!await rW({stopConditions:g,steps:Q})){c.push(...await rX({content:Q[Q.length-1].content,tools:h}));try{await E({currentStep:a+1,responseMessages:c,usage:w})}catch(t){e.enqueue({type:"error",error:t}),ep.closeStream()}}else e.enqueue({type:"finish",finishReason:eZ,rawFinishReason:X,totalUsage:w}),ep.closeStream()}})))}finally{H(),J()}}J.push(...x),await E({currentStep:0,responseMessages:x,usage:rT()})}}).catch(e=>{ep.addStream(new ReadableStream({start(t){t.enqueue({type:"error",error:e}),t.close()}})),ep.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return r3(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){"text-delta"===e.type&&t.enqueue(e.text)}})))}get fullStream(){return r3(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await r7({stream:this.fullStream,onError:null==e?void 0:e.onError})}catch(r){null==(t=null==e?void 0:e.onError)||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return r3(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){null!=e&&t.enqueue(e)}})))}get elementStream(){var e,t,r;let a=null==(e=this.outputSpecification)?void 0:e.createElementStreamTransform();if(null==a)throw new $.A_({functionality:`element streams in ${null!=(r=null==(t=this.outputSpecification)?void 0:t.name)?r:"text"} mode`});return r3(this.teeStream().pipeThrough(a))}get output(){return this.finalStep.then(e=>{var t;return(null!=(t=this.outputSpecification)?t:rP()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:o=!1,sendStart:i=!0,sendFinish:s=!0,onError:l=$.e$}={}){let u=null!=t?function({originalMessages:e,responseMessageId:t}){if(null==e)return;let r=e[e.length-1];return(null==r?void 0:r.role)==="assistant"?r.id:"function"==typeof t?t():t}({originalMessages:e,responseMessageId:t}):void 0,d=e=>{var t;let r=null==(t=this.tools)?void 0:t[e.toolName];return null==r?e.dynamic:(null==r?void 0:r.type)==="dynamic"||void 0};return r3(function({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:a,onError:n,stream:o}){let i=null==t?void 0:t[t.length-1];(null==i?void 0:i.role)!=="assistant"?i=void 0:e=i.id;let s=!1,l=o.pipeThrough(new TransformStream({transform(t,r){"start"===t.type&&null==t.messageId&&null!=e&&(t.messageId=e),"abort"===t.type&&(s=!0),r.enqueue(t)}}));if(null==a&&null==r)return l;let u=function({lastMessage:e,messageId:t}){return{message:(null==e?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}({lastMessage:i?structuredClone(i):void 0,messageId:null!=e?e:""}),d=!1,c=async()=>{if(d||!a)return;d=!0;let e=u.message.id===(null==i?void 0:i.id);await a({isAborted:s,isContinuation:e,responseMessage:u.message,messages:[...e?t.slice(0,-1):t,u.message],finishReason:u.finishReason})},p=async()=>{if(!r)return;let e=u.message.id===(null==i?void 0:i.id);try{await r({isContinuation:e,responseMessage:structuredClone(u.message),messages:[...e?t.slice(0,-1):t,structuredClone(u.message)]})}catch(e){n(e)}};return(function({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(e,s){await a(async({state:a,write:l})=>{var u,d,c,p;function h(e){let t=a.message.parts.filter(r9).find(t=>t.toolCallId===e);if(null==t)throw new tS({chunkType:"tool-invocation",chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function m(e){var t;let r=a.message.parts.find(t=>r2(t)&&t.toolCallId===e.toolCallId);null!=r?(r.state=e.state,r.input=e.input,r.output=e.output,r.errorText=e.errorText,r.rawInput=e.rawInput,r.preliminary=e.preliminary,void 0!==e.title&&(r.title=e.title),r.providerExecuted=null!=(t=e.providerExecuted)?t:r.providerExecuted,null!=e.providerMetadata&&(r.callProviderMetadata=e.providerMetadata)):a.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,input:e.input,output:e.output,rawInput:e.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,preliminary:e.preliminary,...null!=e.providerMetadata?{callProviderMetadata:e.providerMetadata}:{}})}function f(e){var t,r;let n=a.message.parts.find(t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId);null!=n?(n.state=e.state,n.toolName=e.toolName,n.input=e.input,n.output=e.output,n.errorText=e.errorText,n.rawInput=null!=(t=e.rawInput)?t:n.rawInput,n.preliminary=e.preliminary,void 0!==e.title&&(n.title=e.title),n.providerExecuted=null!=(r=e.providerExecuted)?r:n.providerExecuted,null!=e.providerMetadata&&(n.callProviderMetadata=e.providerMetadata)):a.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:e.input,output:e.output,errorText:e.errorText,preliminary:e.preliminary,providerExecuted:e.providerExecuted,title:e.title,...null!=e.providerMetadata?{callProviderMetadata:e.providerMetadata}:{}})}async function y(e){if(null!=e){let r=null!=a.message.metadata?rS(a.message.metadata,e):e;null!=t&&await (0,M.rJ)({value:r,schema:t,context:{field:"message.metadata",entityId:a.message.id}}),a.message.metadata=r}}switch(e.type){case"text-start":{let t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};a.activeTextParts[e.id]=t,a.message.parts.push(t),l();break}case"text-delta":{let t=a.activeTextParts[e.id];if(null==t)throw new tS({chunkType:"text-delta",chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=null!=(u=e.providerMetadata)?u:t.providerMetadata,l();break}case"text-end":{let t=a.activeTextParts[e.id];if(null==t)throw new tS({chunkType:"text-end",chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state="done",t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,delete a.activeTextParts[e.id],l();break}case"reasoning-start":{let t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};a.activeReasoningParts[e.id]=t,a.message.parts.push(t),l();break}case"reasoning-delta":{let t=a.activeReasoningParts[e.id];if(null==t)throw new tS({chunkType:"reasoning-delta",chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,l();break}case"reasoning-end":{let t=a.activeReasoningParts[e.id];if(null==t)throw new tS({chunkType:"reasoning-end",chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete a.activeReasoningParts[e.id],l();break}case"file":a.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}),l();break;case"source-url":a.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),l();break;case"source-document":a.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),l();break;case"tool-input-start":{let t=a.message.parts.filter(r2);a.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title},e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}):m({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}),l();break}case"tool-input-delta":{let t=a.partialToolCalls[e.toolCallId];if(null==t)throw new tS({chunkType:"tool-input-delta",chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:r}=await r$(t.text);t.dynamic?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:r,title:t.title}):m({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:r,title:t.title}),l();break}case"tool-input-available":e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}):m({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}),l(),o&&!e.providerExecuted&&await o({toolCall:e});break;case"tool-input-error":{let t=a.message.parts.filter(r9).find(t=>t.toolCallId===e.toolCallId);(null!=t?"dynamic-tool"===t.type:e.dynamic)?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}):m({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),l();break}case"tool-approval-request":{let t=h(e.toolCallId);t.state="approval-requested",t.approval={id:e.approvalId},l();break}case"tool-output-denied":h(e.toolCallId).state="output-denied",l();break;case"tool-output-available":{let t=h(e.toolCallId);"dynamic-tool"===t.type?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,title:t.title}):m({toolCallId:e.toolCallId,toolName:r5(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,title:t.title}),l();break}case"tool-output-error":{let t=h(e.toolCallId);"dynamic-tool"===t.type?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,title:t.title}):m({toolCallId:e.toolCallId,toolName:r5(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,title:t.title}),l();break}case"start-step":a.message.parts.push({type:"step-start"});break;case"finish-step":a.activeTextParts={},a.activeReasoningParts={};break;case"start":null!=e.messageId&&(a.message.id=e.messageId),await y(e.messageMetadata),(null!=e.messageId||null!=e.messageMetadata)&&l();break;case"finish":null!=e.finishReason&&(a.finishReason=e.finishReason),await y(e.messageMetadata),null!=e.messageMetadata&&l();break;case"message-metadata":await y(e.messageMetadata),null!=e.messageMetadata&&l();break;case"error":null==n||n(Error(e.errorText));break;default:if(e.type.startsWith("data-")){if((null==r?void 0:r[e.type])!=null){let t=a.message.parts.findIndex(t=>"id"in t&&"data"in t&&t.id===e.id&&t.type===e.type),n=t>=0?t:a.message.parts.length;await (0,M.rJ)({value:e.data,schema:r[e.type],context:{field:`message.parts[${n}].data`,entityName:e.type,entityId:e.id}})}if(e.transient){null==i||i(e);break}let t=null!=e.id?a.message.parts.find(t=>e.type===t.type&&e.id===t.id):void 0;null!=t?t.data=e.data:a.message.parts.push(e),null==i||i(e),l()}}s.enqueue(e)})}}))})({stream:l,runUpdateMessageJob:async e=>{await e({state:u,write:()=>{}})},onError:n}).pipeThrough(new TransformStream({async transform(e,t){"finish-step"===e.type&&await p(),t.enqueue(e)},async cancel(){await c()},async flush(){await c()}}))}({stream:this.fullStream.pipeThrough(new TransformStream({transform:async(e,t)=>{let r=null==a?void 0:a({part:e}),c=e.type;switch(c){case"text-start":t.enqueue({type:"text-start",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"text-delta":t.enqueue({type:"text-delta",id:e.id,delta:e.text,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"text-end":t.enqueue({type:"text-end",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"reasoning-start":t.enqueue({type:"reasoning-start",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"reasoning-delta":n&&t.enqueue({type:"reasoning-delta",id:e.id,delta:e.text,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"reasoning-end":t.enqueue({type:"reasoning-end",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"file":t.enqueue({type:"file",mediaType:e.file.mediaType,url:`data:${e.file.mediaType};base64,${e.file.base64}`,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"source":o&&"url"===e.sourceType&&t.enqueue({type:"source-url",sourceId:e.id,url:e.url,title:e.title,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}),o&&"document"===e.sourceType&&t.enqueue({type:"source-document",sourceId:e.id,mediaType:e.mediaType,title:e.title,filename:e.filename,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"tool-input-start":{let r=d(e);t.enqueue({type:"tool-input-start",toolCallId:e.id,toolName:e.toolName,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{},...null!=r?{dynamic:r}:{},...null!=e.title?{title:e.title}:{}});break}case"tool-input-delta":t.enqueue({type:"tool-input-delta",toolCallId:e.id,inputTextDelta:e.delta});break;case"tool-call":{let r=d(e);e.invalid?t.enqueue({type:"tool-input-error",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{},...null!=r?{dynamic:r}:{},errorText:l(e.error),...null!=e.title?{title:e.title}:{}}):t.enqueue({type:"tool-input-available",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{},...null!=r?{dynamic:r}:{},...null!=e.title?{title:e.title}:{}});break}case"tool-approval-request":t.enqueue({type:"tool-approval-request",approvalId:e.approvalId,toolCallId:e.toolCall.toolCallId});break;case"tool-result":{let r=d(e);t.enqueue({type:"tool-output-available",toolCallId:e.toolCallId,output:e.output,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.preliminary?{preliminary:e.preliminary}:{},...null!=r?{dynamic:r}:{}});break}case"tool-error":{let r=d(e);t.enqueue({type:"tool-output-error",toolCallId:e.toolCallId,errorText:l(e.error),...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=r?{dynamic:r}:{}});break}case"tool-output-denied":t.enqueue({type:"tool-output-denied",toolCallId:e.toolCallId});break;case"error":t.enqueue({type:"error",errorText:l(e.error)});break;case"start-step":t.enqueue({type:"start-step"});break;case"finish-step":t.enqueue({type:"finish-step"});break;case"start":i&&t.enqueue({type:"start",...null!=r?{messageMetadata:r}:{},...null!=u?{messageId:u}:{}});break;case"finish":s&&t.enqueue({type:"finish",finishReason:e.finishReason,...null!=r?{messageMetadata:r}:{}});break;case"abort":t.enqueue(e);break;case"tool-input-end":case"raw":break;default:throw Error(`Unknown chunk type: ${c}`)}null!=r&&"start"!==c&&"finish"!==c&&t.enqueue({type:"message-metadata",messageMetadata:r})}})),messageId:null!=u?u:null==t?void 0:t(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:o,sendSources:i,sendFinish:s,sendStart:l,onError:u,...d}={}){(function({response:e,status:t,statusText:r,headers:a,stream:n,consumeSseStream:o}){let i=n.pipeThrough(new rJ);if(o){let[e,t]=i.tee();i=e,o({stream:t})}rK({response:e,status:t,statusText:r,headers:Object.fromEntries(rB(a,rH).entries()),stream:i.pipeThrough(new TextEncoderStream)})})({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:o,sendSources:i,sendFinish:s,sendStart:l,onError:u}),...d})}pipeTextStreamToResponse(e,t){(function({response:e,status:t,statusText:r,headers:a,textStream:n}){rK({response:e,status:t,statusText:r,headers:Object.fromEntries(rB(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})})({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:o,sendFinish:i,sendStart:s,onError:l,...u}={}){return function({status:e,statusText:t,headers:r,stream:a,consumeSseStream:n}){let o=a.pipeThrough(new rJ);if(n){let[e,t]=o.tee();o=e,n({stream:t})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:rB(r,rH)})}({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:o,sendFinish:i,sendStart:s,onError:l}),...u})}toTextStreamResponse(e){return function({status:e,statusText:t,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:null!=e?e:200,statusText:t,headers:rB(r,{"content-type":"text/plain; charset=utf-8"})})}({textStream:this.textStream,...e})}};async function aa(e,t){let r=[];for(let n of((null==t?void 0:t.ignoreIncompleteToolCalls)&&(e=e.map(e=>({...e,parts:e.parts.filter(e=>!r9(e)||"input-streaming"!==e.state&&"input-available"!==e.state)}))),e))switch(n.role){case"system":{let e=n.parts.filter(e=>"text"===e.type),t=e.reduce((e,t)=>null!=t.providerMetadata?{...e,...t.providerMetadata}:e,{});r.push({role:"system",content:e.map(e=>e.text).join(""),...Object.keys(t).length>0?{providerOptions:t}:{}});break}case"user":r.push({role:"user",content:n.parts.map(e=>{var r;return rQ(e)?{type:"text",text:e.text,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}}:r0(e)?{type:"file",mediaType:e.mediaType,filename:e.filename,data:e.url,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}}:rY(e)?null==(r=null==t?void 0:t.convertDataPart)?void 0:r.call(t,e):void 0}).filter(M.C_)});break;case"assistant":if(null!=n.parts){let e=[];async function a(){var a,n,o,i,s,l;if(0===e.length)return;let u=[];for(let r of e)if(rQ(r))u.push({type:"text",text:r.text,...null!=r.providerMetadata?{providerOptions:r.providerMetadata}:{}});else if(r0(r))u.push({type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...null!=r.providerMetadata?{providerOptions:r.providerMetadata}:{}});else if(r1(r))u.push({type:"reasoning",text:r.text,providerOptions:r.providerMetadata});else if(r9(r)){let e=r6(r);"input-streaming"!==r.state&&(u.push({type:"tool-call",toolCallId:r.toolCallId,toolName:e,input:"output-error"===r.state?null!=(a=r.input)?a:"rawInput"in r?r.rawInput:void 0:r.input,providerExecuted:r.providerExecuted,...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}}),null!=r.approval&&u.push({type:"tool-approval-request",approvalId:r.approval.id,toolCallId:r.toolCallId}),!0===r.providerExecuted&&"approval-responded"!==r.state&&("output-available"===r.state||"output-error"===r.state)&&u.push({type:"tool-result",toolCallId:r.toolCallId,toolName:e,output:await t7({toolCallId:r.toolCallId,input:r.input,output:"output-error"===r.state?r.errorText:r.output,tool:null==(n=null==t?void 0:t.tools)?void 0:n[e],errorMode:"output-error"===r.state?"json":"none"}),...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}}))}else if(rY(r)){let e=null==(o=null==t?void 0:t.convertDataPart)?void 0:o.call(t,r);null!=e&&u.push(e)}else throw Error(`Unsupported part: ${r}`);r.push({role:"assistant",content:u});let d=e.filter(e=>{var t;return r9(e)&&(!0!==e.providerExecuted||(null==(t=e.approval)?void 0:t.approved)!=null)});if(d.length>0){let e=[];for(let r of d)if((null==(i=r.approval)?void 0:i.approved)!=null&&e.push({type:"tool-approval-response",approvalId:r.approval.id,approved:r.approval.approved,reason:r.approval.reason,providerExecuted:r.providerExecuted}),!0!==r.providerExecuted)switch(r.state){case"output-denied":e.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r6(r),output:{type:"error-text",value:null!=(s=r.approval.reason)?s:"Tool execution denied."},...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}});break;case"output-error":case"output-available":{let a=r6(r);e.push({type:"tool-result",toolCallId:r.toolCallId,toolName:a,output:await t7({toolCallId:r.toolCallId,input:r.input,output:"output-error"===r.state?r.errorText:r.output,tool:null==(l=null==t?void 0:t.tools)?void 0:l[a],errorMode:"output-error"===r.state?"text":"none"}),...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}})}}e.length>0&&r.push({role:"tool",content:e})}e=[]}for(let t of n.parts)rQ(t)||r1(t)||r0(t)||r9(t)||rY(t)?e.push(t):"step-start"===t.type&&await a();await a()}break;default:{let e=n.role;throw new tF({originalMessage:n,message:`Unsupported role: ${e}`})}}return r}var an=(0,M.DG)(()=>(0,M.r0)(P.IX(P.Ry({id:P.Z_(),role:P.Km(["system","user","assistant"]),metadata:P._4().optional(),parts:P.IX(P.G0([P.Ry({type:P.i0("text"),text:P.Z_(),state:P.Km(["streaming","done"]).optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("reasoning"),text:P.Z_(),state:P.Km(["streaming","done"]).optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("source-url"),sourceId:P.Z_(),url:P.Z_(),title:P.Z_().optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("source-document"),sourceId:P.Z_(),mediaType:P.Z_(),title:P.Z_(),filename:P.Z_().optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("file"),mediaType:P.Z_(),filename:P.Z_().optional(),url:P.Z_(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("step-start")}),P.Ry({type:P.Z_().startsWith("data-"),id:P.Z_().optional(),data:P._4()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("input-streaming"),input:P._4().optional(),providerExecuted:P.O7().optional(),callProviderMetadata:rr.optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),approval:P.Fi().optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("input-available"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Fi().optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("approval-requested"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.Fi().optional(),reason:P.Fi().optional()})}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("approval-responded"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.O7(),reason:P.Z_().optional()})}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("output-available"),input:P._4(),providerExecuted:P.O7().optional(),output:P._4(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),preliminary:P.O7().optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("output-error"),input:P._4(),rawInput:P._4().optional(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Z_(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("output-denied"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!1),reason:P.Z_().optional()})}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("input-streaming"),providerExecuted:P.O7().optional(),callProviderMetadata:rr.optional(),input:P._4().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),approval:P.Fi().optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("input-available"),providerExecuted:P.O7().optional(),input:P._4(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Fi().optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("approval-requested"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.Fi().optional(),reason:P.Fi().optional()})}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("approval-responded"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.O7(),reason:P.Z_().optional()})}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("output-available"),providerExecuted:P.O7().optional(),input:P._4(),output:P._4(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),preliminary:P.O7().optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("output-error"),providerExecuted:P.O7().optional(),input:P._4(),rawInput:P._4().optional(),output:P.Fi().optional(),errorText:P.Z_(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("output-denied"),providerExecuted:P.O7().optional(),input:P._4(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!1),reason:P.Z_().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function ao({messages:e,metadataSchema:t,dataSchemas:r,tools:a}){try{if(null==e)return{success:!1,error:new eJ({parameter:"messages",value:e,message:"messages parameter must be provided"})};let n=await validateTypes2({value:e,schema:an});if(t)for(let[e,r]of n.entries())await validateTypes2({value:r.metadata,schema:t,context:{field:`messages[${e}].metadata`,entityId:r.id}});if(r||a)for(let[e,t]of n.entries())for(let[n,o]of t.parts.entries()){if(r&&o.type.startsWith("data-")){let t=o.type.slice(5),a=r[t];if(!a)return{success:!1,error:new TypeValidationError3({value:o.data,cause:`No data schema found for data part ${t}`,context:{field:`messages[${e}].parts[${n}].data`,entityName:t,entityId:o.id}})};await validateTypes2({value:o.data,schema:a,context:{field:`messages[${e}].parts[${n}].data`,entityName:t,entityId:o.id}})}if(a&&o.type.startsWith("tool-")){let t=o.type.slice(5),r=a[t];if(!r)return{success:!1,error:new TypeValidationError3({value:o.input,cause:`No tool schema found for tool part ${t}`,context:{field:`messages[${e}].parts[${n}].input`,entityName:t,entityId:o.toolCallId}})};("input-available"===o.state||"output-available"===o.state||"output-error"===o.state&&void 0!==o.input)&&await validateTypes2({value:o.input,schema:r.inputSchema,context:{field:`messages[${e}].parts[${n}].input`,entityName:t,entityId:o.toolCallId}}),"output-available"===o.state&&r.outputSchema&&await validateTypes2({value:o.output,schema:r.outputSchema,context:{field:`messages[${e}].parts[${n}].output`,entityName:t,entityId:o.toolCallId}})}}return{success:!0,data:n}}catch(e){return{success:!1,error:e}}}async function ai(e,t,r){let a=await safeParseJSON4({text:e});if(!a.success)throw new ts({message:"No object generated: could not parse the response.",cause:a.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let n=await t.validateFinalResult(a.value,{text:e,response:r.response,usage:r.usage});if(!n.success)throw new ts({message:"No object generated: response did not match schema.",cause:n.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});return n.value}function as(e){return({url:t,abortSignal:r})=>t1({url:t,maxBytes:null==e?void 0:e.maxBytes,abortSignal:r})}(0,M.bF)({prefix:"aiobj",size:24}),(0,M.bF)({prefix:"aiobj",size:24}),as();var al=({model:e,middleware:{transformParams:t,wrapGenerate:r,wrapStream:a,overrideProvider:n,overrideModelId:o,overrideSupportedUrls:i},modelId:s,providerId:l})=>{var u,d,c;async function p({params:r,type:a}){return t?await t({params:r,type:a,model:e}):r}return{specificationVersion:"v3",provider:null!=(u=null!=l?l:null==n?void 0:n({model:e}))?u:e.provider,modelId:null!=(d=null!=s?s:null==o?void 0:o({model:e}))?d:e.modelId,supportedUrls:null!=(c=null==i?void 0:i({model:e}))?c:e.supportedUrls,async doGenerate(t){let a=await p({params:t,type:"generate"}),n=async()=>e.doGenerate(a),o=async()=>e.doStream(a);return r?r({doGenerate:n,doStream:o,params:a,model:e}):n()},async doStream(t){let r=await p({params:t,type:"stream"}),n=async()=>e.doGenerate(r),o=async()=>e.doStream(r);return a?a({doGenerate:n,doStream:o,params:r,model:e}):o()}}},au=({model:e,middleware:{transformParams:t,wrapGenerate:r,overrideProvider:a,overrideModelId:n,overrideMaxImagesPerCall:o},modelId:i,providerId:s})=>{var l,u,d;async function c({params:r}){return t?await t({params:r,model:e}):r}let p=null!=(l=null==o?void 0:o({model:e}))?l:e.maxImagesPerCall,h=p instanceof Function?p.bind(e):p;return{specificationVersion:"v3",provider:null!=(u=null!=s?s:null==a?void 0:a({model:e}))?u:e.provider,modelId:null!=(d=null!=i?i:null==n?void 0:n({model:e}))?d:e.modelId,maxImagesPerCall:h,async doGenerate(t){let a=await c({params:t}),n=async()=>e.doGenerate(a);return r?r({doGenerate:n,params:a,model:e}):n()}}},ad="AI_NoSuchProviderError",ac=`vercel.ai.error.${ad}`,ap=Symbol.for(ac);$.JJ,N=ap,as()},9763:(e,t,r)=>{var a,n,o,i;let s;r.d(t,{pA:()=>i,IX:()=>eE,VK:()=>eN,Km:()=>e$,i0:()=>eM,Rx:()=>eC,Ry:()=>eO,Z_:()=>eZ,G0:()=>eA}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(let e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(a||(a={})),(n||(n={})).mergeShapes=(e,t)=>({...e,...t});let l=a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),u=e=>{switch(typeof e){case"undefined":return l.undefined;case"string":return l.string;case"number":return Number.isNaN(e)?l.nan:l.number;case"boolean":return l.boolean;case"function":return l.function;case"bigint":return l.bigint;case"symbol":return l.symbol;case"object":if(Array.isArray(e))return l.array;if(null===e)return l.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return l.promise;if("undefined"!=typeof Map&&e instanceof Map)return l.map;if("undefined"!=typeof Set&&e instanceof Set)return l.set;if("undefined"!=typeof Date&&e instanceof Date)return l.date;return l.object;default:return l.unknown}},d=a.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 c extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,a=0;for(;a<n.path.length;){let r=n.path[a];a===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof c))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t={},r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);let p=(e,t)=>{let r;switch(e.code){case d.invalid_type:r=e.received===l.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,a.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${a.joinValues(e.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${a.joinValues(e.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${a.joinValues(e.options)}, received '${e.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:a.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case d.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case d.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=t.defaultError,a.assertNever(e)}return{message:r}};!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(o||(o={}));let h=e=>{let{data:t,path:r,errorMaps:a,issueData:n}=e,o=[...r,...n.path||[]],i={...n,path:o};if(void 0!==n.message)return{...n,path:o,message:n.message};let s="";for(let e of a.filter(e=>!!e).slice().reverse())s=e(i,{data:t,defaultError:s}).message;return{...n,path:o,message:s}};function m(e,t){let r=h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,p,p==p?void 0:p].filter(e=>!!e)});e.common.issues.push(r)}class f{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return y;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return f.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:n}=a;if("aborted"===t.status||"aborted"===n.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==n.value||a.alwaysSet)&&(r[t.value]=n.value)}return{status:e.value,value:r}}}let y=Object.freeze({status:"aborted"}),_=e=>({status:"dirty",value:e}),g=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,b=e=>"dirty"===e.status,w=e=>"valid"===e.status,x=e=>"undefined"!=typeof Promise&&e instanceof Promise;class k{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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}}let I=(e,t)=>{if(w(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new c(e.common.issues);return this._error=t,this._error}}};function T(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:n}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{let{message:o}=e;return"invalid_enum_value"===t.code?{message:o??n.defaultError}:void 0===n.data?{message:o??a??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:o??r??n.defaultError}},description:n}}class R{get description(){return this._def.description}_getType(e){return u(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:u(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new f,ctx:{common:e.parent.common,data:e.data,parsedType:u(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(x(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:u(e)},a=this._parseSync({data:e,path:r.path,parent:r});return I(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:u(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return w(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>w(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:u(e)},a=this._parse({data:e,path:r.path,parent:r});return I(r,await (x(a)?a:Promise.resolve(a)))}refine(e,t){let r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{let n=e(t),o=()=>a.addIssue({code:d.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(o(),!1)):!!n||(o(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new ev({schema:this,typeName:i.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:e=>this["~validate"](e)}}optional(){return eb.create(this,this._def)}nullable(){return ew.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return er.create(this)}promise(){return eg.create(this,this._def)}or(e){return en.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new ev({...T(this._def),schema:this,typeName:i.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new ex({...T(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:i.ZodDefault})}brand(){return new eT({typeName:i.ZodBranded,type:this,...T(this._def)})}catch(e){return new ek({...T(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:i.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eR.create(this,e)}readonly(){return eS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let S=/^c[^\s-]{8,}$/i,Z=/^[0-9a-z]+$/,C=/^[0-9A-HJKMNP-TV-Z]{26}$/i,E=/^[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,O=/^[a-z0-9_-]{21}$/i,A=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N=/^[-+]?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)?)??$/,M=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$=/^(?:(?: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])$/,P=/^(?:(?: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])$/,j=/^(([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]))$/,F=/^(([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])$/,z=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,D=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,q="((\\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])))",U=RegExp(`^${q}$`);function L(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class V extends R{_parse(e){var t,r,n,o;let i;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==l.string){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.string,received:t.parsedType}),y}let u=new f;for(let l of this._def.checks)if("min"===l.kind)e.data.length<l.value&&(m(i=this._getOrReturnCtx(e,i),{code:d.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),u.dirty());else if("max"===l.kind)e.data.length>l.value&&(m(i=this._getOrReturnCtx(e,i),{code:d.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),u.dirty());else if("length"===l.kind){let t=e.data.length>l.value,r=e.data.length<l.value;(t||r)&&(i=this._getOrReturnCtx(e,i),t?m(i,{code:d.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):r&&m(i,{code:d.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),u.dirty())}else if("email"===l.kind)M.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"email",code:d.invalid_string,message:l.message}),u.dirty());else if("emoji"===l.kind)s||(s=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),s.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"emoji",code:d.invalid_string,message:l.message}),u.dirty());else if("uuid"===l.kind)E.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"uuid",code:d.invalid_string,message:l.message}),u.dirty());else if("nanoid"===l.kind)O.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"nanoid",code:d.invalid_string,message:l.message}),u.dirty());else if("cuid"===l.kind)S.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"cuid",code:d.invalid_string,message:l.message}),u.dirty());else if("cuid2"===l.kind)Z.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"cuid2",code:d.invalid_string,message:l.message}),u.dirty());else if("ulid"===l.kind)C.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"ulid",code:d.invalid_string,message:l.message}),u.dirty());else if("url"===l.kind)try{new URL(e.data)}catch{m(i=this._getOrReturnCtx(e,i),{validation:"url",code:d.invalid_string,message:l.message}),u.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"regex",code:d.invalid_string,message:l.message}),u.dirty())):"trim"===l.kind?e.data=e.data.trim():"includes"===l.kind?e.data.includes(l.value,l.position)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),u.dirty()):"toLowerCase"===l.kind?e.data=e.data.toLowerCase():"toUpperCase"===l.kind?e.data=e.data.toUpperCase():"startsWith"===l.kind?e.data.startsWith(l.value)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:{startsWith:l.value},message:l.message}),u.dirty()):"endsWith"===l.kind?e.data.endsWith(l.value)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:{endsWith:l.value},message:l.message}),u.dirty()):"datetime"===l.kind?(function(e){let t=`${q}T${L(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(l).test(e.data)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:"datetime",message:l.message}),u.dirty()):"date"===l.kind?U.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:"date",message:l.message}),u.dirty()):"time"===l.kind?RegExp(`^${L(l)}$`).test(e.data)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:"time",message:l.message}),u.dirty()):"duration"===l.kind?N.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"duration",code:d.invalid_string,message:l.message}),u.dirty()):"ip"===l.kind?(t=e.data,("v4"===(r=l.version)||!r)&&$.test(t)||("v6"===r||!r)&&j.test(t)||(m(i=this._getOrReturnCtx(e,i),{validation:"ip",code:d.invalid_string,message:l.message}),u.dirty())):"jwt"===l.kind?!function(e,t){if(!A.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));if("object"!=typeof n||null===n||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)return!1;return!0}catch{return!1}}(e.data,l.alg)&&(m(i=this._getOrReturnCtx(e,i),{validation:"jwt",code:d.invalid_string,message:l.message}),u.dirty()):"cidr"===l.kind?(n=e.data,("v4"===(o=l.version)||!o)&&P.test(n)||("v6"===o||!o)&&F.test(n)||(m(i=this._getOrReturnCtx(e,i),{validation:"cidr",code:d.invalid_string,message:l.message}),u.dirty())):"base64"===l.kind?z.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"base64",code:d.invalid_string,message:l.message}),u.dirty()):"base64url"===l.kind?D.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"base64url",code:d.invalid_string,message:l.message}),u.dirty()):a.assertNever(l);return{status:u.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:d.invalid_string,...o.errToObj(r)})}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...o.errToObj(e)})}url(e){return this._addCheck({kind:"url",...o.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...o.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...o.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...o.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...o.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...o.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...o.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...o.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...o.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...o.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...o.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...o.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...o.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...o.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...o.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...o.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...o.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...o.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...o.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...o.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...o.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...o.errToObj(t)})}nonempty(e){return this.min(1,o.errToObj(e))}trim(){return new V({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new V({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new V({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}V.create=e=>new V({checks:[],typeName:i.ZodString,coerce:e?.coerce??!1,...T(e)});class G extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==l.number){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.number,received:t.parsedType}),y}let r=new f;for(let n of this._def.checks)"int"===n.kind?a.isInteger(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:d.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}(e.data,n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:d.not_finite,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,a){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(a)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:o.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:o.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:o.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:o.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&a.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}G.create=e=>new G({checks:[],typeName:i.ZodNumber,coerce:e?.coerce||!1,...T(e)});class W extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==l.bigint)return this._getInvalidInput(e);let r=new f;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(m(t=this._getOrReturnCtx(e,t),{code:d.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,a){return new W({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(a)}]})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}W.create=e=>new W({checks:[],typeName:i.ZodBigInt,coerce:e?.coerce??!1,...T(e)});class X extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==l.boolean){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.boolean,received:t.parsedType}),y}return g(e.data)}}X.create=e=>new X({typeName:i.ZodBoolean,coerce:e?.coerce||!1,...T(e)});class B extends R{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==l.date){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.date,received:t.parsedType}),y}if(Number.isNaN(e.data.getTime()))return m(this._getOrReturnCtx(e),{code:d.invalid_date}),y;let r=new f;for(let n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):a.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:o.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:o.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}B.create=e=>new B({checks:[],coerce:e?.coerce||!1,typeName:i.ZodDate,...T(e)});class K extends R{_parse(e){if(this._getType(e)!==l.symbol){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.symbol,received:t.parsedType}),y}return g(e.data)}}K.create=e=>new K({typeName:i.ZodSymbol,...T(e)});class J extends R{_parse(e){if(this._getType(e)!==l.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.undefined,received:t.parsedType}),y}return g(e.data)}}J.create=e=>new J({typeName:i.ZodUndefined,...T(e)});class H extends R{_parse(e){if(this._getType(e)!==l.null){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.null,received:t.parsedType}),y}return g(e.data)}}H.create=e=>new H({typeName:i.ZodNull,...T(e)});class Y extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return g(e.data)}}Y.create=e=>new Y({typeName:i.ZodAny,...T(e)});class Q extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return g(e.data)}}Q.create=e=>new Q({typeName:i.ZodUnknown,...T(e)});class ee extends R{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.never,received:t.parsedType}),y}}ee.create=e=>new ee({typeName:i.ZodNever,...T(e)});class et extends R{_parse(e){if(this._getType(e)!==l.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.void,received:t.parsedType}),y}return g(e.data)}}et.create=e=>new et({typeName:i.ZodVoid,...T(e)});class er extends R{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==l.array)return m(t,{code:d.invalid_type,expected:l.array,received:t.parsedType}),y;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(m(t,{code:e?d.too_big:d.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(m(t,{code:d.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(m(t,{code:d.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new k(t,e,t.path,r)))).then(e=>f.mergeArray(r,e));let n=[...t.data].map((e,r)=>a.type._parseSync(new k(t,e,t.path,r)));return f.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new er({...this._def,minLength:{value:e,message:o.toString(t)}})}max(e,t){return new er({...this._def,maxLength:{value:e,message:o.toString(t)}})}length(e,t){return new er({...this._def,exactLength:{value:e,message:o.toString(t)}})}nonempty(e){return this.min(1,e)}}er.create=(e,t)=>new er({type:e,minLength:null,maxLength:null,exactLength:null,typeName:i.ZodArray,...T(t)});class ea extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=a.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==l.object){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.object,received:t.parsedType}),y}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof ee&&"strip"===this._def.unknownKeys))for(let e in r.data)n.includes(e)||o.push(e);let i=[];for(let e of n){let t=a[e],n=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new k(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ee){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of o)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(m(r,{code:d.unrecognized_keys,keys:o}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of o){let a=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new k(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of i){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>f.mergeObjectSync(t,e)):f.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return o.errToObj,new ea({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:o.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ea({...this._def,unknownKeys:"strip"})}passthrough(){return new ea({...this._def,unknownKeys:"passthrough"})}extend(e){return new ea({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ea({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:i.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ea({...this._def,catchall:e})}pick(e){let t={};for(let r of a.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ea({...this._def,shape:()=>t})}omit(e){let t={};for(let r of a.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ea({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof ea){let r={};for(let a in t.shape){let n=t.shape[a];r[a]=eb.create(e(n))}return new ea({...t._def,shape:()=>r})}return t instanceof er?new er({...t._def,type:e(t.element)}):t instanceof eb?eb.create(e(t.unwrap())):t instanceof ew?ew.create(e(t.unwrap())):t instanceof el?el.create(t.items.map(t=>e(t))):t}(this)}partial(e){let t={};for(let r of a.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new ea({...this._def,shape:()=>t})}required(e){let t={};for(let r of a.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eb;)e=e._def.innerType;t[r]=e}return new ea({...this._def,shape:()=>t})}keyof(){return ef(a.objectKeys(this.shape))}}ea.create=(e,t)=>new ea({shape:()=>e,unknownKeys:"strip",catchall:ee.create(),typeName:i.ZodObject,...T(t)}),ea.strictCreate=(e,t)=>new ea({shape:()=>e,unknownKeys:"strict",catchall:ee.create(),typeName:i.ZodObject,...T(t)}),ea.lazycreate=(e,t)=>new ea({shape:e,unknownKeys:"strip",catchall:ee.create(),typeName:i.ZodObject,...T(t)});class en extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new c(e.ctx.common.issues));return m(t,{code:d.invalid_union,unionErrors:r}),y});{let e;let a=[];for(let n of r){let r={...t,common:{...t.common,issues:[]},parent:null},o=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let n=a.map(e=>new c(e));return m(t,{code:d.invalid_union,unionErrors:n}),y}}get options(){return this._def.options}}en.create=(e,t)=>new en({options:e,typeName:i.ZodUnion,...T(t)});let eo=e=>{if(e instanceof eh)return eo(e.schema);if(e instanceof ev)return eo(e.innerType());if(e instanceof em)return[e.value];if(e instanceof ey)return e.options;if(e instanceof e_)return a.objectValues(e.enum);if(e instanceof ex)return eo(e._def.innerType);if(e instanceof J)return[void 0];else if(e instanceof H)return[null];else if(e instanceof eb)return[void 0,...eo(e.unwrap())];else if(e instanceof ew)return[null,...eo(e.unwrap())];else if(e instanceof eT)return eo(e.unwrap());else if(e instanceof eS)return eo(e.unwrap());else if(e instanceof ek)return eo(e._def.innerType);else return[]};class ei extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.object)return m(t,{code:d.invalid_type,expected:l.object,received:t.parsedType}),y;let r=this.discriminator,a=t.data[r],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(m(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let r of t){let t=eo(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of t){if(a.has(n))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);a.set(n,r)}}return new ei({typeName:i.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...T(r)})}}class es extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return y;let o=function e(t,r){let n=u(t),o=u(r);if(t===r)return{valid:!0,data:t};if(n===l.object&&o===l.object){let n=a.objectKeys(r),o=a.objectKeys(t).filter(e=>-1!==n.indexOf(e)),i={...t,...r};for(let a of o){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1};i[a]=n.data}return{valid:!0,data:i}}if(n===l.array&&o===l.array){if(t.length!==r.length)return{valid:!1};let a=[];for(let n=0;n<t.length;n++){let o=e(t[n],r[n]);if(!o.valid)return{valid:!1};a.push(o.data)}return{valid:!0,data:a}}return n===l.date&&o===l.date&&+t==+r?{valid:!0,data:t}:{valid:!1}}(e.value,n.value);return o.valid?((b(e)||b(n))&&t.dirty(),{status:t.value,value:o.data}):(m(r,{code:d.invalid_intersection_types}),y)};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(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}es.create=(e,t,r)=>new es({left:e,right:t,typeName:i.ZodIntersection,...T(r)});class el extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.array)return m(r,{code:d.invalid_type,expected:l.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return m(r,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(m(r,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new k(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>f.mergeArray(t,e)):f.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new el({...this._def,rest:e})}}el.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new el({items:e,typeName:i.ZodTuple,rest:null,...T(t)})};class eu extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.object)return m(r,{code:d.invalid_type,expected:l.object,received:r.parsedType}),y;let a=[],n=this._def.keyType,o=this._def.valueType;for(let e in r.data)a.push({key:n._parse(new k(r,e,r.path,e)),value:o._parse(new k(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?f.mergeObjectAsync(t,a):f.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new eu(t instanceof R?{keyType:e,valueType:t,typeName:i.ZodRecord,...T(r)}:{keyType:V.create(),valueType:e,typeName:i.ZodRecord,...T(t)})}}class ed extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.map)return m(r,{code:d.invalid_type,expected:l.map,received:r.parsedType}),y;let a=this._def.keyType,n=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:a._parse(new k(r,e,r.path,[o,"key"])),value:n._parse(new k(r,t,r.path,[o,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of o){let a=await r.key,n=await r.value;if("aborted"===a.status||"aborted"===n.status)return y;("dirty"===a.status||"dirty"===n.status)&&t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of o){let a=r.key,n=r.value;if("aborted"===a.status||"aborted"===n.status)return y;("dirty"===a.status||"dirty"===n.status)&&t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}}ed.create=(e,t,r)=>new ed({valueType:t,keyType:e,typeName:i.ZodMap,...T(r)});class ec extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.set)return m(r,{code:d.invalid_type,expected:l.set,received:r.parsedType}),y;let a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(m(r,{code:d.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(m(r,{code:d.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function o(e){let r=new Set;for(let a of e){if("aborted"===a.status)return y;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let i=[...r.data.values()].map((e,t)=>n._parse(new k(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>o(e)):o(i)}min(e,t){return new ec({...this._def,minSize:{value:e,message:o.toString(t)}})}max(e,t){return new ec({...this._def,maxSize:{value:e,message:o.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ec.create=(e,t)=>new ec({valueType:e,minSize:null,maxSize:null,typeName:i.ZodSet,...T(t)});class ep extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.function)return m(t,{code:d.invalid_type,expected:l.function,received:t.parsedType}),y;function r(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,p,p].filter(e=>!!e),issueData:{code:d.invalid_arguments,argumentsError:r}})}function a(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,p,p].filter(e=>!!e),issueData:{code:d.invalid_return_type,returnTypeError:r}})}let n={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof eg){let e=this;return g(async function(...t){let i=new c([]),s=await e._def.args.parseAsync(t,n).catch(e=>{throw i.addIssue(r(t,e)),i}),l=await Reflect.apply(o,this,s);return await e._def.returns._def.type.parseAsync(l,n).catch(e=>{throw i.addIssue(a(l,e)),i})})}{let e=this;return g(function(...t){let i=e._def.args.safeParse(t,n);if(!i.success)throw new c([r(t,i.error)]);let s=Reflect.apply(o,this,i.data),l=e._def.returns.safeParse(s,n);if(!l.success)throw new c([a(s,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ep({...this._def,args:el.create(e).rest(Q.create())})}returns(e){return new ep({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ep({args:e||el.create([]).rest(Q.create()),returns:t||Q.create(),typeName:i.ZodFunction,...T(r)})}}class eh extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}eh.create=(e,t)=>new eh({getter:e,typeName:i.ZodLazy,...T(t)});class em extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ef(e,t){return new ey({values:e,typeName:i.ZodEnum,...T(t)})}em.create=(e,t)=>new em({value:e,typeName:i.ZodLiteral,...T(t)});class ey extends R{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{expected:a.joinValues(r),received:t.parsedType,code:d.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{received:t.data,code:d.invalid_enum_value,options:r}),y}return g(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ey.create(e,{...this._def,...t})}exclude(e,t=this._def){return ey.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ey.create=ef;class e_ extends R{_parse(e){let t=a.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==l.string&&r.parsedType!==l.number){let e=a.objectValues(t);return m(r,{expected:a.joinValues(e),received:r.parsedType,code:d.invalid_type}),y}if(this._cache||(this._cache=new Set(a.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=a.objectValues(t);return m(r,{received:r.data,code:d.invalid_enum_value,options:e}),y}return g(e.data)}get enum(){return this._def.values}}e_.create=(e,t)=>new e_({values:e,typeName:i.ZodNativeEnum,...T(t)});class eg extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==l.promise&&!1===t.common.async?(m(t,{code:d.invalid_type,expected:l.promise,received:t.parsedType}),y):g((t.parsedType===l.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}eg.create=(e,t)=>new eg({type:e,typeName:i.ZodPromise,...T(t)});class ev extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===i.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:e=>{m(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){let e=n.transform(r.data,o);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return y;let a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?y:"dirty"===a.status||"dirty"===t.value?_(a.value):a});{if("aborted"===t.value)return y;let a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?y:"dirty"===a.status||"dirty"===t.value?_(a.value):a}}if("refinement"===n.type){let e=e=>{let t=n.refinement(e,o);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?y:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===n.type){if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>w(e)?Promise.resolve(n.transform(e.value,o)).then(e=>({status:t.value,value:e})):y);{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!w(e))return y;let a=n.transform(e.value,o);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}}a.assertNever(n)}}ev.create=(e,t,r)=>new ev({schema:e,typeName:i.ZodEffects,effect:t,...T(r)}),ev.createWithPreprocess=(e,t,r)=>new ev({schema:t,effect:{type:"preprocess",transform:e},typeName:i.ZodEffects,...T(r)});class eb extends R{_parse(e){return this._getType(e)===l.undefined?g(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:i.ZodOptional,...T(t)});class ew extends R{_parse(e){return this._getType(e)===l.null?g(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ew.create=(e,t)=>new ew({innerType:e,typeName:i.ZodNullable,...T(t)});class ex extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===l.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ex.create=(e,t)=>new ex({innerType:e,typeName:i.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...T(t)});class ek extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return x(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ek.create=(e,t)=>new ek({innerType:e,typeName:i.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...T(t)});class eI extends R{_parse(e){if(this._getType(e)!==l.nan){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}eI.create=e=>new eI({typeName:i.ZodNaN,...T(e)}),Symbol("zod_brand");class eT extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eR extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),_(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eR({in:e,out:t,typeName:i.ZodPipeline})}}class eS extends R{_parse(e){let t=this._def.innerType._parse(e),r=e=>(w(e)&&(e.value=Object.freeze(e.value)),e);return x(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}eS.create=(e,t)=>new eS({innerType:e,typeName:i.ZodReadonly,...T(t)}),ea.lazycreate,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"}(i||(i={}));let eZ=V.create,eC=G.create;eI.create,W.create,X.create,B.create,K.create,J.create,H.create,Y.create,Q.create,ee.create,et.create;let eE=er.create,eO=ea.create;ea.strictCreate;let eA=en.create,eN=ei.create;es.create,el.create,eu.create,ed.create,ec.create,ep.create,eh.create;let eM=em.create,e$=ey.create;e_.create,eg.create,ev.create,eb.create,ew.create,ev.createWithPreprocess,eR.create},3947:(e,t,r)=>{r.d(t,{Qc:()=>l,Vw:()=>u,As:()=>d,X9:()=>c});var a=r(7481),n=r(8775),o=r(9921);let i=(e,t)=>{n.h1.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>n.Z(e,t)},flatten:{value:t=>n.MK(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})};o.IF("ZodError",i);let s=o.IF("ZodError",i,{Parent:Error}),l=a.lk(s),u=a.T2(s),d=a.Yn(s),c=a.G(s)},2943:(e,t,r)=>{r.d(t,{o4:()=>tb,Yj:()=>tK,IX:()=>t1,O7:()=>tG,PG:()=>rI,VK:()=>t8,Km:()=>ri,Pp:()=>rT,Vo:()=>rx,i0:()=>rl,d7:()=>t5,Fi:()=>tQ,lB:()=>tX,Rx:()=>tq,Ry:()=>t4,IM:()=>rn,cf:()=>t9,Z_:()=>tv,bc:()=>rr,G0:()=>t3,_4:()=>tH});var a=r(9921);let n=/^[cC][^\s-]{8,}$/,o=/^[0-9a-z]+$/,i=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,s=/^[0-9a-vA-V]{20}$/,l=/^[A-Za-z0-9]{27}$/,u=/^[a-zA-Z0-9_-]{21}$/,d=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,c=/^([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})$/,p=e=>e?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)$/,h=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,m=/^(?:(?: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])$/,f=/^(([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})$/,y=/^((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])$/,_=/^(([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])$/,g=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,v=/^[A-Za-z0-9_-]*$/,b=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,w=/^\+(?:[0-9]){6,14}[0-9]$/,x="(?:(?:\\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])))",k=RegExp(`^${x}$`);function I(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let T=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${t}$`)},R=/^\d+$/,S=/^-?\d+(?:\.\d+)?/i,Z=/true|false/i,C=/null/i,E=/^[^A-Z]*$/,O=/^[^a-z]*$/;var A=r(8510);let N=a.IF("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),M={number:"number",bigint:"bigint",object:"date"},$=a.IF("$ZodCheckLessThan",(e,t)=>{N.init(e,t);let r=M[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),P=a.IF("$ZodCheckGreaterThan",(e,t)=>{N.init(e,t);let r=M[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),j=a.IF("$ZodCheckMultipleOf",(e,t)=>{N.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===A.k8(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),F=a.IF("$ZodCheckNumberFormat",(e,t)=>{N.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[n,o]=A.Fl[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=n,a.maximum=o,r&&(a.pattern=R)}),e._zod.check=i=>{let s=i.value;if(r){if(!Number.isInteger(s)){i.issues.push({expected:a,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?i.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort}):i.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort});return}}s<n&&i.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>o&&i.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),z=a.IF("$ZodCheckMaxLength",(e,t)=>{var r;N.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!A.NZ(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let a=r.value;if(a.length<=t.maximum)return;let n=A.XU(a);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),D=a.IF("$ZodCheckMinLength",(e,t)=>{var r;N.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!A.NZ(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;if(a.length>=t.minimum)return;let n=A.XU(a);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),q=a.IF("$ZodCheckLengthEquals",(e,t)=>{var r;N.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!A.NZ(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let a=r.value,n=a.length;if(n===t.length)return;let o=A.XU(a),i=n>t.length;r.issues.push({origin:o,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),U=a.IF("$ZodCheckStringFormat",(e,t)=>{var r,a;N.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),L=a.IF("$ZodCheckRegex",(e,t)=>{U.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),V=a.IF("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=E),U.init(e,t)}),G=a.IF("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=O),U.init(e,t)}),W=a.IF("$ZodCheckIncludes",(e,t)=>{N.init(e,t);let r=A.yI(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=a,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),X=a.IF("$ZodCheckStartsWith",(e,t)=>{N.init(e,t);let r=RegExp(`^${A.yI(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),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})}}),B=a.IF("$ZodCheckEndsWith",(e,t)=>{N.init(e,t);let r=RegExp(`.*${A.yI(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),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})}}),K=a.IF("$ZodCheckOverwrite",(e,t)=>{N.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class J{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}var H=r(7481);let Y={major:4,minor:0,patch:0},Q=a.IF("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Y;let n=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&n.unshift(e),n))for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,o=A.Ko(e);for(let i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;let t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new a.TG;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s,e.issues.length===t||o||(o=A.Ko(e,t))});else{if(e.issues.length===t)continue;o||(o=A.Ko(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,o)=>{let i=e._zod.parse(r,o);if(i instanceof Promise){if(!1===o.async)throw new a.TG;return i.then(e=>t(e,n,o))}return t(i,n,o)}}e["~standard"]={validate:t=>{try{let r=(0,H.As)(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return(0,H.X9)(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),ee=a.IF("$ZodString",(e,t)=>{Q.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??T(e._zod.bag),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),et=a.IF("$ZodStringFormat",(e,t)=>{U.init(e,t),ee.init(e,t)}),er=a.IF("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=c),et.init(e,t)}),ea=a.IF("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=p(e))}else t.pattern??(t.pattern=p());et.init(e,t)}),en=a.IF("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=h),et.init(e,t)}),eo=a.IF("$ZodURL",(e,t)=>{et.init(e,t),e._zod.check=r=>{try{let a=r.value,n=new URL(a),o=n.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:b.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!a.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ei=a.IF("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),et.init(e,t)}),es=a.IF("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=u),et.init(e,t)}),el=a.IF("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=n),et.init(e,t)}),eu=a.IF("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=o),et.init(e,t)}),ed=a.IF("$ZodULID",(e,t)=>{t.pattern??(t.pattern=i),et.init(e,t)}),ec=a.IF("$ZodXID",(e,t)=>{t.pattern??(t.pattern=s),et.init(e,t)}),ep=a.IF("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=l),et.init(e,t)}),eh=a.IF("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){let t=I({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let a=`${t}(?:${r.join("|")})`;return RegExp(`^${x}T(?:${a})$`)}(t)),et.init(e,t)}),em=a.IF("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=k),et.init(e,t)}),ef=a.IF("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RegExp(`^${I(t)}$`)),et.init(e,t)}),ey=a.IF("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=d),et.init(e,t)}),e_=a.IF("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=m),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),eg=a.IF("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=f),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),ev=a.IF("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=y),et.init(e,t)}),eb=a.IF("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=_),et.init(e,t),e._zod.check=r=>{let[a,n]=r.value.split("/");try{if(!n)throw Error();let e=Number(n);if(`${e}`!==n||e<0||e>128)throw Error();new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function ew(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let ex=a.IF("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=g),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{ew(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),ek=a.IF("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=v),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{!function(e){if(!v.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ew(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),eI=a.IF("$ZodE164",(e,t)=>{t.pattern??(t.pattern=w),et.init(e,t)}),eT=a.IF("$ZodJWT",(e,t)=>{et.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let n=JSON.parse(atob(a));if("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),eR=a.IF("$ZodNumber",(e,t)=>{Q.init(e,t),e._zod.pattern=e._zod.bag.pattern??S,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;let o="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...o?{received:o}:{}}),r}}),eS=a.IF("$ZodNumber",(e,t)=>{F.init(e,t),eR.init(e,t)}),eZ=a.IF("$ZodBoolean",(e,t)=>{Q.init(e,t),e._zod.pattern=Z,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),eC=a.IF("$ZodNull",(e,t)=>{Q.init(e,t),e._zod.pattern=C,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}}),eE=a.IF("$ZodAny",(e,t)=>{Q.init(e,t),e._zod.parse=e=>e}),eO=a.IF("$ZodUnknown",(e,t)=>{Q.init(e,t),e._zod.parse=e=>e}),eA=a.IF("$ZodNever",(e,t)=>{Q.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function eN(e,t,r){e.issues.length&&t.issues.push(...A.Cr(r,e.issues)),t.value[r]=e.value}let eM=a.IF("$ZodArray",(e,t)=>{Q.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let o=[];for(let e=0;e<n.length;e++){let i=n[e],s=t.element._zod.run({value:i,issues:[]},a);s instanceof Promise?o.push(s.then(t=>eN(t,r,e))):eN(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function e$(e,t,r){e.issues.length&&t.issues.push(...A.Cr(r,e.issues)),t.value[r]=e.value}function eP(e,t,r,a){e.issues.length?void 0===a[r]?r in a?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...A.Cr(r,e.issues)):void 0===e.value?r in a&&(t.value[r]=void 0):t.value[r]=e.value}let ej=a.IF("$ZodObject",(e,t)=>{let r,n;Q.init(e,t);let o=A.HX(()=>{let e=Object.keys(t.shape);for(let r of e)if(!(t.shape[r]instanceof Q))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=A.bX(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});A.To(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let i=e=>{let t=new J(["shape","payload","ctx"]),r=o.value,a=e=>{let t=A.v_(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let n=Object.create(null),i=0;for(let e of r.keys)n[e]=`key_${i++}`;for(let e of(t.write("const newResult = {}"),r.keys))if(r.optionalKeys.has(e)){let r=n[e];t.write(`const ${r} = ${a(e)};`);let o=A.v_(e);t.write(`
68
+ `),{name:"GatewayAuthenticationError"})}(i.error)}),"text-start"===i.type&&(et[i.id]={type:"text",text:"",providerMetadata:i.providerMetadata},K.push(et[i.id])),"text-delta"===i.type){let e=et[i.id];if(null==e){t.enqueue({part:{type:"error",error:`text part ${i.id} not found`},partialOutput:void 0});return}e.text+=i.text,e.providerMetadata=null!=(r=i.providerMetadata)?r:e.providerMetadata}if("text-end"===i.type){let e=et[i.id];if(null==e){t.enqueue({part:{type:"error",error:`text part ${i.id} not found`},partialOutput:void 0});return}e.providerMetadata=null!=(a=i.providerMetadata)?a:e.providerMetadata,delete et[i.id]}if("reasoning-start"===i.type&&(er[i.id]={type:"reasoning",text:"",providerMetadata:i.providerMetadata},K.push(er[i.id])),"reasoning-delta"===i.type){let e=er[i.id];if(null==e){t.enqueue({part:{type:"error",error:`reasoning part ${i.id} not found`},partialOutput:void 0});return}e.text+=i.text,e.providerMetadata=null!=(n=i.providerMetadata)?n:e.providerMetadata}if("reasoning-end"===i.type){let e=er[i.id];if(null==e){t.enqueue({part:{type:"error",error:`reasoning part ${i.id} not found`},partialOutput:void 0});return}e.providerMetadata=null!=(o=i.providerMetadata)?o:e.providerMetadata,delete er[i.id]}if("file"===i.type&&K.push({type:"file",file:i.file,...null!=i.providerMetadata?{providerMetadata:i.providerMetadata}:{}}),"source"===i.type&&K.push(i),"tool-call"===i.type&&K.push(i),"tool-result"!==i.type||i.preliminary||K.push(i),"tool-approval-request"===i.type&&K.push(i),"tool-error"===i.type&&K.push(i),"start-step"===i.type&&(K=[],er={},et={},H=i.request,Y=i.warnings),"finish-step"===i.type){let e=await rX({content:K,tools:h}),t=new rV({stepNumber:Q.length,model:eh,...em,experimental_context:z,content:K,finishReason:i.finishReason,rawFinishReason:i.rawFinishReason,usage:i.usage,warnings:Y,request:H,response:{...i.response,messages:[...J,...e]},providerMetadata:i.providerMetadata});await tV({event:t,callbacks:[A,B.onStepFinish]}),tW({warnings:Y,provider:eh.provider,model:eh.modelId}),Q.push(t),J.push(...e),U.resolve()}"finish"===i.type&&(X=i.totalUsage,G=i.finishReason,W=i.rawFinishReason)},async flush(e){try{if(0===Q.length){let e=(null==o?void 0:o.aborted)?o.reason:new tc({message:"No output generated. Check the stream for errors."});ep._finishReason.reject(e),ep._rawFinishReason.reject(e),ep._totalUsage.reject(e),ep._steps.reject(e);return}let e=null!=G?G:"other",r=null!=X?X:rT();ep._finishReason.resolve(e),ep._rawFinishReason.resolve(W),ep._totalUsage.resolve(r),ep._steps.resolve(Q);let a=Q[Q.length-1];await tV({event:{stepNumber:a.stepNumber,model:a.model,functionId:a.functionId,metadata:a.metadata,experimental_context:a.experimental_context,finishReason:a.finishReason,rawFinishReason:a.rawFinishReason,totalUsage:r,usage:a.usage,content:a.content,text:a.text,reasoningText:a.reasoningText,reasoning:a.reasoning,files:a.files,sources:a.sources,toolCalls:a.toolCalls,staticToolCalls:a.staticToolCalls,dynamicToolCalls:a.dynamicToolCalls,toolResults:a.toolResults,staticToolResults:a.staticToolResults,dynamicToolResults:a.dynamicToolResults,request:a.request,response:a.response,warnings:a.warnings,providerMetadata:a.providerMetadata,steps:Q},callbacks:[E,B.onFinish]}),V.setAttributes(await rI({telemetry:t,attributes:{"ai.response.finishReason":e,"ai.response.text":{output:()=>a.text},"ai.response.reasoning":{output:()=>a.reasoningText},"ai.response.toolCalls":{output:()=>{var e;return(null==(e=a.toolCalls)?void 0:e.length)?JSON.stringify(a.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(a.providerMetadata),"ai.usage.inputTokens":r.inputTokens,"ai.usage.outputTokens":r.outputTokens,"ai.usage.totalTokens":r.totalTokens,"ai.usage.reasoningTokens":r.reasoningTokens,"ai.usage.cachedInputTokens":r.cachedInputTokens}}))}catch(t){e.error(t)}finally{V.end()}}}),en=function(){let e=[],t=null,r=!1,a=r7(),n=()=>{r=!0,a.resolve(),e.forEach(e=>e.cancel()),e=[],null==t||t.close()},o=async()=>{if(r&&0===e.length){null==t||t.close();return}if(0===e.length)return a=r7(),await a.promise,o();try{let{value:a,done:n}=await e[0].read();n?(e.shift(),0===e.length&&r?null==t||t.close():await o()):null==t||t.enqueue(a)}catch(r){null==t||t.error(r),e.shift(),n()}};return{stream:new ReadableStream({start(e){t=e},pull:o,async cancel(){for(let t of e)await t.cancel();e=[],r=!0}}),addStream:t=>{if(r)throw Error("Cannot add inner stream: outer stream is closed");e.push(t.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),0===e.length&&(null==t||t.close())},terminate:n}}();this.addStream=en.addStream,this.closeStream=en.close;let eo=en.stream.getReader(),ei=new ReadableStream({async start(e){e.enqueue({type:"start"})},async pull(e){function t(){null==O||O({steps:Q}),e.enqueue({type:"abort",...(null==o?void 0:o.reason)!==void 0?{reason:(0,$.e$)(o.reason)}:{}}),e.close()}try{let{done:r,value:a}=await eo.read();if(r){e.close();return}if(null==o?void 0:o.aborted){t();return}e.enqueue(a)}catch(r){(0,M.D_)(r)&&(null==o?void 0:o.aborted)?t():e.error(r)}},cancel:e=>en.stream.cancel(e)});for(let e of f)ei=ei.pipeThrough(e({tools:h,stopStream(){en.terminate()}}));this.baseStream=ei.pipeThrough(function(e){let t,r;let a="",n="",o="";function i({controller:e,partialOutput:a}){e.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:r},partialOutput:a}),n=""}return new TransformStream({async transform(s,l){var u;if("finish-step"===s.type&&n.length>0&&i({controller:l}),"text-delta"!==s.type&&"text-start"!==s.type&&"text-end"!==s.type){l.enqueue({part:s,partialOutput:void 0});return}if(null==t)t=s.id;else if(s.id!==t){l.enqueue({part:s,partialOutput:void 0});return}if("text-start"===s.type){l.enqueue({part:s,partialOutput:void 0});return}if("text-end"===s.type){n.length>0&&i({controller:l}),l.enqueue({part:s,partialOutput:void 0});return}a+=s.text,n+=s.text,r=null!=(u=s.providerMetadata)?u:r;let d=await e.parsePartialOutput({text:a});if(void 0!==d){let e=JSON.stringify(d.partial);e!==o&&(i({controller:l,partialOutput:d.partial}),o=e)}}})}(null!=v?v:rP())).pipeThrough(ea);let{maxRetries:es,retry:el}=function({maxRetries:e,abortSignal:t}){if(null!=e){if(!Number.isInteger(e))throw new eJ({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new eJ({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}let r=null!=e?e:2;return{maxRetries:r,retry:rZ({maxRetries:r,abortSignal:t})}}({maxRetries:n,abortSignal:o}),eu=function({isEnabled:e=!1,tracer:t}={}){return e?t||eL.g.getTracer("ai"):rv}(t),ed=function({maxOutputTokens:e,temperature:t,topP:r,topK:a,presencePenalty:n,frequencyPenalty:o,seed:i,stopSequences:s}){if(null!=e){if(!Number.isInteger(e))throw new eJ({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new eJ({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(null!=t&&"number"!=typeof t)throw new eJ({parameter:"temperature",value:t,message:"temperature must be a number"});if(null!=r&&"number"!=typeof r)throw new eJ({parameter:"topP",value:r,message:"topP must be a number"});if(null!=a&&"number"!=typeof a)throw new eJ({parameter:"topK",value:a,message:"topK must be a number"});if(null!=n&&"number"!=typeof n)throw new eJ({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(null!=o&&"number"!=typeof o)throw new eJ({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(null!=i&&!Number.isInteger(i))throw new eJ({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:a,presencePenalty:n,frequencyPenalty:o,stopSequences:s,seed:i}}(a),ec=function({model:e,settings:t,telemetry:r,headers:a}){var n;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,r])=>{if("timeout"===t){let a=tH(r);null!=a&&(e[`ai.settings.${t}`]=a)}else e[`ai.settings.${t}`]=r;return e},{}),...Object.entries(null!=(n=null==r?void 0:r.metadata)?n:{}).reduce((e,[t,r])=>(e[`ai.telemetry.metadata.${t}`]=r,e),{}),...Object.entries(null!=a?a:{}).reduce((e,[t,r])=>(void 0!==r&&(e[`ai.request.headers.${t}`]=r),e),{})}}({model:e,telemetry:t,headers:r,settings:{...ed,maxRetries:es}}),ep=this,eh={provider:e.provider,modelId:e.modelId},em={functionId:null==t?void 0:t.functionId,metadata:null==t?void 0:t.metadata};rx({name:"ai.streamText",attributes:rI({telemetry:t,attributes:{...rg({operationId:"ai.streamText",telemetry:t}),...ec,"ai.prompt":{input:()=>JSON.stringify({system:d,prompt:c,messages:p})}}}),tracer:eu,endWhenDone:!1,fn:async a=>{V=a;let n=await r_({system:d,prompt:c,messages:p});await tV({event:{model:eh,system:d,prompt:c,messages:p,tools:h,toolChoice:m,activeTools:y,maxOutputTokens:ed.maxOutputTokens,temperature:ed.temperature,topP:ed.topP,topK:ed.topK,presencePenalty:ed.presencePenalty,frequencyPenalty:ed.frequencyPenalty,stopSequences:ed.stopSequences,seed:ed.seed,maxRetries:es,timeout:T,headers:r,providerOptions:b,stopWhen:R,output:v,abortSignal:S,include:q,...em,experimental_context:z},callbacks:[N,B.onStart]});let f=n.messages,x=[],{approvedToolApprovals:Z,deniedToolApprovals:C}=function({messages:e}){let t=e.at(-1);if((null==t?void 0:t.role)!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};let r={};for(let t of e)if("assistant"===t.role&&"string"!=typeof t.content)for(let e of t.content)"tool-call"===e.type&&(r[e.toolCallId]=e);let a={};for(let t of e)if("assistant"===t.role&&"string"!=typeof t.content)for(let e of t.content)"tool-approval-request"===e.type&&(a[e.approvalId]=e);let n={};for(let e of t.content)"tool-result"===e.type&&(n[e.toolCallId]=e);let o=[],i=[];for(let e of t.content.filter(e=>"tool-approval-response"===e.type)){let t=a[e.approvalId];if(null==t)throw new e0({approvalId:e.approvalId});if(null!=n[t.toolCallId])continue;let s=r[t.toolCallId];if(null==s)throw new e8({toolCallId:t.toolCallId,approvalId:t.approvalId});let l={approvalRequest:t,approvalResponse:e,toolCall:s};e.approved?o.push(l):i.push(l)}return{approvedToolApprovals:o,deniedToolApprovals:i}}({messages:f});if(C.length>0||Z.length>0){let e;let r=[...Z,...C].filter(e=>e.toolCall.providerExecuted),a=Z.filter(e=>!e.toolCall.providerExecuted),n=C.filter(e=>!e.toolCall.providerExecuted),i=C.filter(e=>e.toolCall.providerExecuted),s=new ReadableStream({start(t){e=t}});ep.addStream(s);try{for(let t of[...n,...i])null==e||e.enqueue({type:"tool-output-denied",toolCallId:t.toolCall.toolCallId,toolName:t.toolCall.toolName});let s=[];if(await Promise.all(a.map(async r=>{let a=await rO({toolCall:r.toolCall,tools:h,tracer:eu,telemetry:t,messages:f,abortSignal:o,experimental_context:z,stepNumber:Q.length,model:eh,onToolCallStart:[j,B.onToolCallStart],onToolCallFinish:[F,B.onToolCallFinish],onPreliminaryToolResult:t=>{null==e||e.enqueue(t)}});null!=a&&(null==e||e.enqueue(a),s.push(a))})),r.length>0&&x.push({role:"tool",content:r.map(e=>({type:"tool-approval-response",approvalId:e.approvalResponse.approvalId,approved:e.approvalResponse.approved,reason:e.approvalResponse.reason,providerExecuted:!0}))}),s.length>0||n.length>0){let e=[];for(let t of s)e.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:await t8({toolCallId:t.toolCallId,input:t.input,tool:null==h?void 0:h[t.toolName],output:"tool-result"===t.type?t.output:t.error,errorMode:"tool-error"===t.type?"text":"none"})});for(let t of n)e.push({type:"tool-result",toolCallId:t.toolCall.toolCallId,toolName:t.toolCall.toolName,output:{type:"execution-denied",reason:t.approvalResponse.reason}});x.push({role:"tool",content:e})}}finally{null==e||e.close()}}async function E({currentStep:a,responseMessages:c,usage:p}){var x,Z,C,O,A,N,$,L,V;let G;let W=ep.includeRawChunks,X=null!=i?setTimeout(()=>s.abort(),i):void 0;function J(){null!=G&&(clearTimeout(G),G=void 0)}function H(){null!=X&&clearTimeout(X)}try{let i,s,X;U=new M.eh;let Y=[...f,...c],et=await (null==w?void 0:w({model:e,steps:Q,stepNumber:Q.length,messages:Y,experimental_context:z})),er=tJ(null!=(x=null==et?void 0:et.model)?x:e),ea={provider:er.provider,modelId:er.modelId},en=await t5({prompt:{system:null!=(Z=null==et?void 0:et.system)?Z:n.system,messages:null!=(C=null==et?void 0:et.messages)?C:Y},supportedUrls:await er.supportedUrls,download:D}),eo=null!=(O=null==et?void 0:et.activeTools)?O:y,{toolChoice:ei,tools:es}=await re({tools:h,toolChoice:null!=(A=null==et?void 0:et.toolChoice)?A:m,activeTools:eo});z=null!=(N=null==et?void 0:et.experimental_context)?N:z;let ef=null!=($=null==et?void 0:et.messages)?$:Y,ey=null!=(L=null==et?void 0:et.system)?L:n.system,e_=rS(b,null==et?void 0:et.providerOptions);await tV({event:{stepNumber:Q.length,model:ea,system:ey,messages:ef,tools:h,toolChoice:ei,activeTools:eo,steps:[...Q],providerOptions:e_,timeout:T,headers:r,stopWhen:R,output:v,abortSignal:S,include:q,...em,experimental_context:z},callbacks:[P,B.onStepStart]});let{result:{stream:eg,response:ev,request:eb},doStreamSpan:ew,startTimestampMs:ex}=await el(()=>rx({name:"ai.streamText.doStream",attributes:rI({telemetry:t,attributes:{...rg({operationId:"ai.streamText.doStream",telemetry:t}),...ec,"ai.model.provider":er.provider,"ai.model.id":er.modelId,"ai.prompt.messages":{input:()=>{var e;return e=en,JSON.stringify(e.map(e=>({...e,content:"string"==typeof e.content?e.content:e.content.map(e=>{var t;return"file"===e.type?{...e,data:e.data instanceof Uint8Array?"string"==typeof(t=e.data)?t:t instanceof ArrayBuffer?(0,M.k0)(new Uint8Array(t)):(0,M.k0)(t):e.data}:e})})))}},"ai.prompt.tools":{input:()=>null==es?void 0:es.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>null!=ei?JSON.stringify(ei):void 0},"gen_ai.system":er.provider,"gen_ai.request.model":er.modelId,"gen_ai.request.frequency_penalty":ed.frequencyPenalty,"gen_ai.request.max_tokens":ed.maxOutputTokens,"gen_ai.request.presence_penalty":ed.presencePenalty,"gen_ai.request.stop_sequences":ed.stopSequences,"gen_ai.request.temperature":ed.temperature,"gen_ai.request.top_k":ed.topK,"gen_ai.request.top_p":ed.topP}}),tracer:eu,endWhenDone:!1,fn:async e=>({startTimestampMs:k(),doStreamSpan:e,result:await er.doStream({...ed,tools:es,toolChoice:ei,responseFormat:await (null==v?void 0:v.responseFormat),prompt:en,providerOptions:e_,abortSignal:o,headers:r,includeRawChunks:W})})})),ek=function({tools:e,generatorStream:t,tracer:r,telemetry:a,system:n,messages:o,abortSignal:i,repairToolCall:s,experimental_context:l,generateId:u,stepNumber:d,model:c,onToolCallStart:p,onToolCallFinish:h}){let m,f=null,y=new ReadableStream({start(e){f=e}}),_=new Set,g=new Map,v=new Map,b=!1;function w(){b&&0===_.size&&(null!=m&&f.enqueue(m),f.close())}let x=new TransformStream({async transform(t,y){let b=t.type;switch(b){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":y.enqueue(t);break;case"file":y.enqueue({type:"file",file:new rN({data:t.data,mediaType:t.mediaType}),...null!=t.providerMetadata?{providerMetadata:t.providerMetadata}:{}});break;case"finish":var x;m={type:"finish",finishReason:t.finishReason.unified,rawFinishReason:t.finishReason.raw,usage:{inputTokens:(x=t.usage).inputTokens.total,inputTokenDetails:{noCacheTokens:x.inputTokens.noCache,cacheReadTokens:x.inputTokens.cacheRead,cacheWriteTokens:x.inputTokens.cacheWrite},outputTokens:x.outputTokens.total,outputTokenDetails:{textTokens:x.outputTokens.text,reasoningTokens:x.outputTokens.reasoning},totalTokens:rR(x.inputTokens.total,x.outputTokens.total),raw:x.raw,reasoningTokens:x.outputTokens.reasoning,cachedInputTokens:x.inputTokens.cacheRead},providerMetadata:t.providerMetadata};break;case"tool-approval-request":{let e=v.get(t.toolCallId);if(null==e){f.enqueue({type:"error",error:new e8({toolCallId:t.toolCallId,approvalId:t.approvalId})});break}y.enqueue({type:"tool-approval-request",approvalId:t.approvalId,toolCall:e});break}case"tool-call":try{let m=await rq({toolCall:t,tools:e,repairToolCall:s,system:n,messages:o});if(v.set(m.toolCallId,m),y.enqueue(m),m.invalid){f.enqueue({type:"tool-error",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,error:(0,M.e$)(m.error),dynamic:!0,title:m.title});break}let b=null==e?void 0:e[m.toolName];if(null==b)break;if(null!=b.onInputAvailable&&await b.onInputAvailable({input:m.input,toolCallId:m.toolCallId,messages:o,abortSignal:i,experimental_context:l}),await rM({tool:b,toolCall:m,messages:o,experimental_context:l})){f.enqueue({type:"tool-approval-request",approvalId:u(),toolCall:m});break}if(g.set(m.toolCallId,m.input),null!=b.execute&&!0!==m.providerExecuted){let t=u();_.add(t),rO({toolCall:m,tools:e,tracer:r,telemetry:a,messages:o,abortSignal:i,experimental_context:l,stepNumber:d,model:c,onToolCallStart:p,onToolCallFinish:h,onPreliminaryToolResult:e=>{f.enqueue(e)}}).then(e=>{f.enqueue(e)}).catch(e=>{f.enqueue({type:"error",error:e})}).finally(()=>{_.delete(t),w()})}}catch(e){f.enqueue({type:"error",error:e})}break;case"tool-result":{let e=t.toolName;t.isError?f.enqueue({type:"tool-error",toolCallId:t.toolCallId,toolName:e,input:g.get(t.toolCallId),providerExecuted:!0,error:t.result,dynamic:t.dynamic}):y.enqueue({type:"tool-result",toolCallId:t.toolCallId,toolName:e,input:g.get(t.toolCallId),output:t.result,providerExecuted:!0,dynamic:t.dynamic});break}default:throw Error(`Unhandled chunk type: ${b}`)}},flush(){b=!0,w()}});return new ReadableStream({start:async e=>Promise.all([t.pipeThrough(x).pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){}})),y.pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){e.close()}}))])})}({tools:h,generatorStream:eg,tracer:eu,telemetry:t,system:d,messages:Y,repairToolCall:_,abortSignal:o,experimental_context:z,generateId:I,stepNumber:Q.length,model:ea,onToolCallStart:[j,B.onToolCallStart],onToolCallFinish:[F,B.onToolCallFinish]}),eI=null==(V=null==q?void 0:q.requestBody)||V?null!=eb?eb:{}:{...eb,body:void 0},eT=[],eR=[],eS={},eZ="other",eC=rT(),eE=!0,eO={id:I(),timestamp:new Date,modelId:eh.modelId},eA="";ep.addStream(ek.pipeThrough(new TransformStream({async transform(e,t){var r,a,n,d,c;if(null!=l&&(null!=G&&clearTimeout(G),G=setTimeout(()=>u.abort(),l)),"stream-start"===e.type){i=e.warnings;return}if(eE){let e=k()-ex;eE=!1,ew.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":e}),ew.setAttributes({"ai.response.msToFirstChunk":e}),t.enqueue({type:"start-step",request:eI,warnings:null!=i?i:[]})}let p=e.type;switch(p){case"tool-approval-request":case"text-start":case"text-end":case"reasoning-start":case"reasoning-end":case"file":case"source":t.enqueue(e);break;case"text-delta":e.delta.length>0&&(t.enqueue({type:"text-delta",id:e.id,text:e.delta,providerMetadata:e.providerMetadata}),eA+=e.delta);break;case"reasoning-delta":t.enqueue({type:"reasoning-delta",id:e.id,text:e.delta,providerMetadata:e.providerMetadata});break;case"tool-call":t.enqueue(e),eT.push(e);break;case"tool-result":t.enqueue(e),e.preliminary||eR.push(e);break;case"tool-error":t.enqueue(e),eR.push(e);break;case"response-metadata":eO={id:null!=(r=e.id)?r:eO.id,timestamp:null!=(a=e.timestamp)?a:eO.timestamp,modelId:null!=(n=e.modelId)?n:eO.modelId};break;case"finish":{eC=e.usage,eZ=e.finishReason,X=e.rawFinishReason,s=e.providerMetadata;let t=k()-ex;ew.addEvent("ai.stream.finish"),ew.setAttributes({"ai.response.msToFinish":t,"ai.response.avgOutputTokensPerSecond":1e3*(null!=(d=eC.outputTokens)?d:0)/t});break}case"tool-input-start":{eS[e.id]=e.toolName;let r=null==h?void 0:h[e.toolName];(null==r?void 0:r.onInputStart)!=null&&await r.onInputStart({toolCallId:e.id,messages:Y,abortSignal:o,experimental_context:z}),t.enqueue({...e,dynamic:null!=(c=e.dynamic)?c:(null==r?void 0:r.type)==="dynamic",title:null==r?void 0:r.title});break}case"tool-input-end":delete eS[e.id],t.enqueue(e);break;case"tool-input-delta":{let r=eS[e.id],a=null==h?void 0:h[r];(null==a?void 0:a.onInputDelta)!=null&&await a.onInputDelta({inputTextDelta:e.delta,toolCallId:e.id,messages:Y,abortSignal:o,experimental_context:z}),t.enqueue(e);break}case"error":t.enqueue(e),eZ="error";break;case"raw":W&&t.enqueue(e);break;default:throw Error(`Unknown chunk type: ${p}`)}},async flush(e){var r,n,o,i,l,u,d,m,f,y,_,v;let b=eT.length>0?JSON.stringify(eT):void 0;try{ew.setAttributes(await rI({telemetry:t,attributes:{"ai.response.finishReason":eZ,"ai.response.text":{output:()=>eA},"ai.response.reasoning":{output:()=>{let e=K.filter(e=>"reasoning"===e.type);return e.length>0?e.map(e=>e.text).join("\n"):void 0}},"ai.response.toolCalls":{output:()=>b},"ai.response.id":eO.id,"ai.response.model":eO.modelId,"ai.response.timestamp":eO.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(s),"ai.usage.inputTokens":eC.inputTokens,"ai.usage.outputTokens":eC.outputTokens,"ai.usage.totalTokens":eC.totalTokens,"ai.usage.reasoningTokens":eC.reasoningTokens,"ai.usage.cachedInputTokens":eC.cachedInputTokens,"gen_ai.response.finish_reasons":[eZ],"gen_ai.response.id":eO.id,"gen_ai.response.model":eO.modelId,"gen_ai.usage.input_tokens":eC.inputTokens,"gen_ai.usage.output_tokens":eC.outputTokens}}))}catch(e){}finally{ew.end()}e.enqueue({type:"finish-step",finishReason:eZ,rawFinishReason:X,usage:eC,providerMetadata:s,response:{...eO,headers:null==ev?void 0:ev.headers}});let w=(r=p,n=eC,{inputTokens:rR(r.inputTokens,n.inputTokens),inputTokenDetails:{noCacheTokens:rR(null==(o=r.inputTokenDetails)?void 0:o.noCacheTokens,null==(i=n.inputTokenDetails)?void 0:i.noCacheTokens),cacheReadTokens:rR(null==(l=r.inputTokenDetails)?void 0:l.cacheReadTokens,null==(u=n.inputTokenDetails)?void 0:u.cacheReadTokens),cacheWriteTokens:rR(null==(d=r.inputTokenDetails)?void 0:d.cacheWriteTokens,null==(m=n.inputTokenDetails)?void 0:m.cacheWriteTokens)},outputTokens:rR(r.outputTokens,n.outputTokens),outputTokenDetails:{textTokens:rR(null==(f=r.outputTokenDetails)?void 0:f.textTokens,null==(y=n.outputTokenDetails)?void 0:y.textTokens),reasoningTokens:rR(null==(_=r.outputTokenDetails)?void 0:_.reasoningTokens,null==(v=n.outputTokenDetails)?void 0:v.reasoningTokens)},totalTokens:rR(r.totalTokens,n.totalTokens),reasoningTokens:rR(r.reasoningTokens,n.reasoningTokens),cachedInputTokens:rR(r.cachedInputTokens,n.cachedInputTokens)});await U.promise;let x=eT.filter(e=>!0!==e.providerExecuted),k=eR.filter(e=>!0!==e.providerExecuted);for(let e of eT){if(!0!==e.providerExecuted)continue;let t=null==h?void 0:h[e.toolName];(null==t?void 0:t.type)==="provider"&&t.supportsDeferredResults&&!eR.some(t=>("tool-result"===t.type||"tool-error"===t.type)&&t.toolCallId===e.toolCallId)&&ee.set(e.toolCallId,{toolName:e.toolName})}for(let e of eR)("tool-result"===e.type||"tool-error"===e.type)&&ee.delete(e.toolCallId);if(H(),J(),(x.length>0&&k.length===x.length||ee.size>0)&&!await rW({stopConditions:g,steps:Q})){c.push(...await rX({content:Q[Q.length-1].content,tools:h}));try{await E({currentStep:a+1,responseMessages:c,usage:w})}catch(t){e.enqueue({type:"error",error:t}),ep.closeStream()}}else e.enqueue({type:"finish",finishReason:eZ,rawFinishReason:X,totalUsage:w}),ep.closeStream()}})))}finally{H(),J()}}J.push(...x),await E({currentStep:0,responseMessages:x,usage:rT()})}}).catch(e=>{ep.addStream(new ReadableStream({start(t){t.enqueue({type:"error",error:e}),t.close()}})),ep.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return r3(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){"text-delta"===e.type&&t.enqueue(e.text)}})))}get fullStream(){return r3(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await r8({stream:this.fullStream,onError:null==e?void 0:e.onError})}catch(r){null==(t=null==e?void 0:e.onError)||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return r3(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){null!=e&&t.enqueue(e)}})))}get elementStream(){var e,t,r;let a=null==(e=this.outputSpecification)?void 0:e.createElementStreamTransform();if(null==a)throw new $.A_({functionality:`element streams in ${null!=(r=null==(t=this.outputSpecification)?void 0:t.name)?r:"text"} mode`});return r3(this.teeStream().pipeThrough(a))}get output(){return this.finalStep.then(e=>{var t;return(null!=(t=this.outputSpecification)?t:rP()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:o=!1,sendStart:i=!0,sendFinish:s=!0,onError:l=$.e$}={}){let u=null!=t?function({originalMessages:e,responseMessageId:t}){if(null==e)return;let r=e[e.length-1];return(null==r?void 0:r.role)==="assistant"?r.id:"function"==typeof t?t():t}({originalMessages:e,responseMessageId:t}):void 0,d=e=>{var t;let r=null==(t=this.tools)?void 0:t[e.toolName];return null==r?e.dynamic:(null==r?void 0:r.type)==="dynamic"||void 0};return r3(function({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:a,onError:n,stream:o}){let i=null==t?void 0:t[t.length-1];(null==i?void 0:i.role)!=="assistant"?i=void 0:e=i.id;let s=!1,l=o.pipeThrough(new TransformStream({transform(t,r){"start"===t.type&&null==t.messageId&&null!=e&&(t.messageId=e),"abort"===t.type&&(s=!0),r.enqueue(t)}}));if(null==a&&null==r)return l;let u=function({lastMessage:e,messageId:t}){return{message:(null==e?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}({lastMessage:i?structuredClone(i):void 0,messageId:null!=e?e:""}),d=!1,c=async()=>{if(d||!a)return;d=!0;let e=u.message.id===(null==i?void 0:i.id);await a({isAborted:s,isContinuation:e,responseMessage:u.message,messages:[...e?t.slice(0,-1):t,u.message],finishReason:u.finishReason})},p=async()=>{if(!r)return;let e=u.message.id===(null==i?void 0:i.id);try{await r({isContinuation:e,responseMessage:structuredClone(u.message),messages:[...e?t.slice(0,-1):t,structuredClone(u.message)]})}catch(e){n(e)}};return(function({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(e,s){await a(async({state:a,write:l})=>{var u,d,c,p;function h(e){let t=a.message.parts.filter(r9).find(t=>t.toolCallId===e);if(null==t)throw new tS({chunkType:"tool-invocation",chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function m(e){var t;let r=a.message.parts.find(t=>r2(t)&&t.toolCallId===e.toolCallId);null!=r?(r.state=e.state,r.input=e.input,r.output=e.output,r.errorText=e.errorText,r.rawInput=e.rawInput,r.preliminary=e.preliminary,void 0!==e.title&&(r.title=e.title),r.providerExecuted=null!=(t=e.providerExecuted)?t:r.providerExecuted,null!=e.providerMetadata&&(r.callProviderMetadata=e.providerMetadata)):a.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,input:e.input,output:e.output,rawInput:e.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,preliminary:e.preliminary,...null!=e.providerMetadata?{callProviderMetadata:e.providerMetadata}:{}})}function f(e){var t,r;let n=a.message.parts.find(t=>"dynamic-tool"===t.type&&t.toolCallId===e.toolCallId);null!=n?(n.state=e.state,n.toolName=e.toolName,n.input=e.input,n.output=e.output,n.errorText=e.errorText,n.rawInput=null!=(t=e.rawInput)?t:n.rawInput,n.preliminary=e.preliminary,void 0!==e.title&&(n.title=e.title),n.providerExecuted=null!=(r=e.providerExecuted)?r:n.providerExecuted,null!=e.providerMetadata&&(n.callProviderMetadata=e.providerMetadata)):a.message.parts.push({type:"dynamic-tool",toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:e.input,output:e.output,errorText:e.errorText,preliminary:e.preliminary,providerExecuted:e.providerExecuted,title:e.title,...null!=e.providerMetadata?{callProviderMetadata:e.providerMetadata}:{}})}async function y(e){if(null!=e){let r=null!=a.message.metadata?rS(a.message.metadata,e):e;null!=t&&await (0,M.rJ)({value:r,schema:t,context:{field:"message.metadata",entityId:a.message.id}}),a.message.metadata=r}}switch(e.type){case"text-start":{let t={type:"text",text:"",providerMetadata:e.providerMetadata,state:"streaming"};a.activeTextParts[e.id]=t,a.message.parts.push(t),l();break}case"text-delta":{let t=a.activeTextParts[e.id];if(null==t)throw new tS({chunkType:"text-delta",chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=null!=(u=e.providerMetadata)?u:t.providerMetadata,l();break}case"text-end":{let t=a.activeTextParts[e.id];if(null==t)throw new tS({chunkType:"text-end",chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state="done",t.providerMetadata=null!=(d=e.providerMetadata)?d:t.providerMetadata,delete a.activeTextParts[e.id],l();break}case"reasoning-start":{let t={type:"reasoning",text:"",providerMetadata:e.providerMetadata,state:"streaming"};a.activeReasoningParts[e.id]=t,a.message.parts.push(t),l();break}case"reasoning-delta":{let t=a.activeReasoningParts[e.id];if(null==t)throw new tS({chunkType:"reasoning-delta",chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=null!=(c=e.providerMetadata)?c:t.providerMetadata,l();break}case"reasoning-end":{let t=a.activeReasoningParts[e.id];if(null==t)throw new tS({chunkType:"reasoning-end",chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=null!=(p=e.providerMetadata)?p:t.providerMetadata,t.state="done",delete a.activeReasoningParts[e.id],l();break}case"file":a.message.parts.push({type:"file",mediaType:e.mediaType,url:e.url,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}),l();break;case"source-url":a.message.parts.push({type:"source-url",sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),l();break;case"source-document":a.message.parts.push({type:"source-document",sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),l();break;case"tool-input-start":{let t=a.message.parts.filter(r2);a.partialToolCalls[e.toolCallId]={text:"",toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title},e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}):m({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-streaming",input:void 0,providerExecuted:e.providerExecuted,title:e.title,providerMetadata:e.providerMetadata}),l();break}case"tool-input-delta":{let t=a.partialToolCalls[e.toolCallId];if(null==t)throw new tS({chunkType:"tool-input-delta",chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:r}=await r$(t.text);t.dynamic?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:r,title:t.title}):m({toolCallId:e.toolCallId,toolName:t.toolName,state:"input-streaming",input:r,title:t.title}),l();break}case"tool-input-available":e.dynamic?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}):m({toolCallId:e.toolCallId,toolName:e.toolName,state:"input-available",input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title}),l(),o&&!e.providerExecuted&&await o({toolCall:e});break;case"tool-input-error":{let t=a.message.parts.filter(r9).find(t=>t.toolCallId===e.toolCallId);(null!=t?"dynamic-tool"===t.type:e.dynamic)?f({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}):m({toolCallId:e.toolCallId,toolName:e.toolName,state:"output-error",input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),l();break}case"tool-approval-request":{let t=h(e.toolCallId);t.state="approval-requested",t.approval={id:e.approvalId},l();break}case"tool-output-denied":h(e.toolCallId).state="output-denied",l();break;case"tool-output-available":{let t=h(e.toolCallId);"dynamic-tool"===t.type?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-available",input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,title:t.title}):m({toolCallId:e.toolCallId,toolName:r5(t),state:"output-available",input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,title:t.title}),l();break}case"tool-output-error":{let t=h(e.toolCallId);"dynamic-tool"===t.type?f({toolCallId:e.toolCallId,toolName:t.toolName,state:"output-error",input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,title:t.title}):m({toolCallId:e.toolCallId,toolName:r5(t),state:"output-error",input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,title:t.title}),l();break}case"start-step":a.message.parts.push({type:"step-start"});break;case"finish-step":a.activeTextParts={},a.activeReasoningParts={};break;case"start":null!=e.messageId&&(a.message.id=e.messageId),await y(e.messageMetadata),(null!=e.messageId||null!=e.messageMetadata)&&l();break;case"finish":null!=e.finishReason&&(a.finishReason=e.finishReason),await y(e.messageMetadata),null!=e.messageMetadata&&l();break;case"message-metadata":await y(e.messageMetadata),null!=e.messageMetadata&&l();break;case"error":null==n||n(Error(e.errorText));break;default:if(e.type.startsWith("data-")){if((null==r?void 0:r[e.type])!=null){let t=a.message.parts.findIndex(t=>"id"in t&&"data"in t&&t.id===e.id&&t.type===e.type),n=t>=0?t:a.message.parts.length;await (0,M.rJ)({value:e.data,schema:r[e.type],context:{field:`message.parts[${n}].data`,entityName:e.type,entityId:e.id}})}if(e.transient){null==i||i(e);break}let t=null!=e.id?a.message.parts.find(t=>e.type===t.type&&e.id===t.id):void 0;null!=t?t.data=e.data:a.message.parts.push(e),null==i||i(e),l()}}s.enqueue(e)})}}))})({stream:l,runUpdateMessageJob:async e=>{await e({state:u,write:()=>{}})},onError:n}).pipeThrough(new TransformStream({async transform(e,t){"finish-step"===e.type&&await p(),t.enqueue(e)},async cancel(){await c()},async flush(){await c()}}))}({stream:this.fullStream.pipeThrough(new TransformStream({transform:async(e,t)=>{let r=null==a?void 0:a({part:e}),c=e.type;switch(c){case"text-start":t.enqueue({type:"text-start",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"text-delta":t.enqueue({type:"text-delta",id:e.id,delta:e.text,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"text-end":t.enqueue({type:"text-end",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"reasoning-start":t.enqueue({type:"reasoning-start",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"reasoning-delta":n&&t.enqueue({type:"reasoning-delta",id:e.id,delta:e.text,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"reasoning-end":t.enqueue({type:"reasoning-end",id:e.id,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"file":t.enqueue({type:"file",mediaType:e.file.mediaType,url:`data:${e.file.mediaType};base64,${e.file.base64}`,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"source":o&&"url"===e.sourceType&&t.enqueue({type:"source-url",sourceId:e.id,url:e.url,title:e.title,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}}),o&&"document"===e.sourceType&&t.enqueue({type:"source-document",sourceId:e.id,mediaType:e.mediaType,title:e.title,filename:e.filename,...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{}});break;case"tool-input-start":{let r=d(e);t.enqueue({type:"tool-input-start",toolCallId:e.id,toolName:e.toolName,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{},...null!=r?{dynamic:r}:{},...null!=e.title?{title:e.title}:{}});break}case"tool-input-delta":t.enqueue({type:"tool-input-delta",toolCallId:e.id,inputTextDelta:e.delta});break;case"tool-call":{let r=d(e);e.invalid?t.enqueue({type:"tool-input-error",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{},...null!=r?{dynamic:r}:{},errorText:l(e.error),...null!=e.title?{title:e.title}:{}}):t.enqueue({type:"tool-input-available",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.providerMetadata?{providerMetadata:e.providerMetadata}:{},...null!=r?{dynamic:r}:{},...null!=e.title?{title:e.title}:{}});break}case"tool-approval-request":t.enqueue({type:"tool-approval-request",approvalId:e.approvalId,toolCallId:e.toolCall.toolCallId});break;case"tool-result":{let r=d(e);t.enqueue({type:"tool-output-available",toolCallId:e.toolCallId,output:e.output,...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=e.preliminary?{preliminary:e.preliminary}:{},...null!=r?{dynamic:r}:{}});break}case"tool-error":{let r=d(e);t.enqueue({type:"tool-output-error",toolCallId:e.toolCallId,errorText:l(e.error),...null!=e.providerExecuted?{providerExecuted:e.providerExecuted}:{},...null!=r?{dynamic:r}:{}});break}case"tool-output-denied":t.enqueue({type:"tool-output-denied",toolCallId:e.toolCallId});break;case"error":t.enqueue({type:"error",errorText:l(e.error)});break;case"start-step":t.enqueue({type:"start-step"});break;case"finish-step":t.enqueue({type:"finish-step"});break;case"start":i&&t.enqueue({type:"start",...null!=r?{messageMetadata:r}:{},...null!=u?{messageId:u}:{}});break;case"finish":s&&t.enqueue({type:"finish",finishReason:e.finishReason,...null!=r?{messageMetadata:r}:{}});break;case"abort":t.enqueue(e);break;case"tool-input-end":case"raw":break;default:throw Error(`Unknown chunk type: ${c}`)}null!=r&&"start"!==c&&"finish"!==c&&t.enqueue({type:"message-metadata",messageMetadata:r})}})),messageId:null!=u?u:null==t?void 0:t(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:o,sendSources:i,sendFinish:s,sendStart:l,onError:u,...d}={}){(function({response:e,status:t,statusText:r,headers:a,stream:n,consumeSseStream:o}){let i=n.pipeThrough(new rJ);if(o){let[e,t]=i.tee();i=e,o({stream:t})}rK({response:e,status:t,statusText:r,headers:Object.fromEntries(rB(a,rH).entries()),stream:i.pipeThrough(new TextEncoderStream)})})({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:o,sendSources:i,sendFinish:s,sendStart:l,onError:u}),...d})}pipeTextStreamToResponse(e,t){(function({response:e,status:t,statusText:r,headers:a,textStream:n}){rK({response:e,status:t,statusText:r,headers:Object.fromEntries(rB(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})})({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:o,sendFinish:i,sendStart:s,onError:l,...u}={}){return function({status:e,statusText:t,headers:r,stream:a,consumeSseStream:n}){let o=a.pipeThrough(new rJ);if(n){let[e,t]=o.tee();o=e,n({stream:t})}return new Response(o.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:rB(r,rH)})}({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:o,sendFinish:i,sendStart:s,onError:l}),...u})}toTextStreamResponse(e){return function({status:e,statusText:t,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:null!=e?e:200,statusText:t,headers:rB(r,{"content-type":"text/plain; charset=utf-8"})})}({textStream:this.textStream,...e})}};async function aa(e,t){let r=[];for(let n of((null==t?void 0:t.ignoreIncompleteToolCalls)&&(e=e.map(e=>({...e,parts:e.parts.filter(e=>!r9(e)||"input-streaming"!==e.state&&"input-available"!==e.state)}))),e))switch(n.role){case"system":{let e=n.parts.filter(e=>"text"===e.type),t=e.reduce((e,t)=>null!=t.providerMetadata?{...e,...t.providerMetadata}:e,{});r.push({role:"system",content:e.map(e=>e.text).join(""),...Object.keys(t).length>0?{providerOptions:t}:{}});break}case"user":r.push({role:"user",content:n.parts.map(e=>{var r;return rQ(e)?{type:"text",text:e.text,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}}:r0(e)?{type:"file",mediaType:e.mediaType,filename:e.filename,data:e.url,...null!=e.providerMetadata?{providerOptions:e.providerMetadata}:{}}:rY(e)?null==(r=null==t?void 0:t.convertDataPart)?void 0:r.call(t,e):void 0}).filter(M.C_)});break;case"assistant":if(null!=n.parts){let e=[];async function a(){var a,n,o,i,s,l;if(0===e.length)return;let u=[];for(let r of e)if(rQ(r))u.push({type:"text",text:r.text,...null!=r.providerMetadata?{providerOptions:r.providerMetadata}:{}});else if(r0(r))u.push({type:"file",mediaType:r.mediaType,filename:r.filename,data:r.url,...null!=r.providerMetadata?{providerOptions:r.providerMetadata}:{}});else if(r1(r))u.push({type:"reasoning",text:r.text,providerOptions:r.providerMetadata});else if(r9(r)){let e=r6(r);"input-streaming"!==r.state&&(u.push({type:"tool-call",toolCallId:r.toolCallId,toolName:e,input:"output-error"===r.state?null!=(a=r.input)?a:"rawInput"in r?r.rawInput:void 0:r.input,providerExecuted:r.providerExecuted,...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}}),null!=r.approval&&u.push({type:"tool-approval-request",approvalId:r.approval.id,toolCallId:r.toolCallId}),!0===r.providerExecuted&&"approval-responded"!==r.state&&("output-available"===r.state||"output-error"===r.state)&&u.push({type:"tool-result",toolCallId:r.toolCallId,toolName:e,output:await t8({toolCallId:r.toolCallId,input:r.input,output:"output-error"===r.state?r.errorText:r.output,tool:null==(n=null==t?void 0:t.tools)?void 0:n[e],errorMode:"output-error"===r.state?"json":"none"}),...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}}))}else if(rY(r)){let e=null==(o=null==t?void 0:t.convertDataPart)?void 0:o.call(t,r);null!=e&&u.push(e)}else throw Error(`Unsupported part: ${r}`);r.push({role:"assistant",content:u});let d=e.filter(e=>{var t;return r9(e)&&(!0!==e.providerExecuted||(null==(t=e.approval)?void 0:t.approved)!=null)});if(d.length>0){let e=[];for(let r of d)if((null==(i=r.approval)?void 0:i.approved)!=null&&e.push({type:"tool-approval-response",approvalId:r.approval.id,approved:r.approval.approved,reason:r.approval.reason,providerExecuted:r.providerExecuted}),!0!==r.providerExecuted)switch(r.state){case"output-denied":e.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r6(r),output:{type:"error-text",value:null!=(s=r.approval.reason)?s:"Tool execution denied."},...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}});break;case"output-error":case"output-available":{let a=r6(r);e.push({type:"tool-result",toolCallId:r.toolCallId,toolName:a,output:await t8({toolCallId:r.toolCallId,input:r.input,output:"output-error"===r.state?r.errorText:r.output,tool:null==(l=null==t?void 0:t.tools)?void 0:l[a],errorMode:"output-error"===r.state?"text":"none"}),...null!=r.callProviderMetadata?{providerOptions:r.callProviderMetadata}:{}})}}e.length>0&&r.push({role:"tool",content:e})}e=[]}for(let t of n.parts)rQ(t)||r1(t)||r0(t)||r9(t)||rY(t)?e.push(t):"step-start"===t.type&&await a();await a()}break;default:{let e=n.role;throw new tF({originalMessage:n,message:`Unsupported role: ${e}`})}}return r}var an=(0,M.DG)(()=>(0,M.r0)(P.IX(P.Ry({id:P.Z_(),role:P.Km(["system","user","assistant"]),metadata:P._4().optional(),parts:P.IX(P.G0([P.Ry({type:P.i0("text"),text:P.Z_(),state:P.Km(["streaming","done"]).optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("reasoning"),text:P.Z_(),state:P.Km(["streaming","done"]).optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("source-url"),sourceId:P.Z_(),url:P.Z_(),title:P.Z_().optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("source-document"),sourceId:P.Z_(),mediaType:P.Z_(),title:P.Z_(),filename:P.Z_().optional(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("file"),mediaType:P.Z_(),filename:P.Z_().optional(),url:P.Z_(),providerMetadata:rr.optional()}),P.Ry({type:P.i0("step-start")}),P.Ry({type:P.Z_().startsWith("data-"),id:P.Z_().optional(),data:P._4()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("input-streaming"),input:P._4().optional(),providerExecuted:P.O7().optional(),callProviderMetadata:rr.optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),approval:P.Fi().optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("input-available"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Fi().optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("approval-requested"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.Fi().optional(),reason:P.Fi().optional()})}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("approval-responded"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.O7(),reason:P.Z_().optional()})}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("output-available"),input:P._4(),providerExecuted:P.O7().optional(),output:P._4(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),preliminary:P.O7().optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("output-error"),input:P._4(),rawInput:P._4().optional(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Z_(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.i0("dynamic-tool"),toolName:P.Z_(),toolCallId:P.Z_(),state:P.i0("output-denied"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!1),reason:P.Z_().optional()})}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("input-streaming"),providerExecuted:P.O7().optional(),callProviderMetadata:rr.optional(),input:P._4().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),approval:P.Fi().optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("input-available"),providerExecuted:P.O7().optional(),input:P._4(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Fi().optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("approval-requested"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.Fi().optional(),reason:P.Fi().optional()})}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("approval-responded"),input:P._4(),providerExecuted:P.O7().optional(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.O7(),reason:P.Z_().optional()})}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("output-available"),providerExecuted:P.O7().optional(),input:P._4(),output:P._4(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),preliminary:P.O7().optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("output-error"),providerExecuted:P.O7().optional(),input:P._4(),rawInput:P._4().optional(),output:P.Fi().optional(),errorText:P.Z_(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!0),reason:P.Z_().optional()}).optional()}),P.Ry({type:P.Z_().startsWith("tool-"),toolCallId:P.Z_(),state:P.i0("output-denied"),providerExecuted:P.O7().optional(),input:P._4(),output:P.Fi().optional(),errorText:P.Fi().optional(),callProviderMetadata:rr.optional(),approval:P.Ry({id:P.Z_(),approved:P.i0(!1),reason:P.Z_().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function ao({messages:e,metadataSchema:t,dataSchemas:r,tools:a}){try{if(null==e)return{success:!1,error:new eJ({parameter:"messages",value:e,message:"messages parameter must be provided"})};let n=await validateTypes2({value:e,schema:an});if(t)for(let[e,r]of n.entries())await validateTypes2({value:r.metadata,schema:t,context:{field:`messages[${e}].metadata`,entityId:r.id}});if(r||a)for(let[e,t]of n.entries())for(let[n,o]of t.parts.entries()){if(r&&o.type.startsWith("data-")){let t=o.type.slice(5),a=r[t];if(!a)return{success:!1,error:new TypeValidationError3({value:o.data,cause:`No data schema found for data part ${t}`,context:{field:`messages[${e}].parts[${n}].data`,entityName:t,entityId:o.id}})};await validateTypes2({value:o.data,schema:a,context:{field:`messages[${e}].parts[${n}].data`,entityName:t,entityId:o.id}})}if(a&&o.type.startsWith("tool-")){let t=o.type.slice(5),r=a[t];if(!r)return{success:!1,error:new TypeValidationError3({value:o.input,cause:`No tool schema found for tool part ${t}`,context:{field:`messages[${e}].parts[${n}].input`,entityName:t,entityId:o.toolCallId}})};("input-available"===o.state||"output-available"===o.state||"output-error"===o.state&&void 0!==o.input)&&await validateTypes2({value:o.input,schema:r.inputSchema,context:{field:`messages[${e}].parts[${n}].input`,entityName:t,entityId:o.toolCallId}}),"output-available"===o.state&&r.outputSchema&&await validateTypes2({value:o.output,schema:r.outputSchema,context:{field:`messages[${e}].parts[${n}].output`,entityName:t,entityId:o.toolCallId}})}}return{success:!0,data:n}}catch(e){return{success:!1,error:e}}}async function ai(e,t,r){let a=await safeParseJSON4({text:e});if(!a.success)throw new ts({message:"No object generated: could not parse the response.",cause:a.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let n=await t.validateFinalResult(a.value,{text:e,response:r.response,usage:r.usage});if(!n.success)throw new ts({message:"No object generated: response did not match schema.",cause:n.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});return n.value}function as(e){return({url:t,abortSignal:r})=>t1({url:t,maxBytes:null==e?void 0:e.maxBytes,abortSignal:r})}(0,M.bF)({prefix:"aiobj",size:24}),(0,M.bF)({prefix:"aiobj",size:24}),as();var al=({model:e,middleware:{transformParams:t,wrapGenerate:r,wrapStream:a,overrideProvider:n,overrideModelId:o,overrideSupportedUrls:i},modelId:s,providerId:l})=>{var u,d,c;async function p({params:r,type:a}){return t?await t({params:r,type:a,model:e}):r}return{specificationVersion:"v3",provider:null!=(u=null!=l?l:null==n?void 0:n({model:e}))?u:e.provider,modelId:null!=(d=null!=s?s:null==o?void 0:o({model:e}))?d:e.modelId,supportedUrls:null!=(c=null==i?void 0:i({model:e}))?c:e.supportedUrls,async doGenerate(t){let a=await p({params:t,type:"generate"}),n=async()=>e.doGenerate(a),o=async()=>e.doStream(a);return r?r({doGenerate:n,doStream:o,params:a,model:e}):n()},async doStream(t){let r=await p({params:t,type:"stream"}),n=async()=>e.doGenerate(r),o=async()=>e.doStream(r);return a?a({doGenerate:n,doStream:o,params:r,model:e}):o()}}},au=({model:e,middleware:{transformParams:t,wrapGenerate:r,overrideProvider:a,overrideModelId:n,overrideMaxImagesPerCall:o},modelId:i,providerId:s})=>{var l,u,d;async function c({params:r}){return t?await t({params:r,model:e}):r}let p=null!=(l=null==o?void 0:o({model:e}))?l:e.maxImagesPerCall,h=p instanceof Function?p.bind(e):p;return{specificationVersion:"v3",provider:null!=(u=null!=s?s:null==a?void 0:a({model:e}))?u:e.provider,modelId:null!=(d=null!=i?i:null==n?void 0:n({model:e}))?d:e.modelId,maxImagesPerCall:h,async doGenerate(t){let a=await c({params:t}),n=async()=>e.doGenerate(a);return r?r({doGenerate:n,params:a,model:e}):n()}}},ad="AI_NoSuchProviderError",ac=`vercel.ai.error.${ad}`,ap=Symbol.for(ac);$.JJ,N=ap,as()},9763:(e,t,r)=>{var a,n,o,i;let s;r.d(t,{pA:()=>i,IX:()=>eE,VK:()=>eN,Km:()=>e$,i0:()=>eM,Rx:()=>eC,Ry:()=>eO,Z_:()=>eZ,G0:()=>eA}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(let e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(a||(a={})),(n||(n={})).mergeShapes=(e,t)=>({...e,...t});let l=a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),u=e=>{switch(typeof e){case"undefined":return l.undefined;case"string":return l.string;case"number":return Number.isNaN(e)?l.nan:l.number;case"boolean":return l.boolean;case"function":return l.function;case"bigint":return l.bigint;case"symbol":return l.symbol;case"object":if(Array.isArray(e))return l.array;if(null===e)return l.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return l.promise;if("undefined"!=typeof Map&&e instanceof Map)return l.map;if("undefined"!=typeof Set&&e instanceof Set)return l.set;if("undefined"!=typeof Date&&e instanceof Date)return l.date;return l.object;default:return l.unknown}},d=a.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 c extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)r._errors.push(t(n));else{let e=r,a=0;for(;a<n.path.length;){let r=n.path[a];a===n.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(n))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof c))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t={},r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);let p=(e,t)=>{let r;switch(e.code){case d.invalid_type:r=e.received===l.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,a.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${a.joinValues(e.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${a.joinValues(e.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${a.joinValues(e.options)}, received '${e.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:a.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case d.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case d.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=t.defaultError,a.assertNever(e)}return{message:r}};!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(o||(o={}));let h=e=>{let{data:t,path:r,errorMaps:a,issueData:n}=e,o=[...r,...n.path||[]],i={...n,path:o};if(void 0!==n.message)return{...n,path:o,message:n.message};let s="";for(let e of a.filter(e=>!!e).slice().reverse())s=e(i,{data:t,defaultError:s}).message;return{...n,path:o,message:s}};function m(e,t){let r=h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,p,p==p?void 0:p].filter(e=>!!e)});e.common.issues.push(r)}class f{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return y;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return f.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:n}=a;if("aborted"===t.status||"aborted"===n.status)return y;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==n.value||a.alwaysSet)&&(r[t.value]=n.value)}return{status:e.value,value:r}}}let y=Object.freeze({status:"aborted"}),_=e=>({status:"dirty",value:e}),g=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,b=e=>"dirty"===e.status,w=e=>"valid"===e.status,x=e=>"undefined"!=typeof Promise&&e instanceof Promise;class k{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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}}let I=(e,t)=>{if(w(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new c(e.common.issues);return this._error=t,this._error}}};function T(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:n}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{let{message:o}=e;return"invalid_enum_value"===t.code?{message:o??n.defaultError}:void 0===n.data?{message:o??a??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:o??r??n.defaultError}},description:n}}class R{get description(){return this._def.description}_getType(e){return u(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:u(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new f,ctx:{common:e.parent.common,data:e.data,parsedType:u(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(x(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:u(e)},a=this._parseSync({data:e,path:r.path,parent:r});return I(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:u(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return w(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>w(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:u(e)},a=this._parse({data:e,path:r.path,parent:r});return I(r,await (x(a)?a:Promise.resolve(a)))}refine(e,t){let r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{let n=e(t),o=()=>a.addIssue({code:d.custom,...r(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(o(),!1)):!!n||(o(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new ev({schema:this,typeName:i.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:e=>this["~validate"](e)}}optional(){return eb.create(this,this._def)}nullable(){return ew.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return er.create(this)}promise(){return eg.create(this,this._def)}or(e){return en.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new ev({...T(this._def),schema:this,typeName:i.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new ex({...T(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:i.ZodDefault})}brand(){return new eT({typeName:i.ZodBranded,type:this,...T(this._def)})}catch(e){return new ek({...T(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:i.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eR.create(this,e)}readonly(){return eS.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let S=/^c[^\s-]{8,}$/i,Z=/^[0-9a-z]+$/,C=/^[0-9A-HJKMNP-TV-Z]{26}$/i,E=/^[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,O=/^[a-z0-9_-]{21}$/i,A=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N=/^[-+]?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)?)??$/,M=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$=/^(?:(?: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])$/,P=/^(?:(?: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])$/,j=/^(([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]))$/,F=/^(([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])$/,z=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,D=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,q="((\\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])))",U=RegExp(`^${q}$`);function L(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class V extends R{_parse(e){var t,r,n,o;let i;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==l.string){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.string,received:t.parsedType}),y}let u=new f;for(let l of this._def.checks)if("min"===l.kind)e.data.length<l.value&&(m(i=this._getOrReturnCtx(e,i),{code:d.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),u.dirty());else if("max"===l.kind)e.data.length>l.value&&(m(i=this._getOrReturnCtx(e,i),{code:d.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),u.dirty());else if("length"===l.kind){let t=e.data.length>l.value,r=e.data.length<l.value;(t||r)&&(i=this._getOrReturnCtx(e,i),t?m(i,{code:d.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):r&&m(i,{code:d.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),u.dirty())}else if("email"===l.kind)M.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"email",code:d.invalid_string,message:l.message}),u.dirty());else if("emoji"===l.kind)s||(s=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),s.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"emoji",code:d.invalid_string,message:l.message}),u.dirty());else if("uuid"===l.kind)E.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"uuid",code:d.invalid_string,message:l.message}),u.dirty());else if("nanoid"===l.kind)O.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"nanoid",code:d.invalid_string,message:l.message}),u.dirty());else if("cuid"===l.kind)S.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"cuid",code:d.invalid_string,message:l.message}),u.dirty());else if("cuid2"===l.kind)Z.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"cuid2",code:d.invalid_string,message:l.message}),u.dirty());else if("ulid"===l.kind)C.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"ulid",code:d.invalid_string,message:l.message}),u.dirty());else if("url"===l.kind)try{new URL(e.data)}catch{m(i=this._getOrReturnCtx(e,i),{validation:"url",code:d.invalid_string,message:l.message}),u.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"regex",code:d.invalid_string,message:l.message}),u.dirty())):"trim"===l.kind?e.data=e.data.trim():"includes"===l.kind?e.data.includes(l.value,l.position)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),u.dirty()):"toLowerCase"===l.kind?e.data=e.data.toLowerCase():"toUpperCase"===l.kind?e.data=e.data.toUpperCase():"startsWith"===l.kind?e.data.startsWith(l.value)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:{startsWith:l.value},message:l.message}),u.dirty()):"endsWith"===l.kind?e.data.endsWith(l.value)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:{endsWith:l.value},message:l.message}),u.dirty()):"datetime"===l.kind?(function(e){let t=`${q}T${L(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(l).test(e.data)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:"datetime",message:l.message}),u.dirty()):"date"===l.kind?U.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:"date",message:l.message}),u.dirty()):"time"===l.kind?RegExp(`^${L(l)}$`).test(e.data)||(m(i=this._getOrReturnCtx(e,i),{code:d.invalid_string,validation:"time",message:l.message}),u.dirty()):"duration"===l.kind?N.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"duration",code:d.invalid_string,message:l.message}),u.dirty()):"ip"===l.kind?(t=e.data,("v4"===(r=l.version)||!r)&&$.test(t)||("v6"===r||!r)&&j.test(t)||(m(i=this._getOrReturnCtx(e,i),{validation:"ip",code:d.invalid_string,message:l.message}),u.dirty())):"jwt"===l.kind?!function(e,t){if(!A.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));if("object"!=typeof n||null===n||"typ"in n&&n?.typ!=="JWT"||!n.alg||t&&n.alg!==t)return!1;return!0}catch{return!1}}(e.data,l.alg)&&(m(i=this._getOrReturnCtx(e,i),{validation:"jwt",code:d.invalid_string,message:l.message}),u.dirty()):"cidr"===l.kind?(n=e.data,("v4"===(o=l.version)||!o)&&P.test(n)||("v6"===o||!o)&&F.test(n)||(m(i=this._getOrReturnCtx(e,i),{validation:"cidr",code:d.invalid_string,message:l.message}),u.dirty())):"base64"===l.kind?z.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"base64",code:d.invalid_string,message:l.message}),u.dirty()):"base64url"===l.kind?D.test(e.data)||(m(i=this._getOrReturnCtx(e,i),{validation:"base64url",code:d.invalid_string,message:l.message}),u.dirty()):a.assertNever(l);return{status:u.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:d.invalid_string,...o.errToObj(r)})}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...o.errToObj(e)})}url(e){return this._addCheck({kind:"url",...o.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...o.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...o.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...o.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...o.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...o.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...o.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...o.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...o.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...o.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...o.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...o.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...o.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...o.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...o.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...o.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...o.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...o.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...o.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...o.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...o.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...o.errToObj(t)})}nonempty(e){return this.min(1,o.errToObj(e))}trim(){return new V({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new V({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new V({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}V.create=e=>new V({checks:[],typeName:i.ZodString,coerce:e?.coerce??!1,...T(e)});class G extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==l.number){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.number,received:t.parsedType}),y}let r=new f;for(let n of this._def.checks)"int"===n.kind?a.isInteger(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:d.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}(e.data,n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(m(t=this._getOrReturnCtx(e,t),{code:d.not_finite,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,a){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(a)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:o.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:o.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:o.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:o.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&a.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}G.create=e=>new G({checks:[],typeName:i.ZodNumber,coerce:e?.coerce||!1,...T(e)});class W extends R{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==l.bigint)return this._getInvalidInput(e);let r=new f;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(m(t=this._getOrReturnCtx(e,t),{code:d.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,a){return new W({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(a)}]})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}W.create=e=>new W({checks:[],typeName:i.ZodBigInt,coerce:e?.coerce??!1,...T(e)});class X extends R{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==l.boolean){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.boolean,received:t.parsedType}),y}return g(e.data)}}X.create=e=>new X({typeName:i.ZodBoolean,coerce:e?.coerce||!1,...T(e)});class B extends R{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==l.date){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.date,received:t.parsedType}),y}if(Number.isNaN(e.data.getTime()))return m(this._getOrReturnCtx(e),{code:d.invalid_date}),y;let r=new f;for(let n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(m(t=this._getOrReturnCtx(e,t),{code:d.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):a.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:o.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:o.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}B.create=e=>new B({checks:[],coerce:e?.coerce||!1,typeName:i.ZodDate,...T(e)});class K extends R{_parse(e){if(this._getType(e)!==l.symbol){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.symbol,received:t.parsedType}),y}return g(e.data)}}K.create=e=>new K({typeName:i.ZodSymbol,...T(e)});class J extends R{_parse(e){if(this._getType(e)!==l.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.undefined,received:t.parsedType}),y}return g(e.data)}}J.create=e=>new J({typeName:i.ZodUndefined,...T(e)});class H extends R{_parse(e){if(this._getType(e)!==l.null){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.null,received:t.parsedType}),y}return g(e.data)}}H.create=e=>new H({typeName:i.ZodNull,...T(e)});class Y extends R{constructor(){super(...arguments),this._any=!0}_parse(e){return g(e.data)}}Y.create=e=>new Y({typeName:i.ZodAny,...T(e)});class Q extends R{constructor(){super(...arguments),this._unknown=!0}_parse(e){return g(e.data)}}Q.create=e=>new Q({typeName:i.ZodUnknown,...T(e)});class ee extends R{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.never,received:t.parsedType}),y}}ee.create=e=>new ee({typeName:i.ZodNever,...T(e)});class et extends R{_parse(e){if(this._getType(e)!==l.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.void,received:t.parsedType}),y}return g(e.data)}}et.create=e=>new et({typeName:i.ZodVoid,...T(e)});class er extends R{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==l.array)return m(t,{code:d.invalid_type,expected:l.array,received:t.parsedType}),y;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(m(t,{code:e?d.too_big:d.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(m(t,{code:d.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(m(t,{code:d.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new k(t,e,t.path,r)))).then(e=>f.mergeArray(r,e));let n=[...t.data].map((e,r)=>a.type._parseSync(new k(t,e,t.path,r)));return f.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new er({...this._def,minLength:{value:e,message:o.toString(t)}})}max(e,t){return new er({...this._def,maxLength:{value:e,message:o.toString(t)}})}length(e,t){return new er({...this._def,exactLength:{value:e,message:o.toString(t)}})}nonempty(e){return this.min(1,e)}}er.create=(e,t)=>new er({type:e,minLength:null,maxLength:null,exactLength:null,typeName:i.ZodArray,...T(t)});class ea extends R{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=a.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==l.object){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.object,received:t.parsedType}),y}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),o=[];if(!(this._def.catchall instanceof ee&&"strip"===this._def.unknownKeys))for(let e in r.data)n.includes(e)||o.push(e);let i=[];for(let e of n){let t=a[e],n=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new k(r,n,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ee){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of o)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(m(r,{code:d.unrecognized_keys,keys:o}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of o){let a=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new k(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of i){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>f.mergeObjectSync(t,e)):f.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return o.errToObj,new ea({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:o.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ea({...this._def,unknownKeys:"strip"})}passthrough(){return new ea({...this._def,unknownKeys:"passthrough"})}extend(e){return new ea({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ea({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:i.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ea({...this._def,catchall:e})}pick(e){let t={};for(let r of a.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ea({...this._def,shape:()=>t})}omit(e){let t={};for(let r of a.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ea({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof ea){let r={};for(let a in t.shape){let n=t.shape[a];r[a]=eb.create(e(n))}return new ea({...t._def,shape:()=>r})}return t instanceof er?new er({...t._def,type:e(t.element)}):t instanceof eb?eb.create(e(t.unwrap())):t instanceof ew?ew.create(e(t.unwrap())):t instanceof el?el.create(t.items.map(t=>e(t))):t}(this)}partial(e){let t={};for(let r of a.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new ea({...this._def,shape:()=>t})}required(e){let t={};for(let r of a.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eb;)e=e._def.innerType;t[r]=e}return new ea({...this._def,shape:()=>t})}keyof(){return ef(a.objectKeys(this.shape))}}ea.create=(e,t)=>new ea({shape:()=>e,unknownKeys:"strip",catchall:ee.create(),typeName:i.ZodObject,...T(t)}),ea.strictCreate=(e,t)=>new ea({shape:()=>e,unknownKeys:"strict",catchall:ee.create(),typeName:i.ZodObject,...T(t)}),ea.lazycreate=(e,t)=>new ea({shape:e,unknownKeys:"strip",catchall:ee.create(),typeName:i.ZodObject,...T(t)});class en extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new c(e.ctx.common.issues));return m(t,{code:d.invalid_union,unionErrors:r}),y});{let e;let a=[];for(let n of r){let r={...t,common:{...t.common,issues:[]},parent:null},o=n._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let n=a.map(e=>new c(e));return m(t,{code:d.invalid_union,unionErrors:n}),y}}get options(){return this._def.options}}en.create=(e,t)=>new en({options:e,typeName:i.ZodUnion,...T(t)});let eo=e=>{if(e instanceof eh)return eo(e.schema);if(e instanceof ev)return eo(e.innerType());if(e instanceof em)return[e.value];if(e instanceof ey)return e.options;if(e instanceof e_)return a.objectValues(e.enum);if(e instanceof ex)return eo(e._def.innerType);if(e instanceof J)return[void 0];else if(e instanceof H)return[null];else if(e instanceof eb)return[void 0,...eo(e.unwrap())];else if(e instanceof ew)return[null,...eo(e.unwrap())];else if(e instanceof eT)return eo(e.unwrap());else if(e instanceof eS)return eo(e.unwrap());else if(e instanceof ek)return eo(e._def.innerType);else return[]};class ei extends R{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.object)return m(t,{code:d.invalid_type,expected:l.object,received:t.parsedType}),y;let r=this.discriminator,a=t.data[r],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(m(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let r of t){let t=eo(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let n of t){if(a.has(n))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);a.set(n,r)}}return new ei({typeName:i.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...T(r)})}}class es extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return y;let o=function e(t,r){let n=u(t),o=u(r);if(t===r)return{valid:!0,data:t};if(n===l.object&&o===l.object){let n=a.objectKeys(r),o=a.objectKeys(t).filter(e=>-1!==n.indexOf(e)),i={...t,...r};for(let a of o){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1};i[a]=n.data}return{valid:!0,data:i}}if(n===l.array&&o===l.array){if(t.length!==r.length)return{valid:!1};let a=[];for(let n=0;n<t.length;n++){let o=e(t[n],r[n]);if(!o.valid)return{valid:!1};a.push(o.data)}return{valid:!0,data:a}}return n===l.date&&o===l.date&&+t==+r?{valid:!0,data:t}:{valid:!1}}(e.value,n.value);return o.valid?((b(e)||b(n))&&t.dirty(),{status:t.value,value:o.data}):(m(r,{code:d.invalid_intersection_types}),y)};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(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}es.create=(e,t,r)=>new es({left:e,right:t,typeName:i.ZodIntersection,...T(r)});class el extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.array)return m(r,{code:d.invalid_type,expected:l.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return m(r,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(m(r,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new k(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>f.mergeArray(t,e)):f.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new el({...this._def,rest:e})}}el.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new el({items:e,typeName:i.ZodTuple,rest:null,...T(t)})};class eu extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.object)return m(r,{code:d.invalid_type,expected:l.object,received:r.parsedType}),y;let a=[],n=this._def.keyType,o=this._def.valueType;for(let e in r.data)a.push({key:n._parse(new k(r,e,r.path,e)),value:o._parse(new k(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?f.mergeObjectAsync(t,a):f.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new eu(t instanceof R?{keyType:e,valueType:t,typeName:i.ZodRecord,...T(r)}:{keyType:V.create(),valueType:e,typeName:i.ZodRecord,...T(t)})}}class ed extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.map)return m(r,{code:d.invalid_type,expected:l.map,received:r.parsedType}),y;let a=this._def.keyType,n=this._def.valueType,o=[...r.data.entries()].map(([e,t],o)=>({key:a._parse(new k(r,e,r.path,[o,"key"])),value:n._parse(new k(r,t,r.path,[o,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of o){let a=await r.key,n=await r.value;if("aborted"===a.status||"aborted"===n.status)return y;("dirty"===a.status||"dirty"===n.status)&&t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of o){let a=r.key,n=r.value;if("aborted"===a.status||"aborted"===n.status)return y;("dirty"===a.status||"dirty"===n.status)&&t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}}ed.create=(e,t,r)=>new ed({valueType:t,keyType:e,typeName:i.ZodMap,...T(r)});class ec extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==l.set)return m(r,{code:d.invalid_type,expected:l.set,received:r.parsedType}),y;let a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(m(r,{code:d.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(m(r,{code:d.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function o(e){let r=new Set;for(let a of e){if("aborted"===a.status)return y;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let i=[...r.data.values()].map((e,t)=>n._parse(new k(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>o(e)):o(i)}min(e,t){return new ec({...this._def,minSize:{value:e,message:o.toString(t)}})}max(e,t){return new ec({...this._def,maxSize:{value:e,message:o.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ec.create=(e,t)=>new ec({valueType:e,minSize:null,maxSize:null,typeName:i.ZodSet,...T(t)});class ep extends R{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==l.function)return m(t,{code:d.invalid_type,expected:l.function,received:t.parsedType}),y;function r(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,p,p].filter(e=>!!e),issueData:{code:d.invalid_arguments,argumentsError:r}})}function a(e,r){return h({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,p,p].filter(e=>!!e),issueData:{code:d.invalid_return_type,returnTypeError:r}})}let n={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof eg){let e=this;return g(async function(...t){let i=new c([]),s=await e._def.args.parseAsync(t,n).catch(e=>{throw i.addIssue(r(t,e)),i}),l=await Reflect.apply(o,this,s);return await e._def.returns._def.type.parseAsync(l,n).catch(e=>{throw i.addIssue(a(l,e)),i})})}{let e=this;return g(function(...t){let i=e._def.args.safeParse(t,n);if(!i.success)throw new c([r(t,i.error)]);let s=Reflect.apply(o,this,i.data),l=e._def.returns.safeParse(s,n);if(!l.success)throw new c([a(s,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ep({...this._def,args:el.create(e).rest(Q.create())})}returns(e){return new ep({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ep({args:e||el.create([]).rest(Q.create()),returns:t||Q.create(),typeName:i.ZodFunction,...T(r)})}}class eh extends R{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}eh.create=(e,t)=>new eh({getter:e,typeName:i.ZodLazy,...T(t)});class em extends R{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ef(e,t){return new ey({values:e,typeName:i.ZodEnum,...T(t)})}em.create=(e,t)=>new em({value:e,typeName:i.ZodLiteral,...T(t)});class ey extends R{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{expected:a.joinValues(r),received:t.parsedType,code:d.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return m(t,{received:t.data,code:d.invalid_enum_value,options:r}),y}return g(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ey.create(e,{...this._def,...t})}exclude(e,t=this._def){return ey.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ey.create=ef;class e_ extends R{_parse(e){let t=a.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==l.string&&r.parsedType!==l.number){let e=a.objectValues(t);return m(r,{expected:a.joinValues(e),received:r.parsedType,code:d.invalid_type}),y}if(this._cache||(this._cache=new Set(a.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=a.objectValues(t);return m(r,{received:r.data,code:d.invalid_enum_value,options:e}),y}return g(e.data)}get enum(){return this._def.values}}e_.create=(e,t)=>new e_({values:e,typeName:i.ZodNativeEnum,...T(t)});class eg extends R{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==l.promise&&!1===t.common.async?(m(t,{code:d.invalid_type,expected:l.promise,received:t.parsedType}),y):g((t.parsedType===l.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}eg.create=(e,t)=>new eg({type:e,typeName:i.ZodPromise,...T(t)});class ev extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===i.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:e=>{m(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){let e=n.transform(r.data,o);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return y;let a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?y:"dirty"===a.status||"dirty"===t.value?_(a.value):a});{if("aborted"===t.value)return y;let a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?y:"dirty"===a.status||"dirty"===t.value?_(a.value):a}}if("refinement"===n.type){let e=e=>{let t=n.refinement(e,o);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?y:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===n.type){if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>w(e)?Promise.resolve(n.transform(e.value,o)).then(e=>({status:t.value,value:e})):y);{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!w(e))return y;let a=n.transform(e.value,o);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}}a.assertNever(n)}}ev.create=(e,t,r)=>new ev({schema:e,typeName:i.ZodEffects,effect:t,...T(r)}),ev.createWithPreprocess=(e,t,r)=>new ev({schema:t,effect:{type:"preprocess",transform:e},typeName:i.ZodEffects,...T(r)});class eb extends R{_parse(e){return this._getType(e)===l.undefined?g(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:i.ZodOptional,...T(t)});class ew extends R{_parse(e){return this._getType(e)===l.null?g(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ew.create=(e,t)=>new ew({innerType:e,typeName:i.ZodNullable,...T(t)});class ex extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===l.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ex.create=(e,t)=>new ex({innerType:e,typeName:i.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...T(t)});class ek extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return x(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ek.create=(e,t)=>new ek({innerType:e,typeName:i.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...T(t)});class eI extends R{_parse(e){if(this._getType(e)!==l.nan){let t=this._getOrReturnCtx(e);return m(t,{code:d.invalid_type,expected:l.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}eI.create=e=>new eI({typeName:i.ZodNaN,...T(e)}),Symbol("zod_brand");class eT extends R{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class eR extends R{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),_(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new eR({in:e,out:t,typeName:i.ZodPipeline})}}class eS extends R{_parse(e){let t=this._def.innerType._parse(e),r=e=>(w(e)&&(e.value=Object.freeze(e.value)),e);return x(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}eS.create=(e,t)=>new eS({innerType:e,typeName:i.ZodReadonly,...T(t)}),ea.lazycreate,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"}(i||(i={}));let eZ=V.create,eC=G.create;eI.create,W.create,X.create,B.create,K.create,J.create,H.create,Y.create,Q.create,ee.create,et.create;let eE=er.create,eO=ea.create;ea.strictCreate;let eA=en.create,eN=ei.create;es.create,el.create,eu.create,ed.create,ec.create,ep.create,eh.create;let eM=em.create,e$=ey.create;e_.create,eg.create,ev.create,eb.create,ew.create,ev.createWithPreprocess,eR.create},3947:(e,t,r)=>{r.d(t,{Qc:()=>l,Vw:()=>u,As:()=>d,X9:()=>c});var a=r(7481),n=r(8775),o=r(9921);let i=(e,t)=>{n.h1.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>n.Z(e,t)},flatten:{value:t=>n.MK(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})};o.IF("ZodError",i);let s=o.IF("ZodError",i,{Parent:Error}),l=a.lk(s),u=a.T2(s),d=a.Yn(s),c=a.G(s)},2943:(e,t,r)=>{r.d(t,{o4:()=>tb,Yj:()=>tK,IX:()=>t1,O7:()=>tG,PG:()=>rI,VK:()=>t7,Km:()=>ri,Pp:()=>rT,Vo:()=>rx,i0:()=>rl,d7:()=>t5,Fi:()=>tQ,lB:()=>tX,Rx:()=>tq,Ry:()=>t4,IM:()=>rn,cf:()=>t9,Z_:()=>tv,bc:()=>rr,G0:()=>t3,_4:()=>tH});var a=r(9921);let n=/^[cC][^\s-]{8,}$/,o=/^[0-9a-z]+$/,i=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,s=/^[0-9a-vA-V]{20}$/,l=/^[A-Za-z0-9]{27}$/,u=/^[a-zA-Z0-9_-]{21}$/,d=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,c=/^([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})$/,p=e=>e?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)$/,h=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,m=/^(?:(?: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])$/,f=/^(([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})$/,y=/^((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])$/,_=/^(([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])$/,g=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,v=/^[A-Za-z0-9_-]*$/,b=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,w=/^\+(?:[0-9]){6,14}[0-9]$/,x="(?:(?:\\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])))",k=RegExp(`^${x}$`);function I(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let T=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return RegExp(`^${t}$`)},R=/^\d+$/,S=/^-?\d+(?:\.\d+)?/i,Z=/true|false/i,C=/null/i,E=/^[^A-Z]*$/,O=/^[^a-z]*$/;var A=r(8510);let N=a.IF("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),M={number:"number",bigint:"bigint",object:"date"},$=a.IF("$ZodCheckLessThan",(e,t)=>{N.init(e,t);let r=M[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),P=a.IF("$ZodCheckGreaterThan",(e,t)=>{N.init(e,t);let r=M[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),j=a.IF("$ZodCheckMultipleOf",(e,t)=>{N.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===A.k8(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),F=a.IF("$ZodCheckNumberFormat",(e,t)=>{N.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[n,o]=A.Fl[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=n,a.maximum=o,r&&(a.pattern=R)}),e._zod.check=i=>{let s=i.value;if(r){if(!Number.isInteger(s)){i.issues.push({expected:a,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?i.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort}):i.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort});return}}s<n&&i.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>o&&i.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),z=a.IF("$ZodCheckMaxLength",(e,t)=>{var r;N.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!A.NZ(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let a=r.value;if(a.length<=t.maximum)return;let n=A.XU(a);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),D=a.IF("$ZodCheckMinLength",(e,t)=>{var r;N.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!A.NZ(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;if(a.length>=t.minimum)return;let n=A.XU(a);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),q=a.IF("$ZodCheckLengthEquals",(e,t)=>{var r;N.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return!A.NZ(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let a=r.value,n=a.length;if(n===t.length)return;let o=A.XU(a),i=n>t.length;r.issues.push({origin:o,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),U=a.IF("$ZodCheckStringFormat",(e,t)=>{var r,a;N.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),L=a.IF("$ZodCheckRegex",(e,t)=>{U.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),V=a.IF("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=E),U.init(e,t)}),G=a.IF("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=O),U.init(e,t)}),W=a.IF("$ZodCheckIncludes",(e,t)=>{N.init(e,t);let r=A.yI(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=a,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),X=a.IF("$ZodCheckStartsWith",(e,t)=>{N.init(e,t);let r=RegExp(`^${A.yI(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),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})}}),B=a.IF("$ZodCheckEndsWith",(e,t)=>{N.init(e,t);let r=RegExp(`.*${A.yI(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),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})}}),K=a.IF("$ZodCheckOverwrite",(e,t)=>{N.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class J{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}var H=r(7481);let Y={major:4,minor:0,patch:0},Q=a.IF("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Y;let n=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&n.unshift(e),n))for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,o=A.Ko(e);for(let i of t){if(i._zod.def.when){if(!i._zod.def.when(e))continue}else if(o)continue;let t=e.issues.length,s=i._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new a.TG;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s,e.issues.length===t||o||(o=A.Ko(e,t))});else{if(e.issues.length===t)continue;o||(o=A.Ko(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,o)=>{let i=e._zod.parse(r,o);if(i instanceof Promise){if(!1===o.async)throw new a.TG;return i.then(e=>t(e,n,o))}return t(i,n,o)}}e["~standard"]={validate:t=>{try{let r=(0,H.As)(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return(0,H.X9)(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),ee=a.IF("$ZodString",(e,t)=>{Q.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??T(e._zod.bag),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),et=a.IF("$ZodStringFormat",(e,t)=>{U.init(e,t),ee.init(e,t)}),er=a.IF("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=c),et.init(e,t)}),ea=a.IF("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=p(e))}else t.pattern??(t.pattern=p());et.init(e,t)}),en=a.IF("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=h),et.init(e,t)}),eo=a.IF("$ZodURL",(e,t)=>{et.init(e,t),e._zod.check=r=>{try{let a=r.value,n=new URL(a),o=n.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:b.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!a.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ei=a.IF("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),et.init(e,t)}),es=a.IF("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=u),et.init(e,t)}),el=a.IF("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=n),et.init(e,t)}),eu=a.IF("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=o),et.init(e,t)}),ed=a.IF("$ZodULID",(e,t)=>{t.pattern??(t.pattern=i),et.init(e,t)}),ec=a.IF("$ZodXID",(e,t)=>{t.pattern??(t.pattern=s),et.init(e,t)}),ep=a.IF("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=l),et.init(e,t)}),eh=a.IF("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){let t=I({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let a=`${t}(?:${r.join("|")})`;return RegExp(`^${x}T(?:${a})$`)}(t)),et.init(e,t)}),em=a.IF("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=k),et.init(e,t)}),ef=a.IF("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RegExp(`^${I(t)}$`)),et.init(e,t)}),ey=a.IF("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=d),et.init(e,t)}),e_=a.IF("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=m),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),eg=a.IF("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=f),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),ev=a.IF("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=y),et.init(e,t)}),eb=a.IF("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=_),et.init(e,t),e._zod.check=r=>{let[a,n]=r.value.split("/");try{if(!n)throw Error();let e=Number(n);if(`${e}`!==n||e<0||e>128)throw Error();new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function ew(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let ex=a.IF("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=g),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{ew(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),ek=a.IF("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=v),et.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{!function(e){if(!v.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ew(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),eI=a.IF("$ZodE164",(e,t)=>{t.pattern??(t.pattern=w),et.init(e,t)}),eT=a.IF("$ZodJWT",(e,t)=>{et.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let n=JSON.parse(atob(a));if("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),eR=a.IF("$ZodNumber",(e,t)=>{Q.init(e,t),e._zod.pattern=e._zod.bag.pattern??S,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;let o="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...o?{received:o}:{}}),r}}),eS=a.IF("$ZodNumber",(e,t)=>{F.init(e,t),eR.init(e,t)}),eZ=a.IF("$ZodBoolean",(e,t)=>{Q.init(e,t),e._zod.pattern=Z,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let n=r.value;return"boolean"==typeof n||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),eC=a.IF("$ZodNull",(e,t)=>{Q.init(e,t),e._zod.pattern=C,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}}),eE=a.IF("$ZodAny",(e,t)=>{Q.init(e,t),e._zod.parse=e=>e}),eO=a.IF("$ZodUnknown",(e,t)=>{Q.init(e,t),e._zod.parse=e=>e}),eA=a.IF("$ZodNever",(e,t)=>{Q.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function eN(e,t,r){e.issues.length&&t.issues.push(...A.Cr(r,e.issues)),t.value[r]=e.value}let eM=a.IF("$ZodArray",(e,t)=>{Q.init(e,t),e._zod.parse=(r,a)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let o=[];for(let e=0;e<n.length;e++){let i=n[e],s=t.element._zod.run({value:i,issues:[]},a);s instanceof Promise?o.push(s.then(t=>eN(t,r,e))):eN(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function e$(e,t,r){e.issues.length&&t.issues.push(...A.Cr(r,e.issues)),t.value[r]=e.value}function eP(e,t,r,a){e.issues.length?void 0===a[r]?r in a?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...A.Cr(r,e.issues)):void 0===e.value?r in a&&(t.value[r]=void 0):t.value[r]=e.value}let ej=a.IF("$ZodObject",(e,t)=>{let r,n;Q.init(e,t);let o=A.HX(()=>{let e=Object.keys(t.shape);for(let r of e)if(!(t.shape[r]instanceof Q))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=A.bX(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});A.To(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let i=e=>{let t=new J(["shape","payload","ctx"]),r=o.value,a=e=>{let t=A.v_(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let n=Object.create(null),i=0;for(let e of r.keys)n[e]=`key_${i++}`;for(let e of(t.write("const newResult = {}"),r.keys))if(r.optionalKeys.has(e)){let r=n[e];t.write(`const ${r} = ${a(e)};`);let o=A.v_(e);t.write(`
69
69
  if (${r}.issues.length) {
70
70
  if (input[${o}] === undefined) {
71
71
  if (${o} in input) {
@@ -88,4 +88,4 @@ Learn more: \x1b[34m${t}\x1b[0m
88
88
  if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
89
89
  ...iss,
90
90
  path: iss.path ? [${A.v_(e)}, ...iss.path] : [${A.v_(e)}]
91
- })));`),t.write(`newResult[${A.v_(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");let s=t.compile();return(t,r)=>s(e,t,r)},s=A.Kn,l=!a.w6.jitless,u=A.k1,d=l&&u.value,c=t.catchall;e._zod.parse=(a,u)=>{n??(n=o.value);let p=a.value;if(!s(p))return a.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),a;let h=[];if(l&&d&&u?.async===!1&&!0!==u.jitless)r||(r=i(t.shape)),a=r(a,u);else{a.value={};let e=n.shape;for(let t of n.keys){let r=e[t],n=r._zod.run({value:p[t],issues:[]},u),o="optional"===r._zod.optin&&"optional"===r._zod.optout;n instanceof Promise?h.push(n.then(e=>o?eP(e,a,t,p):e$(e,a,t))):o?eP(n,a,t,p):e$(n,a,t)}}if(!c)return h.length?Promise.all(h).then(()=>a):a;let m=[],f=n.keySet,y=c._zod,_=y.def.type;for(let e of Object.keys(p)){if(f.has(e))continue;if("never"===_){m.push(e);continue}let t=y.run({value:p[e],issues:[]},u);t instanceof Promise?h.push(t.then(t=>e$(t,a,e))):e$(t,a,e)}return(m.length&&a.issues.push({code:"unrecognized_keys",keys:m,input:p,inst:e}),h.length)?Promise.all(h).then(()=>a):a}});function eF(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>A.G$(e,n,a.vc())))}),t}let ez=a.IF("$ZodUnion",(e,t)=>{Q.init(e,t),A.To(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),A.To(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),A.To(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),A.To(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>A.ZA(e.source)).join("|")})$`)}}),e._zod.parse=(r,a)=>{let n=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},a);if(t instanceof Promise)o.push(t),n=!0;else{if(0===t.issues.length)return t;o.push(t)}}return n?Promise.all(o).then(t=>eF(t,r,e,a)):eF(o,r,e,a)}}),eD=a.IF("$ZodDiscriminatedUnion",(e,t)=>{ez.init(e,t);let r=e._zod.parse;A.To(e._zod,"propValues",()=>{let e={};for(let r of t.options){let a=r._zod.propValues;if(!a||0===Object.keys(a).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(a))for(let a of(e[t]||(e[t]=new Set),r))e[t].add(a)}return e});let a=A.HX(()=>{let e=t.options,r=new Map;for(let a of e){let e=a._zod.propValues[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,a)}}return r});e._zod.parse=(n,o)=>{let i=n.value;if(!A.Kn(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let s=a.value.get(i?.[t.discriminator]);return s?s._zod.run(n,o):t.unionFallback?r(n,o):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),n)}}),eq=a.IF("$ZodIntersection",(e,t)=>{Q.init(e,t),e._zod.parse=(e,r)=>{let a=e.value,n=t.left._zod.run({value:a,issues:[]},r),o=t.right._zod.run({value:a,issues:[]},r);return n instanceof Promise||o instanceof Promise?Promise.all([n,o]).then(([t,r])=>eU(e,t,r)):eU(e,n,o)}});function eU(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),A.Ko(e))return e;let a=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(A.PO(t)&&A.PO(r)){let a=Object.keys(r),n=Object.keys(t).filter(e=>-1!==a.indexOf(e)),o={...t,...r};for(let a of n){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1,mergeErrorPath:[a,...n.mergeErrorPath]};o[a]=n.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let a=[];for(let n=0;n<t.length;n++){let o=e(t[n],r[n]);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a.push(o.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}let eL=a.IF("$ZodTuple",(e,t)=>{Q.init(e,t);let r=t.items,a=r.length-[...r].reverse().findIndex(e=>"optional"!==e._zod.optin);e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let s=[];if(!t.rest){let t=i.length>r.length,o=i.length<a-1;if(t||o)return n.issues.push({input:i,inst:e,origin:"array",...t?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),n}let l=-1;for(let e of r){if(++l>=i.length&&l>=a)continue;let t=e._zod.run({value:i[l],issues:[]},o);t instanceof Promise?s.push(t.then(e=>eV(e,n,l))):eV(t,n,l)}if(t.rest)for(let e of i.slice(r.length)){l++;let r=t.rest._zod.run({value:e,issues:[]},o);r instanceof Promise?s.push(r.then(e=>eV(e,n,l))):eV(r,n,l)}return s.length?Promise.all(s).then(()=>n):n}});function eV(e,t,r){e.issues.length&&t.issues.push(...A.Cr(r,e.issues)),t.value[r]=e.value}let eG=a.IF("$ZodRecord",(e,t)=>{Q.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!A.PO(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let a;let s=t.keyType._zod.values;for(let e of(r.value={},s))if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){let a=t.valueType._zod.run({value:o[e],issues:[]},n);a instanceof Promise?i.push(a.then(t=>{t.issues.length&&r.issues.push(...A.Cr(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...A.Cr(e,a.issues)),r.value[e]=a.value)}for(let e in o)s.has(e)||(a=a??[]).push(e);a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else for(let s of(r.value={},Reflect.ownKeys(o))){if("__proto__"===s)continue;let l=t.keyType._zod.run({value:s,issues:[]},n);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:l.issues.map(e=>A.G$(e,n,a.vc())),input:s,path:[s],inst:e}),r.value[l.value]=l.value;continue}let u=t.valueType._zod.run({value:o[s],issues:[]},n);u instanceof Promise?i.push(u.then(e=>{e.issues.length&&r.issues.push(...A.Cr(s,e.issues)),r.value[l.value]=e.value})):(u.issues.length&&r.issues.push(...A.Cr(s,u.issues)),r.value[l.value]=u.value)}return i.length?Promise.all(i).then(()=>r):r}}),eW=a.IF("$ZodEnum",(e,t)=>{Q.init(e,t);let r=A.B8(t.entries);e._zod.values=new Set(r),e._zod.pattern=RegExp(`^(${r.filter(e=>A.A0.has(typeof e)).map(e=>"string"==typeof e?A.yI(e):e.toString()).join("|")})$`),e._zod.parse=(t,a)=>{let n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),eX=a.IF("$ZodLiteral",(e,t)=>{Q.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?A.yI(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,a)=>{let n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}}),eB=a.IF("$ZodTransform",(e,t)=>{Q.init(e,t),e._zod.parse=(e,r)=>{let n=t.transform(e.value,e);if(r.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e));if(n instanceof Promise)throw new a.TG;return e.value=n,e}}),eK=a.IF("$ZodOptional",(e,t)=>{Q.init(e,t),e._zod.optin="optional",e._zod.optout="optional",A.To(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),A.To(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${A.ZA(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),eJ=a.IF("$ZodNullable",(e,t)=>{Q.init(e,t),A.To(e._zod,"optin",()=>t.innerType._zod.optin),A.To(e._zod,"optout",()=>t.innerType._zod.optout),A.To(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${A.ZA(e.source)}|null)$`):void 0}),A.To(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),eH=a.IF("$ZodDefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",A.To(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(e=>eY(e,t)):eY(a,t)}});function eY(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let eQ=a.IF("$ZodPrefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",A.To(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),e0=a.IF("$ZodNonOptional",(e,t)=>{Q.init(e,t),A.To(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,a)=>{let n=t.innerType._zod.run(r,a);return n instanceof Promise?n.then(t=>e1(t,e)):e1(n,e)}});function e1(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}let e2=a.IF("$ZodCatch",(e,t)=>{Q.init(e,t),e._zod.optin="optional",A.To(e._zod,"optout",()=>t.innerType._zod.optout),A.To(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>A.G$(e,r,a.vc()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>A.G$(e,r,a.vc()))},input:e.value}),e.issues=[]),e)}}),e4=a.IF("$ZodPipe",(e,t)=>{Q.init(e,t),A.To(e._zod,"values",()=>t.in._zod.values),A.To(e._zod,"optin",()=>t.in._zod.optin),A.To(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>e9(e,t,r)):e9(a,t,r)}});function e9(e,t,r){return A.Ko(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}let e5=a.IF("$ZodReadonly",(e,t)=>{Q.init(e,t),A.To(e._zod,"propValues",()=>t.innerType._zod.propValues),A.To(e._zod,"values",()=>t.innerType._zod.values),A.To(e._zod,"optin",()=>t.innerType._zod.optin),A.To(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(e6):e6(a)}});function e6(e){return e.value=Object.freeze(e.value),e}let e3=a.IF("$ZodLazy",(e,t)=>{Q.init(e,t),A.To(e._zod,"innerType",()=>t.getter()),A.To(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),A.To(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),A.To(e._zod,"optin",()=>e._zod.innerType._zod.optin),A.To(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),e7=a.IF("$ZodCustom",(e,t)=>{N.init(e,t),Q.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let a=r.value,n=t.fn(a);if(n instanceof Promise)return n.then(t=>e8(t,r,a,e));e8(n,r,a,e)}});function e8(e,t,r,a){if(!e){let e={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(e.params=a._zod.def.params),t.issues.push(A.Q_(e))}}var te=r(6496);function tt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A.de(t)})}function tr(e,t){return new $({check:"less_than",...A.de(t),value:e,inclusive:!1})}function ta(e,t){return new $({check:"less_than",...A.de(t),value:e,inclusive:!0})}function tn(e,t){return new P({check:"greater_than",...A.de(t),value:e,inclusive:!1})}function to(e,t){return new P({check:"greater_than",...A.de(t),value:e,inclusive:!0})}function ti(e,t){return new j({check:"multiple_of",...A.de(t),value:e})}function ts(e,t){return new z({check:"max_length",...A.de(t),maximum:e})}function tl(e,t){return new D({check:"min_length",...A.de(t),minimum:e})}function tu(e,t){return new q({check:"length_equals",...A.de(t),length:e})}function td(e){return new K({check:"overwrite",tx:e})}let tc=a.IF("ZodISODateTime",(e,t)=>{eh.init(e,t),tb.init(e,t)}),tp=a.IF("ZodISODate",(e,t)=>{em.init(e,t),tb.init(e,t)}),th=a.IF("ZodISOTime",(e,t)=>{ef.init(e,t),tb.init(e,t)}),tm=a.IF("ZodISODuration",(e,t)=>{ey.init(e,t),tb.init(e,t)});var tf=r(3947);let ty=a.IF("ZodType",(e,t)=>(Q.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>A.d9(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>tf.Qc(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>tf.As(e,t,r),e.parseAsync=async(t,r)=>tf.Vw(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>tf.X9(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return new rk({type:"custom",check:"custom",fn:e,...A.de(t)})}(t,r)),e.superRefine=t=>e.check(function(e){let t=function(e){let t=new N({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{"string"==typeof e?r.issues.push(A.Q_(e,r.value,t._zod.def)):(e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=r.value),e.inst??(e.inst=t),e.continue??(e.continue=!t._zod.def.abort),r.issues.push(A.Q_(e)))},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(td(t)),e.optional=()=>rc(e),e.nullable=()=>rh(e),e.nullish=()=>rc(rh(e)),e.nonoptional=t=>new ry({type:"nonoptional",innerType:e,...A.de(t)}),e.array=()=>t1(e),e.or=t=>t3([e,t]),e.and=t=>new re({type:"intersection",left:e,right:t}),e.transform=t=>rv(e,new ru({type:"transform",transform:t})),e.default=t=>(function(e,t){return new rm({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})})(e,t),e.prefault=t=>(function(e,t){return new rf({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})})(e,t),e.catch=t=>(function(e,t){return new r_({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})})(e,t),e.pipe=t=>rv(e,t),e.readonly=()=>new rb({type:"readonly",innerType:e}),e.describe=t=>{let r=e.clone();return te.$Z.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>te.$Z.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return te.$Z.get(e);let r=e.clone();return te.$Z.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),t_=a.IF("_ZodString",(e,t)=>{ee.init(e,t),ty.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new L({check:"string_format",format:"regex",...A.de(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new W({check:"string_format",format:"includes",...A.de(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new X({check:"string_format",format:"starts_with",...A.de(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new B({check:"string_format",format:"ends_with",...A.de(t),suffix:e})}(...t)),e.min=(...t)=>e.check(tl(...t)),e.max=(...t)=>e.check(ts(...t)),e.length=(...t)=>e.check(tu(...t)),e.nonempty=(...t)=>e.check(tl(1,...t)),e.lowercase=t=>e.check(new V({check:"string_format",format:"lowercase",...A.de(t)})),e.uppercase=t=>e.check(new G({check:"string_format",format:"uppercase",...A.de(t)})),e.trim=()=>e.check(td(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return td(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(td(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(td(e=>e.toUpperCase()))}),tg=a.IF("ZodString",(e,t)=>{ee.init(e,t),t_.init(e,t),e.email=t=>e.check(new tw({type:"string",format:"email",check:"string_format",abort:!1,...A.de(t)})),e.url=t=>e.check(new tI({type:"string",format:"url",check:"string_format",abort:!1,...A.de(t)})),e.jwt=t=>e.check(new tz({type:"string",format:"jwt",check:"string_format",abort:!1,...A.de(t)})),e.emoji=t=>e.check(new tT({type:"string",format:"emoji",check:"string_format",abort:!1,...A.de(t)})),e.guid=t=>e.check(tt(tx,t)),e.uuid=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,...A.de(t)})),e.uuidv4=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A.de(t)})),e.uuidv6=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A.de(t)})),e.uuidv7=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A.de(t)})),e.nanoid=t=>e.check(new tR({type:"string",format:"nanoid",check:"string_format",abort:!1,...A.de(t)})),e.guid=t=>e.check(tt(tx,t)),e.cuid=t=>e.check(new tS({type:"string",format:"cuid",check:"string_format",abort:!1,...A.de(t)})),e.cuid2=t=>e.check(new tZ({type:"string",format:"cuid2",check:"string_format",abort:!1,...A.de(t)})),e.ulid=t=>e.check(new tC({type:"string",format:"ulid",check:"string_format",abort:!1,...A.de(t)})),e.base64=t=>e.check(new tP({type:"string",format:"base64",check:"string_format",abort:!1,...A.de(t)})),e.base64url=t=>e.check(new tj({type:"string",format:"base64url",check:"string_format",abort:!1,...A.de(t)})),e.xid=t=>e.check(new tE({type:"string",format:"xid",check:"string_format",abort:!1,...A.de(t)})),e.ksuid=t=>e.check(new tO({type:"string",format:"ksuid",check:"string_format",abort:!1,...A.de(t)})),e.ipv4=t=>e.check(new tA({type:"string",format:"ipv4",check:"string_format",abort:!1,...A.de(t)})),e.ipv6=t=>e.check(new tN({type:"string",format:"ipv6",check:"string_format",abort:!1,...A.de(t)})),e.cidrv4=t=>e.check(new tM({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A.de(t)})),e.cidrv6=t=>e.check(new t$({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A.de(t)})),e.e164=t=>e.check(new tF({type:"string",format:"e164",check:"string_format",abort:!1,...A.de(t)})),e.datetime=t=>{var r;return e.check((r=t,new tc({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A.de(r)})))},e.date=t=>{var r;return e.check((r=t,new tp({type:"string",format:"date",check:"string_format",...A.de(r)})))},e.time=t=>{var r;return e.check((r=t,new th({type:"string",format:"time",check:"string_format",precision:null,...A.de(r)})))},e.duration=t=>{var r;return e.check((r=t,new tm({type:"string",format:"duration",check:"string_format",...A.de(r)})))}});function tv(e){return new tg({type:"string",...A.de(e)})}let tb=a.IF("ZodStringFormat",(e,t)=>{et.init(e,t),t_.init(e,t)}),tw=a.IF("ZodEmail",(e,t)=>{en.init(e,t),tb.init(e,t)}),tx=a.IF("ZodGUID",(e,t)=>{er.init(e,t),tb.init(e,t)}),tk=a.IF("ZodUUID",(e,t)=>{ea.init(e,t),tb.init(e,t)}),tI=a.IF("ZodURL",(e,t)=>{eo.init(e,t),tb.init(e,t)}),tT=a.IF("ZodEmoji",(e,t)=>{ei.init(e,t),tb.init(e,t)}),tR=a.IF("ZodNanoID",(e,t)=>{es.init(e,t),tb.init(e,t)}),tS=a.IF("ZodCUID",(e,t)=>{el.init(e,t),tb.init(e,t)}),tZ=a.IF("ZodCUID2",(e,t)=>{eu.init(e,t),tb.init(e,t)}),tC=a.IF("ZodULID",(e,t)=>{ed.init(e,t),tb.init(e,t)}),tE=a.IF("ZodXID",(e,t)=>{ec.init(e,t),tb.init(e,t)}),tO=a.IF("ZodKSUID",(e,t)=>{ep.init(e,t),tb.init(e,t)}),tA=a.IF("ZodIPv4",(e,t)=>{e_.init(e,t),tb.init(e,t)}),tN=a.IF("ZodIPv6",(e,t)=>{eg.init(e,t),tb.init(e,t)}),tM=a.IF("ZodCIDRv4",(e,t)=>{ev.init(e,t),tb.init(e,t)}),t$=a.IF("ZodCIDRv6",(e,t)=>{eb.init(e,t),tb.init(e,t)}),tP=a.IF("ZodBase64",(e,t)=>{ex.init(e,t),tb.init(e,t)}),tj=a.IF("ZodBase64URL",(e,t)=>{ek.init(e,t),tb.init(e,t)}),tF=a.IF("ZodE164",(e,t)=>{eI.init(e,t),tb.init(e,t)}),tz=a.IF("ZodJWT",(e,t)=>{eT.init(e,t),tb.init(e,t)}),tD=a.IF("ZodNumber",(e,t)=>{eR.init(e,t),ty.init(e,t),e.gt=(t,r)=>e.check(tn(t,r)),e.gte=(t,r)=>e.check(to(t,r)),e.min=(t,r)=>e.check(to(t,r)),e.lt=(t,r)=>e.check(tr(t,r)),e.lte=(t,r)=>e.check(ta(t,r)),e.max=(t,r)=>e.check(ta(t,r)),e.int=t=>e.check(tL(t)),e.safe=t=>e.check(tL(t)),e.positive=t=>e.check(tn(0,t)),e.nonnegative=t=>e.check(to(0,t)),e.negative=t=>e.check(tr(0,t)),e.nonpositive=t=>e.check(ta(0,t)),e.multipleOf=(t,r)=>e.check(ti(t,r)),e.step=(t,r)=>e.check(ti(t,r)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function tq(e){return new tD({type:"number",checks:[],...A.de(e)})}let tU=a.IF("ZodNumberFormat",(e,t)=>{eS.init(e,t),tD.init(e,t)});function tL(e){return new tU({type:"number",check:"number_format",abort:!1,format:"safeint",...A.de(e)})}let tV=a.IF("ZodBoolean",(e,t)=>{eZ.init(e,t),ty.init(e,t)});function tG(e){return new tV({type:"boolean",...A.de(e)})}let tW=a.IF("ZodNull",(e,t)=>{eC.init(e,t),ty.init(e,t)});function tX(e){return new tW({type:"null",...A.de(e)})}let tB=a.IF("ZodAny",(e,t)=>{eE.init(e,t),ty.init(e,t)});function tK(){return new tB({type:"any"})}let tJ=a.IF("ZodUnknown",(e,t)=>{eO.init(e,t),ty.init(e,t)});function tH(){return new tJ({type:"unknown"})}let tY=a.IF("ZodNever",(e,t)=>{eA.init(e,t),ty.init(e,t)});function tQ(e){return new tY({type:"never",...A.de(e)})}let t0=a.IF("ZodArray",(e,t)=>{eM.init(e,t),ty.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(tl(t,r)),e.nonempty=t=>e.check(tl(1,t)),e.max=(t,r)=>e.check(ts(t,r)),e.length=(t,r)=>e.check(tu(t,r)),e.unwrap=()=>e.element});function t1(e,t){return new t0({type:"array",element:e,...A.de(t)})}let t2=a.IF("ZodObject",(e,t)=>{ej.init(e,t),ty.init(e,t),A.To(e,"shape",()=>t.shape),e.keyof=()=>ri(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:tH()}),e.loose=()=>e.clone({...e._zod.def,catchall:tH()}),e.strict=()=>e.clone({...e._zod.def,catchall:tQ()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>A.l7(e,t),e.merge=t=>A.TS(e,t),e.pick=t=>A.ei(e,t),e.omit=t=>A.CE(e,t),e.partial=(...t)=>A.r$(rd,e,t[0]),e.required=(...t)=>A.C1(ry,e,t[0])});function t4(e,t){return new t2({type:"object",get shape(){return A.DW(this,"shape",{...e}),this.shape},...A.de(t)})}function t9(e,t){return new t2({type:"object",get shape(){return A.DW(this,"shape",{...e}),this.shape},catchall:tQ(),...A.de(t)})}function t5(e,t){return new t2({type:"object",get shape(){return A.DW(this,"shape",{...e}),this.shape},catchall:tH(),...A.de(t)})}let t6=a.IF("ZodUnion",(e,t)=>{ez.init(e,t),ty.init(e,t),e.options=t.options});function t3(e,t){return new t6({type:"union",options:e,...A.de(t)})}let t7=a.IF("ZodDiscriminatedUnion",(e,t)=>{t6.init(e,t),eD.init(e,t)});function t8(e,t,r){return new t7({type:"union",options:t,discriminator:e,...A.de(r)})}let re=a.IF("ZodIntersection",(e,t)=>{eq.init(e,t),ty.init(e,t)}),rt=a.IF("ZodTuple",(e,t)=>{eL.init(e,t),ty.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})});function rr(e,t,r){let a=t instanceof Q,n=a?r:t;return new rt({type:"tuple",items:e,rest:a?t:null,...A.de(n)})}let ra=a.IF("ZodRecord",(e,t)=>{eG.init(e,t),ty.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function rn(e,t,r){return new ra({type:"record",keyType:e,valueType:t,...A.de(r)})}let ro=a.IF("ZodEnum",(e,t)=>{eW.init(e,t),ty.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,a)=>{let n={};for(let a of e)if(r.has(a))n[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new ro({...t,checks:[],...A.de(a),entries:n})},e.exclude=(e,a)=>{let n={...t.entries};for(let t of e)if(r.has(t))delete n[t];else throw Error(`Key ${t} not found in enum`);return new ro({...t,checks:[],...A.de(a),entries:n})}});function ri(e,t){return new ro({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...A.de(t)})}let rs=a.IF("ZodLiteral",(e,t)=>{eX.init(e,t),ty.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function rl(e,t){return new rs({type:"literal",values:Array.isArray(e)?e:[e],...A.de(t)})}let ru=a.IF("ZodTransform",(e,t)=>{eB.init(e,t),ty.init(e,t),e._zod.parse=(r,a)=>{r.addIssue=a=>{"string"==typeof a?r.issues.push(A.Q_(a,r.value,t)):(a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(A.Q_(a)))};let n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}}),rd=a.IF("ZodOptional",(e,t)=>{eK.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rc(e){return new rd({type:"optional",innerType:e})}let rp=a.IF("ZodNullable",(e,t)=>{eJ.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rh(e){return new rp({type:"nullable",innerType:e})}let rm=a.IF("ZodDefault",(e,t)=>{eH.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),rf=a.IF("ZodPrefault",(e,t)=>{eQ.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ry=a.IF("ZodNonOptional",(e,t)=>{e0.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType}),r_=a.IF("ZodCatch",(e,t)=>{e2.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),rg=a.IF("ZodPipe",(e,t)=>{e4.init(e,t),ty.init(e,t),e.in=t.in,e.out=t.out});function rv(e,t){return new rg({type:"pipe",in:e,out:t})}let rb=a.IF("ZodReadonly",(e,t)=>{e5.init(e,t),ty.init(e,t)}),rw=a.IF("ZodLazy",(e,t)=>{e3.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.getter()});function rx(e){return new rw({type:"lazy",getter:e})}let rk=a.IF("ZodCustom",(e,t)=>{e7.init(e,t),ty.init(e,t)});function rI(e,t){return function(e,t,r){let a=A.de(r);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}(rk,e??(()=>!0),t)}function rT(e,t={error:`Input not instance of ${e.name}`}){let r=new rk({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...A.de(t)});return r._zod.bag.Class=e,r}},9921:(e,t,r)=>{function a(e,t,r){function a(r,a){var n;for(let o in Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,a),i.prototype)o in r||Object.defineProperty(r,o,{value:i.prototype[o].bind(r)});r._zod.constr=i,r._zod.def=a}let n=r?.Parent??Object;class o extends n{}function i(e){var t;let n=r?.Parent?new o:this;for(let r of(a(n,e),(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred))r();return n}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:a}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}r.d(t,{IF:()=>a,TG:()=>n,vc:()=>i,w6:()=>o}),Object.freeze({status:"aborted"}),Symbol("zod_brand");class n extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}let o={};function i(e){return e&&Object.assign(o,e),o}},8775:(e,t,r)=>{r.d(t,{MK:()=>l,Z:()=>u,h1:()=>i,qc:()=>s});var a=r(9921),n=r(8510);let o=(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:()=>JSON.stringify(t,n.$W,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},i=(0,a.IF)("$ZodError",o),s=(0,a.IF)("$ZodError",o,{Parent:Error});function l(e,t=e=>e.message){let r={},a=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):a.push(t(n));return{formErrors:a,fieldErrors:r}}function u(e,t){let r=t||function(e){return e.message},a={_errors:[]},n=e=>{for(let t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)a._errors.push(r(t));else{let e=a,n=0;for(;n<t.path.length;){let a=t.path[n];n===t.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(r(t))):e[a]=e[a]||{_errors:[]},e=e[a],n++}}};return n(e),a}},7481:(e,t,r)=>{r.d(t,{As:()=>u,G:()=>d,T2:()=>s,X9:()=>c,Yn:()=>l,lk:()=>i});var a=r(9921),n=r(8775),o=r(8510);let i=e=>(t,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise)throw new a.TG;if(l.issues.length){let t=new(i?.Err??e)(l.issues.map(e=>o.G$(e,s,a.vc())));throw o.zw(t,i?.callee),t}return l.value};n.qc;let s=e=>async(t,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise&&(l=await l),l.issues.length){let t=new(i?.Err??e)(l.issues.map(e=>o.G$(e,s,a.vc())));throw o.zw(t,i?.callee),t}return l.value};n.qc;let l=e=>(t,r,i)=>{let s=i?{...i,async:!1}:{async:!1},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise)throw new a.TG;return l.issues.length?{success:!1,error:new(e??n.h1)(l.issues.map(e=>o.G$(e,s,a.vc())))}:{success:!0,data:l.value}},u=l(n.qc),d=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>o.G$(e,i,a.vc())))}:{success:!0,data:s.value}},c=d(n.qc)},6496:(e,t,r)=>{r.d(t,{$Z:()=>n,EC:()=>a}),Symbol("ZodOutput"),Symbol("ZodInput");class a{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}let n=new a},8510:(e,t,r)=>{function a(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function n(e,t){return"bigint"==typeof t?t.toString():t}function o(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function i(e){return null==e}function s(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function l(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}function u(e,t,r){Object.defineProperty(e,t,{get(){{let a=r();return e[t]=a,a}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function d(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function c(e){return JSON.stringify(e)}r.d(t,{$W:()=>n,A0:()=>y,B8:()=>a,C1:()=>S,CE:()=>k,Cr:()=>C,DW:()=>d,Fl:()=>w,G$:()=>O,HX:()=>o,Kn:()=>h,Ko:()=>Z,NZ:()=>i,PO:()=>f,Q_:()=>N,TS:()=>T,To:()=>u,XU:()=>A,ZA:()=>s,bX:()=>b,d9:()=>g,de:()=>v,ei:()=>x,k1:()=>m,k8:()=>l,l7:()=>I,r$:()=>R,v_:()=>c,yI:()=>_,zw:()=>p});let p=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function h(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let m=o(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function f(e){if(!1===h(e))return!1;let t=e.constructor;if(void 0===t)return!0;let r=t.prototype;return!1!==h(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let y=new Set(["string","number","symbol"]);function _(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function v(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function b(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let w={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 x(e,t){let r={},a=e._zod.def;for(let e in t){if(!(e in a.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=a.shape[e])}return g(e,{...e._zod.def,shape:r,checks:[]})}function k(e,t){let r={...e._zod.def.shape},a=e._zod.def;for(let e in t){if(!(e in a.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return g(e,{...e._zod.def,shape:r,checks:[]})}function I(e,t){if(!f(t))throw Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let r={...e._zod.def.shape,...t};return d(this,"shape",r),r},checks:[]};return g(e,r)}function T(e,t){return g(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return d(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function R(e,t,r){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in a))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:a[t]}):a[t])}else for(let t in a)n[t]=e?new e({type:"optional",innerType:a[t]}):a[t];return g(t,{...t._zod.def,shape:n,checks:[]})}function S(e,t,r){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:a[t]}))}else for(let t in a)n[t]=new e({type:"nonoptional",innerType:a[t]});return g(t,{...t._zod.def,shape:n,checks:[]})}function Z(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function C(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function E(e){return"string"==typeof e?e:e?.message}function O(e,t,r){let a={...e,path:e.path??[]};if(!e.message){let n=E(e.inst?._zod.def?.error?.(e))??E(t?.error?.(e))??E(r.customError?.(e))??E(r.localeError?.(e))??"Invalid input";a.message=n}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function A(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function N(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}}};
91
+ })));`),t.write(`newResult[${A.v_(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");let s=t.compile();return(t,r)=>s(e,t,r)},s=A.Kn,l=!a.w6.jitless,u=A.k1,d=l&&u.value,c=t.catchall;e._zod.parse=(a,u)=>{n??(n=o.value);let p=a.value;if(!s(p))return a.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),a;let h=[];if(l&&d&&u?.async===!1&&!0!==u.jitless)r||(r=i(t.shape)),a=r(a,u);else{a.value={};let e=n.shape;for(let t of n.keys){let r=e[t],n=r._zod.run({value:p[t],issues:[]},u),o="optional"===r._zod.optin&&"optional"===r._zod.optout;n instanceof Promise?h.push(n.then(e=>o?eP(e,a,t,p):e$(e,a,t))):o?eP(n,a,t,p):e$(n,a,t)}}if(!c)return h.length?Promise.all(h).then(()=>a):a;let m=[],f=n.keySet,y=c._zod,_=y.def.type;for(let e of Object.keys(p)){if(f.has(e))continue;if("never"===_){m.push(e);continue}let t=y.run({value:p[e],issues:[]},u);t instanceof Promise?h.push(t.then(t=>e$(t,a,e))):e$(t,a,e)}return(m.length&&a.issues.push({code:"unrecognized_keys",keys:m,input:p,inst:e}),h.length)?Promise.all(h).then(()=>a):a}});function eF(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>A.G$(e,n,a.vc())))}),t}let ez=a.IF("$ZodUnion",(e,t)=>{Q.init(e,t),A.To(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),A.To(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),A.To(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),A.To(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>A.ZA(e.source)).join("|")})$`)}}),e._zod.parse=(r,a)=>{let n=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},a);if(t instanceof Promise)o.push(t),n=!0;else{if(0===t.issues.length)return t;o.push(t)}}return n?Promise.all(o).then(t=>eF(t,r,e,a)):eF(o,r,e,a)}}),eD=a.IF("$ZodDiscriminatedUnion",(e,t)=>{ez.init(e,t);let r=e._zod.parse;A.To(e._zod,"propValues",()=>{let e={};for(let r of t.options){let a=r._zod.propValues;if(!a||0===Object.keys(a).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(a))for(let a of(e[t]||(e[t]=new Set),r))e[t].add(a)}return e});let a=A.HX(()=>{let e=t.options,r=new Map;for(let a of e){let e=a._zod.propValues[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,a)}}return r});e._zod.parse=(n,o)=>{let i=n.value;if(!A.Kn(i))return n.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),n;let s=a.value.get(i?.[t.discriminator]);return s?s._zod.run(n,o):t.unionFallback?r(n,o):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),n)}}),eq=a.IF("$ZodIntersection",(e,t)=>{Q.init(e,t),e._zod.parse=(e,r)=>{let a=e.value,n=t.left._zod.run({value:a,issues:[]},r),o=t.right._zod.run({value:a,issues:[]},r);return n instanceof Promise||o instanceof Promise?Promise.all([n,o]).then(([t,r])=>eU(e,t,r)):eU(e,n,o)}});function eU(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),A.Ko(e))return e;let a=function e(t,r){if(t===r||t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(A.PO(t)&&A.PO(r)){let a=Object.keys(r),n=Object.keys(t).filter(e=>-1!==a.indexOf(e)),o={...t,...r};for(let a of n){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1,mergeErrorPath:[a,...n.mergeErrorPath]};o[a]=n.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let a=[];for(let n=0;n<t.length;n++){let o=e(t[n],r[n]);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a.push(o.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}let eL=a.IF("$ZodTuple",(e,t)=>{Q.init(e,t);let r=t.items,a=r.length-[...r].reverse().findIndex(e=>"optional"!==e._zod.optin);e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let s=[];if(!t.rest){let t=i.length>r.length,o=i.length<a-1;if(t||o)return n.issues.push({input:i,inst:e,origin:"array",...t?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),n}let l=-1;for(let e of r){if(++l>=i.length&&l>=a)continue;let t=e._zod.run({value:i[l],issues:[]},o);t instanceof Promise?s.push(t.then(e=>eV(e,n,l))):eV(t,n,l)}if(t.rest)for(let e of i.slice(r.length)){l++;let r=t.rest._zod.run({value:e,issues:[]},o);r instanceof Promise?s.push(r.then(e=>eV(e,n,l))):eV(r,n,l)}return s.length?Promise.all(s).then(()=>n):n}});function eV(e,t,r){e.issues.length&&t.issues.push(...A.Cr(r,e.issues)),t.value[r]=e.value}let eG=a.IF("$ZodRecord",(e,t)=>{Q.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!A.PO(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let a;let s=t.keyType._zod.values;for(let e of(r.value={},s))if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){let a=t.valueType._zod.run({value:o[e],issues:[]},n);a instanceof Promise?i.push(a.then(t=>{t.issues.length&&r.issues.push(...A.Cr(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...A.Cr(e,a.issues)),r.value[e]=a.value)}for(let e in o)s.has(e)||(a=a??[]).push(e);a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else for(let s of(r.value={},Reflect.ownKeys(o))){if("__proto__"===s)continue;let l=t.keyType._zod.run({value:s,issues:[]},n);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:l.issues.map(e=>A.G$(e,n,a.vc())),input:s,path:[s],inst:e}),r.value[l.value]=l.value;continue}let u=t.valueType._zod.run({value:o[s],issues:[]},n);u instanceof Promise?i.push(u.then(e=>{e.issues.length&&r.issues.push(...A.Cr(s,e.issues)),r.value[l.value]=e.value})):(u.issues.length&&r.issues.push(...A.Cr(s,u.issues)),r.value[l.value]=u.value)}return i.length?Promise.all(i).then(()=>r):r}}),eW=a.IF("$ZodEnum",(e,t)=>{Q.init(e,t);let r=A.B8(t.entries);e._zod.values=new Set(r),e._zod.pattern=RegExp(`^(${r.filter(e=>A.A0.has(typeof e)).map(e=>"string"==typeof e?A.yI(e):e.toString()).join("|")})$`),e._zod.parse=(t,a)=>{let n=t.value;return e._zod.values.has(n)||t.issues.push({code:"invalid_value",values:r,input:n,inst:e}),t}}),eX=a.IF("$ZodLiteral",(e,t)=>{Q.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>"string"==typeof e?A.yI(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,a)=>{let n=r.value;return e._zod.values.has(n)||r.issues.push({code:"invalid_value",values:t.values,input:n,inst:e}),r}}),eB=a.IF("$ZodTransform",(e,t)=>{Q.init(e,t),e._zod.parse=(e,r)=>{let n=t.transform(e.value,e);if(r.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e));if(n instanceof Promise)throw new a.TG;return e.value=n,e}}),eK=a.IF("$ZodOptional",(e,t)=>{Q.init(e,t),e._zod.optin="optional",e._zod.optout="optional",A.To(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),A.To(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${A.ZA(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),eJ=a.IF("$ZodNullable",(e,t)=>{Q.init(e,t),A.To(e._zod,"optin",()=>t.innerType._zod.optin),A.To(e._zod,"optout",()=>t.innerType._zod.optout),A.To(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${A.ZA(e.source)}|null)$`):void 0}),A.To(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),eH=a.IF("$ZodDefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",A.To(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(e=>eY(e,t)):eY(a,t)}});function eY(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}let eQ=a.IF("$ZodPrefault",(e,t)=>{Q.init(e,t),e._zod.optin="optional",A.To(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),e0=a.IF("$ZodNonOptional",(e,t)=>{Q.init(e,t),A.To(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,a)=>{let n=t.innerType._zod.run(r,a);return n instanceof Promise?n.then(t=>e1(t,e)):e1(n,e)}});function e1(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}let e2=a.IF("$ZodCatch",(e,t)=>{Q.init(e,t),e._zod.optin="optional",A.To(e._zod,"optout",()=>t.innerType._zod.optout),A.To(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>A.G$(e,r,a.vc()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>A.G$(e,r,a.vc()))},input:e.value}),e.issues=[]),e)}}),e4=a.IF("$ZodPipe",(e,t)=>{Q.init(e,t),A.To(e._zod,"values",()=>t.in._zod.values),A.To(e._zod,"optin",()=>t.in._zod.optin),A.To(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{let a=t.in._zod.run(e,r);return a instanceof Promise?a.then(e=>e9(e,t,r)):e9(a,t,r)}});function e9(e,t,r){return A.Ko(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}let e5=a.IF("$ZodReadonly",(e,t)=>{Q.init(e,t),A.To(e._zod,"propValues",()=>t.innerType._zod.propValues),A.To(e._zod,"values",()=>t.innerType._zod.values),A.To(e._zod,"optin",()=>t.innerType._zod.optin),A.To(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{let a=t.innerType._zod.run(e,r);return a instanceof Promise?a.then(e6):e6(a)}});function e6(e){return e.value=Object.freeze(e.value),e}let e3=a.IF("$ZodLazy",(e,t)=>{Q.init(e,t),A.To(e._zod,"innerType",()=>t.getter()),A.To(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),A.To(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),A.To(e._zod,"optin",()=>e._zod.innerType._zod.optin),A.To(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),e8=a.IF("$ZodCustom",(e,t)=>{N.init(e,t),Q.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let a=r.value,n=t.fn(a);if(n instanceof Promise)return n.then(t=>e7(t,r,a,e));e7(n,r,a,e)}});function e7(e,t,r,a){if(!e){let e={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(e.params=a._zod.def.params),t.issues.push(A.Q_(e))}}var te=r(6496);function tt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A.de(t)})}function tr(e,t){return new $({check:"less_than",...A.de(t),value:e,inclusive:!1})}function ta(e,t){return new $({check:"less_than",...A.de(t),value:e,inclusive:!0})}function tn(e,t){return new P({check:"greater_than",...A.de(t),value:e,inclusive:!1})}function to(e,t){return new P({check:"greater_than",...A.de(t),value:e,inclusive:!0})}function ti(e,t){return new j({check:"multiple_of",...A.de(t),value:e})}function ts(e,t){return new z({check:"max_length",...A.de(t),maximum:e})}function tl(e,t){return new D({check:"min_length",...A.de(t),minimum:e})}function tu(e,t){return new q({check:"length_equals",...A.de(t),length:e})}function td(e){return new K({check:"overwrite",tx:e})}let tc=a.IF("ZodISODateTime",(e,t)=>{eh.init(e,t),tb.init(e,t)}),tp=a.IF("ZodISODate",(e,t)=>{em.init(e,t),tb.init(e,t)}),th=a.IF("ZodISOTime",(e,t)=>{ef.init(e,t),tb.init(e,t)}),tm=a.IF("ZodISODuration",(e,t)=>{ey.init(e,t),tb.init(e,t)});var tf=r(3947);let ty=a.IF("ZodType",(e,t)=>(Q.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>A.d9(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>tf.Qc(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>tf.As(e,t,r),e.parseAsync=async(t,r)=>tf.Vw(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>tf.X9(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return new rk({type:"custom",check:"custom",fn:e,...A.de(t)})}(t,r)),e.superRefine=t=>e.check(function(e){let t=function(e){let t=new N({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{"string"==typeof e?r.issues.push(A.Q_(e,r.value,t._zod.def)):(e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=r.value),e.inst??(e.inst=t),e.continue??(e.continue=!t._zod.def.abort),r.issues.push(A.Q_(e)))},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(td(t)),e.optional=()=>rc(e),e.nullable=()=>rh(e),e.nullish=()=>rc(rh(e)),e.nonoptional=t=>new ry({type:"nonoptional",innerType:e,...A.de(t)}),e.array=()=>t1(e),e.or=t=>t3([e,t]),e.and=t=>new re({type:"intersection",left:e,right:t}),e.transform=t=>rv(e,new ru({type:"transform",transform:t})),e.default=t=>(function(e,t){return new rm({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})})(e,t),e.prefault=t=>(function(e,t){return new rf({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})})(e,t),e.catch=t=>(function(e,t){return new r_({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})})(e,t),e.pipe=t=>rv(e,t),e.readonly=()=>new rb({type:"readonly",innerType:e}),e.describe=t=>{let r=e.clone();return te.$Z.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>te.$Z.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return te.$Z.get(e);let r=e.clone();return te.$Z.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),t_=a.IF("_ZodString",(e,t)=>{ee.init(e,t),ty.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new L({check:"string_format",format:"regex",...A.de(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new W({check:"string_format",format:"includes",...A.de(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new X({check:"string_format",format:"starts_with",...A.de(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new B({check:"string_format",format:"ends_with",...A.de(t),suffix:e})}(...t)),e.min=(...t)=>e.check(tl(...t)),e.max=(...t)=>e.check(ts(...t)),e.length=(...t)=>e.check(tu(...t)),e.nonempty=(...t)=>e.check(tl(1,...t)),e.lowercase=t=>e.check(new V({check:"string_format",format:"lowercase",...A.de(t)})),e.uppercase=t=>e.check(new G({check:"string_format",format:"uppercase",...A.de(t)})),e.trim=()=>e.check(td(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return td(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(td(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(td(e=>e.toUpperCase()))}),tg=a.IF("ZodString",(e,t)=>{ee.init(e,t),t_.init(e,t),e.email=t=>e.check(new tw({type:"string",format:"email",check:"string_format",abort:!1,...A.de(t)})),e.url=t=>e.check(new tI({type:"string",format:"url",check:"string_format",abort:!1,...A.de(t)})),e.jwt=t=>e.check(new tz({type:"string",format:"jwt",check:"string_format",abort:!1,...A.de(t)})),e.emoji=t=>e.check(new tT({type:"string",format:"emoji",check:"string_format",abort:!1,...A.de(t)})),e.guid=t=>e.check(tt(tx,t)),e.uuid=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,...A.de(t)})),e.uuidv4=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A.de(t)})),e.uuidv6=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A.de(t)})),e.uuidv7=t=>e.check(new tk({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A.de(t)})),e.nanoid=t=>e.check(new tR({type:"string",format:"nanoid",check:"string_format",abort:!1,...A.de(t)})),e.guid=t=>e.check(tt(tx,t)),e.cuid=t=>e.check(new tS({type:"string",format:"cuid",check:"string_format",abort:!1,...A.de(t)})),e.cuid2=t=>e.check(new tZ({type:"string",format:"cuid2",check:"string_format",abort:!1,...A.de(t)})),e.ulid=t=>e.check(new tC({type:"string",format:"ulid",check:"string_format",abort:!1,...A.de(t)})),e.base64=t=>e.check(new tP({type:"string",format:"base64",check:"string_format",abort:!1,...A.de(t)})),e.base64url=t=>e.check(new tj({type:"string",format:"base64url",check:"string_format",abort:!1,...A.de(t)})),e.xid=t=>e.check(new tE({type:"string",format:"xid",check:"string_format",abort:!1,...A.de(t)})),e.ksuid=t=>e.check(new tO({type:"string",format:"ksuid",check:"string_format",abort:!1,...A.de(t)})),e.ipv4=t=>e.check(new tA({type:"string",format:"ipv4",check:"string_format",abort:!1,...A.de(t)})),e.ipv6=t=>e.check(new tN({type:"string",format:"ipv6",check:"string_format",abort:!1,...A.de(t)})),e.cidrv4=t=>e.check(new tM({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A.de(t)})),e.cidrv6=t=>e.check(new t$({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A.de(t)})),e.e164=t=>e.check(new tF({type:"string",format:"e164",check:"string_format",abort:!1,...A.de(t)})),e.datetime=t=>{var r;return e.check((r=t,new tc({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A.de(r)})))},e.date=t=>{var r;return e.check((r=t,new tp({type:"string",format:"date",check:"string_format",...A.de(r)})))},e.time=t=>{var r;return e.check((r=t,new th({type:"string",format:"time",check:"string_format",precision:null,...A.de(r)})))},e.duration=t=>{var r;return e.check((r=t,new tm({type:"string",format:"duration",check:"string_format",...A.de(r)})))}});function tv(e){return new tg({type:"string",...A.de(e)})}let tb=a.IF("ZodStringFormat",(e,t)=>{et.init(e,t),t_.init(e,t)}),tw=a.IF("ZodEmail",(e,t)=>{en.init(e,t),tb.init(e,t)}),tx=a.IF("ZodGUID",(e,t)=>{er.init(e,t),tb.init(e,t)}),tk=a.IF("ZodUUID",(e,t)=>{ea.init(e,t),tb.init(e,t)}),tI=a.IF("ZodURL",(e,t)=>{eo.init(e,t),tb.init(e,t)}),tT=a.IF("ZodEmoji",(e,t)=>{ei.init(e,t),tb.init(e,t)}),tR=a.IF("ZodNanoID",(e,t)=>{es.init(e,t),tb.init(e,t)}),tS=a.IF("ZodCUID",(e,t)=>{el.init(e,t),tb.init(e,t)}),tZ=a.IF("ZodCUID2",(e,t)=>{eu.init(e,t),tb.init(e,t)}),tC=a.IF("ZodULID",(e,t)=>{ed.init(e,t),tb.init(e,t)}),tE=a.IF("ZodXID",(e,t)=>{ec.init(e,t),tb.init(e,t)}),tO=a.IF("ZodKSUID",(e,t)=>{ep.init(e,t),tb.init(e,t)}),tA=a.IF("ZodIPv4",(e,t)=>{e_.init(e,t),tb.init(e,t)}),tN=a.IF("ZodIPv6",(e,t)=>{eg.init(e,t),tb.init(e,t)}),tM=a.IF("ZodCIDRv4",(e,t)=>{ev.init(e,t),tb.init(e,t)}),t$=a.IF("ZodCIDRv6",(e,t)=>{eb.init(e,t),tb.init(e,t)}),tP=a.IF("ZodBase64",(e,t)=>{ex.init(e,t),tb.init(e,t)}),tj=a.IF("ZodBase64URL",(e,t)=>{ek.init(e,t),tb.init(e,t)}),tF=a.IF("ZodE164",(e,t)=>{eI.init(e,t),tb.init(e,t)}),tz=a.IF("ZodJWT",(e,t)=>{eT.init(e,t),tb.init(e,t)}),tD=a.IF("ZodNumber",(e,t)=>{eR.init(e,t),ty.init(e,t),e.gt=(t,r)=>e.check(tn(t,r)),e.gte=(t,r)=>e.check(to(t,r)),e.min=(t,r)=>e.check(to(t,r)),e.lt=(t,r)=>e.check(tr(t,r)),e.lte=(t,r)=>e.check(ta(t,r)),e.max=(t,r)=>e.check(ta(t,r)),e.int=t=>e.check(tL(t)),e.safe=t=>e.check(tL(t)),e.positive=t=>e.check(tn(0,t)),e.nonnegative=t=>e.check(to(0,t)),e.negative=t=>e.check(tr(0,t)),e.nonpositive=t=>e.check(ta(0,t)),e.multipleOf=(t,r)=>e.check(ti(t,r)),e.step=(t,r)=>e.check(ti(t,r)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function tq(e){return new tD({type:"number",checks:[],...A.de(e)})}let tU=a.IF("ZodNumberFormat",(e,t)=>{eS.init(e,t),tD.init(e,t)});function tL(e){return new tU({type:"number",check:"number_format",abort:!1,format:"safeint",...A.de(e)})}let tV=a.IF("ZodBoolean",(e,t)=>{eZ.init(e,t),ty.init(e,t)});function tG(e){return new tV({type:"boolean",...A.de(e)})}let tW=a.IF("ZodNull",(e,t)=>{eC.init(e,t),ty.init(e,t)});function tX(e){return new tW({type:"null",...A.de(e)})}let tB=a.IF("ZodAny",(e,t)=>{eE.init(e,t),ty.init(e,t)});function tK(){return new tB({type:"any"})}let tJ=a.IF("ZodUnknown",(e,t)=>{eO.init(e,t),ty.init(e,t)});function tH(){return new tJ({type:"unknown"})}let tY=a.IF("ZodNever",(e,t)=>{eA.init(e,t),ty.init(e,t)});function tQ(e){return new tY({type:"never",...A.de(e)})}let t0=a.IF("ZodArray",(e,t)=>{eM.init(e,t),ty.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(tl(t,r)),e.nonempty=t=>e.check(tl(1,t)),e.max=(t,r)=>e.check(ts(t,r)),e.length=(t,r)=>e.check(tu(t,r)),e.unwrap=()=>e.element});function t1(e,t){return new t0({type:"array",element:e,...A.de(t)})}let t2=a.IF("ZodObject",(e,t)=>{ej.init(e,t),ty.init(e,t),A.To(e,"shape",()=>t.shape),e.keyof=()=>ri(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:tH()}),e.loose=()=>e.clone({...e._zod.def,catchall:tH()}),e.strict=()=>e.clone({...e._zod.def,catchall:tQ()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>A.l7(e,t),e.merge=t=>A.TS(e,t),e.pick=t=>A.ei(e,t),e.omit=t=>A.CE(e,t),e.partial=(...t)=>A.r$(rd,e,t[0]),e.required=(...t)=>A.C1(ry,e,t[0])});function t4(e,t){return new t2({type:"object",get shape(){return A.DW(this,"shape",{...e}),this.shape},...A.de(t)})}function t9(e,t){return new t2({type:"object",get shape(){return A.DW(this,"shape",{...e}),this.shape},catchall:tQ(),...A.de(t)})}function t5(e,t){return new t2({type:"object",get shape(){return A.DW(this,"shape",{...e}),this.shape},catchall:tH(),...A.de(t)})}let t6=a.IF("ZodUnion",(e,t)=>{ez.init(e,t),ty.init(e,t),e.options=t.options});function t3(e,t){return new t6({type:"union",options:e,...A.de(t)})}let t8=a.IF("ZodDiscriminatedUnion",(e,t)=>{t6.init(e,t),eD.init(e,t)});function t7(e,t,r){return new t8({type:"union",options:t,discriminator:e,...A.de(r)})}let re=a.IF("ZodIntersection",(e,t)=>{eq.init(e,t),ty.init(e,t)}),rt=a.IF("ZodTuple",(e,t)=>{eL.init(e,t),ty.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})});function rr(e,t,r){let a=t instanceof Q,n=a?r:t;return new rt({type:"tuple",items:e,rest:a?t:null,...A.de(n)})}let ra=a.IF("ZodRecord",(e,t)=>{eG.init(e,t),ty.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function rn(e,t,r){return new ra({type:"record",keyType:e,valueType:t,...A.de(r)})}let ro=a.IF("ZodEnum",(e,t)=>{eW.init(e,t),ty.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,a)=>{let n={};for(let a of e)if(r.has(a))n[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new ro({...t,checks:[],...A.de(a),entries:n})},e.exclude=(e,a)=>{let n={...t.entries};for(let t of e)if(r.has(t))delete n[t];else throw Error(`Key ${t} not found in enum`);return new ro({...t,checks:[],...A.de(a),entries:n})}});function ri(e,t){return new ro({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...A.de(t)})}let rs=a.IF("ZodLiteral",(e,t)=>{eX.init(e,t),ty.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function rl(e,t){return new rs({type:"literal",values:Array.isArray(e)?e:[e],...A.de(t)})}let ru=a.IF("ZodTransform",(e,t)=>{eB.init(e,t),ty.init(e,t),e._zod.parse=(r,a)=>{r.addIssue=a=>{"string"==typeof a?r.issues.push(A.Q_(a,r.value,t)):(a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(A.Q_(a)))};let n=t.transform(r.value,r);return n instanceof Promise?n.then(e=>(r.value=e,r)):(r.value=n,r)}}),rd=a.IF("ZodOptional",(e,t)=>{eK.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rc(e){return new rd({type:"optional",innerType:e})}let rp=a.IF("ZodNullable",(e,t)=>{eJ.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rh(e){return new rp({type:"nullable",innerType:e})}let rm=a.IF("ZodDefault",(e,t)=>{eH.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),rf=a.IF("ZodPrefault",(e,t)=>{eQ.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ry=a.IF("ZodNonOptional",(e,t)=>{e0.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType}),r_=a.IF("ZodCatch",(e,t)=>{e2.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),rg=a.IF("ZodPipe",(e,t)=>{e4.init(e,t),ty.init(e,t),e.in=t.in,e.out=t.out});function rv(e,t){return new rg({type:"pipe",in:e,out:t})}let rb=a.IF("ZodReadonly",(e,t)=>{e5.init(e,t),ty.init(e,t)}),rw=a.IF("ZodLazy",(e,t)=>{e3.init(e,t),ty.init(e,t),e.unwrap=()=>e._zod.def.getter()});function rx(e){return new rw({type:"lazy",getter:e})}let rk=a.IF("ZodCustom",(e,t)=>{e8.init(e,t),ty.init(e,t)});function rI(e,t){return function(e,t,r){let a=A.de(r);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}(rk,e??(()=>!0),t)}function rT(e,t={error:`Input not instance of ${e.name}`}){let r=new rk({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...A.de(t)});return r._zod.bag.Class=e,r}},9921:(e,t,r)=>{function a(e,t,r){function a(r,a){var n;for(let o in Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(n=r._zod).traits??(n.traits=new Set),r._zod.traits.add(e),t(r,a),i.prototype)o in r||Object.defineProperty(r,o,{value:i.prototype[o].bind(r)});r._zod.constr=i,r._zod.def=a}let n=r?.Parent??Object;class o extends n{}function i(e){var t;let n=r?.Parent?new o:this;for(let r of(a(n,e),(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred))r();return n}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:a}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}r.d(t,{IF:()=>a,TG:()=>n,vc:()=>i,w6:()=>o}),Object.freeze({status:"aborted"}),Symbol("zod_brand");class n extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}let o={};function i(e){return e&&Object.assign(o,e),o}},8775:(e,t,r)=>{r.d(t,{MK:()=>l,Z:()=>u,h1:()=>i,qc:()=>s});var a=r(9921),n=r(8510);let o=(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:()=>JSON.stringify(t,n.$W,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},i=(0,a.IF)("$ZodError",o),s=(0,a.IF)("$ZodError",o,{Parent:Error});function l(e,t=e=>e.message){let r={},a=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):a.push(t(n));return{formErrors:a,fieldErrors:r}}function u(e,t){let r=t||function(e){return e.message},a={_errors:[]},n=e=>{for(let t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>n({issues:e}));else if("invalid_key"===t.code)n({issues:t.issues});else if("invalid_element"===t.code)n({issues:t.issues});else if(0===t.path.length)a._errors.push(r(t));else{let e=a,n=0;for(;n<t.path.length;){let a=t.path[n];n===t.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(r(t))):e[a]=e[a]||{_errors:[]},e=e[a],n++}}};return n(e),a}},7481:(e,t,r)=>{r.d(t,{As:()=>u,G:()=>d,T2:()=>s,X9:()=>c,Yn:()=>l,lk:()=>i});var a=r(9921),n=r(8775),o=r(8510);let i=e=>(t,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise)throw new a.TG;if(l.issues.length){let t=new(i?.Err??e)(l.issues.map(e=>o.G$(e,s,a.vc())));throw o.zw(t,i?.callee),t}return l.value};n.qc;let s=e=>async(t,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise&&(l=await l),l.issues.length){let t=new(i?.Err??e)(l.issues.map(e=>o.G$(e,s,a.vc())));throw o.zw(t,i?.callee),t}return l.value};n.qc;let l=e=>(t,r,i)=>{let s=i?{...i,async:!1}:{async:!1},l=t._zod.run({value:r,issues:[]},s);if(l instanceof Promise)throw new a.TG;return l.issues.length?{success:!1,error:new(e??n.h1)(l.issues.map(e=>o.G$(e,s,a.vc())))}:{success:!0,data:l.value}},u=l(n.qc),d=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>o.G$(e,i,a.vc())))}:{success:!0,data:s.value}},c=d(n.qc)},6496:(e,t,r)=>{r.d(t,{$Z:()=>n,EC:()=>a}),Symbol("ZodOutput"),Symbol("ZodInput");class a{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}let n=new a},8510:(e,t,r)=>{function a(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function n(e,t){return"bigint"==typeof t?t.toString():t}function o(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function i(e){return null==e}function s(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function l(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=r>a?r:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}function u(e,t,r){Object.defineProperty(e,t,{get(){{let a=r();return e[t]=a,a}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function d(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function c(e){return JSON.stringify(e)}r.d(t,{$W:()=>n,A0:()=>y,B8:()=>a,C1:()=>S,CE:()=>k,Cr:()=>C,DW:()=>d,Fl:()=>w,G$:()=>O,HX:()=>o,Kn:()=>h,Ko:()=>Z,NZ:()=>i,PO:()=>f,Q_:()=>N,TS:()=>T,To:()=>u,XU:()=>A,ZA:()=>s,bX:()=>b,d9:()=>g,de:()=>v,ei:()=>x,k1:()=>m,k8:()=>l,l7:()=>I,r$:()=>R,v_:()=>c,yI:()=>_,zw:()=>p});let p=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function h(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let m=o(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function f(e){if(!1===h(e))return!1;let t=e.constructor;if(void 0===t)return!0;let r=t.prototype;return!1!==h(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}let y=new Set(["string","number","symbol"]);function _(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function v(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function b(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}let w={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 x(e,t){let r={},a=e._zod.def;for(let e in t){if(!(e in a.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=a.shape[e])}return g(e,{...e._zod.def,shape:r,checks:[]})}function k(e,t){let r={...e._zod.def.shape},a=e._zod.def;for(let e in t){if(!(e in a.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return g(e,{...e._zod.def,shape:r,checks:[]})}function I(e,t){if(!f(t))throw Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let r={...e._zod.def.shape,...t};return d(this,"shape",r),r},checks:[]};return g(e,r)}function T(e,t){return g(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return d(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function R(e,t,r){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in a))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=e?new e({type:"optional",innerType:a[t]}):a[t])}else for(let t in a)n[t]=e?new e({type:"optional",innerType:a[t]}):a[t];return g(t,{...t._zod.def,shape:n,checks:[]})}function S(e,t,r){let a=t._zod.def.shape,n={...a};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(n[t]=new e({type:"nonoptional",innerType:a[t]}))}else for(let t in a)n[t]=new e({type:"nonoptional",innerType:a[t]});return g(t,{...t._zod.def,shape:n,checks:[]})}function Z(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function C(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function E(e){return"string"==typeof e?e:e?.message}function O(e,t,r){let a={...e,path:e.path??[]};if(!e.message){let n=E(e.inst?._zod.def?.error?.(e))??E(t?.error?.(e))??E(r.customError?.(e))??E(r.localeError?.(e))??"Invalid input";a.message=n}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function A(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function N(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}}};