eve 0.27.0 → 0.27.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 +31 -0
- package/dist/src/channel/resolve-active-session.d.ts +4 -0
- package/dist/src/channel/resolve-active-session.js +1 -0
- package/dist/src/channel/routes.d.ts +11 -0
- package/dist/src/chunks/{use-eve-agent-PMY2WkAt.js → use-eve-agent-CbF0l_Fp.js} +66 -27
- package/dist/src/chunks/{use-eve-agent-AeQLLhu9.js → use-eve-agent-CgxB9WQv.js} +66 -27
- package/dist/src/cli/dev/tui/vercel-trusted-sources-policy.d.ts +1 -1
- package/dist/src/cli/dev/tui/vercel-trusted-sources.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/open-stream.d.ts +15 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +3 -2
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +32 -0
- package/dist/src/compiled/.vendor-stamp.json +16 -16
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +9 -2
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +18 -3
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +285 -24
- package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +7 -3
- package/dist/src/compiled/@vercel/oidc/index.js +28 -2
- package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +11 -0
- package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +7 -0
- package/dist/src/compiled/@vercel/sandbox/command.d.ts +8 -0
- package/dist/src/compiled/@vercel/sandbox/execution-context.d.ts +116 -0
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +3 -1
- package/dist/src/compiled/@vercel/sandbox/index.js +20 -19
- package/dist/src/compiled/@vercel/sandbox/network-policy.d.ts +13 -5
- package/dist/src/compiled/@vercel/sandbox/sandbox-user.d.ts +212 -0
- package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +133 -2
- package/dist/src/compiled/@vercel/sandbox/session.d.ts +2 -1
- package/dist/src/compiled/@vercel/sandbox/snapshot.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/create-hook.d.ts +41 -22
- package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +29 -0
- package/dist/src/compiled/@workflow/core/global.d.ts +2 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/private.d.ts +6 -17
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/replay-payload-cache.d.ts +56 -0
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +11 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +6 -4
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +4 -1
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +39 -0
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/serialization.d.ts +44 -4
- package/dist/src/compiled/@workflow/core/symbols.d.ts +13 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
- package/dist/src/compiled/@workflow/errors/index.d.ts +14 -0
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/events.d.ts +15 -0
- package/dist/src/compiled/@workflow/world/hooks.d.ts +2 -1
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +77 -4
- package/dist/src/compiled/@workflow/world-local/index.js +4 -4
- package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
- package/dist/src/compiled/_chunks/node/{auth-BuQkq4Gr.js → auth-l7F2PF2b.js} +2 -2
- package/dist/src/compiled/_chunks/node/{version-DD-FX9rK.js → version-CjHTLx2a.js} +1 -1
- package/dist/src/compiled/_chunks/node/virtual-loader-Cwgujv7l.js +1 -0
- package/dist/src/compiled/_chunks/workflow/attribute-changes-Dk1fP6vt.js +20 -0
- package/dist/src/compiled/_chunks/workflow/{chunk-BHKSVoKr.js → chunk-BTyA9uPd.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-B3qkUnLJ.js +3 -0
- package/dist/src/compiled/_chunks/workflow/{dist-CSfKNxQW.js → dist-BX517Nmz.js} +2 -2
- package/dist/src/compiled/_chunks/workflow/{dist-zLevmMyU.js → dist-C_VDTghO.js} +10 -10
- package/dist/src/compiled/_chunks/workflow/{dist-CttsoN4D.js → dist-CrxV2rsR.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{functions-PT9ri9Hu.js → functions-Dv8dc_-I.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-czpG5xnP.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-6zaMjFY6.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-B2u06FWc.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{src-CQuMexnO.js → src-D1EltLDA.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{token-CaY0nA5J.js → token-Cz223z3C.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/token-DWqA5-DA.js +1 -0
- package/dist/src/compiled/_chunks/workflow/token-util-B6qBs3-0.js +27 -0
- package/dist/src/compiled/_chunks/workflow/{undici-fb54XL8i.js → undici-C2ZhYnV9.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/wrapper-Cc2otuUR.js +6 -0
- package/dist/src/compiled/env-runner/index.js +1 -1
- package/dist/src/compiled/env-runner/node-worker.js +1 -1
- package/dist/src/compiled/eventsource-parser/stream/index.d.ts +16 -3
- package/dist/src/compiled/jose/index.js +1 -1
- package/dist/src/compiler/compile-from-memory.d.ts +5 -0
- package/dist/src/compiler/compile-from-memory.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/execution/deliver-payloads.d.ts +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/session-limit-continuation.d.ts +8 -0
- package/dist/src/harness/session-limit-continuation.js +1 -1
- package/dist/src/harness/session-limit-enforcement.d.ts +9 -6
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/stale-input-responses.d.ts +21 -3
- package/dist/src/harness/stale-input-responses.js +2 -2
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-cancellation.d.ts +13 -0
- package/dist/src/harness/turn-cancellation.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-evaluation-error.d.ts +2 -0
- package/dist/src/internal/authored-module-evaluation-error.js +4 -0
- package/dist/src/internal/authored-module-loader.js +2 -2
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/updateprojectblock.js +1 -0
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/updateprojectprojectsbranchmatcher.js +1 -0
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/public/channels/discord/defaults.js +1 -1
- package/dist/src/public/channels/eve.js +2 -1
- package/dist/src/public/channels/linear/api.d.ts +2 -0
- package/dist/src/public/channels/linear/api.js +3 -1
- package/dist/src/public/channels/linear/defaults.js +2 -2
- package/dist/src/public/channels/linear/hitl.d.ts +8 -13
- package/dist/src/public/channels/linear/hitl.js +3 -3
- package/dist/src/public/channels/linear/index.d.ts +1 -1
- package/dist/src/public/channels/linear/index.js +1 -1
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/slack/api.d.ts +46 -2
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/slack/attachments.d.ts +6 -5
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/slack/inbound.d.ts +31 -0
- package/dist/src/public/channels/slack/inbound.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +2 -2
- package/dist/src/public/channels/slack/interactions.d.ts +2 -1
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +118 -13
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/slack/thread.d.ts +4 -3
- package/dist/src/public/channels/slack/thread.js +1 -1
- package/dist/src/public/channels/teams/defaults.js +2 -2
- package/dist/src/public/channels/teams/index.d.ts +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +7 -2
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/defaults.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +90 -5
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/connections.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +10 -5
- package/docs/channels/slack.mdx +115 -12
- package/docs/channels/teams.mdx +10 -3
- package/docs/guides/client/streaming.mdx +15 -0
- package/docs/guides/deployment/vercel.mdx +1 -1
- package/docs/guides/frontend/overview.mdx +2 -0
- package/package.json +22 -22
- package/dist/src/compiled/@workflow/core/step-hydration-cache.d.ts +0 -148
- package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +0 -1
- package/dist/src/compiled/_chunks/workflow/attribute-changes-CXiYB8h9.js +0 -20
- package/dist/src/compiled/_chunks/workflow/dist-BYo8Gno2.js +0 -3
- package/dist/src/compiled/_chunks/workflow/resume-hook-CHXbXuRZ.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-BjtAGa3_.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-BJAv0MFP.js +0 -1
- package/dist/src/compiled/_chunks/workflow/token-D4VIwGlD.js +0 -1
- package/dist/src/compiled/_chunks/workflow/wrapper-ulTvoTdW.js +0 -6
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.1/node_modules/@vercel/sdk/esm/models/updateprojectprojectsaction.js +0 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.1/node_modules/@vercel/sdk/esm/models/updateprojectprojectsoptionsallowlist.js +0 -1
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/lib/primitives.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/lib/schemas.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/models/aclaction.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/models/sdkvalidationerror.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/defaultToZeroValue.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/fp.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/primitives.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/rfcdate.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/smartUnion.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/unrecognized.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{A as n,C as r,Ct as i,Et as a,G as o,K as s,L as c,W as l,X as u,_t as d,a as f,at as p,b as m,bt as h,dt as g,et as ee,ft as _,gt as v,ht as y,lt as te,n as ne,ut as b,vt as x,wt as S,xt as C,yt as w}from"../../_chunks/workflow/dist-zLevmMyU.js";const re={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var ie;ie||={};let T;T=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ae(e){return(await T).getRandomValues(new Uint8Array(e))}async function oe(e){let t=``;for(;t.length<e;){let n=await ae(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function se(e){return await oe(e)}async function ce(e){let t=await(await T).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function le(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await se(e);return{code_verifier:t,code_challenge:await ce(t)}}var E=`2025-11-25`,ue=[E,`2025-06-18`,`2025-03-26`,`2024-11-05`],de=w(h(C(),S())),fe=v({name:C(),version:C(),title:w(C())}),D=v({_meta:w(x({}).loose())}),O=D,pe=x({method:C(),params:w(D)}),me=x({applyDefaults:w(_())}).loose(),he=v({experimental:w(x({}).loose()),logging:w(x({}).loose()),completions:w(x({}).loose()),prompts:w(v({listChanged:w(_())})),resources:w(v({subscribe:w(_()),listChanged:w(_())})),tools:w(v({listChanged:w(_())})),elicitation:w(me)});x({elicitation:w(me)}).loose();var ge=O.extend({protocolVersion:C(),capabilities:he,serverInfo:fe,instructions:w(C())}),k=O.extend({nextCursor:w(C())}),_e=x({name:C(),title:w(C()),description:w(C()),inputSchema:x({type:y(`object`),properties:w(x({}).loose())}).loose(),outputSchema:w(x({}).loose()),annotations:w(x({title:w(C())}).loose()),_meta:de}).loose(),ve=k.extend({tools:b(_e)}),ye=x({type:y(`text`),text:C()}).loose(),be=x({type:y(`image`),data:g(),mimeType:C()}).loose(),xe=x({uri:C(),name:C(),title:w(C()),description:w(C()),mimeType:w(C()),size:w(d())}).loose(),Se=k.extend({resources:b(xe)}),A=x({uri:C(),name:w(C()),title:w(C()),mimeType:w(C())}).loose(),j=A.extend({text:C()}),M=A.extend({blob:g()}),Ce=x({type:y(`resource`),resource:i([j,M])}).loose(),we=x({type:y(`resource_link`),uri:C(),name:C(),description:w(C()),mimeType:w(C())}).loose(),Te=O.extend({content:b(i([ye,be,Ce,we])),structuredContent:w(S()),isError:_().default(!1).optional()}).or(O.extend({toolResult:S()})),Ee=x({uriTemplate:C(),name:C(),title:w(C()),description:w(C()),mimeType:w(C())}).loose(),De=O.extend({resourceTemplates:b(Ee)}),Oe=O.extend({contents:b(i([j,M]))}),ke=x({type:y(`ref/prompt`),name:C()}).loose(),Ae=x({type:y(`ref/resource`),uri:C()}).loose(),je=x({name:C(),value:C()}).loose();D.extend({ref:i([ke,Ae]),argument:je,context:w(x({arguments:h(C(),C())}).loose())});var Me=O.extend({completion:x({values:b(C()).max(100),total:w(d().int()),hasMore:w(_())}).loose()}),Ne=x({name:C(),description:w(C()),required:w(_())}).loose(),Pe=x({name:C(),title:w(C()),description:w(C()),arguments:w(b(Ne))}).loose(),Fe=k.extend({prompts:b(Pe)}),Ie=x({role:i([y(`user`),y(`assistant`)]),content:i([ye,be,Ce,we])}).loose(),Le=O.extend({description:w(C()),messages:b(Ie)}),Re=D.extend({message:C(),requestedSchema:S()}),N=pe.extend({method:y(`elicitation/create`),params:Re}),ze=O.extend({action:i([y(`accept`),y(`decline`),y(`cancel`)]),content:w(h(C(),S()))}),P=`2.0`,Be=x({jsonrpc:y(P),id:i([C(),d().int()])}).merge(pe).strict(),Ve=x({jsonrpc:y(P),id:i([C(),d().int()]),result:O}).strict(),He=x({jsonrpc:y(P),id:i([C(),d().int()]),error:x({code:d().int(),message:C(),data:w(S())})}).strict(),Ue=i([Be,x({jsonrpc:y(P)}).merge(x({method:C(),params:w(D)})).strict(),Ve,He]);function F(e){return Ue.parse(e)}async function I(e){return F(await c({text:e}))}var We=`vercel.ai.error.AI_MCPClientError`,Ge=Symbol.for(We),Ke,L,R=class extends (L=e,Ke=Ge,L){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ke]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,We)}},qe=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,z=C().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:re.custom,message:`URL must be parseable`,fatal:!0}),a}).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`}),Je=x({access_token:C(),id_token:C().optional(),token_type:C(),expires_in:d().optional(),scope:C().optional(),refresh_token:C().optional(),authorization_server:z.optional(),token_endpoint:z.optional()}).strip(),Ye=v({resource:C().url(),authorization_servers:b(z).optional(),jwks_uri:C().url().optional(),scopes_supported:b(C()).optional(),bearer_methods_supported:b(C()).optional(),resource_signing_alg_values_supported:b(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:_().optional(),authorization_details_types_supported:b(C()).optional(),dpop_signing_alg_values_supported:b(C()).optional(),dpop_bound_access_tokens_required:_().optional()}),Xe=v({issuer:C(),authorization_endpoint:z,token_endpoint:z,registration_endpoint:z.optional(),scopes_supported:b(C()).optional(),response_types_supported:b(C()),grant_types_supported:b(C()).optional(),code_challenge_methods_supported:b(C()),token_endpoint_auth_methods_supported:b(C()).optional(),token_endpoint_auth_signing_alg_values_supported:b(C()).optional()}),Ze=v({issuer:C(),authorization_endpoint:z,token_endpoint:z,userinfo_endpoint:z.optional(),jwks_uri:z,registration_endpoint:z.optional(),scopes_supported:b(C()).optional(),response_types_supported:b(C()),grant_types_supported:b(C()).optional(),subject_types_supported:b(C()),id_token_signing_alg_values_supported:b(C()),claims_supported:b(C()).optional(),token_endpoint_auth_methods_supported:b(C()).optional()}).merge(Xe.pick({code_challenge_methods_supported:!0})),Qe=x({client_id:C(),client_secret:C().optional(),client_id_issued_at:d().optional(),client_secret_expires_at:d().optional(),authorization_server:z.optional(),token_endpoint:z.optional()}).strip(),$e=x({redirect_uris:b(z),token_endpoint_auth_method:C().optional(),grant_types:b(C()).optional(),response_types:b(C()).optional(),client_name:C().optional(),client_uri:z.optional(),logo_uri:z.optional(),scope:C().optional(),contacts:b(C()).optional(),tos_uri:z.optional(),policy_uri:C().optional(),jwks_uri:z.optional(),jwks:te().optional(),software_id:C().optional(),software_version:C().optional(),software_statement:C().optional()}).strip(),et=x({error:C(),error_description:C().optional(),error_uri:C().optional()}),tt=$e.merge(Qe),nt=`vercel.ai.error.AI_MCPClientOAuthError`,rt=Symbol.for(nt),it,at,B=class extends (at=e,it=rt,at){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[it]=!0}static isInstance(t){return e.hasMarker(t,nt)}},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 ot={[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U,[W.errorCode]:W};function st(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 ct({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){return new URL(e).href}function lt(e,t){return{authorizationServerUrl:q(e),tokenEndpoint:q(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function ut(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function dt(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ft(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:q(e.authorization_server),tokenEndpoint:q(e.token_endpoint)}}async function pt({provider:e,clientInformation:t,tokens:n}){let r=ft(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:q(i.authorizationServerUrl),tokenEndpoint:q(i.tokenEndpoint)}:ft(t)}async function mt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(dt(t,n)),!0):!1}function ht(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new B({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function gt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new B({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function J(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 _t(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Y(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Y(e,void 0,n):void 0;throw r}}async function vt(e,t,n=fetch){return await Y(e,{"MCP-Protocol-Version":t},n)}function yt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function bt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??E,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=_t(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await vt(o,a,n);return!r?.metadataUrl&&yt(s,i.pathname)&&(s=await vt(new URL(`/.well-known/${t}`,i),a,n)),s}async function xt(e,t,n=fetch){let r=await bt(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 Ye.parse(await r.json())}function St(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Ct(e,t){if(e.issuer!==t)throw new B({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function wt(e,{fetchFn:t=fetch,protocolVersion:n=E}={}){let r={"MCP-Protocol-Version":n},i=St(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await Y(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`){let e=Xe.parse(await i.json());return Ct(e,a),e}else{let t=Ze.parse(await i.json());if(Ct(t,a),!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 Tt(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 le(),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 Et(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`:Ot(i,a,n);return;case`client_secret_post`:kt(i,a,r);return;case`none`:At(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ot(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 kt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function At(e,t){t.set(`client_id`,e)}async function X(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}=et.parse(await c({text:n}));return new(ot[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 jt(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?await s(d,f,e,t):Dt(Et(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 X(p);return Je.parse(await p.json())}async function Mt(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?await a(l,u,e,t):Dt(Et(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 X(d);return Je.parse({refresh_token:r,...await d.json()})}async function Nt(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 X(a);return tt.parse(await a.json())}async function Z(e,t){try{return await Q(e,t)}catch(n){if(n instanceof H||n instanceof W)return await e.invalidateCredentials?.call(e,`all`),await Q(e,t);if(n instanceof U)return await e.invalidateCredentials?.call(e,`tokens`),await Q(e,t);throw n}}async function Pt(e,t,n){let r=st(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ct({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 Q(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ht(t,a);try{s=await xt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Pt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await wt(c,{fetchFn:o}),d=lt(c,u),f=await Promise.resolve(e.clientInformation());if(!f){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`);f=dt(await Nt(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}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 pt({provider:e,clientInformation:f});if(!t)throw new B({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});gt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await jt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(ut(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await pt({provider:e,clientInformation:f,tokens:p});t?gt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Mt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(ut(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof B)||e instanceof V))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await Tt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await mt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new B({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function Ft(e){return e===void 0||e===`message`}var It=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}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??E};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return ee(t,`ai-sdk/${qe}`,r())}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=J(c);try{if(await Z(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 R({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new R({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new R({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Ft(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new R({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.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,this.endpoint=void 0,(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 R({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=J(c);try{if(await Z(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 R({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()}};function Lt(e){return e===void 0||e===`message`}var Rt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){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.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??E};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return ee(n,`ai-sdk/${qe}`,r())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new R({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});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`in e&&e.method===`initialize`,l=c?void 0:this.sessionId,u={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!c}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},d=await this.fetchFn(this.url.href,u);if(this.applySessionIdFromResponse(d),d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=J(d);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new K}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(d.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!d.ok){let e=await d.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${e}`;d.status===404&&(l?(this.expireSessionId(l),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new R({message:t,statusCode:d.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let f=d.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await d.json(),t=Array.isArray(e)?e.map(e=>F(e)):[F(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(f.includes(`text/event-stream`)){if(!d.body){let e=new R({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:d.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).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(Lt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new R({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)}})().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)});return}let m=new R({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:d.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,m),m}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 R({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=J(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`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(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new R({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).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),Lt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new R({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().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}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 zt(e){switch(e.type){case`sse`:return new It(e);case`http`:return new Rt(e);default:throw new R({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Bt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Vt=`io.modelcontextprotocol/ui`,$=`text/html;profile=mcp-app`,Ht=`ui/resourceUri`,Ut={extensions:{[Vt]:{mimeTypes:[$]}}};function Wt(e){let n=e?.ui;return t(n)?n:void 0}function Gt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Kt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function qt(e){let t=Wt(e._meta),n=t?.resourceUri??e._meta?.[Ht],r=Kt(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 Jt(e){let t=[],n=[];for(let r of e.tools){let e=qt(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 Yt({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(f(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:$,html:r,meta:Gt(n._meta)}}async function Xt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Yt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Zt=`1.0.0`,Qt=0,$t=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function en(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function tn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function nn(e){let t=en(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(R.isInstance(e)&&e.code!=null)return!1;let n=tn(e);return n!=null&&$t.includes(n)}function rn(e){if(e==null)return Qt;if(!Number.isInteger(e))throw new R({message:`maxRetries must be an integer`});if(e<0)throw new R({message:`maxRetries must be >= 0`});return e}function an({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 on(e){let t=new sn(e);return await t.init(),t}var sn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Zt,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:E,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=rn(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,Bt(e)?this.transport=e:this.transport=zt(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 R({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=ge.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:E,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ge});if(e===void 0)throw new R({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!ue.includes(e.protocolVersion))throw new R({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new R({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new R({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new R({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new R({message:`Server does not support prompts`});break;default:throw new R({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new R({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=()=>{i(new R({message:`Request was aborted`,cause:a?.reason}))},l=()=>{this.responseHandlers.delete(o),a?.removeEventListener(`abort`,d)},u=e=>{l(),i(e)},d=()=>{l(),c()};this.responseHandlers.set(o,e=>{if(a?.aborted)return l(),c();if(e instanceof Error)return u(e);try{let n=t.parse(e.result);l(),r(n)}catch(e){u(new R({message:`Failed to parse server response`,cause:e}))}}),a?.addEventListener(`abort`,d,{once:!0}),this.transport.send(s).catch(e=>{u(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:ve,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():l({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:nn,createRetryError:({message:e,errors:t})=>new R({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Te,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Se,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Oe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:De,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,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:Le,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Me,options: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 r={};for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let d=this,f=t===`automatic`?void 0:t[i]?.outputSchema,p=qt({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...p?.resourceUri==null?{}:{app:{...p,mimeType:$}}},g=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let r=await d.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return r.isError||f==null?r:d.extractStructuredContent(r,f,i)};r[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:n({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:an}):u({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...f==null?{}:{outputSchema:f},execute:g,toModelOutput:an}),_meta:l}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await s({value:e.structuredContent,schema:ne(t)});if(!r.success)throw new R({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 o({text:r.text,schema:t});if(!e.success)throw new R({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new R({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})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==N)throw new R({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}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=N.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=ze.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 R({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 R({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new R({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,$ as MCP_APP_MIME_TYPE,K as UnauthorizedError,Z as auth,on as createMCPClient,on as experimental_createMCPClient,Ut as mcpAppClientCapabilities,Xt as readMCPAppResource,Jt as splitMCPAppTools,F as validateJSONRPCMessage};
|
|
1
|
+
import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{A as n,C as r,Ct as i,Et as a,G as o,K as s,L as c,W as l,X as u,_t as d,a as f,at as p,b as m,bt as h,dt as g,et as _,ft as v,gt as y,ht as b,l as ee,lt as te,n as ne,ut as x,vt as S,wt as C,xt as w,yt as T}from"../../_chunks/workflow/dist-C_VDTghO.js";const re={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var ie;ie||={};let E;E=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ae(e){return(await E).getRandomValues(new Uint8Array(e))}async function oe(e){let t=``;for(;t.length<e;){let n=await ae(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function se(e){return await oe(e)}async function ce(e){let t=await(await E).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function le(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await se(e);return{code_verifier:t,code_challenge:await ce(t)}}var D=`2025-11-25`,ue=[D,`2025-06-18`,`2025-03-26`,`2024-11-05`],de=T(h(w(),C())),fe=y({name:w(),version:w(),title:T(w())}),O=y({_meta:T(S({}).loose())}),k=O,pe=S({method:w(),params:T(O)}),me=S({applyDefaults:T(v())}).loose(),he=y({experimental:T(S({}).loose()),logging:T(S({}).loose()),completions:T(S({}).loose()),prompts:T(y({listChanged:T(v())})),resources:T(y({subscribe:T(v()),listChanged:T(v())})),tools:T(y({listChanged:T(v())})),elicitation:T(me)});S({elicitation:T(me)}).loose();var ge=k.extend({protocolVersion:w(),capabilities:he,serverInfo:fe,instructions:T(w())}),A=k.extend({nextCursor:T(w())}),_e=S({name:w(),title:T(w()),description:T(w()),inputSchema:S({type:b(`object`),properties:T(S({}).loose())}).loose(),outputSchema:T(S({}).loose()),annotations:T(S({title:T(w())}).loose()),_meta:de}).loose(),ve=A.extend({tools:x(_e)}),ye=S({type:b(`text`),text:w()}).loose(),be=S({type:b(`image`),data:g(),mimeType:w()}).loose(),xe=S({uri:w(),name:w(),title:T(w()),description:T(w()),mimeType:T(w()),size:T(d())}).loose(),Se=A.extend({resources:x(xe)}),Ce=S({uri:w(),name:T(w()),title:T(w()),mimeType:T(w())}).loose(),we=Ce.extend({text:w()}),Te=Ce.extend({blob:g()}),Ee=S({type:b(`resource`),resource:i([we,Te])}).loose(),De=S({type:b(`resource_link`),uri:w(),name:w(),description:T(w()),mimeType:T(w())}).loose(),Oe=k.extend({content:x(i([ye,be,Ee,De])),structuredContent:T(C()),isError:v().default(!1).optional()}).or(k.extend({toolResult:C()})),ke=S({uriTemplate:w(),name:w(),title:T(w()),description:T(w()),mimeType:T(w())}).loose(),Ae=k.extend({resourceTemplates:x(ke)}),je=k.extend({contents:x(i([we,Te]))}),Me=S({type:b(`ref/prompt`),name:w()}).loose(),Ne=S({type:b(`ref/resource`),uri:w()}).loose(),Pe=S({name:w(),value:w()}).loose();O.extend({ref:i([Me,Ne]),argument:Pe,context:T(S({arguments:h(w(),w())}).loose())});var Fe=k.extend({completion:S({values:x(w()).max(100),total:T(d().int()),hasMore:T(v())}).loose()}),Ie=S({name:w(),description:T(w()),required:T(v())}).loose(),Le=S({name:w(),title:T(w()),description:T(w()),arguments:T(x(Ie))}).loose(),Re=A.extend({prompts:x(Le)}),ze=S({role:i([b(`user`),b(`assistant`)]),content:i([ye,be,Ee,De])}).loose(),Be=k.extend({description:T(w()),messages:x(ze)}),Ve=O.extend({message:w(),requestedSchema:C()}),j=pe.extend({method:b(`elicitation/create`),params:Ve}),He=k.extend({action:i([b(`accept`),b(`decline`),b(`cancel`)]),content:T(h(w(),C()))}),M=`2.0`,Ue=S({jsonrpc:b(M),id:i([w(),d().int()])}).merge(pe).strict(),We=S({jsonrpc:b(M),id:i([w(),d().int()]),result:k}).strict(),Ge=S({jsonrpc:b(M),id:i([w(),d().int()]),error:S({code:d().int(),message:w(),data:T(C())})}).strict(),Ke=i([Ue,S({jsonrpc:b(M)}).merge(S({method:w(),params:T(O)})).strict(),We,Ge]);function N(e){return Ke.parse(e)}async function P(e){return N(await c({text:e}))}var qe=`vercel.ai.error.AI_MCPClientError`,Je=Symbol.for(qe),Ye,Xe,F=class extends (Xe=e,Ye=Je,Xe){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[Ye]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,qe)}},Ze=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,I=w().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:re.custom,message:`URL must be parseable`,fatal:!0}),a}).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`}),Qe=S({access_token:w(),id_token:w().optional(),token_type:w(),expires_in:d().optional(),scope:w().optional(),refresh_token:w().optional(),authorization_server:I.optional(),token_endpoint:I.optional()}).strip(),$e=y({resource:w().url(),authorization_servers:x(I).optional(),jwks_uri:w().url().optional(),scopes_supported:x(w()).optional(),bearer_methods_supported:x(w()).optional(),resource_signing_alg_values_supported:x(w()).optional(),resource_name:w().optional(),resource_documentation:w().optional(),resource_policy_uri:w().url().optional(),resource_tos_uri:w().url().optional(),tls_client_certificate_bound_access_tokens:v().optional(),authorization_details_types_supported:x(w()).optional(),dpop_signing_alg_values_supported:x(w()).optional(),dpop_bound_access_tokens_required:v().optional()}),et=y({issuer:w(),authorization_endpoint:I,token_endpoint:I,registration_endpoint:I.optional(),scopes_supported:x(w()).optional(),response_types_supported:x(w()),grant_types_supported:x(w()).optional(),code_challenge_methods_supported:x(w()).optional(),token_endpoint_auth_methods_supported:x(w()).optional(),token_endpoint_auth_signing_alg_values_supported:x(w()).optional()}),tt=y({issuer:w(),authorization_endpoint:I,token_endpoint:I,userinfo_endpoint:I.optional(),jwks_uri:I,registration_endpoint:I.optional(),scopes_supported:x(w()).optional(),response_types_supported:x(w()),grant_types_supported:x(w()).optional(),subject_types_supported:x(w()),id_token_signing_alg_values_supported:x(w()),claims_supported:x(w()).optional(),token_endpoint_auth_methods_supported:x(w()).optional()}).merge(et.pick({code_challenge_methods_supported:!0})),nt=S({client_id:w(),client_secret:w().optional(),client_id_issued_at:d().optional(),client_secret_expires_at:d().optional(),authorization_server:I.optional(),token_endpoint:I.optional()}).strip(),rt=S({redirect_uris:x(I),token_endpoint_auth_method:w().optional(),grant_types:x(w()).optional(),response_types:x(w()).optional(),client_name:w().optional(),client_uri:I.optional(),logo_uri:I.optional(),scope:w().optional(),contacts:x(w()).optional(),tos_uri:I.optional(),policy_uri:w().optional(),jwks_uri:I.optional(),jwks:te().optional(),software_id:w().optional(),software_version:w().optional(),software_statement:w().optional()}).strip(),it=S({error:w(),error_description:w().optional(),error_uri:w().optional()}),at=rt.merge(nt),ot=`vercel.ai.error.AI_MCPClientOAuthError`,st=Symbol.for(ot),ct,lt,L=class extends (lt=e,ct=st,lt){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[ct]=!0}static isInstance(t){return e.hasMarker(t,ot)}},R=class extends L{};R.errorCode=`server_error`;var z=class extends L{};z.errorCode=`invalid_client`;var B=class extends L{};B.errorCode=`invalid_grant`;var V=class extends L{};V.errorCode=`unauthorized_client`;var ut={[R.errorCode]:R,[z.errorCode]:z,[B.errorCode]:B,[V.errorCode]:V};function dt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function H(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function ft({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 U=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function W(e){return new URL(e).href}function pt(e,t){return{authorizationServerUrl:W(e),tokenEndpoint:W(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function mt(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ht(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function G(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:W(e.authorization_server),tokenEndpoint:W(e.token_endpoint)}}async function gt({provider:e,clientInformation:t,tokens:n}){let r=G(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:W(i.authorizationServerUrl),tokenEndpoint:W(i.tokenEndpoint)}:G(t)}async function _t({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ht(t,n)),!0):!1}function vt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new L({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function yt({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new L({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function K(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 bt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function q(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?q(e,void 0,n):void 0;throw r}}async function xt(e,t,n=fetch){return await q(e,{"MCP-Protocol-Version":t},n)}function St(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function Ct(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??D,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=bt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await xt(o,a,n);return!r?.metadataUrl&&St(s,i.pathname)&&(s=await xt(new URL(`/.well-known/${t}`,i),a,n)),s}async function wt(e,t,n=fetch){let r=await Ct(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 $e.parse(await r.json())}function Tt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=t.origin,i=[];if(!n)return i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:r}),i;let a=t.pathname;a.endsWith(`/`)&&(a=a.slice(0,-1));let o=`${t.origin}${a}`;return i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:`oauth`,expectedIssuer:o}),i.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`,expectedIssuer:r}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:`oidc`,expectedIssuer:o}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:`oidc`,expectedIssuer:o}),i}function Et(e,t){if(e.issuer!==t)throw new L({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function Dt(e,{fetchFn:t=fetch,protocolVersion:n=D}={}){let r={"MCP-Protocol-Version":n},i=Tt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await q(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`){let e=et.parse(await i.json());return Et(e,a),e}else{let t=tt.parse(await i.json());if(Et(t,a),!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 Ot(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 le(),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`,H(o)),{authorizationUrl:l,codeVerifier:d}}function kt(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 At(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:jt(i,a,n);return;case`client_secret_post`:Mt(i,a,r);return;case`none`:Nt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function jt(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 Mt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Nt(e,t){t.set(`client_id`,e)}async function J(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}=it.parse(await c({text:n}));return new(ut[e]||R)({message:t||``,cause:r})}catch(e){return new R({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Pt(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?await s(d,f,e,t):At(kt(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,H(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await J(p);return Qe.parse(await p.json())}async function Ft(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?await a(l,u,e,t):At(kt(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,H(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await J(d);return Qe.parse({refresh_token:r,...await d.json()})}async function It(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 J(a);return at.parse(await a.json())}async function Y(e,t){try{return await X(e,t)}catch(n){if(n instanceof z||n instanceof V)return await e.invalidateCredentials?.call(e,`all`),await X(e,t);if(n instanceof B)return await e.invalidateCredentials?.call(e,`tokens`),await X(e,t);throw n}}async function Lt(e,t,n){let r=dt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ft({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 X(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;vt(t,a);try{s=await wt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Lt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await Dt(c,{fetchFn:o}),d=pt(c,u),f=await Promise.resolve(e.clientInformation());if(!f){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`);f=ht(await It(c,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:o}),d),await e.saveClientInformation(f)}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 gt({provider:e,clientInformation:f});if(!t)throw new L({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});yt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Pt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(mt(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await gt({provider:e,clientInformation:f,tokens:p});t?yt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Ft(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(mt(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof L)||e instanceof R))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:g}=await Ot(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await _t({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new L({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(h),`REDIRECT`}function Rt(e){return e===void 0||e===`message`}var zt=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}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??D};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ze}`,r())}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=K(c);try{if(await Y(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new U;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 F({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new F({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event:s,data:c}=o;if(s===`endpoint`){if(this.endpoint)continue;let t=new URL(c,this.url);if(t.origin!==this.url.origin)throw this.connected=!1,this.endpoint=void 0,(n=this.sseConnection)==null||n.close(),(r=this.abortController)==null||r.abort(),new F({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Rt(s))try{let e=await P(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new F({message:`MCP SSE Transport Error: Failed to parse message`,cause:e});(a=this.onerror)==null||a.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.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,this.endpoint=void 0,(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 F({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=K(c);try{if(await Y(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new U;(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 F({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()}};function Bt(e){return e===void 0||e===`message`}var Vt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){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.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??D};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return _(n,`ai-sdk/${Ze}`,r())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=Y(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:e,fetchFn:this.fetchFn}).finally(()=>{this.authPromise=void 0}),this.authPromise):Promise.resolve(`REDIRECT`)}async start(){if(this.abortController)throw new F({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.startInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});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`in e&&e.method===`initialize`,l=c?void 0:this.sessionId,u={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!c}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},d=await this.fetchFn(this.url.href,u);if(this.applySessionIdFromResponse(d),d.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=K(d);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new U}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(d.status===202){this.inboundSseConnection||this.startInboundSse();return}if(!d.ok){let e=await d.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${d.status}): ${e}`;d.status===404&&(l?(this.expireSessionId(l),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new F({message:t,statusCode:d.status,url:this.url.href,responseBody:e??void 0});throw(i=this.onerror)==null||i.call(this,n),n}if(!(`id`in e))return;let f=d.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await d.json(),t=Array.isArray(e)?e.map(e=>N(e)):[N(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(f.includes(`text/event-stream`)){if(!d.body){let e=new F({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:d.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=d.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).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(Bt(a))try{let e=await P(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new F({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)}})().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)});return}let m=new F({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:d.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,m),m}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 F({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(()=>{this.abortController?.signal.aborted||this.startInboundSse(!1,this.lastInboundEventId)},n)}startInboundSse(e=!1,t){this.openInboundSse(e,t).catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=this.sessionId,o=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(s),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=K(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new U;(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(s.status===405)return;if(!s.ok||!s.body){s.status===404&&a&&this.expireSessionId(a);let e=new F({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new p).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),Bt(i))try{let t=await P(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new F({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().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||(t=this.onerror)==null||t.call(this,e)})}},this.inboundReconnectAttempts=0,l().catch(e=>{var t;e instanceof Error&&e.name===`AbortError`||((t=this.onerror)==null||t.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection())})}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 Ht(e){switch(e.type){case`sse`:return new zt(e);case`http`:return new Vt(e);default:throw new F({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ut(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Wt=`io.modelcontextprotocol/ui`,Z=`text/html;profile=mcp-app`,Gt=`ui/resourceUri`,Kt={extensions:{[Wt]:{mimeTypes:[Z]}}};function qt(e){let n=e?.ui;return t(n)?n:void 0}var Q=x(C()).transform(e=>e.filter(e=>typeof e==`string`)).optional().catch(void 0),Jt=y({connectDomains:Q,resourceDomains:Q,frameDomains:Q}),Yt=y({prefersBorder:v().optional().catch(void 0),csp:Jt.optional().catch(void 0),permissions:h(w(),C()).optional().catch(void 0)});function Xt(e){let n=(t(e)?e:void 0)?.ui;if(!t(n))return;let r=Yt.safeParse(n);return r.success?r.data:void 0}function Zt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Qt(e){let t=qt(e._meta),n=t?.resourceUri??e._meta?.[Gt],r=Zt(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 $t(e){let t=[],n=[];for(let r of e.tools){let e=Qt(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 en({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(f(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Z,html:r,meta:Xt(n._meta)}}async function tn({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return en({uri:t,resource:await e.readResource({uri:t,options:n})})}var nn=`1.0.0`,rn=0,an=[`ConnectionRefused`,`ConnectionClosed`,`FailedToOpenSocket`,`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`];function on(e){if(typeof e==`object`&&e&&`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}function sn(e){if(typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`)return e.code}function cn(e){let t=on(e);if(t!=null)return t===408||t===409||t===429||t>=500;if(F.isInstance(e)&&e.code!=null)return!1;let n=sn(e);return n!=null&&an.includes(n)}function ln(e){if(e==null)return rn;if(!Number.isInteger(e))throw new F({message:`maxRetries must be an integer`});if(e<0)throw new F({message:`maxRetries must be >= 0`});return e}function un({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 dn(e){let t=new fn(e);return await t.init(),t}var fn=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=nn,onUncaughtError:i,maxRetries:a,capabilities:o,initialInitializeResult:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:D,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.maxRetries=ln(a),this.clientCapabilities=o??{},this.initialInitializeResult=s,Ut(e)?this.transport=e:this.transport=Ht(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 F({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=ge.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:D,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ge});if(e===void 0)throw new F({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!ue.includes(e.protocolVersion))throw new F({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`completion/complete`:if(!this.serverCapabilities.completions)throw new F({message:`Server does not support completions`});break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new F({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new F({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new F({message:`Server does not support prompts`});break;default:throw new F({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new F({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=()=>{i(new F({message:`Request was aborted`,cause:a?.reason}))},l=()=>{this.responseHandlers.delete(o),a?.removeEventListener(`abort`,d)},u=e=>{l(),i(e)},d=()=>{l(),c()};this.responseHandlers.set(o,e=>{if(a?.aborted)return l(),c();if(e instanceof Error)return u(e);try{let n=t.parse(e.result);l(),r(n)}catch(e){u(new F({message:`Failed to parse server response`,cause:e}))}}),a?.addEventListener(`abort`,d,{once:!0}),this.transport.send(s).catch(e=>{u(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:ve,options:t})}async callToolWithRetry({options:e,execute:t}){return this.maxRetries===0?t():l({maxRetries:this.maxRetries,abortSignal:e?.signal,shouldRetry:cn,createRetryError:({message:e,errors:t})=>new F({message:e,cause:t[t.length-1]})})(t)}async callTool({name:e,arguments:t={},options:n}){try{return this.callToolWithRetry({options:n,execute:()=>this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Oe,options:n})})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Se,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:je,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:Ae,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Re,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:Be,options:n})}catch(e){throw e}}async completeInternal({options:e,...t}){return this.request({request:{method:`completion/complete`,params:t},resultSchema:Fe,options: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 r={};for(let{name:i,title:a,description:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=a??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,i))continue;let d=this,f=t===`automatic`?void 0:t[i]?.outputSchema,p=Qt({_meta:l}),h={clientName:this.clientInfo.name,toolName:i,...e==null?{}:{title:e},...p?.resourceUri==null?{}:{app:{...p,mimeType:Z}}},g=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let r=await d.callTool({name:i,arguments:e,options:{signal:t?.abortSignal}});return r.isError||f==null?r:d.extractStructuredContent(r,f,i)};r[i]={...t===`automatic`?m({description:o,title:e,metadata:h,inputSchema:n({...s,properties:s.properties??{},additionalProperties:!1}),execute:g,toModelOutput:un}):u({description:o,title:e,metadata:h,inputSchema:t[i].inputSchema,...f==null?{}:{outputSchema:f},execute:g,toModelOutput:un}),_meta:l}}return r}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await s({value:e.structuredContent,schema:ne(t)});if(!r.success)throw new F({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 o({text:r.text,schema:t});if(!e.success)throw new F({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new F({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})}complete(e){return this.completeInternal(e)}onElicitationRequest(e,t){if(e!==j)throw new F({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}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=j.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=He.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 F({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 F({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new F({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},pn=new TextEncoder;function $(e){if(typeof e!=`object`||!e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map($).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${$(t[e])}`).join(`,`)}}`}function mn(e){return ee(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}async function hn(e){let t=await crypto.subtle.digest(`SHA-256`,pn.encode($({html:e.html,csp:e.meta?.csp??null,permissions:e.meta?.permissions??null})));return mn(new Uint8Array(t))}function gn(e,t){return e!==t}export{He as ElicitResultSchema,j as ElicitationRequestSchema,Z as MCP_APP_MIME_TYPE,U as UnauthorizedError,Y as auth,dn as createMCPClient,dn as experimental_createMCPClient,gn as detectMCPAppResourceDrift,hn as fingerprintMCPAppResource,Kt as mcpAppClientCapabilities,tn as readMCPAppResource,$t as splitMCPAppTools,N as validateJSONRPCMessage};
|
|
@@ -2,6 +2,7 @@ import * as _ai_sdk_provider from '#compiled/@ai-sdk/provider/index.js';
|
|
|
2
2
|
import { JSONValue, ProviderV4, LanguageModelV4, EmbeddingModelV4, ImageModelV4, TranscriptionModelV4, SpeechModelV4, Experimental_RealtimeFactoryV4, FilesV4, SkillsV4, Experimental_RealtimeModelV4, Experimental_RealtimeModelV4ClientSecretOptions, Experimental_RealtimeModelV4ClientSecretResult, Experimental_RealtimeModelV4ServerEvent, Experimental_RealtimeModelV4ClientEvent, Experimental_RealtimeModelV4SessionConfig } from '#compiled/@ai-sdk/provider/index.js';
|
|
3
3
|
import * as _ai_sdk_provider_utils from '#compiled/@ai-sdk/provider-utils/index.js';
|
|
4
4
|
import { InferSchema, FetchFunction, WebSocketConstructor } from '#compiled/@ai-sdk/provider-utils/index.js';
|
|
5
|
+
import { z } from '#compiled/zod/index.js';
|
|
5
6
|
|
|
6
7
|
type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-audio-preview-2025-06-03' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4o-mini-audio-preview' | 'gpt-4o-mini-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-16k' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-5.1' | 'gpt-5.1-2025-11-13' | 'gpt-5.1-chat-latest' | 'gpt-5.2' | 'gpt-5.2-2025-12-11' | 'gpt-5.2-chat-latest' | 'gpt-5.2-pro' | 'gpt-5.2-pro-2025-12-11' | 'gpt-5.3-chat-latest' | 'gpt-5.4' | 'gpt-5.4-2026-03-05' | 'gpt-5.4-mini' | 'gpt-5.4-mini-2026-03-17' | 'gpt-5.4-nano' | 'gpt-5.4-nano-2026-03-17' | 'gpt-5.4-pro' | 'gpt-5.4-pro-2026-03-05' | 'gpt-5.5' | 'gpt-5.5-2026-04-23' | 'gpt-5.6' | 'gpt-5.6-luna' | 'gpt-5.6-sol' | 'gpt-5.6-terra' | (string & {});
|
|
7
8
|
declare const openaiLanguageModelChatOptions: _ai_sdk_provider_utils.LazySchema<{
|
|
@@ -307,6 +308,98 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
|
307
308
|
type: "response.output_item.added";
|
|
308
309
|
output_index: number;
|
|
309
310
|
item: {
|
|
311
|
+
type: "computer_call";
|
|
312
|
+
id: string;
|
|
313
|
+
status: "completed" | "in_progress" | "incomplete";
|
|
314
|
+
call_id?: string | null | undefined;
|
|
315
|
+
action?: {
|
|
316
|
+
type: "click";
|
|
317
|
+
button: "left" | "right" | "wheel" | "back" | "forward";
|
|
318
|
+
x: number;
|
|
319
|
+
y: number;
|
|
320
|
+
keys?: string[] | null | undefined;
|
|
321
|
+
} | {
|
|
322
|
+
type: "double_click";
|
|
323
|
+
x: number;
|
|
324
|
+
y: number;
|
|
325
|
+
keys?: string[] | null | undefined;
|
|
326
|
+
} | {
|
|
327
|
+
type: "drag";
|
|
328
|
+
path: {
|
|
329
|
+
x: number;
|
|
330
|
+
y: number;
|
|
331
|
+
}[];
|
|
332
|
+
keys?: string[] | null | undefined;
|
|
333
|
+
} | {
|
|
334
|
+
type: "keypress";
|
|
335
|
+
keys: string[];
|
|
336
|
+
} | {
|
|
337
|
+
type: "move";
|
|
338
|
+
x: number;
|
|
339
|
+
y: number;
|
|
340
|
+
keys?: string[] | null | undefined;
|
|
341
|
+
} | {
|
|
342
|
+
type: "screenshot";
|
|
343
|
+
} | {
|
|
344
|
+
type: "scroll";
|
|
345
|
+
x: number;
|
|
346
|
+
y: number;
|
|
347
|
+
scroll_x: number;
|
|
348
|
+
scroll_y: number;
|
|
349
|
+
keys?: string[] | null | undefined;
|
|
350
|
+
} | {
|
|
351
|
+
type: "type";
|
|
352
|
+
text: string;
|
|
353
|
+
} | {
|
|
354
|
+
type: "wait";
|
|
355
|
+
} | null | undefined;
|
|
356
|
+
actions?: ({
|
|
357
|
+
type: "click";
|
|
358
|
+
button: "left" | "right" | "wheel" | "back" | "forward";
|
|
359
|
+
x: number;
|
|
360
|
+
y: number;
|
|
361
|
+
keys?: string[] | null | undefined;
|
|
362
|
+
} | {
|
|
363
|
+
type: "double_click";
|
|
364
|
+
x: number;
|
|
365
|
+
y: number;
|
|
366
|
+
keys?: string[] | null | undefined;
|
|
367
|
+
} | {
|
|
368
|
+
type: "drag";
|
|
369
|
+
path: {
|
|
370
|
+
x: number;
|
|
371
|
+
y: number;
|
|
372
|
+
}[];
|
|
373
|
+
keys?: string[] | null | undefined;
|
|
374
|
+
} | {
|
|
375
|
+
type: "keypress";
|
|
376
|
+
keys: string[];
|
|
377
|
+
} | {
|
|
378
|
+
type: "move";
|
|
379
|
+
x: number;
|
|
380
|
+
y: number;
|
|
381
|
+
keys?: string[] | null | undefined;
|
|
382
|
+
} | {
|
|
383
|
+
type: "screenshot";
|
|
384
|
+
} | {
|
|
385
|
+
type: "scroll";
|
|
386
|
+
x: number;
|
|
387
|
+
y: number;
|
|
388
|
+
scroll_x: number;
|
|
389
|
+
scroll_y: number;
|
|
390
|
+
keys?: string[] | null | undefined;
|
|
391
|
+
} | {
|
|
392
|
+
type: "type";
|
|
393
|
+
text: string;
|
|
394
|
+
} | {
|
|
395
|
+
type: "wait";
|
|
396
|
+
})[] | null | undefined;
|
|
397
|
+
pending_safety_checks?: {
|
|
398
|
+
id: string;
|
|
399
|
+
code?: string | null | undefined;
|
|
400
|
+
message?: string | null | undefined;
|
|
401
|
+
}[] | null | undefined;
|
|
402
|
+
} | {
|
|
310
403
|
type: "message";
|
|
311
404
|
id: string;
|
|
312
405
|
phase?: "commentary" | "final_answer" | null | undefined;
|
|
@@ -325,10 +418,6 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
|
325
418
|
type: "web_search_call";
|
|
326
419
|
id: string;
|
|
327
420
|
status: string;
|
|
328
|
-
} | {
|
|
329
|
-
type: "computer_call";
|
|
330
|
-
id: string;
|
|
331
|
-
status: string;
|
|
332
421
|
} | {
|
|
333
422
|
type: "file_search_call";
|
|
334
423
|
id: string;
|
|
@@ -428,6 +517,98 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
|
428
517
|
type: "response.output_item.done";
|
|
429
518
|
output_index: number;
|
|
430
519
|
item: {
|
|
520
|
+
type: "computer_call";
|
|
521
|
+
id: string;
|
|
522
|
+
status: "completed" | "in_progress" | "incomplete";
|
|
523
|
+
call_id?: string | null | undefined;
|
|
524
|
+
action?: {
|
|
525
|
+
type: "click";
|
|
526
|
+
button: "left" | "right" | "wheel" | "back" | "forward";
|
|
527
|
+
x: number;
|
|
528
|
+
y: number;
|
|
529
|
+
keys?: string[] | null | undefined;
|
|
530
|
+
} | {
|
|
531
|
+
type: "double_click";
|
|
532
|
+
x: number;
|
|
533
|
+
y: number;
|
|
534
|
+
keys?: string[] | null | undefined;
|
|
535
|
+
} | {
|
|
536
|
+
type: "drag";
|
|
537
|
+
path: {
|
|
538
|
+
x: number;
|
|
539
|
+
y: number;
|
|
540
|
+
}[];
|
|
541
|
+
keys?: string[] | null | undefined;
|
|
542
|
+
} | {
|
|
543
|
+
type: "keypress";
|
|
544
|
+
keys: string[];
|
|
545
|
+
} | {
|
|
546
|
+
type: "move";
|
|
547
|
+
x: number;
|
|
548
|
+
y: number;
|
|
549
|
+
keys?: string[] | null | undefined;
|
|
550
|
+
} | {
|
|
551
|
+
type: "screenshot";
|
|
552
|
+
} | {
|
|
553
|
+
type: "scroll";
|
|
554
|
+
x: number;
|
|
555
|
+
y: number;
|
|
556
|
+
scroll_x: number;
|
|
557
|
+
scroll_y: number;
|
|
558
|
+
keys?: string[] | null | undefined;
|
|
559
|
+
} | {
|
|
560
|
+
type: "type";
|
|
561
|
+
text: string;
|
|
562
|
+
} | {
|
|
563
|
+
type: "wait";
|
|
564
|
+
} | null | undefined;
|
|
565
|
+
actions?: ({
|
|
566
|
+
type: "click";
|
|
567
|
+
button: "left" | "right" | "wheel" | "back" | "forward";
|
|
568
|
+
x: number;
|
|
569
|
+
y: number;
|
|
570
|
+
keys?: string[] | null | undefined;
|
|
571
|
+
} | {
|
|
572
|
+
type: "double_click";
|
|
573
|
+
x: number;
|
|
574
|
+
y: number;
|
|
575
|
+
keys?: string[] | null | undefined;
|
|
576
|
+
} | {
|
|
577
|
+
type: "drag";
|
|
578
|
+
path: {
|
|
579
|
+
x: number;
|
|
580
|
+
y: number;
|
|
581
|
+
}[];
|
|
582
|
+
keys?: string[] | null | undefined;
|
|
583
|
+
} | {
|
|
584
|
+
type: "keypress";
|
|
585
|
+
keys: string[];
|
|
586
|
+
} | {
|
|
587
|
+
type: "move";
|
|
588
|
+
x: number;
|
|
589
|
+
y: number;
|
|
590
|
+
keys?: string[] | null | undefined;
|
|
591
|
+
} | {
|
|
592
|
+
type: "screenshot";
|
|
593
|
+
} | {
|
|
594
|
+
type: "scroll";
|
|
595
|
+
x: number;
|
|
596
|
+
y: number;
|
|
597
|
+
scroll_x: number;
|
|
598
|
+
scroll_y: number;
|
|
599
|
+
keys?: string[] | null | undefined;
|
|
600
|
+
} | {
|
|
601
|
+
type: "type";
|
|
602
|
+
text: string;
|
|
603
|
+
} | {
|
|
604
|
+
type: "wait";
|
|
605
|
+
})[] | null | undefined;
|
|
606
|
+
pending_safety_checks?: {
|
|
607
|
+
id: string;
|
|
608
|
+
code?: string | null | undefined;
|
|
609
|
+
message?: string | null | undefined;
|
|
610
|
+
}[] | null | undefined;
|
|
611
|
+
} | {
|
|
431
612
|
type: "message";
|
|
432
613
|
id: string;
|
|
433
614
|
phase?: "commentary" | "final_answer" | null | undefined;
|
|
@@ -512,10 +693,6 @@ declare const openaiResponsesChunkSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
|
512
693
|
working_directory?: string | undefined;
|
|
513
694
|
env?: Record<string, string> | undefined;
|
|
514
695
|
};
|
|
515
|
-
} | {
|
|
516
|
-
type: "computer_call";
|
|
517
|
-
id: string;
|
|
518
|
-
status: "completed";
|
|
519
696
|
} | {
|
|
520
697
|
type: "mcp_call";
|
|
521
698
|
id: string;
|
|
@@ -789,6 +966,49 @@ declare const openaiTools: {
|
|
|
789
966
|
url: string;
|
|
790
967
|
}> | null;
|
|
791
968
|
}, {}>;
|
|
969
|
+
/**
|
|
970
|
+
* The computer tool allows models to operate a browser or desktop through
|
|
971
|
+
* batched UI actions. Your application executes the actions and returns an
|
|
972
|
+
* updated screenshot.
|
|
973
|
+
*
|
|
974
|
+
* WARNING: Run computer use in an isolated environment, treat on-screen
|
|
975
|
+
* content as untrusted, and require confirmation for consequential actions.
|
|
976
|
+
*/
|
|
977
|
+
computer: (options?: Parameters<_ai_sdk_provider_utils.ProviderDefinedToolFactoryWithOutputSchema<{
|
|
978
|
+
actions: OpenAIComputerAction[];
|
|
979
|
+
pendingSafetyChecks: OpenAIComputerSafetyCheck[];
|
|
980
|
+
status: "in_progress" | "completed" | "incomplete";
|
|
981
|
+
}, {
|
|
982
|
+
output: {
|
|
983
|
+
type: "computer_screenshot";
|
|
984
|
+
imageUrl: string;
|
|
985
|
+
fileId?: string;
|
|
986
|
+
detail?: "auto" | "low" | "high" | "original";
|
|
987
|
+
} | {
|
|
988
|
+
type: "computer_screenshot";
|
|
989
|
+
fileId: string;
|
|
990
|
+
imageUrl?: string;
|
|
991
|
+
detail?: "auto" | "low" | "high" | "original";
|
|
992
|
+
};
|
|
993
|
+
acknowledgedSafetyChecks?: OpenAIComputerSafetyCheck[];
|
|
994
|
+
}, {}, {}>>[0]) => _ai_sdk_provider_utils.ProviderDefinedTool<{
|
|
995
|
+
actions: OpenAIComputerAction[];
|
|
996
|
+
pendingSafetyChecks: OpenAIComputerSafetyCheck[];
|
|
997
|
+
status: "in_progress" | "completed" | "incomplete";
|
|
998
|
+
}, {
|
|
999
|
+
output: {
|
|
1000
|
+
type: "computer_screenshot";
|
|
1001
|
+
imageUrl: string;
|
|
1002
|
+
fileId?: string;
|
|
1003
|
+
detail?: "auto" | "low" | "high" | "original";
|
|
1004
|
+
} | {
|
|
1005
|
+
type: "computer_screenshot";
|
|
1006
|
+
fileId: string;
|
|
1007
|
+
imageUrl?: string;
|
|
1008
|
+
detail?: "auto" | "low" | "high" | "original";
|
|
1009
|
+
};
|
|
1010
|
+
acknowledgedSafetyChecks?: OpenAIComputerSafetyCheck[];
|
|
1011
|
+
}, {}>;
|
|
792
1012
|
/**
|
|
793
1013
|
* File search is a tool available in the Responses API. It enables models to
|
|
794
1014
|
* retrieve information in a knowledge base of previously uploaded files through
|
|
@@ -931,21 +1151,7 @@ declare const openaiTools: {
|
|
|
931
1151
|
containerId: string;
|
|
932
1152
|
} | {
|
|
933
1153
|
type?: "local";
|
|
934
|
-
skills
|
|
935
|
-
/**
|
|
936
|
-
* Web search allows models to access up-to-date information from the internet
|
|
937
|
-
* and provide answers with sourced citations.
|
|
938
|
-
*
|
|
939
|
-
* @param searchContextSize - The search context size to use for the web search.
|
|
940
|
-
* @param userLocation - The user location to use for the web search.
|
|
941
|
-
*/
|
|
942
|
-
? /**
|
|
943
|
-
* Web search allows models to access up-to-date information from the internet
|
|
944
|
-
* and provide answers with sourced citations.
|
|
945
|
-
*
|
|
946
|
-
* @param searchContextSize - The search context size to use for the web search.
|
|
947
|
-
* @param userLocation - The user location to use for the web search.
|
|
948
|
-
*/: Array<{
|
|
1154
|
+
skills?: Array<{
|
|
949
1155
|
name: string;
|
|
950
1156
|
description: string;
|
|
951
1157
|
path: string;
|
|
@@ -1279,6 +1485,61 @@ declare const openaiFilesOptionsSchema: _ai_sdk_provider_utils.LazySchema<{
|
|
|
1279
1485
|
}>;
|
|
1280
1486
|
type OpenAIFilesOptions = InferSchema<typeof openaiFilesOptionsSchema>;
|
|
1281
1487
|
|
|
1488
|
+
declare const safetyCheckSchema: z.ZodObject<{
|
|
1489
|
+
id: z.ZodString;
|
|
1490
|
+
code: z.ZodOptional<z.ZodString>;
|
|
1491
|
+
message: z.ZodOptional<z.ZodString>;
|
|
1492
|
+
}, z.core.$strip>;
|
|
1493
|
+
declare const computerActionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
1494
|
+
type: z.ZodLiteral<"click">;
|
|
1495
|
+
button: z.ZodEnum<{
|
|
1496
|
+
left: "left";
|
|
1497
|
+
right: "right";
|
|
1498
|
+
wheel: "wheel";
|
|
1499
|
+
back: "back";
|
|
1500
|
+
forward: "forward";
|
|
1501
|
+
}>;
|
|
1502
|
+
x: z.ZodNumber;
|
|
1503
|
+
y: z.ZodNumber;
|
|
1504
|
+
keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
1505
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1506
|
+
type: z.ZodLiteral<"double_click">;
|
|
1507
|
+
x: z.ZodNumber;
|
|
1508
|
+
y: z.ZodNumber;
|
|
1509
|
+
keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
1510
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1511
|
+
type: z.ZodLiteral<"drag">;
|
|
1512
|
+
path: z.ZodArray<z.ZodObject<{
|
|
1513
|
+
x: z.ZodNumber;
|
|
1514
|
+
y: z.ZodNumber;
|
|
1515
|
+
}, z.core.$strip>>;
|
|
1516
|
+
keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
1517
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1518
|
+
type: z.ZodLiteral<"keypress">;
|
|
1519
|
+
keys: z.ZodArray<z.ZodString>;
|
|
1520
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1521
|
+
type: z.ZodLiteral<"move">;
|
|
1522
|
+
x: z.ZodNumber;
|
|
1523
|
+
y: z.ZodNumber;
|
|
1524
|
+
keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
1525
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1526
|
+
type: z.ZodLiteral<"screenshot">;
|
|
1527
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1528
|
+
type: z.ZodLiteral<"scroll">;
|
|
1529
|
+
x: z.ZodNumber;
|
|
1530
|
+
y: z.ZodNumber;
|
|
1531
|
+
scrollX: z.ZodNumber;
|
|
1532
|
+
scrollY: z.ZodNumber;
|
|
1533
|
+
keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
1534
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1535
|
+
type: z.ZodLiteral<"type">;
|
|
1536
|
+
text: z.ZodString;
|
|
1537
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
1538
|
+
type: z.ZodLiteral<"wait">;
|
|
1539
|
+
}, z.core.$strip>]>;
|
|
1540
|
+
type OpenAIComputerAction = z.infer<typeof computerActionSchema>;
|
|
1541
|
+
type OpenAIComputerSafetyCheck = z.infer<typeof safetyCheckSchema>;
|
|
1542
|
+
|
|
1282
1543
|
type OpenaiResponsesChunk = InferSchema<typeof openaiResponsesChunkSchema>;
|
|
1283
1544
|
type ResponsesOutputTextAnnotationProviderMetadata = Extract<OpenaiResponsesChunk, {
|
|
1284
1545
|
type: 'response.output_text.annotation.added';
|
|
@@ -1334,4 +1595,4 @@ type OpenaiResponsesSourceDocumentProviderMetadata = {
|
|
|
1334
1595
|
|
|
1335
1596
|
declare const VERSION: string;
|
|
1336
1597
|
|
|
1337
|
-
export { OpenAIRealtimeModel as Experimental_OpenAIRealtimeModel, type OpenAIRealtimeModelConfig as Experimental_OpenAIRealtimeModelConfig, type OpenAILanguageModelChatOptions as OpenAIChatLanguageModelOptions, type OpenAIEmbeddingModelOptions, type OpenAIFilesOptions, type OpenAIImageModelEditOptions, type OpenAIImageModelGenerationOptions, type OpenAIImageModelOptions, type OpenAILanguageModelChatOptions, type OpenAILanguageModelCompletionOptions, type OpenAILanguageModelResponsesOptions, type OpenAIProvider, type OpenAIProviderSettings, type OpenAILanguageModelResponsesOptions as OpenAIResponsesProviderOptions, type OpenAISpeechModelOptions, type OpenAITranscriptionModelOptions, type OpenaiResponsesCompactionProviderMetadata, type OpenaiResponsesProviderMetadata, type OpenaiResponsesReasoningProviderMetadata, type OpenaiResponsesSourceDocumentProviderMetadata, type OpenaiResponsesTextProviderMetadata, VERSION, createOpenAI, openai };
|
|
1598
|
+
export { OpenAIRealtimeModel as Experimental_OpenAIRealtimeModel, type OpenAIRealtimeModelConfig as Experimental_OpenAIRealtimeModelConfig, type OpenAILanguageModelChatOptions as OpenAIChatLanguageModelOptions, type OpenAIComputerAction, type OpenAIComputerSafetyCheck, type OpenAIEmbeddingModelOptions, type OpenAIFilesOptions, type OpenAIImageModelEditOptions, type OpenAIImageModelGenerationOptions, type OpenAIImageModelOptions, type OpenAILanguageModelChatOptions, type OpenAILanguageModelCompletionOptions, type OpenAILanguageModelResponsesOptions, type OpenAIProvider, type OpenAIProviderSettings, type OpenAILanguageModelResponsesOptions as OpenAIResponsesProviderOptions, type OpenAISpeechModelOptions, type OpenAITranscriptionModelOptions, type OpenaiResponsesCompactionProviderMetadata, type OpenaiResponsesProviderMetadata, type OpenaiResponsesReasoningProviderMetadata, type OpenaiResponsesSourceDocumentProviderMetadata, type OpenaiResponsesTextProviderMetadata, VERSION, createOpenAI, openai };
|