eve 0.11.3 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/dist/src/cli/banner.d.ts +0 -1
  4. package/dist/src/cli/banner.js +1 -1
  5. package/dist/src/cli/commands/init.js +1 -1
  6. package/dist/src/cli/dev/tui/agent-header.js +1 -1
  7. package/dist/src/cli/dev/tui/setup-issues.js +1 -1
  8. package/dist/src/compiled/.vendor-stamp.json +1 -1
  9. package/dist/src/compiled/@ai-sdk/anthropic/index.js +1 -1
  10. package/dist/src/compiled/@ai-sdk/google/index.js +1 -1
  11. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  12. package/dist/src/compiled/@ai-sdk/openai/index.js +1 -1
  13. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  14. package/dist/src/compiled/@workflow/core/capabilities.d.ts +3 -0
  15. package/dist/src/compiled/@workflow/core/index.js +2 -2
  16. package/dist/src/compiled/@workflow/core/private.js +1 -1
  17. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +11 -1
  18. package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +6 -0
  19. package/dist/src/compiled/@workflow/core/runtime.js +19 -19
  20. package/dist/src/compiled/@workflow/core/serialization/codec.d.ts +16 -0
  21. package/dist/src/compiled/@workflow/core/serialization/compression.d.ts +104 -0
  22. package/dist/src/compiled/@workflow/core/serialization/index.d.ts +7 -6
  23. package/dist/src/compiled/@workflow/core/serialization/types.d.ts +4 -0
  24. package/dist/src/compiled/@workflow/core/serialization-format.d.ts +15 -0
  25. package/dist/src/compiled/@workflow/core/serialization.d.ts +8 -7
  26. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +24 -0
  27. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  28. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  29. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  30. package/dist/src/compiled/_chunks/workflow/{attribute-changes-Db-CKuLh.js → attribute-changes-Bi5DLT8S.js} +11 -11
  31. package/dist/src/compiled/_chunks/workflow/chunk-BHKSVoKr.js +1 -0
  32. package/dist/src/compiled/_chunks/workflow/coerce-B-Ro4Nfe.js +1 -0
  33. package/dist/src/compiled/_chunks/workflow/{compat-CG1hDp-3.js → compat-DLpWymPP.js} +1 -1
  34. package/dist/src/compiled/_chunks/workflow/{core-5Woff_dW.js → core-CXJbIkCL.js} +1 -1
  35. package/dist/src/compiled/_chunks/workflow/{dist-DhA2lbtB.js → dist-DTchiX0N.js} +1 -1
  36. package/dist/src/compiled/_chunks/workflow/{dist-DvHFhSJM.js → dist-Dxrjttr2.js} +1 -1
  37. package/dist/src/compiled/_chunks/workflow/{dist-aOKD_2KN.js → dist-FLIfyJ4Y.js} +1 -1
  38. package/dist/src/compiled/_chunks/workflow/{functions-DuPjIvMH.js → functions-CnVBREsg.js} +1 -1
  39. package/dist/src/compiled/_chunks/workflow/resume-hook-CKTw-lb5.js +1 -0
  40. package/dist/src/compiled/_chunks/workflow/run-XM8dTRAo.js +1 -0
  41. package/dist/src/compiled/_chunks/workflow/{schemas-DWOIBELG.js → schemas-iG9Z4s4o.js} +1 -1
  42. package/dist/src/compiled/_chunks/workflow/{sleep-BG6X2Bli.js → sleep-DPjVkRY-.js} +1 -1
  43. package/dist/src/compiled/_chunks/workflow/{src-B54rYDvB.js → src-CQuMexnO.js} +1 -1
  44. package/dist/src/compiled/_chunks/workflow/{token-CcaAeZHd.js → token-Bm-WLAUB.js} +1 -1
  45. package/dist/src/compiled/_chunks/workflow/{token-nK4u-N7w.js → token-J7YP0s9a.js} +1 -1
  46. package/dist/src/compiled/_chunks/workflow/wrapper-CQmdlFyy.js +6 -0
  47. package/dist/src/compiled/jose/index.js +1 -1
  48. package/dist/src/compiled/zod/index.js +1 -1
  49. package/dist/src/compiled/zod-validation-error/index.js +1 -1
  50. package/dist/src/execution/workflow-entry.js +1 -1
  51. package/dist/src/internal/application/package.js +1 -1
  52. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  53. package/dist/src/internal/nitro/host/vercel-build-prewarm.js +1 -1
  54. package/dist/src/internal/nitro/routes/info.js +1 -1
  55. package/dist/src/setup/package-manager.d.ts +1 -1
  56. package/dist/src/setup/package-manager.js +1 -1
  57. package/dist/src/setup/scaffold/create/project.js +1 -1
  58. package/docs/agent-config.md +7 -1
  59. package/docs/channels/eve.mdx +1 -1
  60. package/docs/concepts/execution-model-and-durability.md +6 -0
  61. package/docs/getting-started.mdx +2 -2
  62. package/docs/guides/auth-and-route-protection.md +5 -1
  63. package/docs/guides/deployment.md +84 -14
  64. package/docs/guides/instrumentation.md +7 -7
  65. package/docs/reference/cli.md +1 -1
  66. package/docs/sandbox.mdx +1 -1
  67. package/docs/schedules.mdx +7 -1
  68. package/docs/tutorial/first-agent.mdx +1 -1
  69. package/package.json +3 -3
  70. package/dist/src/compiled/_chunks/workflow/chunk-DSjMdhoD.js +0 -1
  71. package/dist/src/compiled/_chunks/workflow/coerce-BTuSKQr5.js +0 -1
  72. package/dist/src/compiled/_chunks/workflow/resume-hook-Uk1RAmYo.js +0 -1
  73. package/dist/src/compiled/_chunks/workflow/run-AA-FTD_U.js +0 -1
@@ -1 +1 @@
1
- import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-5Woff_dW.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-DWOIBELG.js";import{n as ee}from"../../_chunks/workflow/compat-CG1hDp-3.js";import{$ as g,I as te,J as _,K as ne,S as v,U as re,W as ie,i as ae,k as oe,n as se,y as ce}from"../../_chunks/workflow/dist-DhA2lbtB.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,xe=l({method:c(),params:a(S)}),Se=l({applyDefaults:a(r())}).loose(),Ce=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(Se)});l({elicitation:a(Se)}).loose();var we=C.extend({protocolVersion:c(),capabilities:Ce,serverInfo:be,instructions:a(c())}),w=C.extend({nextCursor:a(c())}),Te=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),Ee=w.extend({tools:o(Te)}),De=l({type:p(`text`),text:c()}).loose(),T=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Oe=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),ke=w.extend({resources:o(Oe)}),E=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),D=E.extend({text:c()}),O=E.extend({blob:i()}),Ae=l({type:p(`resource`),resource:d([D,O])}).loose(),je=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),Me=C.extend({content:o(d([De,T,Ae,je])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Ne=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),Pe=C.extend({resourceTemplates:o(Ne)}),Fe=C.extend({contents:o(d([D,O]))}),Ie=l({name:c(),description:a(c()),required:a(r())}).loose(),Le=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(Ie))}).loose(),Re=w.extend({prompts:o(Le)}),ze=l({role:d([p(`user`),p(`assistant`)]),content:d([De,T,Ae,je])}).loose(),Be=C.extend({description:a(c()),messages:o(ze)}),Ve=S.extend({message:c(),requestedSchema:f()}),k=xe.extend({method:p(`elicitation/create`),params:Ve}),He=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),A=`2.0`,Ue=l({jsonrpc:p(A),id:d([c(),h().int()])}).merge(xe).strict(),We=l({jsonrpc:p(A),id:d([c(),h().int()]),result:C}).strict(),Ge=l({jsonrpc:p(A),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),j=d([Ue,l({jsonrpc:p(A)}).merge(l({method:c(),params:a(S)})).strict(),We,Ge]);async function M(e){return j.parse(await te({text:e}))}var Ke=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,N=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),P=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),qe=l({resource:c().url(),authorization_servers:o(N).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),F=l({issuer:c(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),Je=l({issuer:c(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(F.pick({code_challenge_methods_supported:!0})),Ye=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),Xe=l({redirect_uris:o(N),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:N.optional(),policy_uri:c().optional(),jwks_uri:N.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ze=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Qe=Xe.merge(Ye),I=`vercel.ai.error.AI_MCPClientOAuthError`,$e=Symbol.for(I),L,R,z=class extends (R=e,L=$e,R){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[L]=!0}static isInstance(t){return e.hasMarker(t,I)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var et={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function tt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function nt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function rt(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function it(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function st({provider:e,clientInformation:t,tokens:n}){let r=ot(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:ot(t)}async function ct({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(at(t,n)),!0):!1}function lt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function ut({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function dt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function ft(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function pt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function mt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=dt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ft(o,a,n);return!r?.metadataUrl&&pt(s,i.pathname)&&(s=await ft(new URL(`/.well-known/${t}`,i),a,n)),s}async function ht(e,t,n=fetch){let r=await mt(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 qe.parse(await r.json())}function gt(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 _t(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function vt(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=gt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=F.parse(await i.json());return _t(e,a),e}else{let t=Je.parse(await i.json());if(_t(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 yt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,W(o)),{authorizationUrl:l,codeVerifier:d}}function Y(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 bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:xt(i,a,n);return;case`client_secret_post`:St(i,a,r);return;case`none`:Ct(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function xt(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 St(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ct(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}=Ze.parse(await te({text:n}));return new(et[e]||B)({message:t||``,cause:r})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function wt(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):bt(Y(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await X(p);return P.parse(await p.json())}async function Tt(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):bt(Y(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await X(d);return P.parse({refresh_token:r,...await d.json()})}async function Et(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 Qe.parse(await a.json())}async function Z(e,t){try{return await Q(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Q(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Q(e,t);throw n}}async function Dt(e,t,n){let r=tt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!nt({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;lt(t,a);try{s=await ht(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Dt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await vt(c,{fetchFn:o}),d=rt(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=at(await Et(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 st({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});ut({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await wt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(it(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await st({provider:e,clientInformation:f,tokens:p});t?ut({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Tt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(it(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:ee}=await yt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await ct({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(h),`REDIRECT`}function Ot(e){return e===void 0||e===`message`}var kt=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??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ke}`,v())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event: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 b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Ot(s))try{let e=await M(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new b({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 b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function At(e){return e===void 0||e===`message`}var jt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ke}`,v())}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 b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t,statusCode:l.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 d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j.parse(e)):[j.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(At(a))try{let e=await M(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`,statusCode:l.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`,statusCode:o.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),At(i))try{let t=await M(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>c.cancel()},this.inboundReconnectAttempts=0,l()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Mt(e){switch(e.type){case`sse`:return new kt(e);case`http`:return new jt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Nt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Pt=`io.modelcontextprotocol/ui`,$=`text/html;profile=mcp-app`,Ft=`ui/resourceUri`,It={extensions:{[Pt]:{mimeTypes:[$]}}};function Lt(e){let n=e?.ui;return t(n)?n:void 0}function Rt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function zt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Bt(e){let t=Lt(e._meta),n=t?.resourceUri??e._meta?.[Ft],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 Vt(e){let t=[],n=[];for(let r of e.tools){let e=Bt(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 Ht({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(ae(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:$,html:r,meta:Rt(n._meta)}}async function Ut({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Ht({uri:t,resource:await e.readResource({uri:t,options:n})})}var Wt=`1.0.0`;function Gt({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 Kt(e){let t=new qt(e);return await t.init(),t}var qt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Wt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},Nt(e)?this.transport=e:this.transport=Mt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:we});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Ee,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Me,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:ke,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Fe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:Pe,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 notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=Bt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:$}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?ce({description:a,title:e,metadata:f,inputSchema:oe({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Gt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Gt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ie({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==k)throw new b({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=k.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 b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{He as ElicitResultSchema,k as ElicitationRequestSchema,$ as MCP_APP_MIME_TYPE,G as UnauthorizedError,Z as auth,Kt as createMCPClient,Kt as experimental_createMCPClient,It as mcpAppClientCapabilities,Ut as readMCPAppResource,Vt as splitMCPAppTools};
1
+ import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{Bi as n}from"../../_chunks/workflow/core-CXJbIkCL.js";import{At as r,Dt as i,En as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,Zn as f,dn as p,fn as m,wn as h}from"../../_chunks/workflow/schemas-iG9Z4s4o.js";import{n as ee}from"../../_chunks/workflow/compat-DLpWymPP.js";import{$ as g,I as te,J as _,K as ne,S as v,U as re,W as ie,i as ae,k as oe,n as se,y as ce}from"../../_chunks/workflow/dist-DTchiX0N.js";let y;y=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function le(e){return(await y).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await y).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var me=`vercel.ai.error.AI_MCPClientError`,he=Symbol.for(me),ge,_e,b=class extends (_e=e,ge=he,_e){constructor({name:e=`MCPClientError`,message:t,cause:n,data:r,code:i,statusCode:a,url:o,responseBody:s}){super({name:e,message:t,cause:n}),this[ge]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,me)}},x=`2025-11-25`,ve=[x,`2025-06-18`,`2025-03-26`,`2024-11-05`],ye=a(s(c(),f())),be=m({name:c(),version:c(),title:a(c())}),S=m({_meta:a(l({}).loose())}),C=S,xe=l({method:c(),params:a(S)}),Se=l({applyDefaults:a(r())}).loose(),Ce=m({experimental:a(l({}).loose()),logging:a(l({}).loose()),prompts:a(m({listChanged:a(r())})),resources:a(m({subscribe:a(r()),listChanged:a(r())})),tools:a(m({listChanged:a(r())})),elicitation:a(Se)});l({elicitation:a(Se)}).loose();var we=C.extend({protocolVersion:c(),capabilities:Ce,serverInfo:be,instructions:a(c())}),w=C.extend({nextCursor:a(c())}),Te=l({name:c(),title:a(c()),description:a(c()),inputSchema:l({type:p(`object`),properties:a(l({}).loose())}).loose(),outputSchema:a(l({}).loose()),annotations:a(l({title:a(c())}).loose()),_meta:ye}).loose(),Ee=w.extend({tools:o(Te)}),De=l({type:p(`text`),text:c()}).loose(),T=l({type:p(`image`),data:i(),mimeType:c()}).loose(),Oe=l({uri:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c()),size:a(h())}).loose(),ke=w.extend({resources:o(Oe)}),E=l({uri:c(),name:a(c()),title:a(c()),mimeType:a(c())}).loose(),D=E.extend({text:c()}),O=E.extend({blob:i()}),Ae=l({type:p(`resource`),resource:d([D,O])}).loose(),je=l({type:p(`resource_link`),uri:c(),name:c(),description:a(c()),mimeType:a(c())}).loose(),Me=C.extend({content:o(d([De,T,Ae,je])),structuredContent:a(f()),isError:r().default(!1).optional()}).or(C.extend({toolResult:f()})),Ne=l({uriTemplate:c(),name:c(),title:a(c()),description:a(c()),mimeType:a(c())}).loose(),Pe=C.extend({resourceTemplates:o(Ne)}),Fe=C.extend({contents:o(d([D,O]))}),Ie=l({name:c(),description:a(c()),required:a(r())}).loose(),Le=l({name:c(),title:a(c()),description:a(c()),arguments:a(o(Ie))}).loose(),Re=w.extend({prompts:o(Le)}),ze=l({role:d([p(`user`),p(`assistant`)]),content:d([De,T,Ae,je])}).loose(),Be=C.extend({description:a(c()),messages:o(ze)}),Ve=S.extend({message:c(),requestedSchema:f()}),k=xe.extend({method:p(`elicitation/create`),params:Ve}),He=C.extend({action:d([p(`accept`),p(`decline`),p(`cancel`)]),content:a(s(c(),f()))}),A=`2.0`,Ue=l({jsonrpc:p(A),id:d([c(),h().int()])}).merge(xe).strict(),We=l({jsonrpc:p(A),id:d([c(),h().int()]),result:C}).strict(),Ge=l({jsonrpc:p(A),id:d([c(),h().int()]),error:l({code:h().int(),message:c(),data:a(f())})}).strict(),j=d([Ue,l({jsonrpc:p(A)}).merge(l({method:c(),params:a(S)})).strict(),We,Ge]);async function M(e){return j.parse(await te({text:e}))}var Ke=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,N=c().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ee.custom,message:`URL must be parseable`,fatal:!0}),n}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),P=l({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:h().optional(),scope:c().optional(),refresh_token:c().optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),qe=l({resource:c().url(),authorization_servers:o(N).optional(),jwks_uri:c().url().optional(),scopes_supported:o(c()).optional(),bearer_methods_supported:o(c()).optional(),resource_signing_alg_values_supported:o(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:r().optional(),authorization_details_types_supported:o(c()).optional(),dpop_signing_alg_values_supported:o(c()).optional(),dpop_bound_access_tokens_required:r().optional()}).passthrough(),F=l({issuer:c(),authorization_endpoint:N,token_endpoint:N,registration_endpoint:N.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),code_challenge_methods_supported:o(c()),token_endpoint_auth_methods_supported:o(c()).optional(),token_endpoint_auth_signing_alg_values_supported:o(c()).optional()}).passthrough(),Je=l({issuer:c(),authorization_endpoint:N,token_endpoint:N,userinfo_endpoint:N.optional(),jwks_uri:N,registration_endpoint:N.optional(),scopes_supported:o(c()).optional(),response_types_supported:o(c()),grant_types_supported:o(c()).optional(),subject_types_supported:o(c()),id_token_signing_alg_values_supported:o(c()),claims_supported:o(c()).optional(),token_endpoint_auth_methods_supported:o(c()).optional()}).passthrough().merge(F.pick({code_challenge_methods_supported:!0})),Ye=l({client_id:c(),client_secret:c().optional(),client_id_issued_at:h().optional(),client_secret_expires_at:h().optional(),authorization_server:N.optional(),token_endpoint:N.optional()}).strip(),Xe=l({redirect_uris:o(N),token_endpoint_auth_method:c().optional(),grant_types:o(c()).optional(),response_types:o(c()).optional(),client_name:c().optional(),client_uri:N.optional(),logo_uri:N.optional(),scope:c().optional(),contacts:o(c()).optional(),tos_uri:N.optional(),policy_uri:c().optional(),jwks_uri:N.optional(),jwks:u().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ze=l({error:c(),error_description:c().optional(),error_uri:c().optional()}),Qe=Xe.merge(Ye),I=`vercel.ai.error.AI_MCPClientOAuthError`,$e=Symbol.for(I),L,R,z=class extends (R=e,L=$e,R){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[L]=!0}static isInstance(t){return e.hasMarker(t,I)}},B=class extends z{};B.errorCode=`server_error`;var V=class extends z{};V.errorCode=`invalid_client`;var H=class extends z{};H.errorCode=`invalid_grant`;var U=class extends z{};U.errorCode=`unauthorized_client`;var et={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function tt(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function W(e){let t=e.href;return e.pathname===`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function nt({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 G=class extends Error{constructor(e=`Unauthorized`){super(e),this.name=`UnauthorizedError`}};function K(e){return new URL(e).href}function rt(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function it(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function st({provider:e,clientInformation:t,tokens:n}){let r=ot(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:ot(t)}async function ct({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(at(t,n)),!0):!1}function lt(e,t){if(!t)return;let n=new URL(e).origin;if(t.origin!==n)throw new z({message:`OAuth protected resource metadata URL ${t.href} must have the same origin as the MCP server URL ${n}`})}function ut({storedAuthorizationServerInformation:e,currentAuthorizationServerInformation:t}){if(e.authorizationServerUrl!==t.authorizationServerUrl||e.tokenEndpoint!==t.tokenEndpoint)throw new z({message:`OAuth authorization server metadata does not match the metadata that issued the stored credentials`})}function q(e){let t=e.headers.get(`www-authenticate`)??e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return;let i=t.match(/resource_metadata="([^"]*)"/);if(i)try{return new URL(i[1])}catch{return}}function dt(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?J(e,void 0,n):void 0;throw r}}async function ft(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function pt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function mt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??x,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=dt(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await ft(o,a,n);return!r?.metadataUrl&&pt(s,i.pathname)&&(s=await ft(new URL(`/.well-known/${t}`,i),a,n)),s}async function ht(e,t,n=fetch){let r=await mt(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 qe.parse(await r.json())}function gt(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 _t(e,t){if(e.issuer!==t)throw new z({message:`OAuth authorization server metadata issuer ${e.issuer} does not match expected issuer ${t}`})}async function vt(e,{fetchFn:t=fetch,protocolVersion:n=x}={}){let r={"MCP-Protocol-Version":n},i=gt(e);for(let{url:e,type:n,expectedIssuer:a}of i){let i=await J(e,r,t);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}if(n===`oauth`){let e=F.parse(await i.json());return _t(e,a),e}else{let t=Je.parse(await i.json());if(_t(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 yt(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s=`code`,c=`S256`,l;if(t){if(l=new URL(t.authorization_endpoint),!t.response_types_supported.includes(s))throw Error(`Incompatible auth server: does not support response type ${s}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(c))throw Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL(`/authorize`,e);let u=await pe(),d=u.code_verifier,f=u.code_challenge;return l.searchParams.set(`response_type`,s),l.searchParams.set(`client_id`,n.client_id),l.searchParams.set(`code_challenge`,f),l.searchParams.set(`code_challenge_method`,c),l.searchParams.set(`redirect_uri`,String(r)),a&&l.searchParams.set(`state`,a),i&&l.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&l.searchParams.append(`prompt`,`consent`),o&&l.searchParams.set(`resource`,W(o)),{authorizationUrl:l,codeVerifier:d}}function Y(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 bt(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:xt(i,a,n);return;case`client_secret_post`:St(i,a,r);return;case`none`:Ct(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function xt(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 St(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Ct(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}=Ze.parse(await te({text:n}));return new(et[e]||B)({message:t||``,cause:r})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function wt(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):bt(Y(n,t?.token_endpoint_auth_methods_supported??[]),n,d,f),o&&f.set(`resource`,W(o));let p=await(c??fetch)(u,{method:`POST`,headers:d,body:f});if(!p.ok)throw await X(p);return P.parse(await p.json())}async function Tt(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):bt(Y(n,t?.token_endpoint_auth_methods_supported??[]),n,l,u),i&&u.set(`resource`,W(i));let d=await(o??fetch)(c,{method:`POST`,headers:l,body:u});if(!d.ok)throw await X(d);return P.parse({refresh_token:r,...await d.json()})}async function Et(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 Qe.parse(await a.json())}async function Z(e,t){try{return await Q(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Q(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Q(e,t);throw n}}async function Dt(e,t,n){let r=tt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!nt({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;lt(t,a);try{s=await ht(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await Dt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await vt(c,{fetchFn:o}),d=rt(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=at(await Et(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 st({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});ut({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await wt(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(it(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await st({provider:e,clientInformation:f,tokens:p});t?ut({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Tt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(it(t,d)),`AUTHORIZED`}}catch(e){if(!(!(e instanceof z)||e instanceof B))throw e}}let m=e.state?await e.state():void 0;m&&e.saveState&&await e.saveState(m);let{authorizationUrl:h,codeVerifier:ee}=await yt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await ct({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(h),`REDIRECT`}function Ot(e){return e===void 0||e===`message`}var kt=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??x};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ke}`,v())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let n=async(r=!1)=>{var i,a,o,s;try{let s=await this.commonHeaders({Accept:`text/event-stream`}),c=await this.fetchFn(this.url.href,{headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(i=this.onerror)==null||i.call(this,e),t(e)}}catch(e){return(a=this.onerror)==null||a.call(this,e),t(e)}return n(!0)}if(!c.ok||!c.body){let e=`MCP SSE Transport Error: ${c.status} ${c.statusText}`;c.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new b({message:e});return(o=this.onerror)==null||o.call(this,n),t(n)}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),u=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await l.read();if(t){if(this.connected)throw this.connected=!1,new b({message:`MCP SSE Transport Error: Connection closed unexpectedly`});return}let{event: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 b({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(Ot(s))try{let e=await M(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new b({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 b({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await Z(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;(i=this.onerror)==null||i.call(this,e);return}}catch(e){(a=this.onerror)==null||a.call(this,e);return}return n(!0)}if(!c.ok){let e=await c.text().catch(()=>null),t=new b({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${c.status}): ${e}`});(o=this.onerror)==null||o.call(this,t);return}}catch(e){(s=this.onerror)==null||s.call(this,e);return}};await n()}};function At(e){return e===void 0||e===`message`}var jt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,fetch:i}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.fetchFn=i??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders(e){let t={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??x};if(this.sessionId&&(t[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return _(t,`ai-sdk/${Ke}`,v())}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 b({message:`MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically.`});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,n;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(n=!1)=>{var r,i,a,o,s,c;try{let c={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`,Accept:`application/json, text/event-stream`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},l=await this.fetchFn(this.url.href,c),u=l.headers.get(`mcp-session-id`);if(u&&(this.sessionId=u),l.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=q(l);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(r=this.onerror)==null||r.call(this,e),e}return t(!0)}if(l.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!l.ok){let e=await l.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${l.status}): ${e}`;l.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new b({message:t,statusCode:l.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 d=l.headers.get(`content-type`)||``;if(d.includes(`application/json`)){let e=await l.json(),t=Array.isArray(e)?e.map(e=>j.parse(e)):[j.parse(e)];for(let e of t)(a=this.onmessage)==null||a.call(this,e);return}if(d.includes(`text/event-stream`)){if(!l.body){let e=new b({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:l.status,url:this.url.href});throw(o=this.onerror)==null||o.call(this,e),e}let e=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader();(async()=>{var t,n,r;try{for(;;){let{done:r,value:i}=await e.read();if(r)return;let{event:a,data:o}=i;if(At(a))try{let e=await M(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(n=this.onerror)==null||n.call(this,t)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(r=this.onerror)==null||r.call(this,e)}})();return}let f=new b({message:`MCP HTTP Transport Error: Unexpected content type: ${d}`,statusCode:l.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,f),f}catch(e){throw(c=this.onerror)==null||c.call(this,e),e}};await t()}getNextReconnectionDelay(e){let{initialReconnectionDelay:t,reconnectionDelayGrowFactor:n,maxReconnectionDelay:r}=this.reconnectionOptions;return Math.min(t*n**+e,r)}scheduleInboundSseReconnection(){var e;let{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new b({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}let n=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{this.abortController?.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},n)}async openInboundSse(e=!1,t){var n,r,i,a;try{let a=await this.commonHeaders({Accept:`text/event-stream`});t&&(a[`last-event-id`]=t);let o=await this.fetchFn(this.url.href,{method:`GET`,headers:a,signal:this.abortController?.signal,redirect:this.redirectMode}),s=o.headers.get(`mcp-session-id`);if(s&&(this.sessionId=s),o.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(o);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(n=this.onerror)==null||n.call(this,e);return}}catch(e){(r=this.onerror)==null||r.call(this,e);return}return this.openInboundSse(!0,t)}if(o.status===405)return;if(!o.ok||!o.body){let e=new b({message:`MCP HTTP Transport Error: GET SSE failed: ${o.status} ${o.statusText}`,statusCode:o.status,url:this.url.href});(i=this.onerror)==null||i.call(this,e);return}let c=o.body.pipeThrough(new TextDecoderStream).pipeThrough(new g).getReader(),l=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await c.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),At(i))try{let t=await M(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new b({message:`MCP HTTP Transport Error: Failed to parse message`,cause:e});(t=this.onerror)==null||t.call(this,n)}}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(n=this.onerror)==null||n.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>c.cancel()},this.inboundReconnectAttempts=0,l()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(a=this.onerror)==null||a.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Mt(e){switch(e.type){case`sse`:return new kt(e);case`http`:return new jt(e);default:throw new b({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Nt(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var Pt=`io.modelcontextprotocol/ui`,$=`text/html;profile=mcp-app`,Ft=`ui/resourceUri`,It={extensions:{[Pt]:{mimeTypes:[$]}}};function Lt(e){let n=e?.ui;return t(n)?n:void 0}function Rt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function zt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Bt(e){let t=Lt(e._meta),n=t?.resourceUri??e._meta?.[Ft],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 Vt(e){let t=[],n=[];for(let r of e.tools){let e=Bt(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 Ht({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(ae(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:$,html:r,meta:Rt(n._meta)}}async function Ut({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Ht({uri:t,resource:await e.readResource({uri:t,options:n})})}var Wt=`1.0.0`;function Gt({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 Kt(e){let t=new qt(e);return await t.init(),t}var qt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Wt,onUncaughtError:i,capabilities:a}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},Nt(e)?this.transport=e:this.transport=Mt(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=e=>this.onError(e),this.transport.onmessage=e=>{if(`method`in e){`id`in e?this.onRequestMessage(e):this.onError(new b({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get instructions(){return this._serverInstructions}async init(){try{await this.transport.start(),this.isClosed=!1;let e=await this.request({request:{method:`initialize`,params:{protocolVersion:x,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:we});if(e===void 0)throw new b({message:`Server sent invalid initialize result`});if(!ve.includes(e.protocolVersion))throw new b({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions,await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new b({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new b({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new b({message:`Server does not support prompts`});break;default:throw new b({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new b({message:`Attempted to send a request from a closed client`}));this.assertCapability(e.method);let a=n?.signal;a?.throwIfAborted();let o=this.requestMessageId++,s={...e,jsonrpc:`2.0`,id:o},c=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,e=>{if(a?.aborted)return i(new b({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new b({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:Ee,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:Me,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:ke,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Fe,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:Pe,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 notification(e){let t={...e,jsonrpc:`2.0`};await this.transport.send(t)}async tools({schemas:e=`automatic`}={}){let t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t=`automatic`}={}){let n={};for(let{name:r,title:i,description:a,inputSchema:o,annotations:s,_meta:c}of e.tools){let e=i??s?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let l=this,u=t===`automatic`?void 0:t[r]?.outputSchema,d=Bt({_meta:c}),f={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...d?.resourceUri==null?{}:{app:{...d,mimeType:$}}},p=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await l.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||u==null?i:l.extractStructuredContent(i,u,r)};n[r]={...t===`automatic`?ce({description:a,title:e,metadata:f,inputSchema:oe({...o,properties:o.properties??{},additionalProperties:!1}),execute:p,toModelOutput:Gt}):ne({description:a,title:e,metadata:f,inputSchema:t[r].inputSchema,...u==null?{}:{outputSchema:u},execute:p,toModelOutput:Gt}),_meta:c}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await ie({value:e.structuredContent,schema:se(t)});if(!r.success)throw new b({message:`Tool "${n}" returned structuredContent that does not match the expected outputSchema`,cause:r.error});return r.value}if(`content`in e&&Array.isArray(e.content)){let r=e.content.find(e=>e.type===`text`);if(r&&`text`in r){let e=await re({text:r.text,schema:t});if(!e.success)throw new b({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new b({message:`Tool "${n}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:n}){return this.getPromptInternal({name:e,args:t,options:n})}onElicitationRequest(e,t){if(e!==k)throw new b({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=k.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 b({message:`Connection closed`});for(let t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){let t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new b({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new b({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{He as ElicitResultSchema,k as ElicitationRequestSchema,$ as MCP_APP_MIME_TYPE,G as UnauthorizedError,Z as auth,Kt as createMCPClient,Kt as experimental_createMCPClient,It as mcpAppClientCapabilities,Ut as readMCPAppResource,Vt as splitMCPAppTools};
@@ -1,4 +1,4 @@
1
- import{APICallError as e,InvalidPromptError as t,TooManyEmbeddingValuesForCallError as n,UnsupportedFunctionalityError as r}from"../provider/index.js";import{At as i,Bt as a,Et as o,Nn as s,Rn as c,St as l,Tn as u,Tt as d,Xn as f,Zn as p,dn as m,un as h,wn as g,yt as _}from"../../_chunks/workflow/schemas-DWOIBELG.js";import{n as v}from"../../_chunks/workflow/coerce-BTuSKQr5.js";import{A as y,C as b,D as x,F as S,G as C,H as w,I as T,J as E,L as D,M as O,Q as k,R as A,T as ee,V as j,X as M,Y as N,Z as P,a as F,b as I,d as te,f as L,g as ne,h as R,i as z,j as re,l as ie,m as B,o as V,p as ae,q as H,r as U,s as oe,t as se,u as ce,v as le,z as W}from"../../_chunks/workflow/dist-DhA2lbtB.js";var ue=u({error:u({message:c(),type:c().nullish(),param:d().nullish(),code:f([c(),g()]).nullish()})}),G=te({errorSchema:ue,errorToMessage:e=>e.error.message});function de(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)&&!e.startsWith(`gpt-5.4-nano`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),i=e.startsWith(`gpt-5.1`)||e.startsWith(`gpt-5.2`)||e.startsWith(`gpt-5.3`)||e.startsWith(`gpt-5.4`)||e.startsWith(`gpt-5.5`);return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?`developer`:`system`,supportsNonReasoningParameters:i}}async function K({stream:e,getError:t,isOutputChunk:n,url:r,requestBodyValues:i,responseHeaders:a}){let[o,s]=e.tee(),c=o.getReader();try{for(;;){let e=await c.read();if(e.done)return s;let o=e.value;if(!o.success)return s;let l=t(o.value);if(l!=null)throw s.cancel().catch(()=>{}),fe({frame:l,url:r,requestBodyValues:i,responseHeaders:a});if(n(o.value))return s}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function fe({frame:t,url:n,requestBodyValues:r,responseHeaders:i}){let a=pe(t);return new e({message:a?.message??`OpenAI stream failed before any output was generated`,url:n,requestBodyValues:r,statusCode:a==null?500:me(a),responseHeaders:i,responseBody:JSON.stringify(t),data:t})}function pe(e){let t=q(e);if(t==null)return;if(t.type===`response.failed`){let n=q(q(t.response)?.error);return typeof n?.message==`string`?{message:n.message,code:he(n.code),type:`response.failed`,frame:e}:void 0}let n=q(t.error)??t;return typeof n.message==`string`&&(q(t.error)!=null||typeof n.type==`string`||`code`in n||`param`in n)?{message:n.message,code:he(n.code),type:typeof n.type==`string`?n.type:void 0,frame:e}:void 0}function me(e){if(typeof e.code==`number`&&ge(e.code))return e.code;if(typeof e.code==`string`&&/^\d{3}$/.test(e.code)){let t=Number(e.code);if(ge(t))return t}let t=[e.code,e.type].filter(e=>typeof e==`string`||typeof e==`number`).join(` `).toLowerCase();return[`insufficient_quota`,`rate_limit`].some(e=>t.includes(e))?429:t.includes(`authentication`)?401:t.includes(`permission`)?403:t.includes(`not_found`)?404:[`invalid`,`bad_request`,`context_length`].some(e=>t.includes(e))?400:t.includes(`overload`)?503:t.includes(`timeout`)?504:500}function q(e){return typeof e==`object`&&e?e:void 0}function he(e){return typeof e==`string`||typeof e==`number`?e:void 0}function ge(e){return Number.isInteger(e)&&e>=400&&e<=599}function _e(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0,r=e.prompt_tokens_details?.cached_tokens??0,i=e.completion_tokens_details?.reasoning_tokens??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n,text:n-i,reasoning:i},raw:e}}function ve(e){return JSON.stringify(e===void 0?{}:e)}function ye({prompt:e,systemMessageMode:t=`system`}){let n=[],i=[];for(let{role:a,content:o}of e)switch(a){case`system`:switch(t){case`system`:n.push({role:`system`,content:o});break;case`developer`:n.push({role:`developer`,content:o});break;case`remove`:i.push({type:`other`,message:`system messages are removed for this model`});break;default:throw Error(`Unsupported system message mode: ${t}`)}break;case`user`:if(o.length===1&&o[0].type===`text`){n.push({role:`user`,content:o[0].text});break}n.push({role:`user`,content:o.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:switch(e.data.type){case`reference`:return{type:`file`,file:{file_id:w({reference:e.data.reference,provider:`openai`})}};case`text`:throw new r({functionality:`text file parts`});case`url`:case`data`:{let n=b(e.mediaType);if(n===`image`)return{type:`image_url`,image_url:{url:e.data.type===`url`?e.data.url.toString():V(e.data.data),detail:e.providerOptions?.openai?.imageDetail}};if(n===`audio`){if(e.data.type===`url`)throw new r({functionality:`audio file parts with URLs`});let t=j({part:e});switch(t){case`audio/wav`:return{type:`input_audio`,input_audio:{data:V(e.data.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:V(e.data.data),format:`mp3`}};default:throw new r({functionality:`audio content parts with media type ${t}`})}}{let n=j({part:e});if(n!==`application/pdf`)throw new r({functionality:`file part media type ${n}`});if(e.data.type===`url`)throw new r({functionality:`PDF file parts with URLs`});return{type:`file`,file:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${V(e.data.data)}`}}}}}}})});break;case`assistant`:{let e=``,t=[];for(let n of o)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:ve(n.input)}});break}n.push({role:`assistant`,content:t.length>0?e||null:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of o){if(e.type===`tool-approval-response`)continue;let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`execution-denied`:r=t.reason??`Tool call execution denied.`;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:throw Error(`Unsupported role: ${a}`)}return{messages:n,warnings:i}}function J({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function be(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`other`}}var xe=y(()=>M(u({id:c().nullish(),created:g().nullish(),model:c().nullish(),choices:o(u({message:u({role:m(`assistant`).nullish(),content:c().nullish(),tool_calls:o(u({id:c().nullish(),type:m(`function`),function:u({name:c(),arguments:c()})})).nullish(),annotations:o(u({type:m(`url_citation`),url_citation:u({start_index:g(),end_index:g(),url:c(),title:c()})})).nullish()}),index:g(),logprobs:u({content:o(u({token:c(),logprob:g(),top_logprobs:o(u({token:c(),logprob:g()}))})).nullish()}).nullish(),finish_reason:c().nullish()})),usage:u({prompt_tokens:g().nullish(),completion_tokens:g().nullish(),total_tokens:g().nullish(),prompt_tokens_details:u({cached_tokens:g().nullish()}).nullish(),completion_tokens_details:u({reasoning_tokens:g().nullish(),accepted_prediction_tokens:g().nullish(),rejected_prediction_tokens:g().nullish()}).nullish()}).nullish()}))),Se=y(()=>M(f([u({id:c().nullish(),created:g().nullish(),model:c().nullish(),choices:o(u({delta:u({role:_([`assistant`]).nullish(),content:c().nullish(),tool_calls:o(u({index:g(),id:c().nullish(),type:m(`function`).nullish(),function:u({name:c().nullish(),arguments:c().nullish()})})).nullish(),annotations:o(u({type:m(`url_citation`),url_citation:u({start_index:g(),end_index:g(),url:c(),title:c()})})).nullish()}).nullish(),logprobs:u({content:o(u({token:c(),logprob:g(),top_logprobs:o(u({token:c(),logprob:g()}))})).nullish()}).nullish(),finish_reason:c().nullish(),index:g()})),usage:u({prompt_tokens:g().nullish(),completion_tokens:g().nullish(),total_tokens:g().nullish(),prompt_tokens_details:u({cached_tokens:g().nullish()}).nullish(),completion_tokens_details:u({reasoning_tokens:g().nullish(),accepted_prediction_tokens:g().nullish(),rejected_prediction_tokens:g().nullish()}).nullish()}).nullish()}),ue]))),Ce=y(()=>M(u({logitBias:s(v(),g()).optional(),logprobs:f([i(),g()]).optional(),parallelToolCalls:i().optional(),user:c().optional(),reasoningEffort:_([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),maxCompletionTokens:g().optional(),store:i().optional(),metadata:s(c().max(64),c().max(512)).optional(),prediction:s(c(),d()).optional(),serviceTier:_([`auto`,`flex`,`priority`,`default`]).optional(),strictJsonSchema:i().optional(),textVerbosity:_([`low`,`medium`,`high`]).optional(),promptCacheKey:c().optional(),promptCacheRetention:_([`in_memory`,`24h`]).optional(),safetyIdentifier:c().optional(),systemMessageMode:_([`system`,`developer`,`remove`]).optional(),forceReasoning:i().optional()})));function we({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,...t.strict==null?{}:{strict:t.strict}}});break;default:n.push({type:`unsupported`,feature:`tool type: ${t.type}`});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:n};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:n};case`tool`:return{tools:i,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new r({functionality:`tool choice type: ${a}`})}}var Te=class e{constructor(e,t){this.specificationVersion=`v4`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}static[k](e){return C({modelId:e.modelId,config:e.config})}static[P](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p}){let m=[],h=await D({provider:`openai`,providerOptions:p,schema:Ce})??{},g=de(this.modelId),_=h.reasoningEffort??(ee(f)?f:void 0),v=h.forceReasoning??g.isReasoningModel;i!=null&&m.push({type:`unsupported`,feature:`topK`});let{messages:y,warnings:b}=ye({prompt:e,systemMessageMode:h.systemMessageMode??(v?`developer`:g.systemMessageMode)});m.push(...b);let x=h.strictJsonSchema??!0,S={model:this.modelId,logit_bias:h.logitBias,logprobs:h.logprobs===!0||typeof h.logprobs==`number`?!0:void 0,top_logprobs:typeof h.logprobs==`number`?h.logprobs:typeof h.logprobs==`boolean`&&h.logprobs?0:void 0,user:h.user,parallel_tool_calls:h.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?c.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{schema:c.schema,strict:x,name:c.name??`response`,description:c.description}}:void 0,stop:s,seed:l,verbosity:h.textVerbosity,max_completion_tokens:h.maxCompletionTokens,store:h.store,metadata:h.metadata,prediction:h.prediction,reasoning_effort:_,service_tier:h.serviceTier,prompt_cache_key:h.promptCacheKey,prompt_cache_retention:h.promptCacheRetention,safety_identifier:h.safetyIdentifier,messages:y};v?((_!==`none`||!g.supportsNonReasoningParameters)&&(S.temperature!=null&&(S.temperature=void 0,m.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for reasoning models`})),S.top_p!=null&&(S.top_p=void 0,m.push({type:`unsupported`,feature:`topP`,details:`topP is not supported for reasoning models`})),S.logprobs!=null&&(S.logprobs=void 0,m.push({type:`other`,message:`logprobs is not supported for reasoning models`}))),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,m.push({type:`unsupported`,feature:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),S.presence_penalty!=null&&(S.presence_penalty=void 0,m.push({type:`unsupported`,feature:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),S.logit_bias!=null&&(S.logit_bias=void 0,m.push({type:`other`,message:`logitBias is not supported for reasoning models`})),S.top_logprobs!=null&&(S.top_logprobs=void 0,m.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),S.max_tokens!=null&&(S.max_completion_tokens??=S.max_tokens,S.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&S.temperature!=null&&(S.temperature=void 0,m.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),h.serviceTier===`flex`&&!g.supportsFlexProcessing&&(m.push({type:`unsupported`,feature:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),S.service_tier=void 0),h.serviceTier===`priority`&&!g.supportsPriorityProcessing&&(m.push({type:`unsupported`,feature:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),S.service_tier=void 0);let{tools:C,toolChoice:w,toolWarnings:T}=we({tools:u,toolChoice:d});return{args:{...S,tools:C,tool_choice:w},warnings:[...m,...T]}}async doGenerate(e){var t;let{args:n,warnings:r}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:o}=await W({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:U((t=this.config).headers?.call(t),e.headers),body:n,failedResponseHandler:G,successfulResponseHandler:L(xe),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],c=[],l=s.message.content;l!=null&&l.length>0&&c.push({type:`text`,text:l});for(let e of s.message.tool_calls??[])c.push({type:`tool-call`,toolCallId:e.id??I(),toolName:e.function.name,input:e.function.arguments});for(let e of s.message.annotations??[])c.push({type:`source`,sourceType:`url`,id:I(),url:e.url_citation.url,title:e.url_citation.title});let u=a.usage?.completion_tokens_details,d={openai:{}};return u?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=u?.accepted_prediction_tokens),u?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=u?.rejected_prediction_tokens),s.logprobs?.content!=null&&(d.openai.logprobs=s.logprobs.content),{content:c,finishReason:{unified:be(s.finish_reason),raw:s.finish_reason??void 0},usage:_e(a.usage),request:{body:n},response:{...J(a),headers:i,body:o},warnings:r,providerMetadata:d}}async doStream(e){var t;let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},a=this.config.url({path:`/chat/completions`,modelId:this.modelId}),{responseHeaders:o,value:s}=await W({url:a,headers:U((t=this.config).headers?.call(t),e.headers),body:i,failedResponseHandler:G,successfulResponseHandler:ce(Se),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=await K({stream:s,getError:e=>`error`in e?e.error:void 0,isOutputChunk:Ee,url:a,requestBodyValues:i,responseHeaders:o}),l,u={unified:`other`,raw:void 0},d,f=!1,p=!1,m={openai:{}};return{stream:c.pipeThrough(new TransformStream({start(e){l=new se(e,{generateId:I,typeValidation:`if-present`}),e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){u={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){u={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:r.error});return}if(!f){let e=J(r);Object.values(e).some(Boolean)&&(f=!0,n.enqueue({type:`response-metadata`,...J(r)}))}r.usage!=null&&(d=r.usage,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(m.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(m.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(u={unified:be(i.finish_reason),raw:i.finish_reason}),i?.logprobs?.content!=null&&(m.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(p||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls)l.processDelta(e);if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:I(),url:e.url_citation.url,title:e.url_citation.title})},flush(e){p&&e.enqueue({type:`text-end`,id:`0`}),l.flush(),e.enqueue({type:`finish`,finishReason:u,usage:_e(d),...m==null?{}:{providerMetadata:m}})}})),request:{body:i},response:{headers:o}}}};function Ee(e){return`error`in e?!1:e.choices.some(e=>{let t=e.delta;return t?.content!=null&&t.content.length>0||t?.tool_calls!=null&&t.tool_calls.length>0||t?.annotations!=null&&t.annotations.length>0})}function De(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0;return{inputTokens:{total:e.prompt_tokens??void 0,noCache:t,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e.completion_tokens??void 0,text:n,reasoning:void 0},raw:e}}function Oe({prompt:e,user:n=`user`,assistant:i=`assistant`}){let a=``;e[0].role===`system`&&(a+=`${e[0].content}
1
+ import{APICallError as e,InvalidPromptError as t,TooManyEmbeddingValuesForCallError as n,UnsupportedFunctionalityError as r}from"../provider/index.js";import{At as i,Bt as a,Et as o,Nn as s,Rn as c,St as l,Tn as u,Tt as d,Xn as f,Zn as p,dn as m,un as h,wn as g,yt as _}from"../../_chunks/workflow/schemas-iG9Z4s4o.js";import{n as v}from"../../_chunks/workflow/coerce-B-Ro4Nfe.js";import{A as y,C as b,D as x,F as S,G as C,H as w,I as T,J as E,L as D,M as O,Q as k,R as A,T as ee,V as j,X as M,Y as N,Z as P,a as F,b as I,d as te,f as L,g as ne,h as R,i as z,j as re,l as ie,m as B,o as V,p as ae,q as H,r as U,s as oe,t as se,u as ce,v as le,z as W}from"../../_chunks/workflow/dist-DTchiX0N.js";var ue=u({error:u({message:c(),type:c().nullish(),param:d().nullish(),code:f([c(),g()]).nullish()})}),G=te({errorSchema:ue,errorToMessage:e=>e.error.message});function de(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)&&!e.startsWith(`gpt-5.4-nano`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),i=e.startsWith(`gpt-5.1`)||e.startsWith(`gpt-5.2`)||e.startsWith(`gpt-5.3`)||e.startsWith(`gpt-5.4`)||e.startsWith(`gpt-5.5`);return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?`developer`:`system`,supportsNonReasoningParameters:i}}async function K({stream:e,getError:t,isOutputChunk:n,url:r,requestBodyValues:i,responseHeaders:a}){let[o,s]=e.tee(),c=o.getReader();try{for(;;){let e=await c.read();if(e.done)return s;let o=e.value;if(!o.success)return s;let l=t(o.value);if(l!=null)throw s.cancel().catch(()=>{}),fe({frame:l,url:r,requestBodyValues:i,responseHeaders:a});if(n(o.value))return s}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function fe({frame:t,url:n,requestBodyValues:r,responseHeaders:i}){let a=pe(t);return new e({message:a?.message??`OpenAI stream failed before any output was generated`,url:n,requestBodyValues:r,statusCode:a==null?500:me(a),responseHeaders:i,responseBody:JSON.stringify(t),data:t})}function pe(e){let t=q(e);if(t==null)return;if(t.type===`response.failed`){let n=q(q(t.response)?.error);return typeof n?.message==`string`?{message:n.message,code:he(n.code),type:`response.failed`,frame:e}:void 0}let n=q(t.error)??t;return typeof n.message==`string`&&(q(t.error)!=null||typeof n.type==`string`||`code`in n||`param`in n)?{message:n.message,code:he(n.code),type:typeof n.type==`string`?n.type:void 0,frame:e}:void 0}function me(e){if(typeof e.code==`number`&&ge(e.code))return e.code;if(typeof e.code==`string`&&/^\d{3}$/.test(e.code)){let t=Number(e.code);if(ge(t))return t}let t=[e.code,e.type].filter(e=>typeof e==`string`||typeof e==`number`).join(` `).toLowerCase();return[`insufficient_quota`,`rate_limit`].some(e=>t.includes(e))?429:t.includes(`authentication`)?401:t.includes(`permission`)?403:t.includes(`not_found`)?404:[`invalid`,`bad_request`,`context_length`].some(e=>t.includes(e))?400:t.includes(`overload`)?503:t.includes(`timeout`)?504:500}function q(e){return typeof e==`object`&&e?e:void 0}function he(e){return typeof e==`string`||typeof e==`number`?e:void 0}function ge(e){return Number.isInteger(e)&&e>=400&&e<=599}function _e(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0,r=e.prompt_tokens_details?.cached_tokens??0,i=e.completion_tokens_details?.reasoning_tokens??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n,text:n-i,reasoning:i},raw:e}}function ve(e){return JSON.stringify(e===void 0?{}:e)}function ye({prompt:e,systemMessageMode:t=`system`}){let n=[],i=[];for(let{role:a,content:o}of e)switch(a){case`system`:switch(t){case`system`:n.push({role:`system`,content:o});break;case`developer`:n.push({role:`developer`,content:o});break;case`remove`:i.push({type:`other`,message:`system messages are removed for this model`});break;default:throw Error(`Unsupported system message mode: ${t}`)}break;case`user`:if(o.length===1&&o[0].type===`text`){n.push({role:`user`,content:o[0].text});break}n.push({role:`user`,content:o.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:switch(e.data.type){case`reference`:return{type:`file`,file:{file_id:w({reference:e.data.reference,provider:`openai`})}};case`text`:throw new r({functionality:`text file parts`});case`url`:case`data`:{let n=b(e.mediaType);if(n===`image`)return{type:`image_url`,image_url:{url:e.data.type===`url`?e.data.url.toString():V(e.data.data),detail:e.providerOptions?.openai?.imageDetail}};if(n===`audio`){if(e.data.type===`url`)throw new r({functionality:`audio file parts with URLs`});let t=j({part:e});switch(t){case`audio/wav`:return{type:`input_audio`,input_audio:{data:V(e.data.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:V(e.data.data),format:`mp3`}};default:throw new r({functionality:`audio content parts with media type ${t}`})}}{let n=j({part:e});if(n!==`application/pdf`)throw new r({functionality:`file part media type ${n}`});if(e.data.type===`url`)throw new r({functionality:`PDF file parts with URLs`});return{type:`file`,file:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${V(e.data.data)}`}}}}}}})});break;case`assistant`:{let e=``,t=[];for(let n of o)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:ve(n.input)}});break}n.push({role:`assistant`,content:t.length>0?e||null:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of o){if(e.type===`tool-approval-response`)continue;let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`execution-denied`:r=t.reason??`Tool call execution denied.`;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:throw Error(`Unsupported role: ${a}`)}return{messages:n,warnings:i}}function J({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function be(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`other`}}var xe=y(()=>M(u({id:c().nullish(),created:g().nullish(),model:c().nullish(),choices:o(u({message:u({role:m(`assistant`).nullish(),content:c().nullish(),tool_calls:o(u({id:c().nullish(),type:m(`function`),function:u({name:c(),arguments:c()})})).nullish(),annotations:o(u({type:m(`url_citation`),url_citation:u({start_index:g(),end_index:g(),url:c(),title:c()})})).nullish()}),index:g(),logprobs:u({content:o(u({token:c(),logprob:g(),top_logprobs:o(u({token:c(),logprob:g()}))})).nullish()}).nullish(),finish_reason:c().nullish()})),usage:u({prompt_tokens:g().nullish(),completion_tokens:g().nullish(),total_tokens:g().nullish(),prompt_tokens_details:u({cached_tokens:g().nullish()}).nullish(),completion_tokens_details:u({reasoning_tokens:g().nullish(),accepted_prediction_tokens:g().nullish(),rejected_prediction_tokens:g().nullish()}).nullish()}).nullish()}))),Se=y(()=>M(f([u({id:c().nullish(),created:g().nullish(),model:c().nullish(),choices:o(u({delta:u({role:_([`assistant`]).nullish(),content:c().nullish(),tool_calls:o(u({index:g(),id:c().nullish(),type:m(`function`).nullish(),function:u({name:c().nullish(),arguments:c().nullish()})})).nullish(),annotations:o(u({type:m(`url_citation`),url_citation:u({start_index:g(),end_index:g(),url:c(),title:c()})})).nullish()}).nullish(),logprobs:u({content:o(u({token:c(),logprob:g(),top_logprobs:o(u({token:c(),logprob:g()}))})).nullish()}).nullish(),finish_reason:c().nullish(),index:g()})),usage:u({prompt_tokens:g().nullish(),completion_tokens:g().nullish(),total_tokens:g().nullish(),prompt_tokens_details:u({cached_tokens:g().nullish()}).nullish(),completion_tokens_details:u({reasoning_tokens:g().nullish(),accepted_prediction_tokens:g().nullish(),rejected_prediction_tokens:g().nullish()}).nullish()}).nullish()}),ue]))),Ce=y(()=>M(u({logitBias:s(v(),g()).optional(),logprobs:f([i(),g()]).optional(),parallelToolCalls:i().optional(),user:c().optional(),reasoningEffort:_([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),maxCompletionTokens:g().optional(),store:i().optional(),metadata:s(c().max(64),c().max(512)).optional(),prediction:s(c(),d()).optional(),serviceTier:_([`auto`,`flex`,`priority`,`default`]).optional(),strictJsonSchema:i().optional(),textVerbosity:_([`low`,`medium`,`high`]).optional(),promptCacheKey:c().optional(),promptCacheRetention:_([`in_memory`,`24h`]).optional(),safetyIdentifier:c().optional(),systemMessageMode:_([`system`,`developer`,`remove`]).optional(),forceReasoning:i().optional()})));function we({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,...t.strict==null?{}:{strict:t.strict}}});break;default:n.push({type:`unsupported`,feature:`tool type: ${t.type}`});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:n};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:n};case`tool`:return{tools:i,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new r({functionality:`tool choice type: ${a}`})}}var Te=class e{constructor(e,t){this.specificationVersion=`v4`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}static[k](e){return C({modelId:e.modelId,config:e.config})}static[P](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p}){let m=[],h=await D({provider:`openai`,providerOptions:p,schema:Ce})??{},g=de(this.modelId),_=h.reasoningEffort??(ee(f)?f:void 0),v=h.forceReasoning??g.isReasoningModel;i!=null&&m.push({type:`unsupported`,feature:`topK`});let{messages:y,warnings:b}=ye({prompt:e,systemMessageMode:h.systemMessageMode??(v?`developer`:g.systemMessageMode)});m.push(...b);let x=h.strictJsonSchema??!0,S={model:this.modelId,logit_bias:h.logitBias,logprobs:h.logprobs===!0||typeof h.logprobs==`number`?!0:void 0,top_logprobs:typeof h.logprobs==`number`?h.logprobs:typeof h.logprobs==`boolean`&&h.logprobs?0:void 0,user:h.user,parallel_tool_calls:h.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?c.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{schema:c.schema,strict:x,name:c.name??`response`,description:c.description}}:void 0,stop:s,seed:l,verbosity:h.textVerbosity,max_completion_tokens:h.maxCompletionTokens,store:h.store,metadata:h.metadata,prediction:h.prediction,reasoning_effort:_,service_tier:h.serviceTier,prompt_cache_key:h.promptCacheKey,prompt_cache_retention:h.promptCacheRetention,safety_identifier:h.safetyIdentifier,messages:y};v?((_!==`none`||!g.supportsNonReasoningParameters)&&(S.temperature!=null&&(S.temperature=void 0,m.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for reasoning models`})),S.top_p!=null&&(S.top_p=void 0,m.push({type:`unsupported`,feature:`topP`,details:`topP is not supported for reasoning models`})),S.logprobs!=null&&(S.logprobs=void 0,m.push({type:`other`,message:`logprobs is not supported for reasoning models`}))),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,m.push({type:`unsupported`,feature:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),S.presence_penalty!=null&&(S.presence_penalty=void 0,m.push({type:`unsupported`,feature:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),S.logit_bias!=null&&(S.logit_bias=void 0,m.push({type:`other`,message:`logitBias is not supported for reasoning models`})),S.top_logprobs!=null&&(S.top_logprobs=void 0,m.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),S.max_tokens!=null&&(S.max_completion_tokens??=S.max_tokens,S.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&S.temperature!=null&&(S.temperature=void 0,m.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),h.serviceTier===`flex`&&!g.supportsFlexProcessing&&(m.push({type:`unsupported`,feature:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),S.service_tier=void 0),h.serviceTier===`priority`&&!g.supportsPriorityProcessing&&(m.push({type:`unsupported`,feature:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),S.service_tier=void 0);let{tools:C,toolChoice:w,toolWarnings:T}=we({tools:u,toolChoice:d});return{args:{...S,tools:C,tool_choice:w},warnings:[...m,...T]}}async doGenerate(e){var t;let{args:n,warnings:r}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:o}=await W({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:U((t=this.config).headers?.call(t),e.headers),body:n,failedResponseHandler:G,successfulResponseHandler:L(xe),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],c=[],l=s.message.content;l!=null&&l.length>0&&c.push({type:`text`,text:l});for(let e of s.message.tool_calls??[])c.push({type:`tool-call`,toolCallId:e.id??I(),toolName:e.function.name,input:e.function.arguments});for(let e of s.message.annotations??[])c.push({type:`source`,sourceType:`url`,id:I(),url:e.url_citation.url,title:e.url_citation.title});let u=a.usage?.completion_tokens_details,d={openai:{}};return u?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=u?.accepted_prediction_tokens),u?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=u?.rejected_prediction_tokens),s.logprobs?.content!=null&&(d.openai.logprobs=s.logprobs.content),{content:c,finishReason:{unified:be(s.finish_reason),raw:s.finish_reason??void 0},usage:_e(a.usage),request:{body:n},response:{...J(a),headers:i,body:o},warnings:r,providerMetadata:d}}async doStream(e){var t;let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},a=this.config.url({path:`/chat/completions`,modelId:this.modelId}),{responseHeaders:o,value:s}=await W({url:a,headers:U((t=this.config).headers?.call(t),e.headers),body:i,failedResponseHandler:G,successfulResponseHandler:ce(Se),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=await K({stream:s,getError:e=>`error`in e?e.error:void 0,isOutputChunk:Ee,url:a,requestBodyValues:i,responseHeaders:o}),l,u={unified:`other`,raw:void 0},d,f=!1,p=!1,m={openai:{}};return{stream:c.pipeThrough(new TransformStream({start(e){l=new se(e,{generateId:I,typeValidation:`if-present`}),e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){u={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){u={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:r.error});return}if(!f){let e=J(r);Object.values(e).some(Boolean)&&(f=!0,n.enqueue({type:`response-metadata`,...J(r)}))}r.usage!=null&&(d=r.usage,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(m.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(m.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(u={unified:be(i.finish_reason),raw:i.finish_reason}),i?.logprobs?.content!=null&&(m.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(p||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls)l.processDelta(e);if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:I(),url:e.url_citation.url,title:e.url_citation.title})},flush(e){p&&e.enqueue({type:`text-end`,id:`0`}),l.flush(),e.enqueue({type:`finish`,finishReason:u,usage:_e(d),...m==null?{}:{providerMetadata:m}})}})),request:{body:i},response:{headers:o}}}};function Ee(e){return`error`in e?!1:e.choices.some(e=>{let t=e.delta;return t?.content!=null&&t.content.length>0||t?.tool_calls!=null&&t.tool_calls.length>0||t?.annotations!=null&&t.annotations.length>0})}function De(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0;return{inputTokens:{total:e.prompt_tokens??void 0,noCache:t,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e.completion_tokens??void 0,text:n,reasoning:void 0},raw:e}}function Oe({prompt:e,user:n=`user`,assistant:i=`assistant`}){let a=``;e[0].role===`system`&&(a+=`${e[0].content}
2
2
 
3
3
  `,e=e.slice(1));for(let{role:o,content:s}of e)switch(o){case`system`:throw new t({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=s.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);a+=`${n}:
4
4
  ${e}
@@ -1,3 +1,3 @@
1
- import{t as e}from"../../_chunks/workflow/src-B54rYDvB.js";import{convertDataContentToBase64String as t}from"ai";var n=e();function r(e){let t=e.toLowerCase();for(let[e,n]of[[`google.vertex`,`gcp.vertex_ai`],[`google.generative-ai`,`gcp.gemini`],[`google-vertex`,`gcp.vertex_ai`],[`amazon-bedrock`,`aws.bedrock`],[`azure-openai`,`azure.ai.openai`],[`anthropic`,`anthropic`],[`openai`,`openai`],[`azure`,`azure.ai.inference`],[`google`,`gcp.gemini`],[`mistral`,`mistral_ai`],[`cohere`,`cohere`],[`bedrock`,`aws.bedrock`],[`groq`,`groq`],[`deepseek`,`deepseek`],[`perplexity`,`perplexity`],[`xai`,`x_ai`]])if(t===e||t.startsWith(e+`.`)||t.startsWith(e+`-`))return n;return e}function i(e){return{"ai.generateText":`invoke_agent`,"ai.streamText":`invoke_agent`,"ai.generateObject":`invoke_agent`,"ai.streamObject":`invoke_agent`,"ai.embed":`embeddings`,"ai.embedMany":`embeddings`,"ai.rerank":`rerank`}[e]??e}function a(e){return typeof e==`string`?[{type:`text`,content:e}]:Array.isArray(e)?e.map(e=>({type:`text`,content:e.content})):[{type:`text`,content:e.content}]}function o(e){switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})(),i;if(r instanceof Uint8Array)i=t(r);else if(typeof r==`string`){if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r};i=r}else if(r instanceof URL)return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()};else i=String(r);return{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:i}}case`tool-approval-response`:return{type:`tool_approval_response`,approval_id:e.approvalId,approved:e.approved,reason:e.reason};case`custom`:return{type:`custom`,kind:e.kind};case`reasoning-file`:return{type:String(e.type)};default:return{type:String(e.type)}}}function s(e){return!e||e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`image`}function c(e){return e.filter(e=>e.role!==`system`).map(e=>{if(e.role===`system`)return{role:`system`,parts:[{type:`text`,content:e.content}]};let t=e.content.map(o);return{role:e.role,parts:t}})}function l({prompt:e,messages:t}){let n=[];if(typeof e==`string`)n.push({role:`user`,parts:[{type:`text`,content:e}]});else if(Array.isArray(e))for(let t of e){let e=u(t);e&&n.push(e)}if(t)for(let e of t){let t=u(e);t&&n.push(t)}return n}function u(e){if(e.role!==`system`){if(e.role===`user`)return typeof e.content==`string`?{role:`user`,parts:[{type:`text`,content:e.content}]}:{role:`user`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`image`:{let n=e.image;return n instanceof URL?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n.toString()}:typeof n==`string`?n.startsWith(`http://`)||n.startsWith(`https://`)?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:t(n)}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})();return r instanceof URL?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()}:typeof r==`string`?r.startsWith(`http://`)||r.startsWith(`https://`)?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:t(r)}}default:return{type:String(e.type)}}})};if(e.role===`assistant`)return typeof e.content==`string`?{role:`assistant`,parts:[{type:`text`,content:e.content}]}:{role:`assistant`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}default:return{type:String(e.type)}}})};if(e.role===`tool`)return{role:`tool`,parts:e.content.map(e=>{if(e.type===`tool-result`){let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}return{type:String(e.type)}})}}}function d({text:e,reasoning:t,toolCalls:n,files:r,finishReason:i}){let a=[];if(t)for(let e of t)`text`in e&&e.text&&a.push({type:`reasoning`,content:e.text});if(e!=null&&e.length>0&&a.push({type:`text`,content:e}),n)for(let e of n)a.push({type:`tool_call`,id:e.toolCallId,name:e.toolName,arguments:e.input});if(r)for(let e of r)a.push({type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType,content:e.base64});return[{role:`assistant`,parts:a,finish_reason:p(i)}]}function f({objectText:e,finishReason:t}){return[{role:`assistant`,parts:[{type:`text`,content:e}],finish_reason:p(t)}]}function p(e){return{stop:`stop`,length:`length`,"content-filter":`content_filter`,"tool-calls":`tool_call`,error:`error`,other:`stop`,unknown:`stop`}[e]??e}function m(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function h(e){return e?.isEnabled!==!1}function g(e,t){if(!h(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var _={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function v(e){return{..._,usage:e.usage??!1,providerMetadata:e.providerMetadata??!1,embedding:e.embedding??!1,reranking:e.reranking??!1,runtimeContext:e.runtimeContext??!1,headers:e.headers??!1,toolChoice:e.toolChoice??!1,schema:e.schema??!1}}function y(e){let t={};for(let[n,r]of Object.entries(e??{}))b(t,`ai.settings.context.${n}`,r);return t}function b(e,t,n){if(n!=null){if(Array.isArray(n)||typeof n!=`object`){e[t]=n;return}for(let[r,i]of Object.entries(n))b(e,`${t}.${r}`,i)}}function x(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.request.headers.${e}`,t]))}function S(e){return{"ai.usage.inputTokenDetails.noCacheTokens":e.inputTokenDetails?.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":e.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.outputTokenDetails?.reasoningTokens}}function C(e,t,n){let r={};for(let[i,a]of Object.entries(n))!t[i]||a==null||Object.assign(r,g(e,a));return r}var w=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`gen_ai`),this.supplementalAttributes=v(e),this.enrichSpan=e.enrichSpan}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}getSpanAttributes({attributes:e,spanType:t,operationId:n,callId:r,runtimeContext:i}){let a;try{a=this.enrichSpan?.call(this,{spanType:t,operationId:n,callId:r,runtimeContext:i})}catch{a=void 0}return{...a,...e}}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e),i=r?.inferenceContext??r?.stepContext;return i==null?t():n.context.with(i,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=e.runtimeContext,d=C(t,this.supplementalAttributes,{runtimeContext:y(u),headers:x(e.headers)}),f=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions?{input:()=>JSON.stringify(a(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:void 0,messages:e.messages}))},...d}),p=`${c} ${e.modelId}`,m=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:f,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:u}),kind:n.SpanKind.INTERNAL}),h=n.trace.setSpan(n.context.active(),m);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:m,rootContext:h,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:u,baseSupplementalAttributes:d})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=C(t,this.supplementalAttributes,{headers:x(e.headers)}),d=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(a(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:e.prompt,messages:e.messages}))},...u,...C(t,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),f=`${c} ${e.modelId}`,p=this.tracer.startSpan(f,{attributes:this.getSpanAttributes({attributes:d,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.INTERNAL}),m=n.trace.setSpan(n.context.active(),p);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:p,rootContext:m,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:u})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>e.promptMessages?JSON.stringify(c(e.promptMessages)):void 0},...t.baseSupplementalAttributes}),o=`chat ${e.modelId}`;t.inferenceSpan=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),t.inferenceContext=n.trace.setSpan(t.rootContext,t.inferenceSpan)}onObjectStepEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(f({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=e.value,s=e.operationId===`ai.embedMany`,c=g(t,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{embedding:s?{"ai.values":{input:()=>o.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(o)}}})}),l=`embeddings ${e.modelId}`,u=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:c,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),d=n.trace.setSpan(n.context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t;t.runtimeContext=e.runtimeContext;let i=g(r,{"gen_ai.operation.name":`agent_step`,...t.baseSupplementalAttributes,...C(r,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:i,spanType:`step`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onLanguageModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>{let t=l({prompt:void 0,messages:e.messages});return t.length>0?JSON.stringify(t):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});t.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.stepContext),t.inferenceContext=n.trace.setSpan(t.stepContext,t.inferenceSpan)}onLanguageModelCallEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||void 0,reasoning:e.content.filter(e=>e.type===`reasoning`),toolCalls:e.content.filter(e=>e.type===`tool-call`),files:e.content.filter(e=>e.type===`file`).map(e=>e.file),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=g(r,{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),o=`execute_tool ${i.toolName}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`tool`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.stepContext),c=n.trace.setSpan(t.stepContext,s);t.toolSpans.set(i.toolCallId,{span:s,context:c})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(g(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else m(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onStepFinish(e){this.onStepEnd(e)}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.text??void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,files:e.files,finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object==null?void 0:JSON.stringify(f({objectText:JSON.stringify(e.object),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(g(n,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(n,this.supplementalAttributes,{embedding:r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}})}),o=`embeddings ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`embedding`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),c=n.trace.setSpan(t.rootContext,s);t.embedSpans.set(e.embedCallId,{span:s,context:c})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(g(i,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(i,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))}}})})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=g(t,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),s=`rerank ${e.modelId}`,c=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:o,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),o=`rerank ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`reranking`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext);t.rerankSpan={span:s,context:n.trace.setSpan(t.rootContext,s)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(C(r,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;for(let{span:e}of n.toolSpans.values())m(e,r),e.end();n.toolSpans.clear(),n.inferenceSpan&&(m(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(m(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:e}of n.embedSpans.values())m(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(m(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),m(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};function T({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function E({model:e,settings:t,headers:n,context:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...y(r),...Object.entries(n??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}function D(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:O(e.data)}:e)})))}function O(e){switch(e.type){case`data`:return e.data instanceof Uint8Array?t(e.data):e.data;case`url`:return e.url.toString();case`reference`:return e.reference;case`text`:return e.text}}function k(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function A(e){return e?.isEnabled!==!1}function j(e,t){if(!A(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var M=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`ai`)}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e)?.stepContext;return r==null?t():n.context.with(r,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:e.runtimeContext}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt":{input:()=>JSON.stringify({system:e.instructions,messages:e.messages})}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.prompt":{input:()=>JSON.stringify({system:e.system,prompt:e.prompt,messages:e.messages})},"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamObject`?`ai.streamObject.doStream`:`ai.generateObject.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onObjectStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>{try{return JSON.stringify(JSON.parse(e.objectText))}catch{return e.objectText}}},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),e.msToFirstChunk!=null&&(t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.stream.msToFirstChunk":e.msToFirstChunk}),t.stepSpan.setAttributes({"ai.stream.msToFirstChunk":e.msToFirstChunk})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=e.value,o=e.operationId===`ai.embedMany`,s=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,...o?{"ai.values":{input:()=>a.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(a)}}}),c=this.tracer.startSpan(e.operationId,{attributes:s}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamText`?`ai.streamText.doStream`:`ai.generateText.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"ai.prompt.tools":{input:()=>e.stepTools?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=j(r,{...T({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":i.toolName,"ai.toolCall.id":i.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(i.input)}}),o=this.tracer.startSpan(`ai.toolCall`,{attributes:a},t.stepContext),s=n.trace.setSpan(t.stepContext,o);t.toolSpans.set(i.toolCallId,{span:o,context:s})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(j(i,{"ai.toolCall.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else k(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.streamText`;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.reasoning.length>0?e.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
1
+ import{t as e}from"../../_chunks/workflow/src-CQuMexnO.js";import{convertDataContentToBase64String as t}from"ai";var n=e();function r(e){let t=e.toLowerCase();for(let[e,n]of[[`google.vertex`,`gcp.vertex_ai`],[`google.generative-ai`,`gcp.gemini`],[`google-vertex`,`gcp.vertex_ai`],[`amazon-bedrock`,`aws.bedrock`],[`azure-openai`,`azure.ai.openai`],[`anthropic`,`anthropic`],[`openai`,`openai`],[`azure`,`azure.ai.inference`],[`google`,`gcp.gemini`],[`mistral`,`mistral_ai`],[`cohere`,`cohere`],[`bedrock`,`aws.bedrock`],[`groq`,`groq`],[`deepseek`,`deepseek`],[`perplexity`,`perplexity`],[`xai`,`x_ai`]])if(t===e||t.startsWith(e+`.`)||t.startsWith(e+`-`))return n;return e}function i(e){return{"ai.generateText":`invoke_agent`,"ai.streamText":`invoke_agent`,"ai.generateObject":`invoke_agent`,"ai.streamObject":`invoke_agent`,"ai.embed":`embeddings`,"ai.embedMany":`embeddings`,"ai.rerank":`rerank`}[e]??e}function a(e){return typeof e==`string`?[{type:`text`,content:e}]:Array.isArray(e)?e.map(e=>({type:`text`,content:e.content})):[{type:`text`,content:e.content}]}function o(e){switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})(),i;if(r instanceof Uint8Array)i=t(r);else if(typeof r==`string`){if(r.startsWith(`http://`)||r.startsWith(`https://`))return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r};i=r}else if(r instanceof URL)return{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()};else i=String(r);return{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:i}}case`tool-approval-response`:return{type:`tool_approval_response`,approval_id:e.approvalId,approved:e.approved,reason:e.reason};case`custom`:return{type:`custom`,kind:e.kind};case`reasoning-file`:return{type:String(e.type)};default:return{type:String(e.type)}}}function s(e){return!e||e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`image`}function c(e){return e.filter(e=>e.role!==`system`).map(e=>{if(e.role===`system`)return{role:`system`,parts:[{type:`text`,content:e.content}]};let t=e.content.map(o);return{role:e.role,parts:t}})}function l({prompt:e,messages:t}){let n=[];if(typeof e==`string`)n.push({role:`user`,parts:[{type:`text`,content:e}]});else if(Array.isArray(e))for(let t of e){let e=u(t);e&&n.push(e)}if(t)for(let e of t){let t=u(e);t&&n.push(t)}return n}function u(e){if(e.role!==`system`){if(e.role===`user`)return typeof e.content==`string`?{role:`user`,parts:[{type:`text`,content:e.content}]}:{role:`user`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`image`:{let n=e.image;return n instanceof URL?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n.toString()}:typeof n==`string`?n.startsWith(`http://`)||n.startsWith(`https://`)?{type:`uri`,modality:`image`,mime_type:e.mediaType??null,uri:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:n}:{type:`blob`,modality:`image`,mime_type:e.mediaType??null,content:t(n)}}case`file`:{let n=e.data,r=(()=>{if(typeof n==`object`&&n&&!(n instanceof URL)&&!(n instanceof Uint8Array)&&!(n instanceof ArrayBuffer)&&`type`in n)switch(n.type){case`data`:return n.data;case`url`:return n.url;case`text`:return n.text;default:return``}return n})();return r instanceof URL?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r.toString()}:typeof r==`string`?r.startsWith(`http://`)||r.startsWith(`https://`)?{type:`uri`,modality:s(e.mediaType),mime_type:e.mediaType??null,uri:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:r}:{type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType??null,content:t(r)}}default:return{type:String(e.type)}}})};if(e.role===`assistant`)return typeof e.content==`string`?{role:`assistant`,parts:[{type:`text`,content:e.content}]}:{role:`assistant`,parts:e.content.map(e=>{switch(e.type){case`text`:return{type:`text`,content:e.text};case`reasoning`:return{type:`reasoning`,content:e.text};case`tool-call`:return{type:`tool_call`,id:e.toolCallId??null,name:e.toolName,arguments:e.input};case`tool-result`:{let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}default:return{type:String(e.type)}}})};if(e.role===`tool`)return{role:`tool`,parts:e.content.map(e=>{if(e.type===`tool-result`){let t=e.output,n;return t&&(n=t.type===`text`||t.type===`error-text`||t.type===`json`||t.type===`error-json`?t.value:t.type===`execution-denied`?{denied:!0,reason:t.reason}:t),{type:`tool_call_response`,id:e.toolCallId??null,response:n}}return{type:String(e.type)}})}}}function d({text:e,reasoning:t,toolCalls:n,files:r,finishReason:i}){let a=[];if(t)for(let e of t)`text`in e&&e.text&&a.push({type:`reasoning`,content:e.text});if(e!=null&&e.length>0&&a.push({type:`text`,content:e}),n)for(let e of n)a.push({type:`tool_call`,id:e.toolCallId,name:e.toolName,arguments:e.input});if(r)for(let e of r)a.push({type:`blob`,modality:s(e.mediaType),mime_type:e.mediaType,content:e.base64});return[{role:`assistant`,parts:a,finish_reason:p(i)}]}function f({objectText:e,finishReason:t}){return[{role:`assistant`,parts:[{type:`text`,content:e}],finish_reason:p(t)}]}function p(e){return{stop:`stop`,length:`length`,"content-filter":`content_filter`,"tool-calls":`tool_call`,error:`error`,other:`stop`,unknown:`stop`}[e]??e}function m(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function h(e){return e?.isEnabled!==!1}function g(e,t){if(!h(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var _={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function v(e){return{..._,usage:e.usage??!1,providerMetadata:e.providerMetadata??!1,embedding:e.embedding??!1,reranking:e.reranking??!1,runtimeContext:e.runtimeContext??!1,headers:e.headers??!1,toolChoice:e.toolChoice??!1,schema:e.schema??!1}}function y(e){let t={};for(let[n,r]of Object.entries(e??{}))b(t,`ai.settings.context.${n}`,r);return t}function b(e,t,n){if(n!=null){if(Array.isArray(n)||typeof n!=`object`){e[t]=n;return}for(let[r,i]of Object.entries(n))b(e,`${t}.${r}`,i)}}function x(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null).map(([e,t])=>[`ai.request.headers.${e}`,t]))}function S(e){return{"ai.usage.inputTokenDetails.noCacheTokens":e.inputTokenDetails?.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":e.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.outputTokenDetails?.reasoningTokens}}function C(e,t,n){let r={};for(let[i,a]of Object.entries(n))!t[i]||a==null||Object.assign(r,g(e,a));return r}var w=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`gen_ai`),this.supplementalAttributes=v(e),this.enrichSpan=e.enrichSpan}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}getSpanAttributes({attributes:e,spanType:t,operationId:n,callId:r,runtimeContext:i}){let a;try{a=this.enrichSpan?.call(this,{spanType:t,operationId:n,callId:r,runtimeContext:i})}catch{a=void 0}return{...a,...e}}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e),i=r?.inferenceContext??r?.stepContext;return i==null?t():n.context.with(i,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=e.runtimeContext,d=C(t,this.supplementalAttributes,{runtimeContext:y(u),headers:x(e.headers)}),f=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.stop_sequences":e.stopSequences,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.instructions?{input:()=>JSON.stringify(a(e.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:void 0,messages:e.messages}))},...d}),p=`${c} ${e.modelId}`,m=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:f,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:u}),kind:n.SpanKind.INTERNAL}),h=n.trace.setSpan(n.context.active(),m);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:m,rootContext:h,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:u,baseSupplementalAttributes:d})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},o={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},s=r(e.provider),c=i(e.operationId),u=C(t,this.supplementalAttributes,{headers:x(e.headers)}),d=g(t,{"gen_ai.operation.name":c,"gen_ai.provider.name":s,"gen_ai.request.model":e.modelId,"gen_ai.agent.name":t.functionId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":e.frequencyPenalty,"gen_ai.request.max_tokens":e.maxOutputTokens,"gen_ai.request.presence_penalty":e.presencePenalty,"gen_ai.request.temperature":e.temperature??void 0,"gen_ai.request.top_k":e.topK,"gen_ai.request.top_p":e.topP,"gen_ai.request.seed":e.seed,"gen_ai.system_instructions":e.system?{input:()=>JSON.stringify(a(e.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(l({prompt:e.prompt,messages:e.messages}))},...u,...C(t,this.supplementalAttributes,{schema:{"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}})}),f=`${c} ${e.modelId}`,p=this.tracer.startSpan(f,{attributes:this.getSpanAttributes({attributes:d,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.INTERNAL}),m=n.trace.setSpan(n.context.active(),p);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:p,rootContext:m,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:u})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.output.type":`json`,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>e.promptMessages?JSON.stringify(c(e.promptMessages)):void 0},...t.baseSupplementalAttributes}),o=`chat ${e.modelId}`;t.inferenceSpan=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),t.inferenceContext=n.trace.setSpan(t.rootContext,t.inferenceSpan)}onObjectStepEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(f({objectText:e.objectText,finishReason:e.finishReason}))}catch{return e.objectText}}},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=e.value,s=e.operationId===`ai.embedMany`,c=g(t,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{embedding:s?{"ai.values":{input:()=>o.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(o)}}})}),l=`embeddings ${e.modelId}`,u=this.tracer.startSpan(l,{attributes:this.getSpanAttributes({attributes:c,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),d=n.trace.setSpan(n.context.active(),u);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:u,rootContext:d,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t;t.runtimeContext=e.runtimeContext;let i=g(r,{"gen_ai.operation.name":`agent_step`,...t.baseSupplementalAttributes,...C(r,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)}}})});t.stepSpan=this.tracer.startSpan(`step ${e.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:i,spanType:`step`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onLanguageModelCallStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`chat`,"gen_ai.provider.name":r(e.provider),"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP,"gen_ai.input.messages":{input:()=>{let t=l({prompt:void 0,messages:e.messages});return t.length>0?JSON.stringify(t):void 0}},"gen_ai.tool.definitions":{input:()=>e.tools?JSON.stringify(e.tools):void 0}});t.inferenceSpan=this.tracer.startSpan(`chat ${e.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:`languageModel`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.stepContext),t.inferenceContext=n.trace.setSpan(t.stepContext,t.inferenceSpan)}onLanguageModelCallEnd(e){let t=this.getCallState(e.callId);if(!t?.inferenceSpan)return;let{telemetry:n}=t;t.inferenceSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.responseId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||void 0,reasoning:e.content.filter(e=>e.type===`reasoning`),toolCalls:e.content.filter(e=>e.type===`tool-call`),files:e.content.filter(e=>e.type===`file`).map(e=>e.file),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{usage:S(e.usage)})})),t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=g(r,{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":i.toolName,"gen_ai.tool.call.id":i.toolCallId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":{input:()=>JSON.stringify(i.input)}}),o=`execute_tool ${i.toolName}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`tool`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.INTERNAL},t.stepContext),c=n.trace.setSpan(t.stepContext,s);t.toolSpans.set(i.toolCallId,{span:s,context:c})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(g(i,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else m(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onStepFinish(e){this.onStepEnd(e)}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":e.usage.inputTokenDetails?.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(d({text:e.text??void 0,reasoning:e.finalStep.reasoning,toolCalls:e.toolCalls,files:e.files,finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(g(n,{"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.output.messages":{output:()=>e.object==null?void 0:JSON.stringify(f({objectText:JSON.stringify(e.object),finishReason:e.finishReason}))},...C(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0},usage:S(e.usage)})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(g(n,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(n,this.supplementalAttributes,{embedding:r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}}})})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`embeddings`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}})}),o=`embeddings ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`embedding`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext),c=n.trace.setSpan(t.rootContext,s);t.embedSpans.set(e.embedCallId,{span:s,context:c})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(g(i,{"gen_ai.usage.input_tokens":e.usage.tokens,...C(i,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))}}})})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},i=r(e.provider),a=C(t,this.supplementalAttributes,{headers:x(e.headers)}),o=g(t,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":i,"gen_ai.request.model":e.modelId,...a,...C(t,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),s=`rerank ${e.modelId}`,c=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:o,spanType:`operation`,operationId:e.operationId,callId:e.callId,runtimeContext:void 0}),kind:n.SpanKind.CLIENT}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:e.maxRetries},provider:e.provider,modelId:e.modelId,runtimeContext:void 0,baseSupplementalAttributes:a})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:i}=t,a=g(i,{"gen_ai.operation.name":`rerank`,"gen_ai.provider.name":r(t.provider),"gen_ai.request.model":t.modelId,...t.baseSupplementalAttributes,...C(i,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}})}),o=`rerank ${t.modelId}`,s=this.tracer.startSpan(o,{attributes:this.getSpanAttributes({attributes:a,spanType:`reranking`,operationId:t.operationId,callId:e.callId,runtimeContext:t.runtimeContext}),kind:n.SpanKind.CLIENT},t.rootContext);t.rerankSpan={span:s,context:n.trace.setSpan(t.rootContext,s)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(C(r,this.supplementalAttributes,{reranking:{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.inferenceSpan&&(t.inferenceSpan.end(),t.inferenceSpan=void 0,t.inferenceContext=void 0),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;for(let{span:e}of n.toolSpans.values())m(e,r),e.end();n.toolSpans.clear(),n.inferenceSpan&&(m(n.inferenceSpan,r),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0),n.stepSpan&&(m(n.stepSpan,r),n.stepSpan.end(),n.stepSpan=void 0,n.stepContext=void 0);for(let{span:e}of n.embedSpans.values())m(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(m(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),m(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};function T({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function E({model:e,settings:t,headers:n,context:r}){return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...y(r),...Object.entries(n??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}function D(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:O(e.data)}:e)})))}function O(e){switch(e.type){case`data`:return e.data instanceof Uint8Array?t(e.data):e.data;case`url`:return e.url.toString();case`reference`:return e.reference;case`text`:return e.text}}function k(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:n.SpanStatusCode.ERROR,message:t.message})):e.setStatus({code:n.SpanStatusCode.ERROR})}function A(e){return e?.isEnabled!==!1}function j(e,t){if(!A(e))return{};let n={};for(let[r,i]of Object.entries(t))if(i!=null){if(typeof i==`object`&&`input`in i&&typeof i.input==`function`){if(e?.recordInputs===!1)continue;let t=i.input();t!=null&&(n[r]=t);continue}if(typeof i==`object`&&`output`in i&&typeof i.output==`function`){if(e?.recordOutputs===!1)continue;let t=i.output();t!=null&&(n[r]=t);continue}n[r]=i}return n}var M=class{constructor(e={}){this.callStates=new Map,this.tracer=e.tracer??n.trace.getTracer(`ai`)}getCallState(e){return this.callStates.get(e)}cleanupCallState(e){this.callStates.delete(e)}executeTool({callId:e,toolCallId:t,execute:r}){let i=this.getCallState(e)?.toolSpans.get(t);return i==null?r():n.context.with(i.context,r)}executeLanguageModelCall({callId:e,execute:t}){let r=this.getCallState(e)?.stepContext;return r==null?t():n.context.with(r,t)}onStart(e){if(e.operationId===`ai.embed`||e.operationId===`ai.embedMany`){this.onEmbedOperationStart(e);return}if(e.operationId===`ai.rerank`){this.onRerankOperationStart(e);return}if(e.operationId===`ai.generateObject`||e.operationId===`ai.streamObject`){this.onObjectOperationStart(e);return}this.onGenerateStart(e)}onGenerateStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:e.runtimeContext}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt":{input:()=>JSON.stringify({system:e.instructions,messages:e.messages})}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,seed:e.seed,maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.prompt":{input:()=>JSON.stringify({system:e.system,prompt:e.prompt,messages:e.messages})},"ai.schema":e.schema?{input:()=>JSON.stringify(e.schema)}:void 0,"ai.schema.name":e.schemaName,"ai.schema.description":e.schemaDescription,"ai.settings.output":e.output}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onObjectStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamObject`?`ai.streamObject.doStream`:`ai.generateObject.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onObjectStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>{try{return JSON.stringify(JSON.parse(e.objectText))}catch{return e.objectText}}},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),e.msToFirstChunk!=null&&(t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.stream.msToFirstChunk":e.msToFirstChunk}),t.stepSpan.setAttributes({"ai.stream.msToFirstChunk":e.msToFirstChunk})),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onEmbedOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=e.value,o=e.operationId===`ai.embedMany`,s=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,...o?{"ai.values":{input:()=>a.map(e=>JSON.stringify(e))}}:{"ai.value":{input:()=>JSON.stringify(a)}}}),c=this.tracer.startSpan(e.operationId,{attributes:s}),l=n.trace.setSpan(n.context.active(),c);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:c,rootContext:l,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onStepStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=t.operationId===`ai.streamText`?`ai.streamText.doStream`:`ai.generateText.doGenerate`,a=j(r,{...T({operationId:i,telemetry:r}),...t.baseTelemetryAttributes,"ai.model.provider":e.provider,"ai.model.id":e.modelId,"ai.prompt.messages":{input:()=>e.promptMessages?D(e.promptMessages):void 0},"ai.prompt.tools":{input:()=>e.stepTools?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>e.stepToolChoice==null?void 0:JSON.stringify(e.stepToolChoice)},"gen_ai.system":e.provider,"gen_ai.request.model":e.modelId,"gen_ai.request.frequency_penalty":t.settings.frequencyPenalty,"gen_ai.request.max_tokens":t.settings.maxOutputTokens,"gen_ai.request.presence_penalty":t.settings.presencePenalty,"gen_ai.request.stop_sequences":t.settings.stopSequences,"gen_ai.request.temperature":t.settings.temperature??void 0,"gen_ai.request.top_k":t.settings.topK,"gen_ai.request.top_p":t.settings.topP});t.stepSpan=this.tracer.startSpan(i,{attributes:a},t.rootContext),t.stepContext=n.trace.setSpan(t.rootContext,t.stepSpan)}onToolExecutionStart(e){let t=this.getCallState(e.callId);if(!t?.stepContext)return;let{telemetry:r}=t,{toolCall:i}=e,a=j(r,{...T({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":i.toolName,"ai.toolCall.id":i.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(i.input)}}),o=this.tracer.startSpan(`ai.toolCall`,{attributes:a},t.stepContext),s=n.trace.setSpan(t.stepContext,o);t.toolSpans.set(i.toolCallId,{span:o,context:s})}onToolExecutionEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.toolSpans.get(e.toolCall.toolCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t,{toolOutput:a}=e;if(a.type===`tool-result`)try{r.setAttributes(j(i,{"ai.toolCall.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else k(r,a.error);r.end(),t.toolSpans.delete(e.toolCall.toolCallId)}onStepEnd(e){let t=this.getCallState(e.callId);if(!t?.stepSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.streamText`;t.stepSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.reasoning.length>0?e.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
2
2
  `):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.id":e.response.id,"ai.response.model":e.response.modelId,"ai.response.timestamp":e.response.timestamp.toISOString(),"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.response.msToFirstChunk":r?e.performance.timeToFirstOutputMs:void 0,"ai.response.msToFinish":r?e.performance.responseTimeMs:void 0,"ai.response.avgOutputTokensPerSecond":r?e.performance.effectiveOutputTokensPerSecond:void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"gen_ai.response.finish_reasons":[e.finishReason],"gen_ai.response.id":e.response.id,"gen_ai.response.model":e.response.modelId,"gen_ai.usage.input_tokens":e.usage.inputTokens,"gen_ai.usage.output_tokens":e.usage.outputTokens})),r&&e.performance.timeToFirstOutputMs!=null&&t.stepSpan.addEvent(`ai.stream.firstChunk`,{"ai.response.msToFirstChunk":e.performance.timeToFirstOutputMs}),r&&t.stepSpan.addEvent(`ai.stream.finish`,{"ai.response.msToFinish":e.performance.responseTimeMs,"ai.response.avgOutputTokensPerSecond":e.performance.effectiveOutputTokensPerSecond}),t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0}onStepFinish(e){this.onStepEnd(e)}onEnd(e){let t=this.getCallState(e.callId);if(t?.rootSpan){if(t.operationId===`ai.embed`||t.operationId===`ai.embedMany`){this.onEmbedOperationEnd(e);return}if(t.operationId===`ai.rerank`){this.onRerankOperationEnd(e);return}if(t.operationId===`ai.generateObject`||t.operationId===`ai.streamObject`){this.onObjectOperationEnd(e);return}this.onGenerateEnd(e)}}onGenerateEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.text":{output:()=>e.text??void 0},"ai.response.reasoning":{output:()=>e.finalStep.reasoning.length>0?e.finalStep.reasoning.filter(e=>`text`in e).map(e=>e.text).join(`
3
3
  `):void 0},"ai.response.toolCalls":{output:()=>e.toolCalls.length>0?JSON.stringify(e.toolCalls.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}))):void 0},"ai.response.files":{output:()=>e.files.length>0?JSON.stringify(e.files.map(e=>({type:`file`,mediaType:e.mediaType,data:e.base64}))):void 0},"ai.response.providerMetadata":e.finalStep.providerMetadata?JSON.stringify(e.finalStep.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.noCacheTokens":e.usage.inputTokenDetails?.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":e.usage.inputTokenDetails?.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":e.usage.inputTokenDetails?.cacheWriteTokens,"ai.usage.outputTokenDetails.textTokens":e.usage.outputTokenDetails?.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onObjectOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t;t.rootSpan.setAttributes(j(n,{"ai.response.finishReason":e.finishReason,"ai.response.object":{output:()=>e.object==null?void 0:JSON.stringify(e.object)},"ai.response.providerMetadata":e.providerMetadata?JSON.stringify(e.providerMetadata):void 0,"ai.usage.inputTokens":e.usage.inputTokens,"ai.usage.outputTokens":e.usage.outputTokens,"ai.usage.totalTokens":e.usage.totalTokens,"ai.usage.reasoningTokens":e.usage.outputTokenDetails?.reasoningTokens,"ai.usage.cachedInputTokens":e.usage.inputTokenDetails?.cacheReadTokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedOperationEnd(e){let t=this.getCallState(e.callId);if(!t?.rootSpan)return;let{telemetry:n}=t,r=t.operationId===`ai.embedMany`;t.rootSpan.setAttributes(j(n,{...r?{"ai.embeddings":{output:()=>e.embedding.map(e=>JSON.stringify(e))}}:{"ai.embedding":{output:()=>JSON.stringify(e.embedding)}},"ai.usage.tokens":e.usage.tokens})),t.rootSpan.end(),this.cleanupCallState(e.callId)}onEmbedStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=j(r,{...T({operationId:e.operationId,telemetry:r}),...t.baseTelemetryAttributes,"ai.values":{input:()=>e.values.map(e=>JSON.stringify(e))}}),a=this.tracer.startSpan(e.operationId,{attributes:i},t.rootContext),o=n.trace.setSpan(t.rootContext,a);t.embedSpans.set(e.embedCallId,{span:a,context:o})}onEmbedEnd(e){let t=this.getCallState(e.callId);if(!t)return;let n=t.embedSpans.get(e.embedCallId);if(!n)return;let{span:r}=n,{telemetry:i}=t;r.setAttributes(j(i,{"ai.embeddings":{output:()=>e.embeddings.map(e=>JSON.stringify(e))},"ai.usage.tokens":e.usage.tokens})),r.end(),t.embedSpans.delete(e.embedCallId)}onRerankOperationStart(e){let t={recordInputs:e.recordInputs,recordOutputs:e.recordOutputs,functionId:e.functionId},r={maxRetries:e.maxRetries},i=E({model:{provider:e.provider,modelId:e.modelId},headers:e.headers,settings:r,context:void 0}),a=j(t,{...T({operationId:e.operationId,telemetry:t}),...i,"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}),o=this.tracer.startSpan(e.operationId,{attributes:a}),s=n.trace.setSpan(n.context.active(),o);this.callStates.set(e.callId,{operationId:e.operationId,telemetry:t,rootSpan:o,rootContext:s,stepSpan:void 0,stepContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,baseTelemetryAttributes:i,settings:r})}onRerankOperationEnd(e){let t=this.getCallState(e.callId);t?.rootSpan&&(t.rootSpan.end(),this.cleanupCallState(e.callId))}onRerankStart(e){let t=this.getCallState(e.callId);if(!t?.rootSpan||!t.rootContext)return;let{telemetry:r}=t,i=j(r,{...T({operationId:e.operationId,telemetry:r}),...t.baseTelemetryAttributes,"ai.documents":{input:()=>e.documents.map(e=>JSON.stringify(e))}}),a=this.tracer.startSpan(e.operationId,{attributes:i},t.rootContext);t.rerankSpan={span:a,context:n.trace.setSpan(t.rootContext,a)}}onRerankEnd(e){let t=this.getCallState(e.callId);if(!t?.rerankSpan)return;let{span:n}=t.rerankSpan,{telemetry:r}=t;n.setAttributes(j(r,{"ai.ranking.type":e.documentsType,"ai.ranking":{output:()=>e.ranking.map(e=>JSON.stringify(e))}})),n.end(),t.rerankSpan=void 0}onAbort(e){let t=this.getCallState(e.callId);if(t?.rootSpan){for(let{span:e}of t.toolSpans.values())e.end();t.toolSpans.clear(),t.stepSpan&&(t.stepSpan.end(),t.stepSpan=void 0,t.stepContext=void 0);for(let{span:e}of t.embedSpans.values())e.end();t.embedSpans.clear(),t.rerankSpan&&=(t.rerankSpan.span.end(),void 0),t.rootSpan.end(),this.cleanupCallState(e.callId)}}onError(e){let t=e;if(!t?.callId)return;let n=this.getCallState(t.callId);if(!n?.rootSpan)return;let r=t.error??e;n.stepSpan&&(k(n.stepSpan,r),n.stepSpan.end());for(let{span:e}of n.embedSpans.values())k(e,r),e.end();n.embedSpans.clear(),n.rerankSpan&&=(k(n.rerankSpan.span,r),n.rerankSpan.span.end(),void 0),k(n.rootSpan,r),n.rootSpan.end(),this.cleanupCallState(t.callId)}};export{M as LegacyOpenTelemetry,w as OpenTelemetry};
@@ -28,6 +28,9 @@
28
28
  * Commit: 7618ac36 "Wire AES-GCM encryption into serialization layer (#1251)"
29
29
  * https://github.com/vercel/workflow/commit/7618ac36
30
30
  * - `framedByteStreams` (wire-level chunk framing for byte streams): added in `5.0.0-beta.15`
31
+ * - `gzip` (gzip payload compression): added in `5.0.0-beta.18`
32
+ * - `zstd` (zstd payload compression, preferred codec): added in `5.0.0-beta.18`
33
+ * alongside gzip — they co-ship, so any run that can read one can read both.
31
34
  */
32
35
  import { type SerializationFormatType } from './serialization.js';
33
36
  /**
@@ -1,2 +1,2 @@
1
- import{c as e,i as t}from"../../_chunks/workflow/dist-DvHFhSJM.js";import{$n as n,$t as r,L as i,Qt as a,R as o,S as s,Zt as c,cn as l,dn as u,er as d,h as f,ln as p,t as m,tr as h,un as g,w as _}from"../../_chunks/workflow/attribute-changes-Db-CKuLh.js";import{n as v}from"../../_chunks/workflow/resume-hook-Uk1RAmYo.js";import{t as y}from"../../_chunks/workflow/sleep-BG6X2Bli.js";function b(e){d(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,b)}function x(e){d(`createWebhook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook`,x)}function S({schema:e}={}){function t(e){d(`defineHook().create()`,`https://workflow-sdk.dev/docs/api-reference/workflow/define-hook`,t)}return{create:t,async resume(t,n){if(!e?.[`~standard`])return await v(t,n);let r=e[`~standard`].validate(n);if(r instanceof Promise&&(r=await r),r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>String(typeof e==`object`&&e?e.key:e)).join(`.`);return t?` at "${t}": ${e.message}`:` ${e.message}`});throw Error(`Hook payload did not match the defined schema:\n${e.join(`
2
- `)}`)}return await v(t,r.value)}}}async function C(e,n={}){let r=o.getStore(),i=r?.workflowMetadata?.workflowRunId;if(!i)throw new t(`experimental_setAttributes() must be called from a 'use workflow' or 'use step' function. Calling it from plain host code is not supported.`);let a=m(e,n);a.length!==0&&await(await l()).events.create(i,{eventType:`attr_set`,specVersion:4,eventData:{changes:a,writer:{type:`step`,stepId:r.stepMetadata.stepId,attempt:r.stepMetadata.attempt},...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}}})}function w(){let e=o.getStore();return e||n(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,w),e.stepMetadata}function T(){let e=o.getStore();return e||h(`getWorkflowMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-workflow-metadata`,T),e.workflowMetadata}function E(e={}){let t=o.getStore();t||h(`getWritable()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-writable`,E);let{namespace:n}=e,l=t.workflowMetadata.workflowRunId,d=i(l,n),m=t.writables??=new Map,v=m.get(d);if(v)return v.writable;let y=_(s(globalThis,t.ops,l,t.encryptionKey,!0),t.encryptionKey),b=new f(l,d),x=p();return t.ops.push(x.promise),g(y.readable,b,x).catch(()=>{}),u(y.writable,x),Object.defineProperty(y.writable,c,{value:d,writable:!1}),Object.defineProperty(y.writable,r,{value:l,writable:!1}),t.workflowDeploymentId&&Object.defineProperty(y.writable,a,{value:t.workflowDeploymentId,writable:!1}),m.set(d,{writable:y.writable,state:x}),y.writable}export{t as FatalError,e as RetryableError,b as createHook,x as createWebhook,S as defineHook,C as experimental_setAttributes,w as getStepMetadata,T as getWorkflowMetadata,E as getWritable,y as sleep};
1
+ import{c as e,i as t}from"../../_chunks/workflow/dist-Dxrjttr2.js";import{$n as n,$t as r,L as i,Qt as a,R as o,S as s,Zt as c,cn as l,dn as u,er as d,h as f,ln as p,t as m,tr as h,un as g,w as _}from"../../_chunks/workflow/attribute-changes-Bi5DLT8S.js";import{n as v}from"../../_chunks/workflow/resume-hook-CKTw-lb5.js";import{t as y}from"../../_chunks/workflow/sleep-DPjVkRY-.js";function b(e){d(`createHook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-hook`,b)}function x(e){d(`createWebhook()`,`https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook`,x)}function S({schema:e}={}){function t(e){d(`defineHook().create()`,`https://workflow-sdk.dev/docs/api-reference/workflow/define-hook`,t)}return{create:t,async resume(t,n){if(!e?.[`~standard`])return await v(t,n);let r=e[`~standard`].validate(n);if(r instanceof Promise&&(r=await r),r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>String(typeof e==`object`&&e?e.key:e)).join(`.`);return t?` at "${t}": ${e.message}`:` ${e.message}`});throw Error(`Hook payload did not match the defined schema:\n${e.join(`
2
+ `)}`)}return await v(t,r.value)}}}async function C(e,n={}){let r=o.getStore(),i=r?.workflowMetadata?.workflowRunId;if(!i)throw new t(`experimental_setAttributes() must be called from a 'use workflow' or 'use step' function. Calling it from plain host code is not supported.`);let a=m(e,n);a.length!==0&&await(await l()).events.create(i,{eventType:`attr_set`,specVersion:5,eventData:{changes:a,writer:{type:`step`,stepId:r.stepMetadata.stepId,attempt:r.stepMetadata.attempt},...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}}})}function w(){let e=o.getStore();return e||n(`getStepMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata`,w),e.stepMetadata}function T(){let e=o.getStore();return e||h(`getWorkflowMetadata()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-workflow-metadata`,T),e.workflowMetadata}function E(e={}){let t=o.getStore();t||h(`getWritable()`,`https://workflow-sdk.dev/docs/api-reference/workflow/get-writable`,E);let{namespace:n}=e,l=t.workflowMetadata.workflowRunId,d=i(l,n),m=t.writables??=new Map,v=m.get(d);if(v)return v.writable;let y=_(s(globalThis,t.ops,l,t.encryptionKey,!0),t.encryptionKey),b=new f(l,d),x=p();return t.ops.push(x.promise),g(y.readable,b,x).catch(()=>{}),u(y.writable,x),Object.defineProperty(y.writable,c,{value:d,writable:!1}),Object.defineProperty(y.writable,r,{value:l,writable:!1}),t.workflowDeploymentId&&Object.defineProperty(y.writable,a,{value:t.workflowDeploymentId,writable:!1}),m.set(d,{writable:y.writable,state:x}),y.writable}export{t as FatalError,e as RetryableError,b as createHook,x as createWebhook,S as defineHook,C as experimental_setAttributes,w as getStepMetadata,T as getWorkflowMetadata,E as getWritable,y as sleep};
@@ -1 +1 @@
1
- import{a as e}from"../../_chunks/workflow/dist-aOKD_2KN.js";const t=Symbol.for(`@workflow/core//registeredSteps`),n=globalThis,r=n[t]??=new Map,i=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);function a(e){let t=e.split(`//`);if(t.length!==3||t[0]!==`step`)return[];let n=t[1],r=t[2],i=new Set,a=e=>{e!==n&&i.add(e)};if(n.startsWith(`./workflows/`)){let e=n.slice(2);a(`./example/${e}`),a(`./src/${e}`)}else if(n.startsWith(`./example/workflows/`)){let e=n.slice(10);a(`./${e}`),a(`./src/${e}`)}else if(n.startsWith(`./src/workflows/`)){let e=n.slice(6);a(`./${e}`),a(`./example/${e}`)}return Array.from(i,e=>`step//${e}//${r}`)}function o(e){if(i.has(e)){for(let[t,n]of r.entries())if(t.endsWith(`//${e}`))return n}}function s(e,t){r.set(e,t),t.stepId=e}function c(e){let t=r.get(e);if(t)return t;for(let t of a(e)){let e=r.get(t);if(e)return e}let n=o(e);if(n)return n}async function l(e,t,n){if(t===void 0||!e.pendingDeliveryBarriers||e.pendingDeliveryBarriers.size===0)return;let r=[];for(let[i,a]of e.pendingDeliveryBarriers)i<t&&n.includes(a.kind)&&r.push(a.delivered);r.length>0&&await Promise.all(r)}function u(t,n,r){let i=t.pendingDeliveryBarriers;if(!i||n===void 0)return{markDelivered:()=>{}};let a=!1,{promise:o,resolve:s}=e(),c={kind:r,delivered:o};i.set(n,c);let l=()=>{a||(a=!0,i.get(n)===c&&i.delete(n),s())};return d(t,l),{markDelivered:l}}function d(e,t){let n=()=>{e.pendingDeliveries>0?e.promiseQueue.then(()=>{setTimeout(n,0)}):t()};setTimeout(n,0)}export{l as awaitEarlierDeliveries,c as getStepFunction,u as registerDeliveryBarrier,s as registerStepFunction,d as scheduleWhenIdle};
1
+ import{a as e}from"../../_chunks/workflow/dist-FLIfyJ4Y.js";const t=Symbol.for(`@workflow/core//registeredSteps`),n=globalThis,r=n[t]??=new Map,i=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);function a(e){let t=e.split(`//`);if(t.length!==3||t[0]!==`step`)return[];let n=t[1],r=t[2],i=new Set,a=e=>{e!==n&&i.add(e)};if(n.startsWith(`./workflows/`)){let e=n.slice(2);a(`./example/${e}`),a(`./src/${e}`)}else if(n.startsWith(`./example/workflows/`)){let e=n.slice(10);a(`./${e}`),a(`./src/${e}`)}else if(n.startsWith(`./src/workflows/`)){let e=n.slice(6);a(`./${e}`),a(`./example/${e}`)}return Array.from(i,e=>`step//${e}//${r}`)}function o(e){if(i.has(e)){for(let[t,n]of r.entries())if(t.endsWith(`//${e}`))return n}}function s(e,t){r.set(e,t),t.stepId=e}function c(e){let t=r.get(e);if(t)return t;for(let t of a(e)){let e=r.get(t);if(e)return e}let n=o(e);if(n)return n}async function l(e,t,n){if(t===void 0||!e.pendingDeliveryBarriers||e.pendingDeliveryBarriers.size===0)return;let r=[];for(let[i,a]of e.pendingDeliveryBarriers)i<t&&n.includes(a.kind)&&r.push(a.delivered);r.length>0&&await Promise.all(r)}function u(t,n,r){let i=t.pendingDeliveryBarriers;if(!i||n===void 0)return{markDelivered:()=>{}};let a=!1,{promise:o,resolve:s}=e(),c={kind:r,delivered:o};i.set(n,c);let l=()=>{a||(a=!0,i.get(n)===c&&i.delete(n),s())};return d(t,l),{markDelivered:l}}function d(e,t){let n=()=>{e.pendingDeliveries>0?e.promiseQueue.then(()=>{setTimeout(n,0)}):t()};setTimeout(n,0)}export{l as awaitEarlierDeliveries,c as getStepFunction,u as registerDeliveryBarrier,s as registerStepFunction,d as scheduleWhenIdle};
@@ -1,5 +1,12 @@
1
1
  import type { World } from '#compiled/@workflow/world/index.js';
2
2
  import { Run } from './run.js';
3
+ /**
4
+ * Reset the `deploymentId: 'latest'` no-op warn-once guard. Test-only —
5
+ * exported so unit tests can exercise the warn path across `start()` calls.
6
+ *
7
+ * @internal
8
+ */
9
+ export declare function _resetLatestNoOpWarnForTests(): void;
3
10
  export interface StartOptionsBase {
4
11
  /**
5
12
  * The world to use for the workflow run creation,
@@ -39,7 +46,10 @@ export interface StartOptionsWithDeploymentId extends StartOptionsBase {
39
46
  *
40
47
  * Set to `'latest'` to automatically resolve the most recent deployment
41
48
  * for the current environment (same production target or git branch).
42
- * This is currently a Vercel-specific feature.
49
+ * This is only meaningful in worlds with atomic, immutable deployments
50
+ * (currently Vercel). In other worlds (local dev, Postgres) there is no
51
+ * notion of multiple deployments to resolve between, so `'latest'` has no
52
+ * effect — a warning is logged and the run targets the current deployment.
43
53
  *
44
54
  * **Note:** When `deploymentId` is provided, the argument and return types become `unknown`
45
55
  * since there is no guarantee the types will be consistent across deployments.
@@ -10,6 +10,12 @@ export interface StepExecutorParams {
10
10
  stepId: string;
11
11
  stepName: string;
12
12
  encryptionKey?: CryptoKey;
13
+ /**
14
+ * The workflow run's specVersion, used to gate payload compression.
15
+ * Step outputs/errors are only gzip-compressed when the run is marked
16
+ * as possibly containing compressed payloads (specVersion >= 5).
17
+ */
18
+ runSpecVersion?: number;
13
19
  }
14
20
  /**
15
21
  * Result of a step execution attempt. The caller decides what to do