experimental-ash 0.24.1 → 0.24.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/src/chunks/authored-module-loader-DcCfCiBm.js +4 -0
- package/dist/src/chunks/client-DLHAGI2g.js +4 -0
- package/dist/src/chunks/dev-authored-source-watcher-CBID_Dwh.js +1 -0
- package/dist/src/chunks/{errors-DsO9xmQL.js → errors-HYWjHxV6.js} +1 -1
- package/dist/src/chunks/{gray-matter-BxS7ZG-J.js → gray-matter-D-9jHwOT.js} +4 -4
- package/dist/src/chunks/host-zBy9FyyX.js +70 -0
- package/dist/src/chunks/{jsdist-M7JFZoA4.js → jsdist-BkeWZ7EZ.js} +61 -61
- package/dist/src/chunks/package-HUaeub_D.js +1 -0
- package/dist/src/chunks/{paths-jcVjBqc3.js → paths-CebY5GCi.js} +2 -2
- package/dist/src/chunks/{picocolors-Bq-tZK9u.js → picocolors-aAkqW4On.js} +1 -1
- package/dist/src/chunks/token-D98SQdvs.js +1 -0
- package/dist/src/chunks/{url-BVRhVE2O.js → url-JdCGA634.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/environment.d.ts +16 -2
- package/dist/src/cli/dev/environment.js +1 -1
- package/dist/src/cli/dev/input-requests.js +1 -1
- package/dist/src/cli/dev/repl.js +3 -3
- package/dist/src/cli/dev/url.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/cli/ui/output.js +1 -1
- package/dist/src/client/index.d.ts +1 -0
- package/dist/src/client/index.js +1 -0
- package/dist/src/compiled/.vendor-stamp.json +7 -6
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/google/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@chat-adapter/slack/_slack-web-api.d.ts +7 -0
- package/dist/src/compiled/@chat-adapter/slack/index.d.ts +418 -109
- package/dist/src/compiled/@chat-adapter/slack/index.js +31 -27
- package/dist/src/compiled/@chat-adapter/slack/package.json +1 -1
- package/dist/src/compiled/@chat-adapter/state-memory/index.d.ts +8 -2
- package/dist/src/compiled/@chat-adapter/state-memory/index.js +1 -1
- package/dist/src/compiled/@chat-adapter/state-memory/package.json +1 -1
- package/dist/src/compiled/@opentelemetry/api/index.js +1 -1
- package/dist/src/compiled/@vercel/sandbox/index.js +19 -17
- package/dist/src/compiled/@vercel/sandbox/package.json +1 -1
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/runtime.js +22 -22
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/_chunks/node/auth-ZhCJAHxl.js +2 -0
- package/dist/src/compiled/_chunks/node/{dist-BdWHjlRQ.js → dist-BQYUcBqu.js} +31 -31
- package/dist/src/compiled/_chunks/node/{chunk-Dd2tEFlW.js → dist-BdTs18CF.js} +1 -1
- package/dist/src/compiled/_chunks/node/retry-DkR2H1Y0.js +1 -0
- package/dist/src/compiled/_chunks/node/token-CoIbMZkq.js +1 -0
- package/dist/src/compiled/_chunks/node/{version-BMyZn3Y2.js → version-D4IYmfaS.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/coerce-BhzIW-Hm.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{compat-CIROS3w4.js → compat-DcEvieoj.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{core-DOVmxHH8.js → core-XWIi7wKc.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/{dist-C7wPwOI9.js → dist-DO14ZaQj.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-CpUQh3NH.js → dist-DZZY3Zyp.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-DOMbNs-S.js +51 -0
- package/dist/src/compiled/_chunks/workflow/{schemas-DFZoEyCn.js → schemas-DmgDnhW3.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/sleep-CRjce49s.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{src-ClRYdO4-.js → src-B54rYDvB.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/symbols-D8paKc8P.js +9 -0
- package/dist/src/compiled/_chunks/workflow/{token-CsNmv7KW.js → token-D9z1dMB6.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{token-j5Cl4rrs.js → token-DV7rQw_t.js} +1 -1
- package/dist/src/compiled/chat/index.d.ts +6 -3143
- package/dist/src/compiled/chat/index.js +1 -1
- package/dist/src/compiled/chat/{jsx-runtime-DxGwoLu2.d.ts → jsx-runtime-CFq1K_Ve.d.ts} +1 -1
- package/dist/src/compiled/chat/package.json +1 -1
- package/dist/src/compiled/jose/index.js +2 -2
- package/dist/src/compiled/jsonc-parser/LICENSE.md +21 -0
- package/dist/src/compiled/jsonc-parser/index.d.ts +13 -0
- package/dist/src/compiled/jsonc-parser/index.js +15 -0
- package/dist/src/compiled/jsonc-parser/package.json +7 -0
- package/dist/src/compiled/just-bash/index.js +773 -773
- package/dist/src/compiled/just-bash/package.json +1 -1
- package/dist/src/compiled/turndown/index.js +1 -1
- package/dist/src/compiled/zod/index.js +1 -1
- package/dist/src/compiled/zod-validation-error/index.js +1 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/evals/loaders/yaml.js +1 -1
- package/dist/src/evals/runner/discover.js +1 -1
- package/dist/src/evals/runner/execute-suite.js +1 -1
- package/dist/src/evals/runner/reporters/console.js +1 -1
- package/dist/src/evals/scorers/autoevals-client.js +1 -1
- package/dist/src/evals/scorers/autoevals.js +1 -1
- package/dist/src/evals/scorers/json.js +1 -1
- package/dist/src/evals/scorers/run.js +1 -1
- package/dist/src/evals/scorers/sql.js +1 -1
- package/dist/src/evals/scorers/text.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-asset-import-plugin.d.ts +5 -0
- package/dist/src/internal/authored-asset-import-plugin.js +141 -0
- package/dist/src/internal/authored-module-bundle.d.ts +4 -0
- package/dist/src/internal/authored-module-bundle.js +19 -0
- package/dist/src/internal/authored-module-loader.d.ts +6 -0
- package/dist/src/internal/authored-module-loader.js +114 -125
- package/dist/src/internal/authored-package-tsconfig-paths.d.ts +9 -0
- package/dist/src/internal/authored-package-tsconfig-paths.js +209 -0
- package/dist/src/internal/nitro/host/channel-routes.d.ts +9 -2
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +12 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +19 -3
- package/dist/src/internal/nitro/host/schedule-task-routes.d.ts +7 -3
- package/dist/src/internal/nitro/host/start-development-server.js +2 -0
- package/package.json +17 -17
- package/dist/src/chunks/authored-module-loader-XcFLnl49.js +0 -2
- package/dist/src/chunks/client-nshDsWNF.js +0 -4
- package/dist/src/chunks/dev-authored-source-watcher-CApkYfee.js +0 -7
- package/dist/src/chunks/host-3sfHdmXL.js +0 -65
- package/dist/src/chunks/package-DmsQgn4v.js +0 -1
- package/dist/src/chunks/prewarm-DslujbK5.js +0 -6
- package/dist/src/chunks/token-DtoyQZy2.js +0 -1
- package/dist/src/chunks/token-util-CHjOk3A7.js +0 -1
- package/dist/src/compiled/_chunks/node/auth-vbe4XEEK.js +0 -2
- package/dist/src/compiled/_chunks/node/dist-DMSq2ehP.js +0 -1
- package/dist/src/compiled/_chunks/node/retry-BOcy5BbJ.js +0 -1
- package/dist/src/compiled/_chunks/node/token-D-BTJHoU.js +0 -1
- package/dist/src/compiled/_chunks/workflow/coerce-Dh0wa7P9.js +0 -1
- package/dist/src/compiled/_chunks/workflow/context-errors-Bbvvp-li.js +0 -6
- package/dist/src/compiled/_chunks/workflow/dist-C_oiE-l7.js +0 -40
- package/dist/src/compiled/_chunks/workflow/resume-hook-C3VWUPii.js +0 -12
- package/dist/src/compiled/_chunks/workflow/sleep-QTkC1VFe.js +0 -1
- package/dist/src/compiled/_chunks/workflow/symbols-QezhMuLg.js +0 -4
- package/dist/src/compiled/chat/_workflow-serde.d.ts +0 -5
- /package/dist/src/chunks/{chunk-8L7ocgPr.js → chunk-DSjMdhoD.js} +0 -0
- /package/dist/src/chunks/{guards-CjJ3lmju.js → guards-26p6sOw3.js} +0 -0
- /package/dist/src/chunks/{input-requests-BsBi7_5K.js → input-requests-DJiy6dG9.js} +0 -0
- /package/dist/src/chunks/{runtime-model-BWu6M_hq.js → runtime-model-Dh0Nz64z.js} +0 -0
- /package/dist/src/chunks/{types-MZUhN0Zy.js → types-DDA2QUED.js} +0 -0
- /package/dist/src/compiled/_chunks/workflow/{chunk-DHhdAPOb.js → chunk-DSjMdhoD.js} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{APICallError as e,InvalidArgumentError as t,NoSuchModelError as n,UnsupportedFunctionalityError as r}from"../provider/index.js";import{At as i,Bt as a,Et as o,Kn as s,Nn as c,Rn as l,Tn as u,Xn as d,Zn as f,dn as p,fn as m,wn as h,yt as g}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{A as _,B as v,C as y,D as b,I as x,J as S,K as C,L as w,M as T,N as E,R as D,T as O,V as k,W as A,X as ee,Y as j,Z as M,a as N,b as P,d as F,f as I,g as te,h as L,i as R,j as z,k as B,o as V,p as H,q as U,r as W,u as G,x as K,z as q}from"../../_chunks/workflow/dist-CpUQh3NH.js";var J=F({errorSchema:B(()=>j(u({type:p(`error`),error:u({type:l(),message:l()})}))),errorToMessage:e=>e.error.message}),ne=B(()=>j(u({id:l(),type:p(`file`),filename:l(),mime_type:l(),size_bytes:h(),created_at:l(),downloadable:i().nullish()}))),re=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile({data:e,mediaType:t,filename:n}){let r=N(e),i=new Blob([r],{type:t}),a=new FormData;n==null?a.append(`file`,i):a.append(`file`,i,n);let{value:o}=await w({url:`${this.config.baseURL}/files`,headers:W(this.config.headers(),{"anthropic-beta":`files-api-2025-04-14`}),formData:a,failedResponseHandler:J,successfulResponseHandler:I(ne),fetch:this.config.fetch});return{warnings:[],providerReference:{anthropic:o.id},mediaType:o.mime_type??t,filename:o.filename??n,providerMetadata:{anthropic:{filename:o.filename,mimeType:o.mime_type,sizeBytes:o.size_bytes,createdAt:o.created_at,...o.downloadable==null?{}:{downloadable:o.downloadable}}}}}},ie=B(()=>j(u({type:p(`message`),id:l().nullish(),model:l().nullish(),content:o(a(`type`,[u({type:p(`text`),text:l(),citations:o(a(`type`,[u({type:p(`web_search_result_location`),cited_text:l(),url:l(),title:l(),encrypted_index:l()}),u({type:p(`page_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_page_number:h(),end_page_number:h()}),u({type:p(`char_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_char_index:h(),end_char_index:h()})])).optional()}),u({type:p(`thinking`),thinking:l(),signature:l()}),u({type:p(`redacted_thinking`),data:l()}),u({type:p(`compaction`),content:l()}),u({type:p(`tool_use`),id:l(),name:l(),input:f(),caller:d([u({type:p(`code_execution_20250825`),tool_id:l()}),u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`server_tool_use`),id:l(),name:l(),input:c(l(),f()).nullish(),caller:d([u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`mcp_tool_use`),id:l(),name:l(),input:f(),server_name:l()}),u({type:p(`mcp_tool_result`),tool_use_id:l(),is_error:i(),content:o(d([l(),u({type:p(`text`),text:l()})]))}),u({type:p(`web_fetch_tool_result`),tool_use_id:l(),content:d([u({type:p(`web_fetch_result`),url:l(),retrieved_at:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),media_type:p(`application/pdf`),data:l()}),u({type:p(`text`),media_type:p(`text/plain`),data:l()})])})}),u({type:p(`web_fetch_tool_result_error`),error_code:l()})])}),u({type:p(`web_search_tool_result`),tool_use_id:l(),content:d([o(u({type:p(`web_search_result`),url:l(),title:l(),encrypted_content:l(),page_age:l().nullish()})),u({type:p(`web_search_tool_result_error`),error_code:l()})])}),u({type:p(`code_execution_tool_result`),tool_use_id:l(),content:d([u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`encrypted_code_execution_result`),encrypted_stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`bash_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`text_editor_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})])}),u({type:p(`tool_search_tool_result`),tool_use_id:l(),content:d([u({type:p(`tool_search_tool_search_result`),tool_references:o(u({type:p(`tool_reference`),tool_name:l()}))}),u({type:p(`tool_search_tool_result_error`),error_code:l()})])}),u({type:p(`advisor_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`advisor_result`),text:l()}),u({type:p(`advisor_redacted_result`),encrypted_content:l()}),u({type:p(`advisor_tool_result_error`),error_code:l()})])})])),stop_reason:l().nullish(),stop_sequence:l().nullish(),usage:m({input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish(),iterations:o(d([u({type:d([p(`compaction`),p(`message`)]),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()}),u({type:p(`advisor_message`),model:l(),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()})])).nullish()}),container:u({expires_at:l(),id:l(),skills:o(u({type:d([p(`anthropic`),p(`custom`)]),skill_id:l(),version:l()})).nullish()}).nullish(),context_management:u({applied_edits:o(d([u({type:p(`clear_tool_uses_20250919`),cleared_tool_uses:h(),cleared_input_tokens:h()}),u({type:p(`clear_thinking_20251015`),cleared_thinking_turns:h(),cleared_input_tokens:h()}),u({type:p(`compact_20260112`)})]))}).nullish()}))),ae=B(()=>j(a(`type`,[u({type:p(`message_start`),message:u({id:l().nullish(),model:l().nullish(),role:l().nullish(),usage:m({input_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()}),content:o(a(`type`,[u({type:p(`tool_use`),id:l(),name:l(),input:f(),caller:d([u({type:p(`code_execution_20250825`),tool_id:l()}),u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()})])).nullish(),stop_reason:l().nullish(),container:u({expires_at:l(),id:l()}).nullish()})}),u({type:p(`content_block_start`),index:h(),content_block:a(`type`,[u({type:p(`text`),text:l()}),u({type:p(`thinking`),thinking:l()}),u({type:p(`tool_use`),id:l(),name:l(),input:c(l(),f()).optional(),caller:d([u({type:p(`code_execution_20250825`),tool_id:l()}),u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`redacted_thinking`),data:l()}),u({type:p(`compaction`),content:l().nullish()}),u({type:p(`server_tool_use`),id:l(),name:l(),input:c(l(),f()).nullish(),caller:d([u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`mcp_tool_use`),id:l(),name:l(),input:f(),server_name:l()}),u({type:p(`mcp_tool_result`),tool_use_id:l(),is_error:i(),content:o(d([l(),u({type:p(`text`),text:l()})]))}),u({type:p(`web_fetch_tool_result`),tool_use_id:l(),content:d([u({type:p(`web_fetch_result`),url:l(),retrieved_at:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),media_type:p(`application/pdf`),data:l()}),u({type:p(`text`),media_type:p(`text/plain`),data:l()})])})}),u({type:p(`web_fetch_tool_result_error`),error_code:l()})])}),u({type:p(`web_search_tool_result`),tool_use_id:l(),content:d([o(u({type:p(`web_search_result`),url:l(),title:l(),encrypted_content:l(),page_age:l().nullish()})),u({type:p(`web_search_tool_result_error`),error_code:l()})])}),u({type:p(`code_execution_tool_result`),tool_use_id:l(),content:d([u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`encrypted_code_execution_result`),encrypted_stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`bash_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`text_editor_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})])}),u({type:p(`tool_search_tool_result`),tool_use_id:l(),content:d([u({type:p(`tool_search_tool_search_result`),tool_references:o(u({type:p(`tool_reference`),tool_name:l()}))}),u({type:p(`tool_search_tool_result_error`),error_code:l()})])}),u({type:p(`advisor_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`advisor_result`),text:l()}),u({type:p(`advisor_redacted_result`),encrypted_content:l()}),u({type:p(`advisor_tool_result_error`),error_code:l()})])})])}),u({type:p(`content_block_delta`),index:h(),delta:a(`type`,[u({type:p(`input_json_delta`),partial_json:l()}),u({type:p(`text_delta`),text:l()}),u({type:p(`thinking_delta`),thinking:l()}),u({type:p(`signature_delta`),signature:l()}),u({type:p(`compaction_delta`),content:l().nullish()}),u({type:p(`citations_delta`),citation:a(`type`,[u({type:p(`web_search_result_location`),cited_text:l(),url:l(),title:l(),encrypted_index:l()}),u({type:p(`page_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_page_number:h(),end_page_number:h()}),u({type:p(`char_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_char_index:h(),end_char_index:h()})])})])}),u({type:p(`content_block_stop`),index:h()}),u({type:p(`error`),error:u({type:l(),message:l()})}),u({type:p(`message_delta`),delta:u({stop_reason:l().nullish(),stop_sequence:l().nullish(),container:u({expires_at:l(),id:l(),skills:o(u({type:d([p(`anthropic`),p(`custom`)]),skill_id:l(),version:l()})).nullish()}).nullish()}),usage:m({input_tokens:h().nullish(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish(),iterations:o(d([u({type:d([p(`compaction`),p(`message`)]),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()}),u({type:p(`advisor_message`),model:l(),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()})])).nullish()}),context_management:u({applied_edits:o(d([u({type:p(`clear_tool_uses_20250919`),cleared_tool_uses:h(),cleared_input_tokens:h()}),u({type:p(`clear_thinking_20251015`),cleared_thinking_turns:h(),cleared_input_tokens:h()}),u({type:p(`compact_20260112`)})]))}).nullish()}),u({type:p(`message_stop`)}),u({type:p(`ping`)})]))),oe=B(()=>j(u({signature:l().optional(),redactedData:l().optional()}))),Y=u({citations:u({enabled:i()}).optional(),title:l().optional(),context:l().optional()}),se=u({sendReasoning:i().optional(),structuredOutputMode:g([`outputFormat`,`jsonTool`,`auto`]).optional(),thinking:a(`type`,[u({type:p(`adaptive`),display:g([`omitted`,`summarized`]).optional()}),u({type:p(`enabled`),budgetTokens:h().optional()}),u({type:p(`disabled`)})]).optional(),disableParallelToolUse:i().optional(),cacheControl:u({type:p(`ephemeral`),ttl:d([p(`5m`),p(`1h`)]).optional()}).optional(),metadata:u({userId:l().optional()}).optional(),mcpServers:o(u({type:p(`url`),name:l(),url:l(),authorizationToken:l().nullish(),toolConfiguration:u({enabled:i().nullish(),allowedTools:o(l()).nullish()}).nullish()})).optional(),container:u({id:l().optional(),skills:o(a(`type`,[u({type:p(`anthropic`),skillId:l(),version:l().optional()}),u({type:p(`custom`),providerReference:c(l(),l()),version:l().optional()})])).optional()}).optional(),toolStreaming:i().optional(),effort:g([`low`,`medium`,`high`,`xhigh`,`max`]).optional(),taskBudget:u({type:p(`tokens`),total:h().int().min(2e4),remaining:h().int().min(0).optional()}).optional(),speed:g([`fast`,`standard`]).optional(),inferenceGeo:g([`us`,`global`]).optional(),anthropicBeta:o(l()).optional(),contextManagement:u({edits:o(a(`type`,[u({type:p(`clear_tool_uses_20250919`),trigger:a(`type`,[u({type:p(`input_tokens`),value:h()}),u({type:p(`tool_uses`),value:h()})]).optional(),keep:u({type:p(`tool_uses`),value:h()}).optional(),clearAtLeast:u({type:p(`input_tokens`),value:h()}).optional(),clearToolInputs:i().optional(),excludeTools:o(l()).optional()}),u({type:p(`clear_thinking_20251015`),keep:d([p(`all`),u({type:p(`thinking_turns`),value:h()})]).optional()}),u({type:p(`compact_20260112`),trigger:u({type:p(`input_tokens`),value:h()}).optional(),pauseAfterCompaction:i().optional(),instructions:l().optional()})]))}).optional()}),ce=4;function le(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var X=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=le(e);if(n){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>ce){this.warnings.push({type:`unsupported`,feature:`cacheControl breakpoint limit`,details:`Maximum ${ce} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},ue=B(()=>j(u({model:l(),maxUses:h().optional(),caching:u({type:p(`ephemeral`),ttl:d([p(`5m`),p(`1h`)])}).optional()}))),de=B(()=>j(a(`type`,[u({type:p(`advisor_result`),text:l()}),u({type:p(`advisor_redacted_result`),encryptedContent:l()}),u({type:p(`advisor_tool_result_error`),errorCode:l()})]))),fe=L({id:`anthropic.advisor_20260301`,inputSchema:B(()=>j(u({}).strict())),outputSchema:de,supportsDeferredResults:!0}),pe=e=>fe(e),me=B(()=>j(u({maxCharacters:h().optional()}))),he=H({id:`anthropic.text_editor_20250728`,inputSchema:B(()=>j(u({command:g([`view`,`create`,`str_replace`,`insert`]),path:l(),file_text:l().optional(),insert_line:h().int().optional(),new_str:l().optional(),insert_text:l().optional(),old_str:l().optional(),view_range:o(h().int()).optional()})))}),ge=(e={})=>he(e),_e=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),userLocation:u({type:p(`approximate`),city:l().optional(),region:l().optional(),country:l().optional(),timezone:l().optional()}).optional()}))),ve=B(()=>j(o(u({url:l(),title:l().nullable(),pageAge:l().nullable(),encryptedContent:l(),type:p(`web_search_result`)})))),ye=L({id:`anthropic.web_search_20260209`,inputSchema:B(()=>j(u({query:l()}))),outputSchema:ve,supportsDeferredResults:!0}),be=(e={})=>ye(e),xe=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),userLocation:u({type:p(`approximate`),city:l().optional(),region:l().optional(),country:l().optional(),timezone:l().optional()}).optional()}))),Se=B(()=>j(o(u({url:l(),title:l().nullable(),pageAge:l().nullable(),encryptedContent:l(),type:p(`web_search_result`)})))),Ce=L({id:`anthropic.web_search_20250305`,inputSchema:B(()=>j(u({query:l()}))),outputSchema:Se,supportsDeferredResults:!0}),we=(e={})=>Ce(e),Te=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),citations:u({enabled:i()}).optional(),maxContentTokens:h().optional()}))),Ee=B(()=>j(u({type:p(`web_fetch_result`),url:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),mediaType:p(`application/pdf`),data:l()}),u({type:p(`text`),mediaType:p(`text/plain`),data:l()})])}),retrievedAt:l().nullable()}))),De=L({id:`anthropic.web_fetch_20260209`,inputSchema:B(()=>j(u({url:l()}))),outputSchema:Ee,supportsDeferredResults:!0}),Oe=(e={})=>De(e),ke=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),citations:u({enabled:i()}).optional(),maxContentTokens:h().optional()}))),Ae=B(()=>j(u({type:p(`web_fetch_result`),url:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),mediaType:p(`application/pdf`),data:l()}),u({type:p(`text`),mediaType:p(`text/plain`),data:l()})])}),retrievedAt:l().nullable()}))),je=L({id:`anthropic.web_fetch_20250910`,inputSchema:B(()=>j(u({url:l()}))),outputSchema:Ae,supportsDeferredResults:!0}),Me=(e={})=>je(e);async function Ne({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:i,supportsStructuredOutput:a,supportsStrictTools:o,defaultEagerInputStreaming:s=!1}){e=e?.length?e:void 0;let c=[],l=new Set,u=i||new X;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:c,betas:l};let d=[];for(let t of e)switch(t.type){case`function`:{let e=u.getCacheControl(t.providerOptions,{type:`tool definition`,canCache:!0}),n=t.providerOptions?.anthropic,r=n?.eagerInputStreaming??s,i=n?.deferLoading,f=n?.allowedCallers;!o&&t.strict!=null&&c.push({type:`unsupported`,feature:`strict`,details:`Tool '${t.name}' has strict: ${t.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),d.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...r?{eager_input_streaming:!0}:{},...o===!0&&t.strict!=null?{strict:t.strict}:{},...i==null?{}:{defer_loading:i},...f==null?{}:{allowed_callers:f},...t.inputExamples==null?{}:{input_examples:t.inputExamples.map(e=>e.input)}}),a===!0&&l.add(`structured-outputs-2025-11-13`),(t.inputExamples!=null||f!=null)&&l.add(`advanced-tool-use-2025-11-20`);break}case`provider`:switch(t.id){case`anthropic.code_execution_20250522`:l.add(`code-execution-2025-05-22`),d.push({type:`code_execution_20250522`,name:`code_execution`,cache_control:void 0});break;case`anthropic.code_execution_20250825`:l.add(`code-execution-2025-08-25`),d.push({type:`code_execution_20250825`,name:`code_execution`});break;case`anthropic.code_execution_20260120`:d.push({type:`code_execution_20260120`,name:`code_execution`});break;case`anthropic.computer_20250124`:l.add(`computer-use-2025-01-24`),d.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`:l.add(`computer-use-2025-11-24`),d.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`:l.add(`computer-use-2024-10-22`),d.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`:l.add(`computer-use-2025-01-24`),d.push({name:`str_replace_editor`,type:`text_editor_20250124`,cache_control:void 0});break;case`anthropic.text_editor_20241022`:l.add(`computer-use-2024-10-22`),d.push({name:`str_replace_editor`,type:`text_editor_20241022`,cache_control:void 0});break;case`anthropic.text_editor_20250429`:l.add(`computer-use-2025-01-24`),d.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`,cache_control:void 0});break;case`anthropic.text_editor_20250728`:{let e=await C({value:t.args,schema:me});d.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters,cache_control:void 0});break}case`anthropic.bash_20250124`:l.add(`computer-use-2025-01-24`),d.push({name:`bash`,type:`bash_20250124`,cache_control:void 0});break;case`anthropic.bash_20241022`:l.add(`computer-use-2024-10-22`),d.push({name:`bash`,type:`bash_20241022`,cache_control:void 0});break;case`anthropic.memory_20250818`:l.add(`context-management-2025-06-27`),d.push({name:`memory`,type:`memory_20250818`});break;case`anthropic.web_fetch_20250910`:{l.add(`web-fetch-2025-09-10`);let e=await C({value:t.args,schema:ke});d.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`:{l.add(`code-execution-web-tools-2026-02-09`);let e=await C({value:t.args,schema:Te});d.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 C({value:t.args,schema:xe});d.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`:{l.add(`code-execution-web-tools-2026-02-09`);let e=await C({value:t.args,schema:_e});d.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`:d.push({type:`tool_search_tool_regex_20251119`,name:`tool_search_tool_regex`});break;case`anthropic.tool_search_bm25_20251119`:d.push({type:`tool_search_tool_bm25_20251119`,name:`tool_search_tool_bm25`});break;case`anthropic.advisor_20260301`:{l.add(`advisor-tool-2026-03-01`);let e=await C({value:t.args,schema:ue});d.push({type:`advisor_20260301`,name:`advisor`,model:e.model,...e.maxUses!==void 0&&{max_uses:e.maxUses},...e.caching!==void 0&&{caching:e.caching}});break}default:c.push({type:`unsupported`,feature:`provider-defined tool ${t.id}`});break}break;default:c.push({type:`unsupported`,feature:`tool ${t}`});break}if(t==null)return{tools:d,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:c,betas:l};let f=t.type;switch(f){case`auto`:return{tools:d,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:c,betas:l};case`required`:return{tools:d,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:c,betas:l};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:c,betas:l};case`tool`:return{tools:d,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:c,betas:l};default:throw new r({functionality:`tool choice type: ${f}`})}}function Pe({usage:e,rawUsage:t}){let n=e.cache_creation_input_tokens??0,r=e.cache_read_input_tokens??0,i,a;if(e.iterations&&e.iterations.length>0){let t=e.iterations.filter(e=>e.type===`compaction`||e.type===`message`);if(t.length>0){let e=t.reduce((e,t)=>({input:e.input+t.input_tokens,output:e.output+t.output_tokens}),{input:0,output:0});i=e.input,a=e.output}else i=e.input_tokens,a=e.output_tokens}else i=e.input_tokens,a=e.output_tokens;return{inputTokens:{total:i+n+r,noCache:i,cacheRead:r,cacheWrite:n},outputTokens:{total:a,text:void 0,reasoning:void 0},raw:t??e}}var Fe=B(()=>j(u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}))),Ie=L({id:`anthropic.code_execution_20250522`,inputSchema:B(()=>j(u({code:l()}))),outputSchema:Fe}),Le=(e={})=>Ie(e),Re=B(()=>j(a(`type`,[u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})]))),ze=L({id:`anthropic.code_execution_20250825`,inputSchema:B(()=>j(a(`type`,[u({type:p(`programmatic-tool-call`),code:l()}),u({type:p(`bash_code_execution`),command:l()}),a(`command`,[u({type:p(`text_editor_code_execution`),command:p(`view`),path:l()}),u({type:p(`text_editor_code_execution`),command:p(`create`),path:l(),file_text:l().nullish()}),u({type:p(`text_editor_code_execution`),command:p(`str_replace`),path:l(),old_str:l(),new_str:l()})])]))),outputSchema:Re,supportsDeferredResults:!0}),Be=(e={})=>ze(e),Ve=B(()=>j(a(`type`,[u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`encrypted_code_execution_result`),encrypted_stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})]))),He=L({id:`anthropic.code_execution_20260120`,inputSchema:B(()=>j(a(`type`,[u({type:p(`programmatic-tool-call`),code:l()}),u({type:p(`bash_code_execution`),command:l()}),a(`command`,[u({type:p(`text_editor_code_execution`),command:p(`view`),path:l()}),u({type:p(`text_editor_code_execution`),command:p(`create`),path:l(),file_text:l().nullish()}),u({type:p(`text_editor_code_execution`),command:p(`str_replace`),path:l(),old_str:l(),new_str:l()})])]))),outputSchema:Ve,supportsDeferredResults:!0}),Ue=(e={})=>He(e),We=B(()=>j(o(u({type:p(`tool_reference`),toolName:l()})))),Ge=L({id:`anthropic.tool_search_regex_20251119`,inputSchema:B(()=>j(u({pattern:l(),limit:h().optional()}))),outputSchema:We,supportsDeferredResults:!0}),Ke=(e={})=>Ge(e);function qe(e){return typeof e==`string`?new TextDecoder().decode(R(e)):new TextDecoder().decode(e)}async function Je({prompt:e,sendReasoning:t,warnings:n,cacheControlValidator:i,toolNameMapping:a}){let o=new Set,s=Ye(e),c=i||new X,l,u=[];async function d(e){return(await x({provider:`anthropic`,providerOptions:e,schema:Y}))?.citations?.enabled??!1}async function f(e){let t=await x({provider:`anthropic`,providerOptions:e,schema:Y});return{title:t?.title,context:t?.context}}for(let e=0;e<s.length;e++){let i=s[e],p=e===s.length-1,m=i.type;switch(m){case`system`:if(l!=null)throw new r({functionality:`Multiple system messages that are separated by user/assistant messages`});l=i.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:c.getCacheControl(t,{type:`system message`,canCache:!0})}));break;case`user`:{let e=[];for(let t of i.messages){let{role:i,content:a}=t;switch(i){case`user`:for(let n=0;n<a.length;n++){let i=a[n],s=n===a.length-1,l=c.getCacheControl(i.providerOptions,{type:`user message part`,canCache:!0})??(s?c.getCacheControl(t.providerOptions,{type:`user message`,canCache:!0}):void 0);switch(i.type){case`text`:e.push({type:`text`,text:i.text,cache_control:l});break;case`file`:switch(i.data.type){case`reference`:{let t=k({reference:i.data.reference,provider:`anthropic`});o.add(`files-api-2025-04-14`),y(i.mediaType)===`image`?e.push({type:`image`,source:{type:`file`,file_id:t},cache_control:l}):e.push({type:`document`,source:{type:`file`,file_id:t},cache_control:l});break}case`text`:{let t=await d(i.providerOptions),n=await f(i.providerOptions);e.push({type:`document`,source:{type:`text`,media_type:`text/plain`,data:i.data.text},title:n.title??i.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l});break}case`url`:case`data`:{let t=y(i.mediaType);if(t===`image`)e.push({type:`image`,source:i.data.type===`url`?{type:`url`,url:i.data.url.toString()}:{type:`base64`,media_type:v({part:i}),data:V(i.data.data)},cache_control:l});else if(t===`application`&&(i.data.type===`url`?i.mediaType===`application/pdf`:v({part:i})===`application/pdf`)){o.add(`pdfs-2024-09-25`);let t=await d(i.providerOptions),n=await f(i.providerOptions);e.push({type:`document`,source:i.data.type===`url`?{type:`url`,url:i.data.url.toString()}:{type:`base64`,media_type:`application/pdf`,data:V(i.data.data)},title:n.title??i.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(i.mediaType===`text/plain`){let t=await d(i.providerOptions),n=await f(i.providerOptions);e.push({type:`document`,source:i.data.type===`url`?{type:`url`,url:i.data.url.toString()}:{type:`text`,media_type:`text/plain`,data:qe(i.data.data)},title:n.title??i.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new r({functionality:`media type: ${i.mediaType}`});break}}break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r];if(i.type===`tool-approval-response`)continue;let s=i.output,l=`providerOptions`in s?s.providerOptions:s.type===`content`?s.value.find(e=>e.providerOptions!=null)?.providerOptions:void 0,u=r===a.length-1,d=c.getCacheControl(i.providerOptions,{type:`tool result part`,canCache:!0})??c.getCacheControl(l,{type:`tool result output`,canCache:!0})??(u?c.getCacheControl(t.providerOptions,{type:`tool result message`,canCache:!0}):void 0),f;switch(s.type){case`content`:f=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:{let t=y(e.mediaType);if(e.data.type===`url`)return t===`image`?{type:`image`,source:{type:`url`,url:e.data.url.toString()}}:{type:`document`,source:{type:`url`,url:e.data.url.toString()}};if(e.data.type===`data`){if(t===`image`)return{type:`image`,source:{type:`base64`,media_type:v({part:e}),data:V(e.data.data)}};if(v({part:e})===`application/pdf`)return o.add(`pdfs-2024-09-25`),{type:`document`,source:{type:`base64`,media_type:`application/pdf`,data:V(e.data.data)}};n.push({type:`other`,message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return}n.push({type:`other`,message:`unsupported tool content part type: ${e.type} with data type: ${e.data.type}`});return}case`custom`:{let t=e.providerOptions?.anthropic;if(t?.type===`tool-reference`)return{type:`tool_reference`,tool_name:t.toolName};n.push({type:`other`,message:`unsupported custom tool content part`});return}default:n.push({type:`other`,message:`unsupported tool content part type: ${e.type}`});return}}).filter(b);break;case`text`:case`error-text`:f=s.value;break;case`execution-denied`:f=s.reason??`Tool call execution denied.`;break;default:f=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:f,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:d})}break;default:throw Error(`Unsupported role: ${i}`)}}u.push({role:`user`,content:e});break}case`assistant`:{let e=[],r=new Set;for(let o=0;o<i.messages.length;o++){let s=i.messages[o],l=o===i.messages.length-1,{content:u}=s;for(let i=0;i<u.length;i++){let o=u[i],d=i===u.length-1,f=c.getCacheControl(o.providerOptions,{type:`assistant message part`,canCache:!0})??(d?c.getCacheControl(s.providerOptions,{type:`assistant message`,canCache:!0}):void 0);switch(o.type){case`text`:o.providerOptions?.anthropic?.type===`compaction`?e.push({type:`compaction`,content:o.text,cache_control:f}):e.push({type:`text`,text:p&&l&&d?o.text.trim():o.text,cache_control:f});break;case`reasoning`:if(t){let t=await x({provider:`anthropic`,providerOptions:o.providerOptions,schema:oe});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):(c.getCacheControl(o.providerOptions,{type:`redacted thinking block`,canCache:!1}),e.push({type:`redacted_thinking`,data:t.redactedData})):(c.getCacheControl(o.providerOptions,{type:`thinking block`,canCache:!1}),e.push({type:`thinking`,thinking:o.text,signature:t.signature}))}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:{if(o.providerExecuted){let t=a.toProviderToolName(o.toolName);if(o.providerOptions?.anthropic?.type===`mcp-tool-use`){r.add(o.toolCallId);let t=o.providerOptions?.anthropic?.serverName;if(t==null||typeof t!=`string`){n.push({type:`other`,message:`mcp tool use server name is required and must be a string`});break}e.push({type:`mcp_tool_use`,id:o.toolCallId,name:o.toolName,input:o.input,server_name:t,cache_control:f})}else if(t===`code_execution`&&o.input!=null&&typeof o.input==`object`&&`type`in o.input&&typeof o.input.type==`string`&&(o.input.type===`bash_code_execution`||o.input.type===`text_editor_code_execution`))e.push({type:`server_tool_use`,id:o.toolCallId,name:o.input.type,input:o.input,cache_control:f});else if(t===`code_execution`&&o.input!=null&&typeof o.input==`object`&&`type`in o.input&&o.input.type===`programmatic-tool-call`){let{type:t,...n}=o.input;e.push({type:`server_tool_use`,id:o.toolCallId,name:`code_execution`,input:n,cache_control:f})}else t===`code_execution`||t===`web_fetch`||t===`web_search`||t===`tool_search_tool_regex`||t===`tool_search_tool_bm25`?e.push({type:`server_tool_use`,id:o.toolCallId,name:t,input:o.input,cache_control:f}):t===`advisor`?e.push({type:`server_tool_use`,id:o.toolCallId,name:`advisor`,input:{},cache_control:f}):n.push({type:`other`,message:`provider executed tool call for tool ${o.toolName} is not supported`});break}let t=o.providerOptions?.anthropic,i=t?.caller?(t.caller.type===`code_execution_20250825`||t.caller.type===`code_execution_20260120`)&&t.caller.toolId?{type:t.caller.type,tool_id:t.caller.toolId}:t.caller.type===`direct`?{type:`direct`}:void 0:void 0;e.push({type:`tool_use`,id:o.toolCallId,name:o.toolName,input:o.input,...i&&{caller:i},cache_control:f});break}case`tool-result`:{let t=a.toProviderToolName(o.toolName);if(r.has(o.toolCallId)){let t=o.output;if(t.type!==`json`&&t.type!==`error-json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}e.push({type:`mcp_tool_result`,tool_use_id:o.toolCallId,is_error:t.type===`error-json`,content:t.value,cache_control:f})}else if(t===`code_execution`){let t=o.output;if(t.type===`error-text`||t.type===`error-json`){let n={};try{typeof t.value==`string`?n=JSON.parse(t.value):typeof t.value==`object`&&t.value!==null&&(n=t.value)}catch{}n.type===`code_execution_tool_result_error`?e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:`code_execution_tool_result_error`,error_code:n.errorCode??`unknown`},cache_control:f}):e.push({type:`bash_code_execution_tool_result`,tool_use_id:o.toolCallId,cache_control:f,content:{type:`bash_code_execution_tool_result_error`,error_code:n.errorCode??`unknown`}});break}if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}if(t.value==null||typeof t.value!=`object`||!(`type`in t.value)||typeof t.value.type!=`string`){n.push({type:`other`,message:`provider executed tool result output value is not a valid code execution result for tool ${o.toolName}`});break}if(t.value.type===`code_execution_result`){let n=await C({value:t.value,schema:Fe});e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:n.content??[]},cache_control:f})}else if(t.value.type===`encrypted_code_execution_result`){let n=await C({value:t.value,schema:Ve});n.type===`encrypted_code_execution_result`&&e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:n.type,encrypted_stdout:n.encrypted_stdout,stderr:n.stderr,return_code:n.return_code,content:n.content??[]},cache_control:f})}else{let n=await C({value:t.value,schema:Re});n.type===`code_execution_result`?e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:n.content??[]},cache_control:f}):n.type===`bash_code_execution_result`||n.type===`bash_code_execution_tool_result_error`?e.push({type:`bash_code_execution_tool_result`,tool_use_id:o.toolCallId,cache_control:f,content:n}):e.push({type:`text_editor_code_execution_tool_result`,tool_use_id:o.toolCallId,cache_control:f,content:n})}break}if(t===`web_fetch`){let t=o.output;if(t.type===`error-json`){let n={};try{typeof t.value==`string`?n=JSON.parse(t.value):typeof t.value==`object`&&t.value!==null&&(n=t.value)}catch{let e=t.value?.errorCode;n={errorCode:typeof e==`string`?e:`unavailable`}}e.push({type:`web_fetch_tool_result`,tool_use_id:o.toolCallId,content:{type:`web_fetch_tool_result_error`,error_code:n.errorCode??`unavailable`},cache_control:f});break}if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=await C({value:t.value,schema:Ae});e.push({type:`web_fetch_tool_result`,tool_use_id:o.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:f});break}if(t===`web_search`){let t=o.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=await C({value:t.value,schema:Se});e.push({type:`web_search_tool_result`,tool_use_id:o.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:f});break}if(t===`tool_search_tool_regex`||t===`tool_search_tool_bm25`){let t=o.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=(await C({value:t.value,schema:We})).map(e=>({type:`tool_reference`,tool_name:e.toolName}));e.push({type:`tool_search_tool_result`,tool_use_id:o.toolCallId,content:{type:`tool_search_tool_search_result`,tool_references:r},cache_control:f});break}if(t===`advisor`){let t=o.output;if(t.type!==`json`&&t.type!==`error-json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=await C({value:t.value,schema:de});r.type===`advisor_result`?e.push({type:`advisor_tool_result`,tool_use_id:o.toolCallId,content:{type:`advisor_result`,text:r.text},cache_control:f}):r.type===`advisor_redacted_result`?e.push({type:`advisor_tool_result`,tool_use_id:o.toolCallId,content:{type:`advisor_redacted_result`,encrypted_content:r.encryptedContent},cache_control:f}):e.push({type:`advisor_tool_result`,tool_use_id:o.toolCallId,content:{type:`advisor_tool_result_error`,error_code:r.errorCode},cache_control:f});break}n.push({type:`other`,message:`provider executed tool result for tool ${o.toolName} is not supported`});break}}}}u.push({role:`assistant`,content:e});break}default:throw Error(`content type: ${m}`)}}return{prompt:{system:l,messages:u},betas:o}}function Ye(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:throw Error(`Unsupported role: ${e}`)}}return t}function Z({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`;case`compaction`:return`other`;default:return`other`}}var Xe=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),Ze=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`minLength`,`maxLength`,`pattern`,`minItems`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`,`not`];function Qe(e){return $(e)}function Q(e){return typeof e==`boolean`||!nt(e)?e:$(e)}function $(e){let t={},n=e;if(e.$ref!=null)return{$ref:e.$ref};if(e.$schema!=null&&(t.$schema=e.$schema),e.$id!=null&&(t.$id=e.$id),e.title!=null&&(t.title=e.title),e.description!=null&&(t.description=e.description),e.default!==void 0&&(t.default=e.default),e.const!==void 0&&(t.const=e.const),e.enum!=null&&(t.enum=e.enum),e.type!=null&&(t.type=e.type),e.anyOf==null?e.oneOf!=null&&(t.anyOf=e.oneOf.map(Q)):t.anyOf=e.anyOf.map(Q),e.allOf!=null&&(t.allOf=e.allOf.map(Q)),e.definitions!=null&&(t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([e,t])=>[e,Q(t)]))),n.$defs!=null){let e=t;e.$defs=Object.fromEntries(Object.entries(n.$defs).map(([e,t])=>[e,Q(t)]))}(e.type===`object`||e.properties!=null)&&(e.properties!=null&&(t.properties=Object.fromEntries(Object.entries(e.properties).map(([e,t])=>[e,Q(t)]))),t.additionalProperties=!1,e.required!=null&&(t.required=e.required)),e.items!=null&&(t.items=Array.isArray(e.items)?e.items.map(Q):Q(e.items)),typeof e.format==`string`&&Xe.has(e.format)&&(t.format=e.format);let r=$e(e);return r!=null&&(t.description=t.description==null?r:`${t.description}
|
|
1
|
+
import{APICallError as e,InvalidArgumentError as t,NoSuchModelError as n,UnsupportedFunctionalityError as r}from"../provider/index.js";import{At as i,Bt as a,Et as o,Kn as s,Nn as c,Rn as l,Tn as u,Xn as d,Zn as f,dn as p,fn as m,wn as h,yt as g}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{A as _,B as v,C as y,D as b,I as x,J as S,K as C,L as w,M as T,N as E,R as D,T as O,V as k,W as A,X as ee,Y as j,Z as M,a as N,b as P,d as F,f as I,g as te,h as L,i as R,j as z,k as B,o as V,p as H,q as U,r as W,u as G,x as K,z as q}from"../../_chunks/workflow/dist-DZZY3Zyp.js";var J=F({errorSchema:B(()=>j(u({type:p(`error`),error:u({type:l(),message:l()})}))),errorToMessage:e=>e.error.message}),ne=B(()=>j(u({id:l(),type:p(`file`),filename:l(),mime_type:l(),size_bytes:h(),created_at:l(),downloadable:i().nullish()}))),re=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile({data:e,mediaType:t,filename:n}){let r=N(e),i=new Blob([r],{type:t}),a=new FormData;n==null?a.append(`file`,i):a.append(`file`,i,n);let{value:o}=await w({url:`${this.config.baseURL}/files`,headers:W(this.config.headers(),{"anthropic-beta":`files-api-2025-04-14`}),formData:a,failedResponseHandler:J,successfulResponseHandler:I(ne),fetch:this.config.fetch});return{warnings:[],providerReference:{anthropic:o.id},mediaType:o.mime_type??t,filename:o.filename??n,providerMetadata:{anthropic:{filename:o.filename,mimeType:o.mime_type,sizeBytes:o.size_bytes,createdAt:o.created_at,...o.downloadable==null?{}:{downloadable:o.downloadable}}}}}},ie=B(()=>j(u({type:p(`message`),id:l().nullish(),model:l().nullish(),content:o(a(`type`,[u({type:p(`text`),text:l(),citations:o(a(`type`,[u({type:p(`web_search_result_location`),cited_text:l(),url:l(),title:l(),encrypted_index:l()}),u({type:p(`page_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_page_number:h(),end_page_number:h()}),u({type:p(`char_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_char_index:h(),end_char_index:h()})])).optional()}),u({type:p(`thinking`),thinking:l(),signature:l()}),u({type:p(`redacted_thinking`),data:l()}),u({type:p(`compaction`),content:l()}),u({type:p(`tool_use`),id:l(),name:l(),input:f(),caller:d([u({type:p(`code_execution_20250825`),tool_id:l()}),u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`server_tool_use`),id:l(),name:l(),input:c(l(),f()).nullish(),caller:d([u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`mcp_tool_use`),id:l(),name:l(),input:f(),server_name:l()}),u({type:p(`mcp_tool_result`),tool_use_id:l(),is_error:i(),content:o(d([l(),u({type:p(`text`),text:l()})]))}),u({type:p(`web_fetch_tool_result`),tool_use_id:l(),content:d([u({type:p(`web_fetch_result`),url:l(),retrieved_at:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),media_type:p(`application/pdf`),data:l()}),u({type:p(`text`),media_type:p(`text/plain`),data:l()})])})}),u({type:p(`web_fetch_tool_result_error`),error_code:l()})])}),u({type:p(`web_search_tool_result`),tool_use_id:l(),content:d([o(u({type:p(`web_search_result`),url:l(),title:l(),encrypted_content:l(),page_age:l().nullish()})),u({type:p(`web_search_tool_result_error`),error_code:l()})])}),u({type:p(`code_execution_tool_result`),tool_use_id:l(),content:d([u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`encrypted_code_execution_result`),encrypted_stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`bash_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`text_editor_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})])}),u({type:p(`tool_search_tool_result`),tool_use_id:l(),content:d([u({type:p(`tool_search_tool_search_result`),tool_references:o(u({type:p(`tool_reference`),tool_name:l()}))}),u({type:p(`tool_search_tool_result_error`),error_code:l()})])}),u({type:p(`advisor_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`advisor_result`),text:l()}),u({type:p(`advisor_redacted_result`),encrypted_content:l()}),u({type:p(`advisor_tool_result_error`),error_code:l()})])})])),stop_reason:l().nullish(),stop_sequence:l().nullish(),usage:m({input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish(),iterations:o(d([u({type:d([p(`compaction`),p(`message`)]),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()}),u({type:p(`advisor_message`),model:l(),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()})])).nullish()}),container:u({expires_at:l(),id:l(),skills:o(u({type:d([p(`anthropic`),p(`custom`)]),skill_id:l(),version:l()})).nullish()}).nullish(),context_management:u({applied_edits:o(d([u({type:p(`clear_tool_uses_20250919`),cleared_tool_uses:h(),cleared_input_tokens:h()}),u({type:p(`clear_thinking_20251015`),cleared_thinking_turns:h(),cleared_input_tokens:h()}),u({type:p(`compact_20260112`)})]))}).nullish()}))),ae=B(()=>j(a(`type`,[u({type:p(`message_start`),message:u({id:l().nullish(),model:l().nullish(),role:l().nullish(),usage:m({input_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()}),content:o(a(`type`,[u({type:p(`tool_use`),id:l(),name:l(),input:f(),caller:d([u({type:p(`code_execution_20250825`),tool_id:l()}),u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()})])).nullish(),stop_reason:l().nullish(),container:u({expires_at:l(),id:l()}).nullish()})}),u({type:p(`content_block_start`),index:h(),content_block:a(`type`,[u({type:p(`text`),text:l()}),u({type:p(`thinking`),thinking:l()}),u({type:p(`tool_use`),id:l(),name:l(),input:c(l(),f()).optional(),caller:d([u({type:p(`code_execution_20250825`),tool_id:l()}),u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`redacted_thinking`),data:l()}),u({type:p(`compaction`),content:l().nullish()}),u({type:p(`server_tool_use`),id:l(),name:l(),input:c(l(),f()).nullish(),caller:d([u({type:p(`code_execution_20260120`),tool_id:l()}),u({type:p(`direct`)})]).optional()}),u({type:p(`mcp_tool_use`),id:l(),name:l(),input:f(),server_name:l()}),u({type:p(`mcp_tool_result`),tool_use_id:l(),is_error:i(),content:o(d([l(),u({type:p(`text`),text:l()})]))}),u({type:p(`web_fetch_tool_result`),tool_use_id:l(),content:d([u({type:p(`web_fetch_result`),url:l(),retrieved_at:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),media_type:p(`application/pdf`),data:l()}),u({type:p(`text`),media_type:p(`text/plain`),data:l()})])})}),u({type:p(`web_fetch_tool_result_error`),error_code:l()})])}),u({type:p(`web_search_tool_result`),tool_use_id:l(),content:d([o(u({type:p(`web_search_result`),url:l(),title:l(),encrypted_content:l(),page_age:l().nullish()})),u({type:p(`web_search_tool_result_error`),error_code:l()})])}),u({type:p(`code_execution_tool_result`),tool_use_id:l(),content:d([u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`encrypted_code_execution_result`),encrypted_stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`bash_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()})])}),u({type:p(`text_editor_code_execution_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})])}),u({type:p(`tool_search_tool_result`),tool_use_id:l(),content:d([u({type:p(`tool_search_tool_search_result`),tool_references:o(u({type:p(`tool_reference`),tool_name:l()}))}),u({type:p(`tool_search_tool_result_error`),error_code:l()})])}),u({type:p(`advisor_tool_result`),tool_use_id:l(),content:a(`type`,[u({type:p(`advisor_result`),text:l()}),u({type:p(`advisor_redacted_result`),encrypted_content:l()}),u({type:p(`advisor_tool_result_error`),error_code:l()})])})])}),u({type:p(`content_block_delta`),index:h(),delta:a(`type`,[u({type:p(`input_json_delta`),partial_json:l()}),u({type:p(`text_delta`),text:l()}),u({type:p(`thinking_delta`),thinking:l()}),u({type:p(`signature_delta`),signature:l()}),u({type:p(`compaction_delta`),content:l().nullish()}),u({type:p(`citations_delta`),citation:a(`type`,[u({type:p(`web_search_result_location`),cited_text:l(),url:l(),title:l(),encrypted_index:l()}),u({type:p(`page_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_page_number:h(),end_page_number:h()}),u({type:p(`char_location`),cited_text:l(),document_index:h(),document_title:l().nullable(),start_char_index:h(),end_char_index:h()})])})])}),u({type:p(`content_block_stop`),index:h()}),u({type:p(`error`),error:u({type:l(),message:l()})}),u({type:p(`message_delta`),delta:u({stop_reason:l().nullish(),stop_sequence:l().nullish(),container:u({expires_at:l(),id:l(),skills:o(u({type:d([p(`anthropic`),p(`custom`)]),skill_id:l(),version:l()})).nullish()}).nullish()}),usage:m({input_tokens:h().nullish(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish(),iterations:o(d([u({type:d([p(`compaction`),p(`message`)]),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()}),u({type:p(`advisor_message`),model:l(),input_tokens:h(),output_tokens:h(),cache_creation_input_tokens:h().nullish(),cache_read_input_tokens:h().nullish()})])).nullish()}),context_management:u({applied_edits:o(d([u({type:p(`clear_tool_uses_20250919`),cleared_tool_uses:h(),cleared_input_tokens:h()}),u({type:p(`clear_thinking_20251015`),cleared_thinking_turns:h(),cleared_input_tokens:h()}),u({type:p(`compact_20260112`)})]))}).nullish()}),u({type:p(`message_stop`)}),u({type:p(`ping`)})]))),oe=B(()=>j(u({signature:l().optional(),redactedData:l().optional()}))),Y=u({citations:u({enabled:i()}).optional(),title:l().optional(),context:l().optional()}),se=u({sendReasoning:i().optional(),structuredOutputMode:g([`outputFormat`,`jsonTool`,`auto`]).optional(),thinking:a(`type`,[u({type:p(`adaptive`),display:g([`omitted`,`summarized`]).optional()}),u({type:p(`enabled`),budgetTokens:h().optional()}),u({type:p(`disabled`)})]).optional(),disableParallelToolUse:i().optional(),cacheControl:u({type:p(`ephemeral`),ttl:d([p(`5m`),p(`1h`)]).optional()}).optional(),metadata:u({userId:l().optional()}).optional(),mcpServers:o(u({type:p(`url`),name:l(),url:l(),authorizationToken:l().nullish(),toolConfiguration:u({enabled:i().nullish(),allowedTools:o(l()).nullish()}).nullish()})).optional(),container:u({id:l().optional(),skills:o(a(`type`,[u({type:p(`anthropic`),skillId:l(),version:l().optional()}),u({type:p(`custom`),providerReference:c(l(),l()),version:l().optional()})])).optional()}).optional(),toolStreaming:i().optional(),effort:g([`low`,`medium`,`high`,`xhigh`,`max`]).optional(),taskBudget:u({type:p(`tokens`),total:h().int().min(2e4),remaining:h().int().min(0).optional()}).optional(),speed:g([`fast`,`standard`]).optional(),inferenceGeo:g([`us`,`global`]).optional(),anthropicBeta:o(l()).optional(),contextManagement:u({edits:o(a(`type`,[u({type:p(`clear_tool_uses_20250919`),trigger:a(`type`,[u({type:p(`input_tokens`),value:h()}),u({type:p(`tool_uses`),value:h()})]).optional(),keep:u({type:p(`tool_uses`),value:h()}).optional(),clearAtLeast:u({type:p(`input_tokens`),value:h()}).optional(),clearToolInputs:i().optional(),excludeTools:o(l()).optional()}),u({type:p(`clear_thinking_20251015`),keep:d([p(`all`),u({type:p(`thinking_turns`),value:h()})]).optional()}),u({type:p(`compact_20260112`),trigger:u({type:p(`input_tokens`),value:h()}).optional(),pauseAfterCompaction:i().optional(),instructions:l().optional()})]))}).optional()}),ce=4;function le(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var X=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=le(e);if(n){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>ce){this.warnings.push({type:`unsupported`,feature:`cacheControl breakpoint limit`,details:`Maximum ${ce} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},ue=B(()=>j(u({model:l(),maxUses:h().optional(),caching:u({type:p(`ephemeral`),ttl:d([p(`5m`),p(`1h`)])}).optional()}))),de=B(()=>j(a(`type`,[u({type:p(`advisor_result`),text:l()}),u({type:p(`advisor_redacted_result`),encryptedContent:l()}),u({type:p(`advisor_tool_result_error`),errorCode:l()})]))),fe=L({id:`anthropic.advisor_20260301`,inputSchema:B(()=>j(u({}).strict())),outputSchema:de,supportsDeferredResults:!0}),pe=e=>fe(e),me=B(()=>j(u({maxCharacters:h().optional()}))),he=H({id:`anthropic.text_editor_20250728`,inputSchema:B(()=>j(u({command:g([`view`,`create`,`str_replace`,`insert`]),path:l(),file_text:l().optional(),insert_line:h().int().optional(),new_str:l().optional(),insert_text:l().optional(),old_str:l().optional(),view_range:o(h().int()).optional()})))}),ge=(e={})=>he(e),_e=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),userLocation:u({type:p(`approximate`),city:l().optional(),region:l().optional(),country:l().optional(),timezone:l().optional()}).optional()}))),ve=B(()=>j(o(u({url:l(),title:l().nullable(),pageAge:l().nullable(),encryptedContent:l(),type:p(`web_search_result`)})))),ye=L({id:`anthropic.web_search_20260209`,inputSchema:B(()=>j(u({query:l()}))),outputSchema:ve,supportsDeferredResults:!0}),be=(e={})=>ye(e),xe=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),userLocation:u({type:p(`approximate`),city:l().optional(),region:l().optional(),country:l().optional(),timezone:l().optional()}).optional()}))),Se=B(()=>j(o(u({url:l(),title:l().nullable(),pageAge:l().nullable(),encryptedContent:l(),type:p(`web_search_result`)})))),Ce=L({id:`anthropic.web_search_20250305`,inputSchema:B(()=>j(u({query:l()}))),outputSchema:Se,supportsDeferredResults:!0}),we=(e={})=>Ce(e),Te=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),citations:u({enabled:i()}).optional(),maxContentTokens:h().optional()}))),Ee=B(()=>j(u({type:p(`web_fetch_result`),url:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),mediaType:p(`application/pdf`),data:l()}),u({type:p(`text`),mediaType:p(`text/plain`),data:l()})])}),retrievedAt:l().nullable()}))),De=L({id:`anthropic.web_fetch_20260209`,inputSchema:B(()=>j(u({url:l()}))),outputSchema:Ee,supportsDeferredResults:!0}),Oe=(e={})=>De(e),ke=B(()=>j(u({maxUses:h().optional(),allowedDomains:o(l()).optional(),blockedDomains:o(l()).optional(),citations:u({enabled:i()}).optional(),maxContentTokens:h().optional()}))),Ae=B(()=>j(u({type:p(`web_fetch_result`),url:l(),content:u({type:p(`document`),title:l().nullable(),citations:u({enabled:i()}).optional(),source:d([u({type:p(`base64`),mediaType:p(`application/pdf`),data:l()}),u({type:p(`text`),mediaType:p(`text/plain`),data:l()})])}),retrievedAt:l().nullable()}))),je=L({id:`anthropic.web_fetch_20250910`,inputSchema:B(()=>j(u({url:l()}))),outputSchema:Ae,supportsDeferredResults:!0}),Me=(e={})=>je(e);async function Ne({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:i,supportsStructuredOutput:a,supportsStrictTools:o,defaultEagerInputStreaming:s=!1}){e=e?.length?e:void 0;let c=[],l=new Set,u=i||new X;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:c,betas:l};let d=[];for(let t of e)switch(t.type){case`function`:{let e=u.getCacheControl(t.providerOptions,{type:`tool definition`,canCache:!0}),n=t.providerOptions?.anthropic,r=n?.eagerInputStreaming??s,i=n?.deferLoading,f=n?.allowedCallers;!o&&t.strict!=null&&c.push({type:`unsupported`,feature:`strict`,details:`Tool '${t.name}' has strict: ${t.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),d.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...r?{eager_input_streaming:!0}:{},...o===!0&&t.strict!=null?{strict:t.strict}:{},...i==null?{}:{defer_loading:i},...f==null?{}:{allowed_callers:f},...t.inputExamples==null?{}:{input_examples:t.inputExamples.map(e=>e.input)}}),a===!0&&l.add(`structured-outputs-2025-11-13`),(t.inputExamples!=null||f!=null)&&l.add(`advanced-tool-use-2025-11-20`);break}case`provider`:switch(t.id){case`anthropic.code_execution_20250522`:l.add(`code-execution-2025-05-22`),d.push({type:`code_execution_20250522`,name:`code_execution`,cache_control:void 0});break;case`anthropic.code_execution_20250825`:l.add(`code-execution-2025-08-25`),d.push({type:`code_execution_20250825`,name:`code_execution`});break;case`anthropic.code_execution_20260120`:d.push({type:`code_execution_20260120`,name:`code_execution`});break;case`anthropic.computer_20250124`:l.add(`computer-use-2025-01-24`),d.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`:l.add(`computer-use-2025-11-24`),d.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`:l.add(`computer-use-2024-10-22`),d.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`:l.add(`computer-use-2025-01-24`),d.push({name:`str_replace_editor`,type:`text_editor_20250124`,cache_control:void 0});break;case`anthropic.text_editor_20241022`:l.add(`computer-use-2024-10-22`),d.push({name:`str_replace_editor`,type:`text_editor_20241022`,cache_control:void 0});break;case`anthropic.text_editor_20250429`:l.add(`computer-use-2025-01-24`),d.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`,cache_control:void 0});break;case`anthropic.text_editor_20250728`:{let e=await C({value:t.args,schema:me});d.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters,cache_control:void 0});break}case`anthropic.bash_20250124`:l.add(`computer-use-2025-01-24`),d.push({name:`bash`,type:`bash_20250124`,cache_control:void 0});break;case`anthropic.bash_20241022`:l.add(`computer-use-2024-10-22`),d.push({name:`bash`,type:`bash_20241022`,cache_control:void 0});break;case`anthropic.memory_20250818`:l.add(`context-management-2025-06-27`),d.push({name:`memory`,type:`memory_20250818`});break;case`anthropic.web_fetch_20250910`:{l.add(`web-fetch-2025-09-10`);let e=await C({value:t.args,schema:ke});d.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`:{l.add(`code-execution-web-tools-2026-02-09`);let e=await C({value:t.args,schema:Te});d.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 C({value:t.args,schema:xe});d.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`:{l.add(`code-execution-web-tools-2026-02-09`);let e=await C({value:t.args,schema:_e});d.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`:d.push({type:`tool_search_tool_regex_20251119`,name:`tool_search_tool_regex`});break;case`anthropic.tool_search_bm25_20251119`:d.push({type:`tool_search_tool_bm25_20251119`,name:`tool_search_tool_bm25`});break;case`anthropic.advisor_20260301`:{l.add(`advisor-tool-2026-03-01`);let e=await C({value:t.args,schema:ue});d.push({type:`advisor_20260301`,name:`advisor`,model:e.model,...e.maxUses!==void 0&&{max_uses:e.maxUses},...e.caching!==void 0&&{caching:e.caching}});break}default:c.push({type:`unsupported`,feature:`provider-defined tool ${t.id}`});break}break;default:c.push({type:`unsupported`,feature:`tool ${t}`});break}if(t==null)return{tools:d,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:c,betas:l};let f=t.type;switch(f){case`auto`:return{tools:d,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:c,betas:l};case`required`:return{tools:d,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:c,betas:l};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:c,betas:l};case`tool`:return{tools:d,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:c,betas:l};default:throw new r({functionality:`tool choice type: ${f}`})}}function Pe({usage:e,rawUsage:t}){let n=e.cache_creation_input_tokens??0,r=e.cache_read_input_tokens??0,i,a;if(e.iterations&&e.iterations.length>0){let t=e.iterations.filter(e=>e.type===`compaction`||e.type===`message`);if(t.length>0){let e=t.reduce((e,t)=>({input:e.input+t.input_tokens,output:e.output+t.output_tokens}),{input:0,output:0});i=e.input,a=e.output}else i=e.input_tokens,a=e.output_tokens}else i=e.input_tokens,a=e.output_tokens;return{inputTokens:{total:i+n+r,noCache:i,cacheRead:r,cacheWrite:n},outputTokens:{total:a,text:void 0,reasoning:void 0},raw:t??e}}var Fe=B(()=>j(u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}))),Ie=L({id:`anthropic.code_execution_20250522`,inputSchema:B(()=>j(u({code:l()}))),outputSchema:Fe}),Le=(e={})=>Ie(e),Re=B(()=>j(a(`type`,[u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})]))),ze=L({id:`anthropic.code_execution_20250825`,inputSchema:B(()=>j(a(`type`,[u({type:p(`programmatic-tool-call`),code:l()}),u({type:p(`bash_code_execution`),command:l()}),a(`command`,[u({type:p(`text_editor_code_execution`),command:p(`view`),path:l()}),u({type:p(`text_editor_code_execution`),command:p(`create`),path:l(),file_text:l().nullish()}),u({type:p(`text_editor_code_execution`),command:p(`str_replace`),path:l(),old_str:l(),new_str:l()})])]))),outputSchema:Re,supportsDeferredResults:!0}),Be=(e={})=>ze(e),Ve=B(()=>j(a(`type`,[u({type:p(`code_execution_result`),stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`encrypted_code_execution_result`),encrypted_stdout:l(),stderr:l(),return_code:h(),content:o(u({type:p(`code_execution_output`),file_id:l()})).optional().default([])}),u({type:p(`bash_code_execution_result`),content:o(u({type:p(`bash_code_execution_output`),file_id:l()})),stdout:l(),stderr:l(),return_code:h()}),u({type:p(`bash_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_tool_result_error`),error_code:l()}),u({type:p(`text_editor_code_execution_view_result`),content:l(),file_type:l(),num_lines:h().nullable(),start_line:h().nullable(),total_lines:h().nullable()}),u({type:p(`text_editor_code_execution_create_result`),is_file_update:i()}),u({type:p(`text_editor_code_execution_str_replace_result`),lines:o(l()).nullable(),new_lines:h().nullable(),new_start:h().nullable(),old_lines:h().nullable(),old_start:h().nullable()})]))),He=L({id:`anthropic.code_execution_20260120`,inputSchema:B(()=>j(a(`type`,[u({type:p(`programmatic-tool-call`),code:l()}),u({type:p(`bash_code_execution`),command:l()}),a(`command`,[u({type:p(`text_editor_code_execution`),command:p(`view`),path:l()}),u({type:p(`text_editor_code_execution`),command:p(`create`),path:l(),file_text:l().nullish()}),u({type:p(`text_editor_code_execution`),command:p(`str_replace`),path:l(),old_str:l(),new_str:l()})])]))),outputSchema:Ve,supportsDeferredResults:!0}),Ue=(e={})=>He(e),We=B(()=>j(o(u({type:p(`tool_reference`),toolName:l()})))),Ge=L({id:`anthropic.tool_search_regex_20251119`,inputSchema:B(()=>j(u({pattern:l(),limit:h().optional()}))),outputSchema:We,supportsDeferredResults:!0}),Ke=(e={})=>Ge(e);function qe(e){return typeof e==`string`?new TextDecoder().decode(R(e)):new TextDecoder().decode(e)}async function Je({prompt:e,sendReasoning:t,warnings:n,cacheControlValidator:i,toolNameMapping:a}){let o=new Set,s=Ye(e),c=i||new X,l,u=[];async function d(e){return(await x({provider:`anthropic`,providerOptions:e,schema:Y}))?.citations?.enabled??!1}async function f(e){let t=await x({provider:`anthropic`,providerOptions:e,schema:Y});return{title:t?.title,context:t?.context}}for(let e=0;e<s.length;e++){let i=s[e],p=e===s.length-1,m=i.type;switch(m){case`system`:if(l!=null)throw new r({functionality:`Multiple system messages that are separated by user/assistant messages`});l=i.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:c.getCacheControl(t,{type:`system message`,canCache:!0})}));break;case`user`:{let e=[];for(let t of i.messages){let{role:i,content:a}=t;switch(i){case`user`:for(let n=0;n<a.length;n++){let i=a[n],s=n===a.length-1,l=c.getCacheControl(i.providerOptions,{type:`user message part`,canCache:!0})??(s?c.getCacheControl(t.providerOptions,{type:`user message`,canCache:!0}):void 0);switch(i.type){case`text`:e.push({type:`text`,text:i.text,cache_control:l});break;case`file`:switch(i.data.type){case`reference`:{let t=k({reference:i.data.reference,provider:`anthropic`});o.add(`files-api-2025-04-14`),y(i.mediaType)===`image`?e.push({type:`image`,source:{type:`file`,file_id:t},cache_control:l}):e.push({type:`document`,source:{type:`file`,file_id:t},cache_control:l});break}case`text`:{let t=await d(i.providerOptions),n=await f(i.providerOptions);e.push({type:`document`,source:{type:`text`,media_type:`text/plain`,data:i.data.text},title:n.title??i.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l});break}case`url`:case`data`:{let t=y(i.mediaType);if(t===`image`)e.push({type:`image`,source:i.data.type===`url`?{type:`url`,url:i.data.url.toString()}:{type:`base64`,media_type:v({part:i}),data:V(i.data.data)},cache_control:l});else if(t===`application`&&(i.data.type===`url`?i.mediaType===`application/pdf`:v({part:i})===`application/pdf`)){o.add(`pdfs-2024-09-25`);let t=await d(i.providerOptions),n=await f(i.providerOptions);e.push({type:`document`,source:i.data.type===`url`?{type:`url`,url:i.data.url.toString()}:{type:`base64`,media_type:`application/pdf`,data:V(i.data.data)},title:n.title??i.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(i.mediaType===`text/plain`){let t=await d(i.providerOptions),n=await f(i.providerOptions);e.push({type:`document`,source:i.data.type===`url`?{type:`url`,url:i.data.url.toString()}:{type:`text`,media_type:`text/plain`,data:qe(i.data.data)},title:n.title??i.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new r({functionality:`media type: ${i.mediaType}`});break}}break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r];if(i.type===`tool-approval-response`)continue;let s=i.output,l=`providerOptions`in s?s.providerOptions:s.type===`content`?s.value.find(e=>e.providerOptions!=null)?.providerOptions:void 0,u=r===a.length-1,d=c.getCacheControl(i.providerOptions,{type:`tool result part`,canCache:!0})??c.getCacheControl(l,{type:`tool result output`,canCache:!0})??(u?c.getCacheControl(t.providerOptions,{type:`tool result message`,canCache:!0}):void 0),f;switch(s.type){case`content`:f=s.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:{let t=y(e.mediaType);if(e.data.type===`url`)return t===`image`?{type:`image`,source:{type:`url`,url:e.data.url.toString()}}:{type:`document`,source:{type:`url`,url:e.data.url.toString()}};if(e.data.type===`data`){if(t===`image`)return{type:`image`,source:{type:`base64`,media_type:v({part:e}),data:V(e.data.data)}};if(v({part:e})===`application/pdf`)return o.add(`pdfs-2024-09-25`),{type:`document`,source:{type:`base64`,media_type:`application/pdf`,data:V(e.data.data)}};n.push({type:`other`,message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return}n.push({type:`other`,message:`unsupported tool content part type: ${e.type} with data type: ${e.data.type}`});return}case`custom`:{let t=e.providerOptions?.anthropic;if(t?.type===`tool-reference`)return{type:`tool_reference`,tool_name:t.toolName};n.push({type:`other`,message:`unsupported custom tool content part`});return}default:n.push({type:`other`,message:`unsupported tool content part type: ${e.type}`});return}}).filter(b);break;case`text`:case`error-text`:f=s.value;break;case`execution-denied`:f=s.reason??`Tool call execution denied.`;break;default:f=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:f,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:d})}break;default:throw Error(`Unsupported role: ${i}`)}}u.push({role:`user`,content:e});break}case`assistant`:{let e=[],r=new Set;for(let o=0;o<i.messages.length;o++){let s=i.messages[o],l=o===i.messages.length-1,{content:u}=s;for(let i=0;i<u.length;i++){let o=u[i],d=i===u.length-1,f=c.getCacheControl(o.providerOptions,{type:`assistant message part`,canCache:!0})??(d?c.getCacheControl(s.providerOptions,{type:`assistant message`,canCache:!0}):void 0);switch(o.type){case`text`:o.providerOptions?.anthropic?.type===`compaction`?e.push({type:`compaction`,content:o.text,cache_control:f}):e.push({type:`text`,text:p&&l&&d?o.text.trim():o.text,cache_control:f});break;case`reasoning`:if(t){let t=await x({provider:`anthropic`,providerOptions:o.providerOptions,schema:oe});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):(c.getCacheControl(o.providerOptions,{type:`redacted thinking block`,canCache:!1}),e.push({type:`redacted_thinking`,data:t.redactedData})):(c.getCacheControl(o.providerOptions,{type:`thinking block`,canCache:!1}),e.push({type:`thinking`,thinking:o.text,signature:t.signature}))}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:{if(o.providerExecuted){let t=a.toProviderToolName(o.toolName);if(o.providerOptions?.anthropic?.type===`mcp-tool-use`){r.add(o.toolCallId);let t=o.providerOptions?.anthropic?.serverName;if(t==null||typeof t!=`string`){n.push({type:`other`,message:`mcp tool use server name is required and must be a string`});break}e.push({type:`mcp_tool_use`,id:o.toolCallId,name:o.toolName,input:o.input,server_name:t,cache_control:f})}else if(t===`code_execution`&&o.input!=null&&typeof o.input==`object`&&`type`in o.input&&typeof o.input.type==`string`&&(o.input.type===`bash_code_execution`||o.input.type===`text_editor_code_execution`))e.push({type:`server_tool_use`,id:o.toolCallId,name:o.input.type,input:o.input,cache_control:f});else if(t===`code_execution`&&o.input!=null&&typeof o.input==`object`&&`type`in o.input&&o.input.type===`programmatic-tool-call`){let{type:t,...n}=o.input;e.push({type:`server_tool_use`,id:o.toolCallId,name:`code_execution`,input:n,cache_control:f})}else t===`code_execution`||t===`web_fetch`||t===`web_search`||t===`tool_search_tool_regex`||t===`tool_search_tool_bm25`?e.push({type:`server_tool_use`,id:o.toolCallId,name:t,input:o.input,cache_control:f}):t===`advisor`?e.push({type:`server_tool_use`,id:o.toolCallId,name:`advisor`,input:{},cache_control:f}):n.push({type:`other`,message:`provider executed tool call for tool ${o.toolName} is not supported`});break}let t=o.providerOptions?.anthropic,i=t?.caller?(t.caller.type===`code_execution_20250825`||t.caller.type===`code_execution_20260120`)&&t.caller.toolId?{type:t.caller.type,tool_id:t.caller.toolId}:t.caller.type===`direct`?{type:`direct`}:void 0:void 0;e.push({type:`tool_use`,id:o.toolCallId,name:o.toolName,input:o.input,...i&&{caller:i},cache_control:f});break}case`tool-result`:{let t=a.toProviderToolName(o.toolName);if(r.has(o.toolCallId)){let t=o.output;if(t.type!==`json`&&t.type!==`error-json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}e.push({type:`mcp_tool_result`,tool_use_id:o.toolCallId,is_error:t.type===`error-json`,content:t.value,cache_control:f})}else if(t===`code_execution`){let t=o.output;if(t.type===`error-text`||t.type===`error-json`){let n={};try{typeof t.value==`string`?n=JSON.parse(t.value):typeof t.value==`object`&&t.value!==null&&(n=t.value)}catch{}n.type===`code_execution_tool_result_error`?e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:`code_execution_tool_result_error`,error_code:n.errorCode??`unknown`},cache_control:f}):e.push({type:`bash_code_execution_tool_result`,tool_use_id:o.toolCallId,cache_control:f,content:{type:`bash_code_execution_tool_result_error`,error_code:n.errorCode??`unknown`}});break}if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}if(t.value==null||typeof t.value!=`object`||!(`type`in t.value)||typeof t.value.type!=`string`){n.push({type:`other`,message:`provider executed tool result output value is not a valid code execution result for tool ${o.toolName}`});break}if(t.value.type===`code_execution_result`){let n=await C({value:t.value,schema:Fe});e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:n.content??[]},cache_control:f})}else if(t.value.type===`encrypted_code_execution_result`){let n=await C({value:t.value,schema:Ve});n.type===`encrypted_code_execution_result`&&e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:n.type,encrypted_stdout:n.encrypted_stdout,stderr:n.stderr,return_code:n.return_code,content:n.content??[]},cache_control:f})}else{let n=await C({value:t.value,schema:Re});n.type===`code_execution_result`?e.push({type:`code_execution_tool_result`,tool_use_id:o.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code,content:n.content??[]},cache_control:f}):n.type===`bash_code_execution_result`||n.type===`bash_code_execution_tool_result_error`?e.push({type:`bash_code_execution_tool_result`,tool_use_id:o.toolCallId,cache_control:f,content:n}):e.push({type:`text_editor_code_execution_tool_result`,tool_use_id:o.toolCallId,cache_control:f,content:n})}break}if(t===`web_fetch`){let t=o.output;if(t.type===`error-json`){let n={};try{typeof t.value==`string`?n=JSON.parse(t.value):typeof t.value==`object`&&t.value!==null&&(n=t.value)}catch{let e=t.value?.errorCode;n={errorCode:typeof e==`string`?e:`unavailable`}}e.push({type:`web_fetch_tool_result`,tool_use_id:o.toolCallId,content:{type:`web_fetch_tool_result_error`,error_code:n.errorCode??`unavailable`},cache_control:f});break}if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=await C({value:t.value,schema:Ae});e.push({type:`web_fetch_tool_result`,tool_use_id:o.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:f});break}if(t===`web_search`){let t=o.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=await C({value:t.value,schema:Se});e.push({type:`web_search_tool_result`,tool_use_id:o.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:f});break}if(t===`tool_search_tool_regex`||t===`tool_search_tool_bm25`){let t=o.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=(await C({value:t.value,schema:We})).map(e=>({type:`tool_reference`,tool_name:e.toolName}));e.push({type:`tool_search_tool_result`,tool_use_id:o.toolCallId,content:{type:`tool_search_tool_search_result`,tool_references:r},cache_control:f});break}if(t===`advisor`){let t=o.output;if(t.type!==`json`&&t.type!==`error-json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${o.toolName} is not supported`});break}let r=await C({value:t.value,schema:de});r.type===`advisor_result`?e.push({type:`advisor_tool_result`,tool_use_id:o.toolCallId,content:{type:`advisor_result`,text:r.text},cache_control:f}):r.type===`advisor_redacted_result`?e.push({type:`advisor_tool_result`,tool_use_id:o.toolCallId,content:{type:`advisor_redacted_result`,encrypted_content:r.encryptedContent},cache_control:f}):e.push({type:`advisor_tool_result`,tool_use_id:o.toolCallId,content:{type:`advisor_tool_result_error`,error_code:r.errorCode},cache_control:f});break}n.push({type:`other`,message:`provider executed tool result for tool ${o.toolName} is not supported`});break}}}}u.push({role:`assistant`,content:e});break}default:throw Error(`content type: ${m}`)}}return{prompt:{system:l,messages:u},betas:o}}function Ye(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:throw Error(`Unsupported role: ${e}`)}}return t}function Z({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`;case`compaction`:return`other`;default:return`other`}}var Xe=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),Ze=[`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`,`minLength`,`maxLength`,`pattern`,`minItems`,`maxItems`,`uniqueItems`,`minProperties`,`maxProperties`,`not`];function Qe(e){return $(e)}function Q(e){return typeof e==`boolean`||!nt(e)?e:$(e)}function $(e){let t={},n=e;if(e.$ref!=null)return{$ref:e.$ref};if(e.$schema!=null&&(t.$schema=e.$schema),e.$id!=null&&(t.$id=e.$id),e.title!=null&&(t.title=e.title),e.description!=null&&(t.description=e.description),e.default!==void 0&&(t.default=e.default),e.const!==void 0&&(t.const=e.const),e.enum!=null&&(t.enum=e.enum),e.type!=null&&(t.type=e.type),e.anyOf==null?e.oneOf!=null&&(t.anyOf=e.oneOf.map(Q)):t.anyOf=e.anyOf.map(Q),e.allOf!=null&&(t.allOf=e.allOf.map(Q)),e.definitions!=null&&(t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([e,t])=>[e,Q(t)]))),n.$defs!=null){let e=t;e.$defs=Object.fromEntries(Object.entries(n.$defs).map(([e,t])=>[e,Q(t)]))}(e.type===`object`||e.properties!=null)&&(e.properties!=null&&(t.properties=Object.fromEntries(Object.entries(e.properties).map(([e,t])=>[e,Q(t)]))),t.additionalProperties=!1,e.required!=null&&(t.required=e.required)),e.items!=null&&(t.items=Array.isArray(e.items)?e.items.map(Q):Q(e.items)),typeof e.format==`string`&&Xe.has(e.format)&&(t.format=e.format);let r=$e(e);return r!=null&&(t.description=t.description==null?r:`${t.description}
|
|
2
2
|
${r}`),t}function $e(e){let t=Ze.flatMap(t=>{let n=e[t];return n==null||n===!1?[]:`${et(t)}: ${tt(n)}`});return typeof e.format==`string`&&!Xe.has(e.format)&&t.push(`format: ${e.format}`),t.length===0?void 0:`${t.join(`; `)}.`}function et(e){return e.replace(/[A-Z]/g,e=>` ${e.toLowerCase()}`)}function tt(e){return typeof e==`string`?e:JSON.stringify(e)}function nt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rt(e,t,n){if(e.type===`web_search_result_location`)return{type:`source`,sourceType:`url`,id:n(),url:e.url,title:e.title,providerMetadata:{anthropic:{citedText:e.cited_text,encryptedIndex:e.encrypted_index}}};if(e.type!==`page_location`&&e.type!==`char_location`)return;let r=t[e.document_index];if(r)return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}var it=class t{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??P}static[M](e){return A({modelId:e.modelId,config:e.config})}static[ee](e){return new t(e.modelId,e.config)}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get providerOptionsName(){let e=this.config.provider,t=e.indexOf(`.`);return t===-1?e:e.substring(0,t)}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,reasoning:p,providerOptions:m,stream:h}){let g=[];o!=null&&g.push({type:`unsupported`,feature:`frequencyPenalty`}),s!=null&&g.push({type:`unsupported`,feature:`presencePenalty`}),u!=null&&g.push({type:`unsupported`,feature:`seed`}),r!=null&&r>1?(g.push({type:`unsupported`,feature:`temperature`,details:`${r} exceeds anthropic maximum of 1.0. clamped to 1.0`}),r=1):r!=null&&r<0&&(g.push({type:`unsupported`,feature:`temperature`,details:`${r} is below anthropic minimum of 0. clamped to 0`}),r=0),l?.type===`json`&&(l.schema??g.push({type:`unsupported`,feature:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}));let _=this.providerOptionsName,v=await x({provider:`anthropic`,providerOptions:m,schema:se}),y=_===`anthropic`?null:await x({provider:_,providerOptions:m,schema:se}),b=y!=null,S=Object.assign({},v??{},y??{}),{maxOutputTokens:C,supportsStructuredOutput:w,supportsAdaptiveThinking:T,rejectsSamplingParameters:E,supportsXhighEffort:D,isKnownModel:A}=at(this.modelId);E&&(r!=null&&(g.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported by ${this.modelId} and will be ignored`}),r=void 0),a!=null&&(g.push({type:`unsupported`,feature:`topK`,details:`topK is not supported by ${this.modelId} and will be ignored`}),a=void 0),i!=null&&(g.push({type:`unsupported`,feature:`topP`,details:`topP is not supported by ${this.modelId} and will be ignored`}),i=void 0));let ee=A||this.modelId.startsWith(`claude-`),j=(this.config.supportsNativeStructuredOutput??!0)&&w,M=(this.config.supportsStrictTools??!0)&&w,N=S?.structuredOutputMode??`auto`,P=N===`outputFormat`||N===`auto`&&j,F=l?.type===`json`&&l.schema!=null&&!P?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,I=S?.contextManagement,L=new X,R=te({tools:d,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`,"anthropic.advisor_20260301":`advisor`}}),{prompt:z,betas:B}=await Je({prompt:t,sendReasoning:S?.sendReasoning??!0,warnings:g,cacheControlValidator:L,toolNameMapping:R});if(O(p)&&S?.effort==null){let e=st({reasoning:p,supportsAdaptiveThinking:T,supportsXhighEffort:D,maxOutputTokensForModel:C,warnings:g});e!=null&&(S.thinking??=e.thinking,e.effort!=null&&S.thinking?.type!==`disabled`&&(S.effort=e.effort))}let V=S?.thinking?.type,H=V===`enabled`||V===`adaptive`,U=V===`enabled`?S?.thinking?.budgetTokens:void 0,W=V===`adaptive`?S?.thinking?.display:void 0,G=n??C,K={model:this.modelId,max_tokens:G,temperature:r,top_k:a,top_p:i,stop_sequences:c,...H&&{thinking:{type:V,...U!=null&&{budget_tokens:U},...W!=null&&{display:W}}},...(S?.effort||S?.taskBudget||P&&l?.type===`json`&&l.schema!=null)&&{output_config:{...S?.effort&&{effort:S.effort},...S?.taskBudget&&{task_budget:{type:S.taskBudget.type,total:S.taskBudget.total,...S.taskBudget.remaining!=null&&{remaining:S.taskBudget.remaining}}},...P&&l?.type===`json`&&l.schema!=null&&{format:{type:`json_schema`,schema:Qe(l.schema)}}}},...S?.speed&&{speed:S.speed},...S?.inferenceGeo&&{inference_geo:S.inferenceGeo},...S?.cacheControl&&{cache_control:S.cacheControl},...S?.metadata?.userId!=null&&{metadata:{user_id:S.metadata.userId}},...S?.mcpServers&&S.mcpServers.length>0&&{mcp_servers:S.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}))},...S?.container&&{container:S.container.skills&&S.container.skills.length>0?{id:S.container.id,skills:S.container.skills.map(e=>({type:e.type,skill_id:e.type===`custom`?k({reference:e.providerReference,provider:`anthropic`}):e.skillId,version:e.version}))}:S.container.id},system:z.system,messages:z.messages,...I&&{context_management:{edits:I.edits.map(e=>{let t=e.type;switch(t){case`clear_tool_uses_20250919`:return{type:e.type,...e.trigger!==void 0&&{trigger:e.trigger},...e.keep!==void 0&&{keep:e.keep},...e.clearAtLeast!==void 0&&{clear_at_least:e.clearAtLeast},...e.clearToolInputs!==void 0&&{clear_tool_inputs:e.clearToolInputs},...e.excludeTools!==void 0&&{exclude_tools:e.excludeTools}};case`clear_thinking_20251015`:return{type:e.type,...e.keep!==void 0&&{keep:e.keep}};case`compact_20260112`:return{type:e.type,...e.trigger!==void 0&&{trigger:e.trigger},...e.pauseAfterCompaction!==void 0&&{pause_after_compaction:e.pauseAfterCompaction},...e.instructions!==void 0&&{instructions:e.instructions}};default:g.push({type:`other`,message:`Unknown context management strategy: ${t}`});return}}).filter(e=>e!==void 0)}}};H?(V===`enabled`&&U==null&&(g.push({type:`compatibility`,feature:`extended thinking`,details:`thinking budget is required when thinking is enabled. using default budget of 1024 tokens.`}),K.thinking={type:`enabled`,budget_tokens:1024},U=1024),K.temperature!=null&&(K.temperature=void 0,g.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(K.top_k=void 0,g.push({type:`unsupported`,feature:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(K.top_p=void 0,g.push({type:`unsupported`,feature:`topP`,details:`topP is not supported when thinking is enabled`})),K.max_tokens=G+(U??0)):ee&&i!=null&&r!=null&&(g.push({type:`unsupported`,feature:`topP`,details:`topP is not supported when temperature is set. topP is ignored.`}),K.top_p=void 0),A&&K.max_tokens>C&&(n!=null&&g.push({type:`unsupported`,feature:`maxOutputTokens`,details:`${K.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${C} max output tokens. The max output tokens have been limited to ${C}.`}),K.max_tokens=C),S?.mcpServers&&S.mcpServers.length>0&&B.add(`mcp-client-2025-04-04`),I&&(B.add(`context-management-2025-06-27`),I.edits.some(e=>e.type===`compact_20260112`)&&B.add(`compact-2026-01-12`)),S?.container&&S.container.skills&&S.container.skills.length>0&&(B.add(`code-execution-2025-08-25`),B.add(`skills-2025-10-02`),B.add(`files-api-2025-04-14`),d?.some(e=>e.type===`provider`&&(e.id===`anthropic.code_execution_20250825`||e.id===`anthropic.code_execution_20260120`))||g.push({type:`other`,message:`code execution tool is required when using skills`})),S?.taskBudget&&B.add(`task-budgets-2026-03-13`),S?.speed===`fast`&&B.add(`fast-mode-2026-02-01`);let q=h&&(S?.toolStreaming??!0),{tools:J,toolChoice:ne,toolWarnings:re,betas:ie}=await Ne(F==null?{tools:d??[],toolChoice:f,disableParallelToolUse:S?.disableParallelToolUse,cacheControlValidator:L,supportsStructuredOutput:j,supportsStrictTools:M,defaultEagerInputStreaming:q}:{tools:[...d??[],F],toolChoice:{type:`required`},disableParallelToolUse:!0,cacheControlValidator:L,supportsStructuredOutput:!1,supportsStrictTools:M,defaultEagerInputStreaming:q}),ae=L.getWarnings();return{args:{...K,tools:J,tool_choice:ne,stream:h===!0?!0:void 0},warnings:[...g,...re,...ae],betas:new Set([...B,...ie,...e,...S?.anthropicBeta??[]]),usesJsonResponseTool:F!=null,toolNameMapping:R,providerOptionsName:_,usedCustomProviderKey:b}}async getHeaders({betas:e,headers:t}){return W(this.config.headers?await q(this.config.headers):void 0,t,e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{})}async getBetasFromHeaders(e){let t=(this.config.headers?await q(this.config.headers):void 0)?.[`anthropic-beta`]??``,n=e?.[`anthropic-beta`]??``;return new Set([...t.toLowerCase().split(`,`),...n.toLowerCase().split(`,`)].map(e=>e.trim()).filter(e=>e!==``))}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e,t){var n;return(n=this.config).transformRequestBody?.call(n,e,t)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i,toolNameMapping:a,providerOptionsName:o,usedCustomProviderKey:s}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),c=[...this.extractCitationDocuments(e.prompt)],l=ot(t.tools),{responseHeaders:u,value:d,rawValue:f}=await D({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t,r),failedResponseHandler:J,successfulResponseHandler:I(ie),abortSignal:e.abortSignal,fetch:this.config.fetch}),p=[],m={},h={},g=!1;for(let e of d.content)switch(e.type){case`text`:if(!i&&(p.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations){let e=rt(t,c,this.generateId);e&&p.push(e)}break;case`thinking`:p.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:p.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`compaction`:p.push({type:`text`,text:e.content,providerMetadata:{anthropic:{type:`compaction`}}});break;case`tool_use`:if(i&&e.name===`json`)g=!0,p.push({type:`text`,text:JSON.stringify(e.input)});else{let t=e.caller,n=t?{type:t.type,toolId:`tool_id`in t?t.tool_id:void 0}:void 0;p.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),...n&&{providerMetadata:{anthropic:{caller:n}}}})}break;case`server_tool_use`:if(e.name===`text_editor_code_execution`||e.name===`bash_code_execution`)p.push({type:`tool-call`,toolCallId:e.id,toolName:a.toCustomToolName(`code_execution`),input:JSON.stringify({type:e.name,...e.input}),providerExecuted:!0});else if(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`){let t=e.name===`code_execution`&&e.input!=null&&typeof e.input==`object`&&`code`in e.input&&!(`type`in e.input)?{type:`programmatic-tool-call`,...e.input}:e.input;p.push({type:`tool-call`,toolCallId:e.id,toolName:a.toCustomToolName(e.name),input:JSON.stringify(t),providerExecuted:!0,...l&&e.name===`code_execution`?{dynamic:!0}:{}})}else e.name===`tool_search_tool_regex`||e.name===`tool_search_tool_bm25`?(h[e.id]=e.name,p.push({type:`tool-call`,toolCallId:e.id,toolName:a.toCustomToolName(e.name),input:JSON.stringify(e.input),providerExecuted:!0})):e.name===`advisor`&&p.push({type:`tool-call`,toolCallId:e.id,toolName:a.toCustomToolName(`advisor`),input:JSON.stringify(e.input),providerExecuted:!0});break;case`mcp_tool_use`:m[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}}},p.push(m[e.id]);break;case`mcp_tool_result`:p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:m[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:m[e.tool_use_id].providerMetadata});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?(c.push({title:e.content.content.title??e.content.url,mediaType:e.content.content.source.media_type}),p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.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}}}})):e.content.type===`web_fetch_tool_result_error`&&p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.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)){p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`web_search`),result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type}))});for(let t of e.content)p.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`web_search`),isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code}});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`code_execution`),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:e.content.content??[]}}):e.content.type===`encrypted_code_execution_result`?p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.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:e.content.content??[]}}):e.content.type===`code_execution_tool_result_error`&&p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.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`:p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`code_execution`),result:e.content});break;case`tool_search_tool_result`:{let t=h[e.tool_use_id];if(t==null){let e=a.toCustomToolName(`tool_search_tool_bm25`);a.toCustomToolName(`tool_search_tool_regex`),t=e===`tool_search_tool_bm25`?`tool_search_tool_regex`:`tool_search_tool_bm25`}e.content.type===`tool_search_tool_search_result`?p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(t),isError:!0,result:{type:`tool_search_tool_result_error`,errorCode:e.content.error_code}});break}case`advisor_tool_result`:{let t=a.toCustomToolName(`advisor`);e.content.type===`advisor_result`?p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:t,result:{type:`advisor_result`,text:e.content.text}}):e.content.type===`advisor_redacted_result`?p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:t,result:{type:`advisor_redacted_result`,encryptedContent:e.content.encrypted_content}}):p.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:t,isError:!0,result:{type:`advisor_tool_result_error`,errorCode:e.content.error_code}});break}}return{content:p,finishReason:{unified:Z({finishReason:d.stop_reason,isJsonResponseFromTool:g}),raw:d.stop_reason??void 0},usage:Pe({usage:d.usage}),request:{body:t},response:{id:d.id??void 0,modelId:d.model??void 0,headers:u,body:f},warnings:n,providerMetadata:(()=>{let e={usage:d.usage,stopSequence:d.stop_sequence??null,iterations:d.usage.iterations?d.usage.iterations.map(e=>e.type===`advisor_message`?{type:e.type,model:e.model,inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}}:{type:e.type,inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}}):null,container:d.container?{expiresAt:d.container.expires_at,id:d.container.id,skills:d.container.skills?.map(e=>({type:e.type,skillId:e.skill_id,version:e.version}))??null}:null,contextManagement:ct(d.context_management)??null},t={anthropic:e};return s&&o!==`anthropic`&&(t[o]=e),t})()}}async doStream(t){"use step";let{args:n,warnings:r,betas:i,usesJsonResponseTool:a,toolNameMapping:o,providerOptionsName:s,usedCustomProviderKey:c}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),l=[...this.extractCitationDocuments(t.prompt)],u=ot(n.tools),d=this.buildRequestUrl(!0),{responseHeaders:f,value:p}=await D({url:d,headers:await this.getHeaders({betas:i,headers:t.headers}),body:this.transformRequestBody(n,i),failedResponseHandler:J,successfulResponseHandler:G(ae),abortSignal:t.abortSignal,fetch:this.config.fetch}),m={unified:`other`,raw:void 0},h={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},g={},_={},v={},y=null,b,x=null,S=null,C=!1,w,T=this.generateId,[E,O]=p.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(e,n){if(t.includeRawChunks&&n.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){n.enqueue({type:`error`,error:e.error});return}let r=e.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block,t=e.type;switch(w=t,t){case`text`:if(a)return;g[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:g[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:g[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:e.data}}});return;case`compaction`:g[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index),providerMetadata:{anthropic:{type:`compaction`}}});return;case`tool_use`:if(a&&e.name===`json`)C=!0,g[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});else{let t=e.caller,i=t?{type:t.type,toolId:`tool_id`in t?t.tool_id:void 0}:void 0,a=e.input&&Object.keys(e.input).length>0?JSON.stringify(e.input):``;g[r.index]={type:`tool-call`,toolCallId:e.id,toolName:e.name,input:a,firstDelta:a.length===0,...i&&{caller:i}},n.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=e.name===`text_editor_code_execution`||e.name===`bash_code_execution`?`code_execution`:e.name,i=o.toCustomToolName(t),a=e.input!=null&&typeof e.input==`object`&&Object.keys(e.input).length>0?JSON.stringify(e.input):``;g[r.index]={type:`tool-call`,toolCallId:e.id,toolName:i,input:a,providerExecuted:!0,...u&&t===`code_execution`?{dynamic:!0}:{},firstDelta:!0,providerToolName:e.name},n.enqueue({type:`tool-input-start`,id:e.id,toolName:i,providerExecuted:!0,...u&&t===`code_execution`?{dynamic:!0}:{}})}else if(e.name===`tool_search_tool_regex`||e.name===`tool_search_tool_bm25`){v[e.id]=e.name;let t=o.toCustomToolName(e.name);g[r.index]={type:`tool-call`,toolCallId:e.id,toolName:t,input:``,providerExecuted:!0,firstDelta:!0,providerToolName:e.name},n.enqueue({type:`tool-input-start`,id:e.id,toolName:t,providerExecuted:!0})}else if(e.name===`advisor`){let t=o.toCustomToolName(`advisor`);g[r.index]={type:`tool-call`,toolCallId:e.id,toolName:t,input:`{}`,providerExecuted:!0,firstDelta:!0,providerToolName:e.name},n.enqueue({type:`tool-input-start`,id:e.id,toolName:t,providerExecuted:!0})}return;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?(l.push({title:e.content.content.title??e.content.url,mediaType:e.content.content.source.media_type}),n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.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}}}})):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.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)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.toCustomToolName(`web_search`),result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type}))});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:T(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.toCustomToolName(`web_search`),isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code}});return;case`code_execution_tool_result`:e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.toCustomToolName(`code_execution`),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code,content:e.content.content??[]}}):e.content.type===`encrypted_code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.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:e.content.content??[]}}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.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`:n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.toCustomToolName(`code_execution`),result:e.content});return;case`tool_search_tool_result`:{let t=v[e.tool_use_id];if(t==null){let e=o.toCustomToolName(`tool_search_tool_bm25`);o.toCustomToolName(`tool_search_tool_regex`),t=e===`tool_search_tool_bm25`?`tool_search_tool_regex`:`tool_search_tool_bm25`}e.content.type===`tool_search_tool_search_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.toCustomToolName(t),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:o.toCustomToolName(t),isError:!0,result:{type:`tool_search_tool_result_error`,errorCode:e.content.error_code}});return}case`advisor_tool_result`:{let t=o.toCustomToolName(`advisor`);e.content.type===`advisor_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:t,result:{type:`advisor_result`,text:e.content.text}}):e.content.type===`advisor_redacted_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:t,result:{type:`advisor_redacted_result`,encryptedContent:e.content.encrypted_content}}):n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:t,isError:!0,result:{type:`advisor_tool_result_error`,errorCode:e.content.error_code}});return}case`mcp_tool_use`:_[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}}},n.enqueue(_[e.id]);return;case`mcp_tool_result`:n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:_[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:_[e.tool_use_id].providerMetadata});return;default:throw Error(`Unsupported content block type: ${t}`)}}case`content_block_stop`:if(g[r.index]!=null){let e=g[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:if(!(a&&e.toolName===`json`)){n.enqueue({type:`tool-input-end`,id:e.toolCallId});let t=e.input===``?`{}`:e.input;if(e.providerToolName===`code_execution`)try{let e=JSON.parse(t);typeof e==`object`&&e&&`code`in e&&!(`type`in e)&&(t=JSON.stringify({type:`programmatic-tool-call`,...e}))}catch{}n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:t,providerExecuted:e.providerExecuted,...u&&e.providerToolName===`code_execution`?{dynamic:!0}:{},...e.caller&&{providerMetadata:{anthropic:{caller:e.caller}}}})}break}delete g[r.index]}w=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(a)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:w===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`compaction_delta`:r.delta.content!=null&&n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.content});return;case`input_json_delta`:{let e=g[r.index],t=r.delta.partial_json;if(t.length===0)return;if(C){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;e.firstDelta&&(e.providerToolName===`bash_code_execution`||e.providerToolName===`text_editor_code_execution`)&&(t=`{"type": "${e.providerToolName}",${t.substring(1)}`),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t,e.firstDelta=!1}return}case`citations_delta`:{let e=r.delta.citation,t=rt(e,l,T);t&&n.enqueue(t);return}default:throw Error(`Unsupported delta type: ${e}`)}}case`message_start`:if(h.input_tokens=r.message.usage.input_tokens,h.cache_read_input_tokens=r.message.usage.cache_read_input_tokens??0,h.cache_creation_input_tokens=r.message.usage.cache_creation_input_tokens??0,b={...r.message.usage},r.message.container!=null&&(S={expiresAt:r.message.container.expires_at,id:r.message.container.id,skills:null}),r.message.stop_reason!=null&&(m={unified:Z({finishReason:r.message.stop_reason,isJsonResponseFromTool:C}),raw:r.message.stop_reason}),n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0}),r.message.content!=null)for(let e=0;e<r.message.content.length;e++){let t=r.message.content[e];if(t.type===`tool_use`){let e=t.caller,r=e?{type:e.type,toolId:`tool_id`in e?e.tool_id:void 0}:void 0;n.enqueue({type:`tool-input-start`,id:t.id,toolName:t.name});let i=JSON.stringify(t.input??{});n.enqueue({type:`tool-input-delta`,id:t.id,delta:i}),n.enqueue({type:`tool-input-end`,id:t.id}),n.enqueue({type:`tool-call`,toolCallId:t.id,toolName:t.name,input:i,...r&&{providerMetadata:{anthropic:{caller:r}}}})}}return;case`message_delta`:r.usage.input_tokens!=null&&h.input_tokens!==r.usage.input_tokens&&(h.input_tokens=r.usage.input_tokens),h.output_tokens=r.usage.output_tokens,r.usage.cache_read_input_tokens!=null&&(h.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.cache_creation_input_tokens!=null&&(h.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.iterations!=null&&(h.iterations=r.usage.iterations),m={unified:Z({finishReason:r.delta.stop_reason,isJsonResponseFromTool:C}),raw:r.delta.stop_reason??void 0},x=r.delta.stop_sequence??null,S=r.delta.container==null?null:{expiresAt:r.delta.container.expires_at,id:r.delta.container.id,skills:r.delta.container.skills?.map(e=>({type:e.type,skillId:e.skill_id,version:e.version}))??null},r.context_management&&(y=ct(r.context_management)),b={...b,...r.usage};return;case`message_stop`:{let e={usage:b??null,stopSequence:x,iterations:h.iterations?h.iterations.map(e=>e.type===`advisor_message`?{type:e.type,model:e.model,inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}}:{type:e.type,inputTokens:e.input_tokens,outputTokens:e.output_tokens,...e.cache_creation_input_tokens?{cacheCreationInputTokens:e.cache_creation_input_tokens}:{},...e.cache_read_input_tokens?{cacheReadInputTokens:e.cache_read_input_tokens}:{}}):null,container:S,contextManagement:y},t={anthropic:e};c&&s!==`anthropic`&&(t[s]=e),n.enqueue({type:`finish`,finishReason:m,usage:Pe({usage:h,rawUsage:b}),providerMetadata:t});return}case`error`:n.enqueue({type:`error`,error:r.error});return;default:throw Error(`Unsupported chunk type: ${r}`)}}})).tee(),k=E.getReader();try{await k.read();let t=await k.read();if(t.value?.type===`raw`&&(t=await k.read()),t.value?.type===`error`){let r=t.value.error;throw new e({message:r.message,url:d,requestBodyValues:n,statusCode:r.type===`overloaded_error`?529:500,responseHeaders:f,responseBody:JSON.stringify(r),isRetryable:r.type===`overloaded_error`})}}finally{k.cancel().catch(()=>{}),k.releaseLock()}return{stream:O,request:{body:n},response:{headers:f}}}};function at(e){return e.includes(`claude-opus-4-7`)?{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!0,supportsXhighEffort:!0,isKnownModel:!0}:e.includes(`claude-sonnet-4-6`)||e.includes(`claude-opus-4-6`)?{maxOutputTokens:128e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!0,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-sonnet-4-5`)||e.includes(`claude-opus-4-5`)||e.includes(`claude-haiku-4-5`)?{maxOutputTokens:64e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-opus-4-1`)?{maxOutputTokens:32e3,supportsStructuredOutput:!0,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-sonnet-4-`)?{maxOutputTokens:64e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-opus-4-`)?{maxOutputTokens:32e3,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:e.includes(`claude-3-haiku`)?{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,supportsAdaptiveThinking:!1,rejectsSamplingParameters:!1,supportsXhighEffort:!1,isKnownModel:!1}}function ot(e){if(!e)return!1;let t=!1,n=!1;for(let r of e){if(`type`in r&&(r.type===`web_fetch_20260209`||r.type===`web_search_20260209`)){t=!0;continue}if(r.name===`code_execution`){n=!0;break}}return t&&!n}function st({reasoning:e,supportsAdaptiveThinking:t,supportsXhighEffort:n,maxOutputTokensForModel:r,warnings:i}){if(!O(e))return;if(e===`none`)return{thinking:{type:`disabled`}};if(t)return{thinking:{type:`adaptive`},effort:E({reasoning:e,effortMap:{minimal:`low`,low:`low`,medium:`medium`,high:`high`,xhigh:n?`xhigh`:`max`},warnings:i})};let a=T({reasoning:e,maxOutputTokens:r,maxReasoningBudget:r,warnings:i});if(a!=null)return{thinking:{type:`enabled`,budgetTokens:a}}}function ct(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=>e!==void 0)}:null}var lt=H({id:`anthropic.bash_20241022`,inputSchema:B(()=>j(u({command:l(),restart:i().optional()})))});function ut(e={}){let{execute:t,...n}=e;return lt(t===void 0?{...n,execute:async({command:e},{abortSignal:t,experimental_sandbox:n})=>{if(!n)throw Error(`Sandbox is not available`);return await n.runCommand({command:e,abortSignal:t})}}:{...n,...t===null?{}:{execute:t}})}var dt=H({id:`anthropic.bash_20250124`,inputSchema:B(()=>j(u({command:l(),restart:i().optional()})))});function ft(e={}){let{execute:t,...n}=e;return dt(t===void 0?{...n,execute:async({command:e},{abortSignal:t,experimental_sandbox:n})=>{if(!n)throw Error(`Sandbox is not available`);return await n.runCommand({command:e,abortSignal:t})}}:{...n,...t===null?{}:{execute:t}})}var pt=H({id:`anthropic.computer_20241022`,inputSchema:B(()=>j(u({action:g([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:o(h().int()).optional(),text:l().optional()})))}),mt=H({id:`anthropic.computer_20250124`,inputSchema:B(()=>j(u({action:g([`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:s([h().int(),h().int()]).optional(),duration:h().optional(),scroll_amount:h().optional(),scroll_direction:g([`up`,`down`,`left`,`right`]).optional(),start_coordinate:s([h().int(),h().int()]).optional(),text:l().optional()})))}),ht=H({id:`anthropic.computer_20251124`,inputSchema:B(()=>j(u({action:g([`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:s([h().int(),h().int()]).optional(),duration:h().optional(),region:s([h().int(),h().int(),h().int(),h().int()]).optional(),scroll_amount:h().optional(),scroll_direction:g([`up`,`down`,`left`,`right`]).optional(),start_coordinate:s([h().int(),h().int()]).optional(),text:l().optional()})))}),gt=H({id:`anthropic.memory_20250818`,inputSchema:B(()=>j(a(`command`,[u({command:p(`view`),path:l(),view_range:s([h(),h()]).optional()}),u({command:p(`create`),path:l(),file_text:l()}),u({command:p(`str_replace`),path:l(),old_str:l(),new_str:l()}),u({command:p(`insert`),path:l(),insert_line:h(),insert_text:l()}),u({command:p(`delete`),path:l()}),u({command:p(`rename`),old_path:l(),new_path:l()})])))}),_t=H({id:`anthropic.text_editor_20241022`,inputSchema:B(()=>j(u({command:g([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:l(),file_text:l().optional(),insert_line:h().int().optional(),new_str:l().optional(),insert_text:l().optional(),old_str:l().optional(),view_range:o(h().int()).optional()})))}),vt=H({id:`anthropic.text_editor_20250124`,inputSchema:B(()=>j(u({command:g([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:l(),file_text:l().optional(),insert_line:h().int().optional(),new_str:l().optional(),insert_text:l().optional(),old_str:l().optional(),view_range:o(h().int()).optional()})))}),yt=H({id:`anthropic.text_editor_20250429`,inputSchema:B(()=>j(u({command:g([`view`,`create`,`str_replace`,`insert`]),path:l(),file_text:l().optional(),insert_line:h().int().optional(),new_str:l().optional(),insert_text:l().optional(),old_str:l().optional(),view_range:o(h().int()).optional()})))}),bt=B(()=>j(o(u({type:p(`tool_reference`),toolName:l()})))),xt=L({id:`anthropic.tool_search_bm25_20251119`,inputSchema:B(()=>j(u({query:l(),limit:h().optional()}))),outputSchema:bt,supportsDeferredResults:!0}),St={advisor_20260301:pe,bash_20241022:ut,bash_20250124:ft,codeExecution_20250522:Le,codeExecution_20250825:Be,codeExecution_20260120:Ue,computer_20241022:pt,computer_20250124:mt,computer_20251124:ht,memory_20250818:gt,textEditor_20241022:_t,textEditor_20250124:vt,textEditor_20250429:yt,textEditor_20250728:ge,webFetch_20250910:Me,webFetch_20260209:Oe,webSearch_20250305:we,webSearch_20260209:be,toolSearchRegex_20251119:Ke,toolSearchBm25_20251119:(e={})=>xt(e)},Ct=B(()=>j(u({id:l(),display_title:l().nullish(),name:l().nullish(),description:l().nullish(),latest_version:l().nullish(),source:l(),created_at:l(),updated_at:l()})));B(()=>j(u({data:o(u({version:l()}))})));var wt=B(()=>j(u({type:l(),skill_id:l(),name:l().nullish(),description:l().nullish()}))),Tt=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async getHeaders(){return W(await q(this.config.headers),{"anthropic-beta":`skills-2025-10-02`})}async fetchVersionMetadata({skillId:e,version:t,headers:n}){let{value:r}=await K({url:`${this.config.baseURL}/skills/${e}/versions/${t}`,headers:n,failedResponseHandler:J,successfulResponseHandler:I(wt),fetch:this.config.fetch});return{...r.name==null?{}:{name:r.name},...r.description==null?{}:{description:r.description}}}async uploadSkill(e){let t=[],n=new FormData;e.displayTitle!=null&&n.append(`display_title`,e.displayTitle);for(let t of e.files){let e=N(t.data);n.append(`files[]`,new Blob([e]),t.path)}let r=await this.getHeaders(),{value:i}=await w({url:`${this.config.baseURL}/skills`,headers:r,formData:n,failedResponseHandler:J,successfulResponseHandler:I(Ct),fetch:this.config.fetch}),a=i.latest_version==null?{}:await this.fetchVersionMetadata({skillId:i.id,version:i.latest_version,headers:r}),o=a.name??i.name,s=a.description??i.description;return{providerReference:{anthropic:i.id},...i.display_title==null?{}:{displayTitle:i.display_title},...o==null?{}:{name:o},...s==null?{}:{description:s},...i.latest_version==null?{}:{latestVersion:i.latest_version},providerMetadata:{anthropic:{...i.source==null?{}:{source:i.source},...i.created_at==null?{}:{createdAt:i.created_at},...i.updated_at==null?{}:{updatedAt:i.updated_at}}},warnings:t}}},Et=`4.0.0-canary.57`;function Dt(e={}){let r=S(z({settingValue:e.baseURL,environmentVariableName:`ANTHROPIC_BASE_URL`}))??`https://api.anthropic.com/v1`,i=e.name??`anthropic.messages`;if(e.apiKey&&e.authToken)throw new t({argument:`apiKey/authToken`,message:`Both apiKey and authToken were provided. Please use only one authentication method.`});let a=()=>U({"anthropic-version":`2023-06-01`,...e.authToken?{Authorization:`Bearer ${e.authToken}`}:{"x-api-key":_({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`})},...e.headers},`ai-sdk/anthropic/${Et}`),o=t=>new it(t,{provider:i,baseURL:r,headers:a,fetch:e.fetch,generateId:e.generateId??P,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})}),s=()=>new Tt({provider:`${i.replace(`.messages`,``)}.skills`,baseURL:r,headers:a,fetch:e.fetch}),c=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return o(e)};return c.specificationVersion=`v4`,c.languageModel=o,c.chat=o,c.messages=o,c.embeddingModel=e=>{throw new n({modelId:e,modelType:`embeddingModel`})},c.textEmbeddingModel=c.embeddingModel,c.imageModel=e=>{throw new n({modelId:e,modelType:`imageModel`})},c.files=()=>new re({provider:i,baseURL:r,headers:a,fetch:e.fetch}),c.skills=s,c.tools=St,c}var Ot=Dt();function kt({steps:e}){for(let t=e.length-1;t>=0;t--){let n=e[t].providerMetadata?.anthropic?.container?.id;if(n)return{providerOptions:{anthropic:{container:{id:n}}}}}}export{Et as VERSION,Ot as anthropic,Dt as createAnthropic,kt as forwardAnthropicContainerIdFromLastStep};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-
|
|
1
|
+
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{A as p,B as m,C as h,E as g,I as _,J as v,M as y,N as b,R as x,S,T as C,V as w,W as T,X as E,Y as D,Z as O,_ as k,a as ee,b as A,c as te,d as ne,f as j,h as M,k as N,o as P,q as re,r as F,u as I,w as L,x as R,z}from"../../_chunks/workflow/dist-DZZY3Zyp.js";var ie=`4.0.0-canary.69`,B=ne({errorSchema:N(()=>D(s({error:s({code:d().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),ae=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})}),s({fileData:s({fileUri:o(),mimeType:o()})})]),oe=N(()=>D(s({outputDimensionality:d().optional(),taskType:f([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(ae).min(1).nullable()).optional()}))),se=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[O](e){return T({modelId:e.modelId,config:e.config})}static[E](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await _({provider:`google`,providerOptions:i,schema:oe});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=F(this.config.headers?await z(this.config.headers):void 0,n),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],n=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:c,value:l,rawValue:u}=await x({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:B,successfulResponseHandler:j(le),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await x({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:B,successfulResponseHandler:j(ce),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},ce=N(()=>D(s({embeddings:i(s({values:i(d())}))}))),le=N(()=>D(s({embedding:s({values:i(d())})})));function ue(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.promptTokenCount??0,n=e.candidatesTokenCount??0,r=e.cachedContentTokenCount??0,i=e.thoughtsTokenCount??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n+i,text:n,reasoning:i},raw:e}}function V(e,t=!0){if(e==null)return;if(de(e))return t?void 0:typeof e==`object`&&e.description?{type:`object`,description:e.description}:{type:`object`};if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:n,description:r,required:i,properties:a,items:o,allOf:s,anyOf:c,oneOf:l,format:u,const:d,minLength:f,enum:p}=e,m={};if(r&&(m.description=r),i&&(m.required=i),u&&(m.format=u),d!==void 0&&(m.enum=[d]),n)if(Array.isArray(n)){let e=n.includes(`null`),t=n.filter(e=>e!==`null`);t.length===0?m.type=`null`:(m.anyOf=t.map(e=>({type:e})),e&&(m.nullable=!0))}else m.type=n;if(p!==void 0&&(m.enum=p),a!=null&&(m.properties=Object.entries(a).reduce((e,[t,n])=>(e[t]=V(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>V(e,!1)):V(o,!1)),s&&(m.allOf=s.map(e=>V(e,!1))),c)if(c.some(e=>typeof e==`object`&&e?.type===`null`)){let e=c.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=V(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>V(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>V(e,!1));return l&&(m.oneOf=l.map(e=>V(e,!1))),f!==void 0&&(m.minLength=f),m}function de(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var fe=/^data:([^;,]+);base64,(.+)$/s;function pe(e){let t=fe.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function me(e){let t=pe(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function he(e,t,n,r){let i=[],a=[];for(let e of n)switch(e.type){case`text`:a.push(e.text);break;case`file`:if(e.data.type===`data`)i.push({inlineData:{mimeType:m({part:e}),data:P(e.data.data)}});else if(e.data.type===`url`){let t=me(e.data.url.toString());t==null?a.push(JSON.stringify(e)):i.push(t)}else a.push(JSON.stringify(e));break;default:a.push(JSON.stringify(e));break}e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:a.length>0?a.join(`
|
|
2
2
|
`):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function ge(e,t,n,r){for(let i of n)switch(i.type){case`text`:e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:i.text}}});break;case`file`:i.data.type===`data`&&h(i.mediaType)===`image`?e.push({inlineData:{mimeType:m({part:i}),data:P(i.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function _e(e,t){let r=[],i=[],a=!0,o=t?.isGemmaModel??!1,s=t?.providerOptionsNames??[`google`],c=!s.includes(`google`),l=t?.supportsFunctionResponseParts??!0,u=e=>{for(let t of s){let n=e.providerOptions?.[t];if(n!=null)return n}return c?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:m({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(c)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:m({part:t}),fileUri:w({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:g(t.mediaType)?t.mediaType:`text/plain`,data:P(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:m({part:t}),data:P(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{let t=u(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:P(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(c)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:w({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:g(e.mediaType)?e.mediaType:`text/plain`,data:P(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:P(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:n},thoughtSignature:r}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:r}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=u(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?l?he(e,t.toolName,o.value,t.toolCallId):ge(e,t.toolName,o.value,t.toolCallId):e.push({functionResponse:{...t.toolCallId==null?{}:{id:t.toolCallId},name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
3
3
|
|
|
4
4
|
`);i[0].parts.unshift({text:e+`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-DOVmxHH8.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-DFZoEyCn.js";import{n as ee}from"../../_chunks/workflow/compat-CIROS3w4.js";import{F as te,G as ne,H as re,O as ie,Q as g,S as _,U as ae,i as oe,n as se,q as v,y as ce}from"../../_chunks/workflow/dist-CpUQh3NH.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i}){super({name:e,message:t,cause:n}),this[ge]=!0,this.data=r,this.code=i}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,w=l({method:c(),params:a(S)}),T=l({applyDefaults:a(r())}).loose(),xe=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(T)});l({elicitation:a(T)}).loose();var Se=C.extend({protocolVersion:c(),capabilities:xe,serverInfo:be,instructions:a(c())}),E=C.extend({nextCursor:a(c())}),Ce=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),we=E.extend({tools:o(Ce)}),D=l({type:p(`text`),text:c()}).loose(),O=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Te=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),Ee=E.extend({resources:o(Te)}),k=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),A=k.extend({text:c()}),j=k.extend({blob:i()}),M=l({type:p(`resource`),resource:d([A,j])}).loose(),N=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),De=C.extend({content:o(d([D,O,M,N])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Oe=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),ke=C.extend({resourceTemplates:o(Oe)}),Ae=C.extend({contents:o(d([A,j]))}),je=l({name:c(),description:a(c()),required:a(r())}).loose(),Me=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(je))}).loose(),Ne=E.extend({prompts:o(Me)}),Pe=l({role:d([p(`user`),p(`assistant`)]),content:d([D,O,M,N])}).loose(),Fe=C.extend({description:a(c()),messages:o(Pe)}),Ie=S.extend({message:c(),requestedSchema:f()}),P=w.extend({method:p(`elicitation/create`),params:Ie}),F=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),I=`2.0`,Le=l({jsonrpc:p(I),id:d([c(),h().int()])}).merge(w).strict(),Re=l({jsonrpc:p(I),id:d([c(),h().int()]),result:C}).strict(),ze=l({jsonrpc:p(I),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),L=d([Le,l({jsonrpc:p(I)}).merge(l({method:c(),params:a(S)})).strict(),Re,ze]);async function R(e){return L.parse(await te({text:e}))}var Be=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Ve=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),z=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),He=l({resource:c().url(),authorization_servers:o(z).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),Ue=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),We=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(Ue.pick({code_challenge_methods_supported:!0})),Ge=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional()}).strip(),Ke=l({redirect_uris:o(z),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:z.optional(),policy_uri:c().optional(),jwks_uri:z.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),qe=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Je=Ke.merge(Ge),Ye=`vercel.ai.error.AI_MCPClientOAuthError`,Xe=Symbol.for(Ye),Ze,Qe,B=class extends (Qe=e,Ze=Xe,Qe){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ze]=!0}static isInstance(t){return e.hasMarker(t,Ye)}},V=class extends B{};V.errorCode=`server_error`;var H=class extends B{};H.errorCode=`invalid_client`;var U=class extends B{};U.errorCode=`invalid_grant`;var W=class extends B{};W.errorCode=`unauthorized_client`;var $e={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function et(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function G(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function tt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var K=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function nt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function rt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function it(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function at(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=nt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await rt(o,a,n);return!r?.metadataUrl&&it(s,i.pathname)&&(s=await rt(new URL(`/.well-known/${t}`,i),a,n)),s}async function ot(e,t,n=fetch){let r=await at(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return He.parse(await r.json())}function st(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function ct(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=st(e);for(let{url:e,type:n}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return Ue.parse(await i.json());{let t=We.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function lt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,G(o)),{authorizationUrl:l,codeVerifier:d}}function ut(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function dt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:ft(i,a,n);return;case`client_secret_post`:pt(i,a,r);return;case`none`:mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function ft(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function pt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function mt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=qe.parse(await te({text:n}));return new($e[e]||V)({message:t||``,cause:r})}catch(e){return new V({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ht(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?s(d,f,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,G(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return Ve.parse(await p.json())}async function gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?a(l,u,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,G(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return Ve.parse({refresh_token:r,...await d.json()})}async function _t(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Je.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function vt(e,t,n){let r=et(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!tt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;try{s=await ot(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await vt(t,e,s),u=await ct(c,{fetchFn:o}),d=await Promise.resolve(e.clientInformation());if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await _t(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),d=t}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await e.codeVerifier(),i=await ht(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(i),`AUTHORIZED`}let f=await e.tokens();if(f?.refresh_token)try{let t=await gt(c,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}let p=e.state?await e.state():void 0;p&&e.saveState&&await e.saveState(p);let{authorizationUrl:m,codeVerifier:h}=await lt(c,{metadata:u,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(m),`REDIRECT`}var yt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:a,data:o}=i;if(a===`endpoint`){if(this.endpoint=new URL(o,this.url),this.endpoint.origin!==this.url.origin)throw new b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(a===`message`)try{let e=await R(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new b({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}},bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>L.parse(e)):[L.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(a===`message`)try{let e=await R(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),i===`message`)try{let t=await R(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>c.cancel()},this.inboundReconnectAttempts=0,l()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function xt(e){switch(e.type){case`sse`:return new yt(e);case`http`:return new bt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function St(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Ct=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,wt=`ui/resourceUri`,Tt={extensions:{[Ct]:{mimeTypes:[Q]}}};function Et(e){let n=e?.ui;return t(n)?n:void 0}function Dt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Ot(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function kt(e){let t=Et(e._meta),n=t?.resourceUri??e._meta?.[wt],r=Ot(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function At(e){let t=[],n=[];for(let r of e.tools){let e=kt(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function jt({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(oe(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Dt(n._meta)}}async function Mt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return jt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Nt=`1.0.0`;function Pt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Ft(e);return await t.init(),t}var Ft=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Nt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},St(e)?this.transport=e:this.transport=xt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Se});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:De,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ae,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:ke,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Ne,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Fe,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!(r in t))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=kt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:Q}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?ce({description:a,title:e,metadata:f,inputSchema:ie({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Pt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Pt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ae({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==P)throw new b({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=P.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=F.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{F as ElicitResultSchema,P as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,K as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Tt as mcpAppClientCapabilities,Mt as readMCPAppResource,At as splitMCPAppTools};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-XWIi7wKc.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-DmgDnhW3.js";import{n as ee}from"../../_chunks/workflow/compat-DcEvieoj.js";import{F as te,G as ne,H as re,O as ie,Q as g,S as _,U as ae,i as oe,n as se,q as v,y as ce}from"../../_chunks/workflow/dist-DZZY3Zyp.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i}){super({name:e,message:t,cause:n}),this[ge]=!0,this.data=r,this.code=i}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,w=l({method:c(),params:a(S)}),T=l({applyDefaults:a(r())}).loose(),xe=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(T)});l({elicitation:a(T)}).loose();var Se=C.extend({protocolVersion:c(),capabilities:xe,serverInfo:be,instructions:a(c())}),E=C.extend({nextCursor:a(c())}),Ce=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),we=E.extend({tools:o(Ce)}),D=l({type:p(`text`),text:c()}).loose(),O=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Te=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),Ee=E.extend({resources:o(Te)}),k=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),A=k.extend({text:c()}),j=k.extend({blob:i()}),M=l({type:p(`resource`),resource:d([A,j])}).loose(),N=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),De=C.extend({content:o(d([D,O,M,N])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Oe=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),ke=C.extend({resourceTemplates:o(Oe)}),Ae=C.extend({contents:o(d([A,j]))}),je=l({name:c(),description:a(c()),required:a(r())}).loose(),Me=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(je))}).loose(),Ne=E.extend({prompts:o(Me)}),Pe=l({role:d([p(`user`),p(`assistant`)]),content:d([D,O,M,N])}).loose(),Fe=C.extend({description:a(c()),messages:o(Pe)}),Ie=S.extend({message:c(),requestedSchema:f()}),P=w.extend({method:p(`elicitation/create`),params:Ie}),F=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),I=`2.0`,Le=l({jsonrpc:p(I),id:d([c(),h().int()])}).merge(w).strict(),Re=l({jsonrpc:p(I),id:d([c(),h().int()]),result:C}).strict(),ze=l({jsonrpc:p(I),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),L=d([Le,l({jsonrpc:p(I)}).merge(l({method:c(),params:a(S)})).strict(),Re,ze]);async function R(e){return L.parse(await te({text:e}))}var Be=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,Ve=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),z=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),He=l({resource:c().url(),authorization_servers:o(z).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),Ue=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),We=l({issuer:c(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(Ue.pick({code_challenge_methods_supported:!0})),Ge=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional()}).strip(),Ke=l({redirect_uris:o(z),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:z.optional(),policy_uri:c().optional(),jwks_uri:z.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),qe=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Je=Ke.merge(Ge),Ye=`vercel.ai.error.AI_MCPClientOAuthError`,Xe=Symbol.for(Ye),Ze,Qe,B=class extends (Qe=e,Ze=Xe,Qe){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[Ze]=!0}static isInstance(t){return e.hasMarker(t,Ye)}},V=class extends B{};V.errorCode=`server_error`;var H=class extends B{};H.errorCode=`invalid_client`;var U=class extends B{};U.errorCode=`invalid_grant`;var W=class extends B{};W.errorCode=`unauthorized_client`;var $e={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function et(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function G(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function tt({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var K=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function nt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function rt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function it(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function at(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=nt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await rt(o,a,n);return!r?.metadataUrl&&it(s,i.pathname)&&(s=await rt(new URL(`/.well-known/${t}`,i),a,n)),s}async function ot(e,t,n=fetch){let r=await at(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return He.parse(await r.json())}function st(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function ct(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=st(e);for(let{url:e,type:n}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`)return Ue.parse(await i.json());{let t=We.parse(await i.json());if(!t.code_challenge_methods_supported?.includes(`S256`))throw Error(`Incompatible OIDC provider at ${e}: does not support S256 code challenge method required by MCP specification`);return t}}}}async function lt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,G(o)),{authorizationUrl:l,codeVerifier:d}}function ut(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function dt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:ft(i,a,n);return;case`client_secret_post`:pt(i,a,r);return;case`none`:mt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function ft(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function pt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function mt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=qe.parse(await te({text:n}));return new($e[e]||V)({message:t||``,cause:r})}catch(e){return new V({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function ht(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){let l=`authorization_code`,u=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(l))throw Error(`Incompatible auth server: does not support grant type ${l}`);let d=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),f=new URLSearchParams({grant_type:l,code:r,code_verifier:i,redirect_uri:String(a)});s?s(d,f,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,G(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await Y(p);return Ve.parse(await p.json())}async function gt(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){let s=`refresh_token`,c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(s))throw Error(`Incompatible auth server: does not support grant type ${s}`)}else c=new URL(`/token`,e);let l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`}),u=new URLSearchParams({grant_type:s,refresh_token:r});a?a(l,u,e,t):dt(ut(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,G(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await Y(d);return Ve.parse({refresh_token:r,...await d.json()})}async function _t(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Je.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function vt(e,t,n){let r=et(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!tt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;try{s=await ot(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await vt(t,e,s),u=await ct(c,{fetchFn:o}),d=await Promise.resolve(e.clientInformation());if(!d){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await _t(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),d=t}if(n!==void 0){if(e.storedState){let t=await e.storedState();if(t!==void 0&&t!==r)throw Error(`OAuth state parameter mismatch - possible CSRF attack`)}let t=await e.codeVerifier(),i=await ht(c,{metadata:u,clientInformation:d,authorizationCode:n,codeVerifier:t,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(i),`AUTHORIZED`}let f=await e.tokens();if(f?.refresh_token)try{let t=await gt(c,{metadata:u,clientInformation:d,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}let p=e.state?await e.state():void 0;p&&e.saveState&&await e.saveState(p);let{authorizationUrl:m,codeVerifier:h}=await lt(c,{metadata:u,clientInformation:d,state:p,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(m),`REDIRECT`}var yt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i;try{for(;;){let{done:t,value:i}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:a,data:o}=i;if(a===`endpoint`){if(this.endpoint=new URL(o,this.url),this.endpoint.origin!==this.url.origin)throw new b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(a===`message`)try{let e=await R(o);(n=this.onmessage)==null||n.call(this,e)}catch(e){let t=new b({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(r=this.onerror)==null||r.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(i=this.onerror)==null||i.call(this,e),t(e)}};this.sseConnection={close:()=>l.cancel()},u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(s=this.onerror)==null||s.call(this,e),t(e)}};n()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}},bt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return v(t,`ai-sdk/${Be}`,_())}async start(){if(this.abortController)throw new b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>L.parse(e)):[L.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(a===`message`)try{let e=await R(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new K;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),i===`message`)try{let t=await R(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>c.cancel()},this.inboundReconnectAttempts=0,l()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function xt(e){switch(e.type){case`sse`:return new yt(e);case`http`:return new bt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function St(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Ct=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,wt=`ui/resourceUri`,Tt={extensions:{[Ct]:{mimeTypes:[Q]}}};function Et(e){let n=e?.ui;return t(n)?n:void 0}function Dt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Ot(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function kt(e){let t=Et(e._meta),n=t?.resourceUri??e._meta?.[wt],r=Ot(t?.visibility);if(n!==void 0){if(typeof n!=`string`||!n.startsWith(`ui://`))throw Error(`Invalid MCP App resource URI: ${JSON.stringify(n)}`)}else if(t==null)return;return{...t,...n==null?{}:{resourceUri:n},...r==null?{}:{visibility:r}}}function At(e){let t=[],n=[];for(let r of e.tools){let e=kt(r)?.visibility;(e==null||e.includes(`model`))&&t.push(r),e?.includes(`app`)===!0&&n.push(r)}return{modelVisible:{...e,tools:t},appVisible:{...e,tools:n}}}function jt({uri:e,resource:t}){let n=t.contents.find(t=>t.uri===e);if(n==null)throw Error(`MCP App resource not found in read result: ${e}`);if(n.mimeType!==`text/html;profile=mcp-app`)throw Error(`Unsupported MCP App resource MIME type: ${n.mimeType}`);let r=`text`in n&&typeof n.text==`string`?n.text:`blob`in n&&typeof n.blob==`string`?new TextDecoder().decode(oe(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Dt(n._meta)}}async function Mt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return jt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Nt=`1.0.0`;function Pt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Ft(e);return await t.init(),t}var Ft=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Nt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},St(e)?this.transport=e:this.transport=xt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Se});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:De,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Ae,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:ke,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Ne,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Fe,options:n})}catch(e){throw e}}async notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!(r in t))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=kt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:Q}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?ce({description:a,title:e,metadata:f,inputSchema:ie({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Pt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Pt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ae({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==P)throw new b({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=P.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=F.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{F as ElicitResultSchema,P as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,K as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Tt as mcpAppClientCapabilities,Mt as readMCPAppResource,At as splitMCPAppTools};
|