eve 0.15.5 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/channel/compiled-channel.d.ts +2 -0
  3. package/dist/src/channel/cors.d.ts +43 -0
  4. package/dist/src/channel/cors.js +1 -0
  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/agent-info-probe.d.ts +16 -0
  8. package/dist/src/cli/dev/tui/agent-info-probe.js +1 -0
  9. package/dist/src/cli/dev/tui/blocks.js +8 -8
  10. package/dist/src/cli/dev/tui/mcp-connection-status.d.ts +19 -0
  11. package/dist/src/cli/dev/tui/mcp-connection-status.js +1 -0
  12. package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
  13. package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
  14. package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
  15. package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
  16. package/dist/src/cli/dev/tui/runner.d.ts +14 -3
  17. package/dist/src/cli/dev/tui/runner.js +1 -1
  18. package/dist/src/cli/dev/tui/setup-commands.d.ts +10 -1
  19. package/dist/src/cli/dev/tui/setup-commands.js +2 -2
  20. package/dist/src/cli/dev/tui/setup-flow.d.ts +8 -1
  21. package/dist/src/cli/dev/tui/setup-issues.d.ts +2 -14
  22. package/dist/src/cli/dev/tui/setup-issues.js +1 -1
  23. package/dist/src/cli/dev/tui/setup-panel.d.ts +14 -8
  24. package/dist/src/cli/dev/tui/setup-panel.js +3 -3
  25. package/dist/src/cli/dev/tui/terminal-renderer.js +6 -6
  26. package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
  27. package/dist/src/cli/dev/tui/tui.d.ts +2 -3
  28. package/dist/src/cli/dev/tui/tui.js +1 -1
  29. package/dist/src/cli/dev/ui-options.d.ts +21 -0
  30. package/dist/src/cli/dev/ui-options.js +1 -0
  31. package/dist/src/cli/run.d.ts +6 -42
  32. package/dist/src/cli/run.js +2 -2
  33. package/dist/src/compiled/.vendor-stamp.json +1 -1
  34. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +71 -1
  35. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  36. package/dist/src/compiler/manifest.d.ts +8 -2
  37. package/dist/src/compiler/manifest.js +1 -1
  38. package/dist/src/compiler/normalize-channel.js +1 -1
  39. package/dist/src/context/providers/connection-key.d.ts +9 -0
  40. package/dist/src/context/providers/connection-key.js +1 -0
  41. package/dist/src/context/providers/connection.d.ts +1 -9
  42. package/dist/src/context/providers/connection.js +1 -1
  43. package/dist/src/harness/emission.d.ts +3 -3
  44. package/dist/src/harness/emission.js +1 -1
  45. package/dist/src/harness/input-requests.d.ts +1 -0
  46. package/dist/src/harness/input-requests.js +1 -1
  47. package/dist/src/harness/stream-actions.d.ts +17 -0
  48. package/dist/src/harness/stream-actions.js +1 -0
  49. package/dist/src/harness/tool-loop.js +1 -1
  50. package/dist/src/internal/application/package.js +1 -1
  51. package/dist/src/internal/nitro/host/channel-routes.d.ts +2 -0
  52. package/dist/src/internal/nitro/host/channel-routes.js +5 -3
  53. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  54. package/dist/src/internal/nitro/host/dev-authored-source-watcher.d.ts +1 -0
  55. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  56. package/dist/src/internal/nitro/host/start-development-server.d.ts +8 -0
  57. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  58. package/dist/src/internal/nitro/host.d.ts +1 -1
  59. package/dist/src/internal/nitro/host.js +1 -1
  60. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  61. package/dist/src/internal/nitro/routes/dev-runtime-artifacts.d.ts +0 -3
  62. package/dist/src/internal/nitro/routes/dev-runtime-artifacts.js +1 -1
  63. package/dist/src/internal/nitro/routes/info.js +1 -1
  64. package/dist/src/internal/vercel/project-link.d.ts +10 -0
  65. package/dist/src/internal/vercel/project-link.js +1 -0
  66. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  67. package/dist/src/public/channels/auth.d.ts +26 -13
  68. package/dist/src/public/channels/auth.js +1 -1
  69. package/dist/src/public/channels/eve.d.ts +31 -0
  70. package/dist/src/public/channels/eve.js +1 -1
  71. package/dist/src/public/channels/github/githubChannel.js +1 -1
  72. package/dist/src/public/channels/github/inbound-types.d.ts +189 -0
  73. package/dist/src/public/channels/github/inbound-types.js +1 -0
  74. package/dist/src/public/channels/github/inbound.d.ts +2 -190
  75. package/dist/src/public/channels/github/inbound.js +2 -2
  76. package/dist/src/public/channels/index.d.ts +1 -1
  77. package/dist/src/public/definitions/defineChannel.d.ts +10 -0
  78. package/dist/src/public/definitions/defineChannel.js +1 -1
  79. package/dist/src/runtime/agent/mock-model-adapter.d.ts +3 -2
  80. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  81. package/dist/src/runtime/connections/principal.d.ts +2 -0
  82. package/dist/src/runtime/connections/principal.js +1 -1
  83. package/dist/src/runtime/connections/scoped-authorization.d.ts +9 -0
  84. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  85. package/dist/src/runtime/connections/types.d.ts +8 -5
  86. package/dist/src/runtime/framework-channels/index.d.ts +1 -6
  87. package/dist/src/runtime/framework-channels/index.js +1 -1
  88. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  89. package/dist/src/runtime/framework-tools/index.d.ts +1 -1
  90. package/dist/src/runtime/framework-tools/index.js +1 -1
  91. package/dist/src/runtime/framework-tools/skill.js +1 -1
  92. package/dist/src/runtime/governance/auth/oidc.js +1 -1
  93. package/dist/src/runtime/governance/auth/types.d.ts +14 -10
  94. package/dist/src/runtime/governance/auth/vercel-oidc-project.d.ts +12 -0
  95. package/dist/src/runtime/governance/auth/vercel-oidc-project.js +1 -0
  96. package/dist/src/runtime/resolve-channel.js +1 -1
  97. package/dist/src/runtime/types.d.ts +2 -0
  98. package/dist/src/services/dev-client/client-options.d.ts +5 -0
  99. package/dist/src/services/dev-client/client-options.js +1 -1
  100. package/dist/src/services/dev-client/request-headers.d.ts +8 -0
  101. package/dist/src/services/dev-client/request-headers.js +1 -1
  102. package/dist/src/services/dev-client/runtime-artifacts.d.ts +1 -0
  103. package/dist/src/services/dev-client/runtime-artifacts.js +1 -1
  104. package/dist/src/services/dev-client.d.ts +8 -0
  105. package/dist/src/services/dev-client.js +1 -1
  106. package/dist/src/setup/boxes/add-connections.d.ts +10 -8
  107. package/dist/src/setup/boxes/add-connections.js +1 -1
  108. package/dist/src/setup/boxes/resolve-provisioning.d.ts +1 -0
  109. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  110. package/dist/src/setup/boxes/select-connections.js +1 -1
  111. package/dist/src/setup/cli/channel-setup-prompter.d.ts +9 -2
  112. package/dist/src/setup/cli/channel-setup-prompter.js +1 -1
  113. package/dist/src/setup/cli/index.d.ts +1 -1
  114. package/dist/src/setup/cli/option-row.d.ts +2 -0
  115. package/dist/src/setup/cli/option-row.js +1 -1
  116. package/dist/src/setup/cli/prompt-ui.d.ts +2 -0
  117. package/dist/src/setup/cli/select-state.js +1 -1
  118. package/dist/src/setup/connection-connector.d.ts +26 -52
  119. package/dist/src/setup/connection-connector.js +2 -1
  120. package/dist/src/setup/flows/channels.js +1 -1
  121. package/dist/src/setup/flows/connections.d.ts +37 -0
  122. package/dist/src/setup/flows/connections.js +3 -0
  123. package/dist/src/setup/flows/link.d.ts +1 -0
  124. package/dist/src/setup/flows/link.js +1 -1
  125. package/dist/src/setup/project-resolution.d.ts +2 -8
  126. package/dist/src/setup/project-resolution.js +1 -1
  127. package/dist/src/setup/prompter.d.ts +2 -0
  128. package/dist/src/setup/scaffold/connections/catalog.d.ts +10 -5
  129. package/dist/src/setup/scaffold/connections/catalog.js +1 -1
  130. package/dist/src/setup/scaffold/create/project.js +11 -11
  131. package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
  132. package/dist/src/setup/scaffold/create/web-template.js +2 -2
  133. package/dist/src/setup/scaffold/index.d.ts +1 -1
  134. package/dist/src/setup/scaffold/index.js +1 -1
  135. package/dist/src/setup/scaffold/update/connections.d.ts +6 -0
  136. package/dist/src/setup/scaffold/update/connections.js +3 -3
  137. package/docs/channels/custom.mdx +19 -0
  138. package/docs/channels/eve.mdx +26 -3
  139. package/docs/concepts/sessions-runs-and-streaming.md +3 -1
  140. package/docs/connections/mcp.mdx +161 -19
  141. package/docs/connections/openapi.mdx +133 -36
  142. package/docs/connections/overview.mdx +4 -4
  143. package/docs/guides/auth-and-route-protection.md +5 -5
  144. package/docs/guides/dev-tui.md +11 -4
  145. package/docs/guides/frontend/nextjs.mdx +2 -2
  146. package/docs/guides/frontend/nuxt.mdx +2 -2
  147. package/docs/guides/frontend/sveltekit.mdx +2 -2
  148. package/docs/patterns/multi-tenant-approvals.md +4 -0
  149. package/docs/patterns/multi-tenant-auth.md +156 -37
  150. package/docs/reference/cli.md +3 -1
  151. package/docs/tools/human-in-the-loop.md +3 -1
  152. package/docs/tutorial/ship-it.mdx +1 -1
  153. package/docs/tutorial/team-playbooks.mdx +1 -1
  154. package/package.json +2 -2
  155. package/dist/src/internal/nitro/host/dev-rebuild-registry.d.ts +0 -5
  156. package/dist/src/internal/nitro/host/dev-rebuild-registry.js +0 -1
@@ -273,6 +273,37 @@ type MCPTransportConfig = {
273
273
  * @default 'error'
274
274
  */
275
275
  redirect?: 'follow' | 'error';
276
+ /**
277
+ * Initial MCP session id to send with resumed Streamable HTTP requests after
278
+ * initialization.
279
+ * Only used by the HTTP transport.
280
+ */
281
+ initialSessionId?: string;
282
+ /**
283
+ * Initial MCP protocol version to send before initialize negotiates one.
284
+ * Only used by the HTTP transport.
285
+ */
286
+ initialProtocolVersion?: string;
287
+ /**
288
+ * Called when the Streamable HTTP server creates, changes, or clears the MCP
289
+ * session id.
290
+ * Only used by the HTTP transport.
291
+ */
292
+ onSessionIdChange?: (sessionId: string | undefined) => void;
293
+ /**
294
+ * Called when a Streamable HTTP request returns 404 for an existing MCP
295
+ * session id. The transport clears the session id before reporting the
296
+ * underlying HTTP error.
297
+ * Only used by the HTTP transport.
298
+ */
299
+ onSessionExpired?: (sessionId: string) => void;
300
+ /**
301
+ * Whether close() should send DELETE for the current MCP session id.
302
+ * Set to false when the application intends to reattach to the session later.
303
+ * Only used by the HTTP transport.
304
+ * @default true
305
+ */
306
+ terminateSessionOnClose?: boolean;
276
307
  /**
277
308
  * Optional custom fetch implementation to use for HTTP requests.
278
309
  * Useful for runtimes that need a request-local fetch.
@@ -337,6 +368,34 @@ declare const ClientCapabilitiesSchema: z.ZodObject<{
337
368
  }, z.core.$loose>>;
338
369
  }, z.core.$loose>;
339
370
  type ClientCapabilities = z.infer<typeof ClientCapabilitiesSchema>;
371
+ declare const InitializeResultSchema: z.ZodObject<{
372
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
373
+ protocolVersion: z.ZodString;
374
+ capabilities: z.ZodObject<{
375
+ experimental: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
376
+ logging: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
377
+ prompts: z.ZodOptional<z.ZodObject<{
378
+ listChanged: z.ZodOptional<z.ZodBoolean>;
379
+ }, z.core.$loose>>;
380
+ resources: z.ZodOptional<z.ZodObject<{
381
+ subscribe: z.ZodOptional<z.ZodBoolean>;
382
+ listChanged: z.ZodOptional<z.ZodBoolean>;
383
+ }, z.core.$loose>>;
384
+ tools: z.ZodOptional<z.ZodObject<{
385
+ listChanged: z.ZodOptional<z.ZodBoolean>;
386
+ }, z.core.$loose>>;
387
+ elicitation: z.ZodOptional<z.ZodObject<{
388
+ applyDefaults: z.ZodOptional<z.ZodBoolean>;
389
+ }, z.core.$loose>>;
390
+ }, z.core.$loose>;
391
+ serverInfo: z.ZodObject<{
392
+ name: z.ZodString;
393
+ version: z.ZodString;
394
+ title: z.ZodOptional<z.ZodString>;
395
+ }, z.core.$loose>;
396
+ instructions: z.ZodOptional<z.ZodString>;
397
+ }, z.core.$loose>;
398
+ type InitializeResult = z.infer<typeof InitializeResultSchema>;
340
399
  type PaginatedRequest = Request & {
341
400
  params?: BaseParams & {
342
401
  cursor?: string;
@@ -513,6 +572,12 @@ interface MCPClientConfig {
513
572
  transport: MCPTransportConfig | MCPTransport;
514
573
  /** Optional callback for uncaught errors */
515
574
  onUncaughtError?: (error: unknown) => void;
575
+ /**
576
+ * Initialize result from a previous MCP session. When provided, the client
577
+ * starts the transport and reuses this metadata without sending a new
578
+ * initialize request.
579
+ */
580
+ initialInitializeResult?: InitializeResult;
516
581
  /** Optional client name, defaults to 'ai-sdk-mcp-client' */
517
582
  clientName?: string;
518
583
  /**
@@ -537,6 +602,11 @@ interface MCPClient {
537
602
  * @see https://modelcontextprotocol.io/specification/2025-11-25/schema#implementation
538
603
  */
539
604
  readonly serverInfo: Configuration;
605
+ /**
606
+ * The full initialize result used by this client, either from the server
607
+ * during initialization or from `initialInitializeResult`.
608
+ */
609
+ readonly initializeResult: InitializeResult;
540
610
  /**
541
611
  * Optional instructions provided by the server during the initialize handshake.
542
612
  *
@@ -651,4 +721,4 @@ declare function readMCPAppResource({ client, uri, options, }: {
651
721
  options?: RequestOptions;
652
722
  }): Promise<MCPAppResource>;
653
723
 
654
- export { type CallToolResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools };
724
+ export { type CallToolResult, type Configuration, type ElicitResult, ElicitResultSchema, type ElicitationRequest, ElicitationRequestSchema, type InitializeResult, type JSONRPCError, type JSONRPCMessage, type JSONRPCNotification, type JSONRPCRequest, type JSONRPCResponse, type ListToolsResult, type MCPAppResource, type MCPAppResourceCSP, type MCPAppResourceMeta, type MCPClient, type ClientCapabilities as MCPClientCapabilities, type MCPClientConfig, type MCPTransport, MCP_APP_MIME_TYPE, type McpProviderMetadata, type OAuthAuthorizationServerInformation, type OAuthClientInformation, type OAuthClientMetadata, type OAuthClientProvider, type OAuthTokens, UnauthorizedError, auth, createMCPClient, type MCPClient as experimental_MCPClient, type ClientCapabilities as experimental_MCPClientCapabilities, type MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, mcpAppClientCapabilities, readMCPAppResource, splitMCPAppTools };
@@ -1 +1 @@
1
- import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-D7CzPkf8.js";const oe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){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[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var Ce=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),E=T.extend({nextCursor:v(m())}),we=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),Te=E.extend({tools:h(we)}),D=p({type:g(`text`),text:m()}).loose(),O=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Ee=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),De=E.extend({resources:h(Ee)}),k=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),A=k.extend({text:m()}),j=k.extend({blob:u()}),M=p({type:g(`resource`),resource:l([A,j])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([D,O,M,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([A,j]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=E.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([D,O,M,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).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`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},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 tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(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 rt({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 it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(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 dt({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 ft(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 pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(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 Ge.parse(await r.json())}function _t(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 vt(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 yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(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=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(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 bt(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 fe(),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 xt(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 St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(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 wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(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):St(xt(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 Y(p);return We.parse(await p.json())}async function Dt(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):St(xt(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 Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(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=ot(await Ot(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 ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(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:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}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.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??C};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({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 S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({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:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}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 S({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new 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 S({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 Mt(e){return e===void 0||e===`message`}var Nt=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??C};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 i(t,`ai-sdk/${Ue}`,o())}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(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 S({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(r=!1)=>{var i,a,o,s,c,l;try{let l={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},u=await this.fetchFn(this.url.href,l),d=u.headers.get(`mcp-session-id`);if(d&&(this.sessionId=d),u.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(u);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(u.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!u.ok){let e=await u.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${u.status}): ${e}`;u.status===404&&(t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:u.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let f=u.headers.get(`content-type`)||``;if(f.includes(`application/json`)){let e=await u.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(f.includes(`text/event-stream`)){if(!u.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:u.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).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(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({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 p=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`,statusCode:u.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,p),p}catch(e){throw(l=this.onerror)==null||l.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 S({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 r,i,a,o;try{let o=await this.commonHeaders({Accept:`text/event-stream`});t&&(o[`last-event-id`]=t);let s=await this.fetchFn(this.url.href,{method:`GET`,headers:o,signal:this.abortController?.signal,redirect:this.redirectMode}),c=s.headers.get(`mcp-session-id`);if(c&&(this.sessionId=c),s.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(s);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(s.status===405)return;if(!s.ok||!s.body){let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${s.status} ${s.statusText}`,statusCode:s.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=s.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({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:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(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 Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(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 Wt({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(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,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??{},Ft(e)?this.transport=e:this.transport=Pt(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 S({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:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:Ce});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});if(!_e.includes(e.protocolVersion))throw new S({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 S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({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 S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({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:Te,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ke,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:De,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Me,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:je,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async 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:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({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 s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({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!==N)throw new S({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=N.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=ze.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new S({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 S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
1
+ import{AISDKError as e,isJSONObject as t}from"../provider/index.js";import{$ as n,I as r,J as i,K as a,S as o,U as s,W as c,_t as l,at as u,bt as d,dt as f,ft as p,ht as m,i as ee,it as h,k as te,lt as g,mt as ne,n as re,ot as _,pt as v,rt as ie,ut as y,vt as b,y as ae}from"../../_chunks/workflow/dist-D7CzPkf8.js";const oe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var se;se||={};let x;x=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function ce(e){return(await x).getRandomValues(new Uint8Array(e))}async function le(e){let t=``;for(;t.length<e;){let n=await ce(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function ue(e){return await le(e)}async function de(e){let t=await(await x).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function fe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ue(e);return{code_verifier:t,code_challenge:await de(t)}}var pe=`vercel.ai.error.AI_MCPClientError`,me=Symbol.for(pe),he,ge,S=class extends (ge=e,he=me,ge){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[he]=!0,this.data=r,this.code=i,this.statusCode=a,this.url=o,this.responseBody=s}static isInstance(t){return e.hasMarker(t,pe)}},C=`2025-11-25`,_e=[C,`2025-06-18`,`2025-03-26`,`2024-11-05`],ve=v(ne(m(),b())),ye=y({name:m(),version:m(),title:v(m())}),w=y({_meta:v(p({}).loose())}),T=w,be=p({method:m(),params:v(w)}),xe=p({applyDefaults:v(_())}).loose(),Se=y({experimental:v(p({}).loose()),logging:v(p({}).loose()),prompts:v(y({listChanged:v(_())})),resources:v(y({subscribe:v(_()),listChanged:v(_())})),tools:v(y({listChanged:v(_())})),elicitation:v(xe)});p({elicitation:v(xe)}).loose();var E=T.extend({protocolVersion:m(),capabilities:Se,serverInfo:ye,instructions:v(m())}),D=T.extend({nextCursor:v(m())}),Ce=p({name:m(),title:v(m()),description:v(m()),inputSchema:p({type:g(`object`),properties:v(p({}).loose())}).loose(),outputSchema:v(p({}).loose()),annotations:v(p({title:v(m())}).loose()),_meta:ve}).loose(),we=D.extend({tools:h(Ce)}),O=p({type:g(`text`),text:m()}).loose(),k=p({type:g(`image`),data:u(),mimeType:m()}).loose(),Te=p({uri:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m()),size:v(f())}).loose(),Ee=D.extend({resources:h(Te)}),A=p({uri:m(),name:v(m()),title:v(m()),mimeType:v(m())}).loose(),j=A.extend({text:m()}),M=A.extend({blob:u()}),De=p({type:g(`resource`),resource:l([j,M])}).loose(),Oe=p({type:g(`resource_link`),uri:m(),name:m(),description:v(m()),mimeType:v(m())}).loose(),ke=T.extend({content:h(l([O,k,De,Oe])),structuredContent:v(b()),isError:_().default(!1).optional()}).or(T.extend({toolResult:b()})),Ae=p({uriTemplate:m(),name:m(),title:v(m()),description:v(m()),mimeType:v(m())}).loose(),je=T.extend({resourceTemplates:h(Ae)}),Me=T.extend({contents:h(l([j,M]))}),Ne=p({name:m(),description:v(m()),required:v(_())}).loose(),Pe=p({name:m(),title:v(m()),description:v(m()),arguments:v(h(Ne))}).loose(),Fe=D.extend({prompts:h(Pe)}),Ie=p({role:l([g(`user`),g(`assistant`)]),content:l([O,k,De,Oe])}).loose(),Le=T.extend({description:v(m()),messages:h(Ie)}),Re=w.extend({message:m(),requestedSchema:b()}),N=be.extend({method:g(`elicitation/create`),params:Re}),ze=T.extend({action:l([g(`accept`),g(`decline`),g(`cancel`)]),content:v(ne(m(),b()))}),P=`2.0`,Be=p({jsonrpc:g(P),id:l([m(),f().int()])}).merge(be).strict(),Ve=p({jsonrpc:g(P),id:l([m(),f().int()]),result:T}).strict(),He=p({jsonrpc:g(P),id:l([m(),f().int()]),error:p({code:f().int(),message:m(),data:v(b())})}).strict(),F=l([Be,p({jsonrpc:g(P)}).merge(p({method:m(),params:v(w)})).strict(),Ve,He]);async function I(e){return F.parse(await r({text:e}))}var Ue=typeof __PACKAGE_VERSION__<`u`?__PACKAGE_VERSION__:`0.0.0-test`,L=m().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:oe.custom,message:`URL must be parseable`,fatal:!0}),d}).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`}),We=p({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:f().optional(),scope:m().optional(),refresh_token:m().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Ge=p({resource:m().url(),authorization_servers:h(L).optional(),jwks_uri:m().url().optional(),scopes_supported:h(m()).optional(),bearer_methods_supported:h(m()).optional(),resource_signing_alg_values_supported:h(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:_().optional(),authorization_details_types_supported:h(m()).optional(),dpop_signing_alg_values_supported:h(m()).optional(),dpop_bound_access_tokens_required:_().optional()}).passthrough(),R=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),code_challenge_methods_supported:h(m()),token_endpoint_auth_methods_supported:h(m()).optional(),token_endpoint_auth_signing_alg_values_supported:h(m()).optional()}).passthrough(),Ke=p({issuer:m(),authorization_endpoint:L,token_endpoint:L,userinfo_endpoint:L.optional(),jwks_uri:L,registration_endpoint:L.optional(),scopes_supported:h(m()).optional(),response_types_supported:h(m()),grant_types_supported:h(m()).optional(),subject_types_supported:h(m()),id_token_signing_alg_values_supported:h(m()),claims_supported:h(m()).optional(),token_endpoint_auth_methods_supported:h(m()).optional()}).passthrough().merge(R.pick({code_challenge_methods_supported:!0})),qe=p({client_id:m(),client_secret:m().optional(),client_id_issued_at:f().optional(),client_secret_expires_at:f().optional(),authorization_server:L.optional(),token_endpoint:L.optional()}).strip(),Je=p({redirect_uris:h(L),token_endpoint_auth_method:m().optional(),grant_types:h(m()).optional(),response_types:h(m()).optional(),client_name:m().optional(),client_uri:L.optional(),logo_uri:L.optional(),scope:m().optional(),contacts:h(m()).optional(),tos_uri:L.optional(),policy_uri:m().optional(),jwks_uri:L.optional(),jwks:ie().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),Ye=p({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xe=Je.merge(qe),Ze=`vercel.ai.error.AI_MCPClientOAuthError`,Qe=Symbol.for(Ze),$e,et,z=class extends (et=e,$e=Qe,et){constructor({name:e=`MCPClientOAuthError`,message:t,cause:n}){super({name:e,message:t,cause:n}),this[$e]=!0}static isInstance(t){return e.hasMarker(t,Ze)}},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 tt={[B.errorCode]:B,[V.errorCode]:V,[H.errorCode]:H,[U.errorCode]:U};function nt(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 rt({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 it(e,t){return{authorizationServerUrl:K(e),tokenEndpoint:K(t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e))}}function at(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function ot(e,t){return{...e,authorization_server:t.authorizationServerUrl,token_endpoint:t.tokenEndpoint}}function st(e){if(!(!e?.authorization_server||!e.token_endpoint))return{authorizationServerUrl:K(e.authorization_server),tokenEndpoint:K(e.token_endpoint)}}async function ct({provider:e,clientInformation:t,tokens:n}){let r=st(n);if(r)return r;let i=await e.authorizationServerInformation?.call(e);return i?{authorizationServerUrl:K(i.authorizationServerUrl),tokenEndpoint:K(i.tokenEndpoint)}:st(t)}async function lt({provider:e,clientInformation:t,authorizationServerInformation:n}){return e.saveAuthorizationServerInformation?(await e.saveAuthorizationServerInformation(n),!0):e.saveClientInformation?(await e.saveClientInformation(ot(t,n)),!0):!1}function ut(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 dt({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 ft(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 pt(e,t,n=fetch){return await J(e,{"MCP-Protocol-Version":t},n)}function mt(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function ht(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??C,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=ft(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await pt(o,a,n);return!r?.metadataUrl&&mt(s,i.pathname)&&(s=await pt(new URL(`/.well-known/${t}`,i),a,n)),s}async function gt(e,t,n=fetch){let r=await ht(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 Ge.parse(await r.json())}function _t(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 vt(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 yt(e,{fetchFn:t=fetch,protocolVersion:n=C}={}){let r={"MCP-Protocol-Version":n},i=_t(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=R.parse(await i.json());return vt(e,a),e}else{let t=Ke.parse(await i.json());if(vt(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 bt(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 fe(),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 xt(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 St(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Ct(i,a,n);return;case`client_secret_post`:wt(i,a,r);return;case`none`:Tt(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Ct(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 wt(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Tt(e,t){t.set(`client_id`,e)}async function Y(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=Ye.parse(await r({text:n}));return new(tt[e]||B)({message:t||``,cause:i})}catch(e){return new B({message:`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`})}}async function Et(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):St(xt(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 Y(p);return We.parse(await p.json())}async function Dt(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):St(xt(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 Y(d);return We.parse({refresh_token:r,...await d.json()})}async function Ot(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Y(a);return Xe.parse(await a.json())}async function X(e,t){try{return await Z(e,t)}catch(n){if(n instanceof V||n instanceof U)return await e.invalidateCredentials?.call(e,`all`),await Z(e,t);if(n instanceof H)return await e.invalidateCredentials?.call(e,`tokens`),await Z(e,t);throw n}}async function kt(e,t,n){let r=nt(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!rt({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function Z(e,{serverUrl:t,authorizationCode:n,callbackState:r,scope:i,resourceMetadataUrl:a,fetchFn:o}){let s,c;ut(t,a);try{s=await gt(t,{resourceMetadataUrl:a},o),s.authorization_servers&&s.authorization_servers.length>0&&(c=s.authorization_servers[0])}catch{}c||=t;let l=await kt(t,e,s);await e.validateAuthorizationServerURL?.call(e,t,c);let u=await yt(c,{fetchFn:o}),d=it(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=ot(await Ot(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 ct({provider:e,clientInformation:f});if(!t)throw new z({message:`Stored OAuth authorization server metadata is required when exchanging an authorization code`});dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d});let i=await e.codeVerifier(),a=await Et(c,{metadata:u,clientInformation:f,authorizationCode:n,codeVerifier:i,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(a,d)),`AUTHORIZED`}let p=await e.tokens();if(p?.refresh_token){let t=await ct({provider:e,clientInformation:f,tokens:p});t?dt({storedAuthorizationServerInformation:t,currentAuthorizationServerInformation:d}):await e.invalidateCredentials?.call(e,`tokens`);try{if(t){let t=await Dt(c,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(at(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:ee,codeVerifier:h}=await bt(c,{metadata:u,clientInformation:f,state:m,redirectUrl:e.redirectUrl,scope:i||e.clientMetadata.scope,resource:l});if(!await lt({provider:e,clientInformation:f,authorizationServerInformation:d}))throw new z({message:`OAuth authorization server metadata must be saveable before starting authorization`});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(ee),`REDIRECT`}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.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??C};if(this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(t.Authorization=`Bearer ${e.access_token}`)}return i(t,`ai-sdk/${Ue}`,o())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;let r=async(i=!1)=>{var a,o,s,c;try{let c=await this.commonHeaders({Accept:`text/event-stream`}),l=await this.fetchFn(this.url.href,{headers:c,signal:this.abortController?.signal,redirect:this.redirectMode});if(l.status===401&&this.authProvider&&!i){this.resourceMetadataUrl=q(l);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new G;return(a=this.onerror)==null||a.call(this,e),t(e)}}catch(e){return(o=this.onerror)==null||o.call(this,e),t(e)}return r(!0)}if(!l.ok||!l.body){let e=`MCP SSE Transport Error: ${l.status} ${l.statusText}`;l.status===405&&(e+=". This server does not support SSE transport. Try using `http` transport instead");let n=new S({message:e});return(s=this.onerror)==null||s.call(this,n),t(n)}let u=l.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),d=async()=>{var n,r,i,a,o;try{for(;;){let{done:t,value:o}=await u.read();if(t){if(this.connected)throw this.connected=!1,new S({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 S({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${t.origin}`});this.endpoint=t,this.connected=!0,e()}else if(At(s))try{let e=await I(c);(i=this.onmessage)==null||i.call(this,e)}catch(e){let t=new S({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:()=>u.cancel()},d()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(c=this.onerror)==null||c.call(this,e),t(e)}};r()})}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 S({message:`MCP SSE Transport Error: Not connected`});let t=this.endpoint,n=async(r=!1)=>{var i,a,o,s;try{let s={method:`POST`,headers:await this.commonHeaders({"Content-Type":`application/json`}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},c=await this.fetchFn(t.href,s);if(c.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(c);try{if(await X(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl,fetchFn:this.fetchFn})!==`AUTHORIZED`){let e=new 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 S({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 Mt(e){return e===void 0||e===`message`}var Nt=class{constructor({url:e,headers:t,authProvider:n,redirect:r=`error`,initialSessionId:i,initialProtocolVersion:a,onSessionIdChange:o,onSessionExpired:s,terminateSessionOnClose:c=!0,fetch:l}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=n,this.redirectMode=r,this.sessionId=i,this.protocolVersion=a,this.onSessionIdChange=o,this.onSessionExpired=s,this.terminateSessionOnClose=c,this.fetchFn=l??globalThis.fetch}setProtocolVersion(e){this.protocolVersion=e}async commonHeaders({base:e,includeSessionId:t=!0}){let n={...this.headers,...e,"mcp-protocol-version":this.protocolVersion??C};if(t&&this.sessionId&&(n[`mcp-session-id`]=this.sessionId),this.authProvider){let e=await this.authProvider.tokens();e?.access_token&&(n.Authorization=`Bearer ${e.access_token}`)}return i(n,`ai-sdk/${Ue}`,o())}setSessionId(e){var t;this.sessionId!==e&&(this.sessionId=e,(t=this.onSessionIdChange)==null||t.call(this,e))}applySessionIdFromResponse(e){let t=e.headers.get(`mcp-session-id`);t&&this.setSessionId(t)}expireSessionId(e){var t;this.sessionId===e&&this.setSessionId(void 0),(t=this.onSessionExpired)==null||t.call(this,e)}authorizeOnce(e){return this.authProvider?(this.authPromise||=X(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 S({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.terminateSessionOnClose&&this.abortController&&!this.abortController.signal.aborted){let e=await this.commonHeaders({base:{}});await this.fetchFn(this.url.href,{method:`DELETE`,headers:e,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>void 0)}}catch{}(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){let t=async(r=!1)=>{var i,a,o,s,c,l;try{let l=`method`in e&&e.method===`initialize`,u=l?void 0:this.sessionId,d={method:`POST`,headers:await this.commonHeaders({base:{"Content-Type":`application/json`,Accept:`application/json, text/event-stream`},includeSessionId:!l}),body:JSON.stringify(e),signal:this.abortController?.signal,redirect:this.redirectMode},f=await this.fetchFn(this.url.href,d);if(this.applySessionIdFromResponse(f),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=q(f);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`)throw new G}catch(e){throw(i=this.onerror)==null||i.call(this,e),e}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){let e=await f.text().catch(()=>null),t=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${e}`;f.status===404&&(u?(this.expireSessionId(u),t+=". The MCP session expired. Create a new client without `initialSessionId` to start a fresh session"):t+=". This server does not support HTTP transport. Try using `sse` transport instead");let n=new S({message:t,statusCode:f.status,url:this.url.href,responseBody:e??void 0});throw(a=this.onerror)==null||a.call(this,n),n}if(!(`id`in e))return;let p=f.headers.get(`content-type`)||``;if(p.includes(`application/json`)){let e=await f.json(),t=Array.isArray(e)?e.map(e=>F.parse(e)):[F.parse(e)];for(let e of t)(o=this.onmessage)==null||o.call(this,e);return}if(p.includes(`text/event-stream`)){if(!f.body){let e=new S({message:`MCP HTTP Transport Error: text/event-stream response without body`,statusCode:f.status,url:this.url.href});throw(s=this.onerror)==null||s.call(this,e),e}let e=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).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(Mt(a))try{let e=await I(o);(t=this.onmessage)==null||t.call(this,e)}catch(e){let t=new S({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 m=new S({message:`MCP HTTP Transport Error: Unexpected content type: ${p}`,statusCode:f.status,url:this.url.href});throw(c=this.onerror)==null||c.call(this,m),m}catch(e){throw(l=this.onerror)==null||l.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 S({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 r,i,a,o;try{let o=this.sessionId,s=await this.commonHeaders({base:{Accept:`text/event-stream`}});t&&(s[`last-event-id`]=t);let c=await this.fetchFn(this.url.href,{method:`GET`,headers:s,signal:this.abortController?.signal,redirect:this.redirectMode});if(this.applySessionIdFromResponse(c),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=q(c);try{if(await this.authorizeOnce(this.resourceMetadataUrl)!==`AUTHORIZED`){let e=new G;(r=this.onerror)==null||r.call(this,e);return}}catch(e){(i=this.onerror)==null||i.call(this,e);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){c.status===404&&o&&this.expireSessionId(o);let e=new S({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`,statusCode:c.status,url:this.url.href});(a=this.onerror)==null||a.call(this,e);return}let l=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new n).getReader(),u=async()=>{var e,t,n;try{for(;;){let{done:n,value:r}=await l.read();if(n)return;let{event:i,data:a,id:o}=r;if(o&&(this.lastInboundEventId=o),Mt(i))try{let t=await I(a);(e=this.onmessage)==null||e.call(this,t)}catch(e){let n=new S({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:()=>l.cancel()},this.inboundReconnectAttempts=0,u()}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;(o=this.onerror)==null||o.call(this,e),this.abortController?.signal.aborted||this.scheduleInboundSseReconnection()}}};function Pt(e){switch(e.type){case`sse`:return new jt(e);case`http`:return new Nt(e);default:throw new S({message:`Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface.`})}}function Ft(e){return`start`in e&&typeof e.start==`function`&&`send`in e&&typeof e.send==`function`&&`close`in e&&typeof e.close==`function`}var It=`io.modelcontextprotocol/ui`,Q=`text/html;profile=mcp-app`,Lt=`ui/resourceUri`,Rt={extensions:{[It]:{mimeTypes:[Q]}}};function zt(e){let n=e?.ui;return t(n)?n:void 0}function Bt(e){let n=(t(e)?e:void 0)?.ui;return t(n)?n:void 0}function Vt(e){return Array.isArray(e)?e.filter(e=>e===`model`||e===`app`):void 0}function Ht(e){let t=zt(e._meta),n=t?.resourceUri??e._meta?.[Lt],r=Vt(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 Ut(e){let t=[],n=[];for(let r of e.tools){let e=Ht(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 Wt({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(ee(n.blob)):void 0;if(r==null)throw Error(`Unsupported MCP App resource content format: ${e}`);return{uri:e,mimeType:Q,html:r,meta:Bt(n._meta)}}async function Gt({client:e,uri:t,options:n}){if(!t.startsWith(`ui://`))throw Error(`Unsupported MCP App resource URI: ${t}`);return Wt({uri:t,resource:await e.readResource({uri:t,options:n})})}var Kt=`1.0.0`;function qt({output:e}){let t=e;return!(`content`in t)||!Array.isArray(t.content)?{type:`json`,value:t}:{type:`content`,value:t.content.map(e=>e.type===`text`&&`text`in e?{type:`text`,text:e.text}:e.type===`image`&&`data`in e&&`mimeType`in e?{type:`file`,mediaType:e.mimeType,data:{type:`data`,data:e.data}}:{type:`text`,text:JSON.stringify(e)})}}async function $(e){let t=new Jt(e);return await t.init(),t}var Jt=class{constructor({transport:e,name:t,clientName:n=t??`ai-sdk-mcp-client`,version:r=Kt,onUncaughtError:i,capabilities:a,initialInitializeResult:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this._serverInfo={name:``,version:``},this._initializeResult={protocolVersion:C,capabilities:{},serverInfo:this._serverInfo},this.isClosed=!0,this.onUncaughtError=i,this.clientCapabilities=a??{},this.initialInitializeResult=o,Ft(e)?this.transport=e:this.transport=Pt(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 S({message:`Unsupported message type`}));return}this.onResponse(e)},this.clientInfo={name:n,version:r}}get serverInfo(){return this._serverInfo}get initializeResult(){return this._initializeResult}get instructions(){return this._serverInstructions}async init(){try{if(await this.transport.start(),this.isClosed=!1,this.initialInitializeResult){let e=E.parse(this.initialInitializeResult);return this.applyInitializeResult(e),this}let e=await this.request({request:{method:`initialize`,params:{protocolVersion:C,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:E});if(e===void 0)throw new S({message:`Server sent invalid initialize result`});return this.applyInitializeResult(e),await this.notification({method:`notifications/initialized`}),this}catch(e){throw await this.close(),e}}applyInitializeResult(e){if(!_e.includes(e.protocolVersion))throw new S({message:`Server's protocol version is not supported: ${e.protocolVersion}`});this.serverCapabilities=e.capabilities,this._serverInfo=e.serverInfo,this._initializeResult=e,this.transport.setProtocolVersion?this.transport.setProtocolVersion(e.protocolVersion):this.transport.protocolVersion=e.protocolVersion,this._serverInstructions=e.instructions}async close(){this.isClosed||(await this.transport?.close(),this.onClose())}assertCapability(e){switch(e){case`initialize`:break;case`tools/list`:case`tools/call`:if(!this.serverCapabilities.tools)throw new S({message:`Server does not support tools`});break;case`resources/list`:case`resources/read`:case`resources/templates/list`:if(!this.serverCapabilities.resources)throw new S({message:`Server does not support resources`});break;case`prompts/list`:case`prompts/get`:if(!this.serverCapabilities.prompts)throw new S({message:`Server does not support prompts`});break;default:throw new S({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,i)=>{if(this.isClosed)return i(new S({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 S({message:`Request was aborted`,cause:a.reason}));if(e instanceof Error)return i(e);try{r(t.parse(e.result))}catch(e){i(new S({message:`Failed to parse server response`,cause:e}))}}),this.transport.send(s).catch(e=>{c(),i(e)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:`tools/list`,params:e},resultSchema:we,options:t})}async callTool({name:e,arguments:t={},options:n}){try{return this.request({request:{method:`tools/call`,params:{name:e,arguments:t}},resultSchema:ke,options:n})}catch(e){throw e}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:`resources/list`,params:e},resultSchema:Ee,options:t})}catch(e){throw e}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:`resources/read`,params:{uri:e}},resultSchema:Me,options:t})}catch(e){throw e}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:`resources/templates/list`},resultSchema:je,options:e})}catch(e){throw e}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:`prompts/list`,params:e},resultSchema:Fe,options:t})}catch(e){throw e}}async getPromptInternal({name:e,args:t,options:n}){try{return this.request({request:{method:`prompts/get`,params:{name:e,arguments:t}},resultSchema:Le,options:n})}catch(e){throw e}}async 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:o,inputSchema:s,annotations:c,_meta:l}of e.tools){let e=i??c?.title;if(t!==`automatic`&&!Object.prototype.hasOwnProperty.call(t,r))continue;let u=this,d=t===`automatic`?void 0:t[r]?.outputSchema,f=Ht({_meta:l}),p={clientName:this.clientInfo.name,toolName:r,...e==null?{}:{title:e},...f?.resourceUri==null?{}:{app:{...f,mimeType:Q}}},m=async(e,t)=>{var n;(n=t?.abortSignal)==null||n.throwIfAborted();let i=await u.callTool({name:r,arguments:e,options:{signal:t?.abortSignal}});return i.isError||d==null?i:u.extractStructuredContent(i,d,r)};n[r]={...t===`automatic`?ae({description:o,title:e,metadata:p,inputSchema:te({...s,properties:s.properties??{},additionalProperties:!1}),execute:m,toModelOutput:qt}):a({description:o,title:e,metadata:p,inputSchema:t[r].inputSchema,...d==null?{}:{outputSchema:d},execute:m,toModelOutput:qt}),_meta:l}}return n}async extractStructuredContent(e,t,n){if(`structuredContent`in e&&e.structuredContent!=null){let r=await c({value:e.structuredContent,schema:re(t)});if(!r.success)throw new S({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 s({text:r.text,schema:t});if(!e.success)throw new S({message:`Tool "${n}" returned content that does not match the expected outputSchema`,cause:e.error});return e.value}}throw new S({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!==N)throw new S({message:`Unsupported request schema. Only ElicitationRequestSchema is supported.`});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method===`ping`){await this.transport.send({jsonrpc:`2.0`,id:e.id,result:{}});return}if(e.method!==`elicitation/create`){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`No elicitation handler registered on client`}});return}let t=N.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{let n=await this.elicitationRequestHandler(t.data),r=ze.parse(n);await this.transport.send({jsonrpc:`2.0`,id:e.id,result:r})}catch(t){await this.transport.send({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:t instanceof Error?t.message:`Failed to handle elicitation request`}}),this.onError(t)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;let e=new S({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 S({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n(`result`in e?e:new S({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};export{ze as ElicitResultSchema,N as ElicitationRequestSchema,Q as MCP_APP_MIME_TYPE,G as UnauthorizedError,X as auth,$ as createMCPClient,$ as experimental_createMCPClient,Rt as mcpAppClientCapabilities,Gt as readMCPAppResource,Ut as splitMCPAppTools};
@@ -2,6 +2,7 @@ import { z } from "#compiled/zod/index.js";
2
2
  import { type DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
3
3
  import { type CompiledRemoteAgentNode } from "#compiler/remote-agent-node.js";
4
4
  import type { ChannelRouteMethod } from "#public/definitions/channel.js";
5
+ import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
5
6
  import type { Node } from "#shared/node.js";
6
7
  import type { MarkdownSourceRef, ModuleSourceRef, SkillPackageSourceRef } from "#shared/source-ref.js";
7
8
  import type { NamedSkillDefinition } from "#shared/skill-definition.js";
@@ -18,7 +19,7 @@ export declare const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
18
19
  /**
19
20
  * Current compiled manifest schema version.
20
21
  */
21
- export declare const COMPILED_AGENT_MANIFEST_VERSION = 30;
22
+ export declare const COMPILED_AGENT_MANIFEST_VERSION = 31;
22
23
  /**
23
24
  * Compiled channel entry preserved in the compiled manifest.
24
25
  */
@@ -45,6 +46,11 @@ export interface CompiledChannelDefinition {
45
46
  * Omitted when the route does not register an adapter.
46
47
  */
47
48
  readonly adapterKind?: string;
49
+ /**
50
+ * Serializable CORS options to apply to this channel route. Omitted when the
51
+ * channel leaves CORS untouched.
52
+ */
53
+ readonly cors?: NormalizedChannelCorsOptions;
48
54
  }
49
55
  /**
50
56
  * Disabled compiled channel entry — marker that an authored file at this
@@ -449,7 +455,7 @@ export declare const compiledAgentManifestSchema: z.ZodObject<{
449
455
  sourceId: z.ZodString;
450
456
  sourceKind: z.ZodLiteral<"module">;
451
457
  }, z.core.$strict>>;
452
- version: z.ZodLiteral<30>;
458
+ version: z.ZodLiteral<31>;
453
459
  workspaceResourceRoot: z.ZodObject<{
454
460
  contentHash: z.ZodOptional<z.ZodString>;
455
461
  logicalPath: z.ZodString;
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`eve-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=30,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`WEBSOCKET`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),modelRoutingSchema=z.union([z.object({kind:z.literal(`gateway`),target:z.string(),byok:z.string().optional()}).strict(),z.object({kind:z.literal(`external`),provider:z.string()}).strict()]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional(),routing:modelRoutingSchema}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentWorkflowWorldDefinitionSchema=z.string(),compiledAgentWorkflowDefinitionSchema=z.object({world:compiledAgentWorkflowWorldDefinitionSchema.optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),experimental:z.object({workflow:compiledAgentWorkflowDefinitionSchema.optional()}).strict().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),outputSchema:jsonObjectSchema.optional(),reasoning:z.enum([`provider-default`,`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({backendName:z.string().optional(),description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),revalidationKey:z.string().optional(),sourceHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),protocol:z.enum([`mcp`,`openapi`]).default(`mcp`),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),outputSchema:jsonObjectSchema.optional(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),workflowEnabled:z.boolean().default(!1),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),workflowEnabled:z.boolean().default(!1),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(30),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,experimental:e.config.experimental===void 0?void 0:{workflow:e.config.experimental.workflow===void 0?void 0:{world:e.config.experimental.workflow.world}},model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,outputSchema:e.config.outputSchema,reasoning:e.config.reasoning,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],workflowEnabled:e.workflowEnabled??!1,dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:30}}function cloneCompiledRuntimeModelReference(e){let t={id:e.id,routing:cloneModelRouting(e.routing)};return e.contextWindowTokens!==void 0&&(t.contextWindowTokens=e.contextWindowTokens),e.providerOptions!==void 0&&(t.providerOptions={...e.providerOptions}),e.source!==void 0&&(t.source={...e.source}),t}function cloneModelRouting(e){return e.kind===`external`?{kind:`external`,provider:e.provider}:e.byok===void 0?{kind:`gateway`,target:e.target}:{kind:`gateway`,target:e.target,byok:e.byok}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
1
+ import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`eve-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=31,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`WEBSOCKET`)]),compiledChannelCorsSchema=z.object({origin:z.union([z.literal(`*`),z.literal(`null`),z.array(z.string())]).optional(),methods:z.union([z.literal(`*`),z.array(z.string())]).optional(),allowHeaders:z.union([z.literal(`*`),z.array(z.string())]).optional(),exposeHeaders:z.union([z.literal(`*`),z.array(z.string())]).optional(),credentials:z.boolean().optional(),maxAge:z.union([z.string(),z.literal(!1)]).optional(),preflight:z.object({statusCode:z.number().int().min(100).max(599).optional()}).strict().optional()}).strict(),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional(),cors:compiledChannelCorsSchema.optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),modelRoutingSchema=z.union([z.object({kind:z.literal(`gateway`),target:z.string(),byok:z.string().optional()}).strict(),z.object({kind:z.literal(`external`),provider:z.string()}).strict()]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional(),routing:modelRoutingSchema}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentWorkflowWorldDefinitionSchema=z.string(),compiledAgentWorkflowDefinitionSchema=z.object({world:compiledAgentWorkflowWorldDefinitionSchema.optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),experimental:z.object({workflow:compiledAgentWorkflowDefinitionSchema.optional()}).strict().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),outputSchema:jsonObjectSchema.optional(),reasoning:z.enum([`provider-default`,`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({backendName:z.string().optional(),description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),revalidationKey:z.string().optional(),sourceHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),protocol:z.enum([`mcp`,`openapi`]).default(`mcp`),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),outputSchema:jsonObjectSchema.optional(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),workflowEnabled:z.boolean().default(!1),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),workflowEnabled:z.boolean().default(!1),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(31),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,experimental:e.config.experimental===void 0?void 0:{workflow:e.config.experimental.workflow===void 0?void 0:{world:e.config.experimental.workflow.world}},model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,outputSchema:e.config.outputSchema,reasoning:e.config.reasoning,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],workflowEnabled:e.workflowEnabled??!1,dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:31}}function cloneCompiledRuntimeModelReference(e){let t={id:e.id,routing:cloneModelRouting(e.routing)};return e.contextWindowTokens!==void 0&&(t.contextWindowTokens=e.contextWindowTokens),e.providerOptions!==void 0&&(t.providerOptions={...e.providerOptions}),e.source!==void 0&&(t.source={...e.source}),t}function cloneModelRouting(e){return e.kind===`external`?{kind:`external`,provider:e.provider}:e.byok===void 0?{kind:`gateway`,target:e.target}:{kind:`gateway`,target:e.target,byok:e.byok}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
@@ -1 +1 @@
1
- import{stripLogicalPathExtension}from"#discover/filesystem.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{normalizeChannelDefinition}from"#internal/authored-definition/channel.js";import{isDisabledRouteSentinel}from"#public/definitions/channel.js";async function compileChannelDefinition(n,r,i={}){let a=await loadModuleBackedDefinition({agentRoot:n,externalDependencies:i.externalDependencies,kind:`channel`,source:r}),o=stripLogicalPathExtension(r.logicalPath).replace(/^channels\//,``);if(isDisabledRouteSentinel(a))return{kind:`disabled`,name:o,logicalPath:r.logicalPath};let s=normalizeChannelDefinition(a,`Expected the channel export "${r.exportName??`default`}" from "${r.logicalPath}" to match the public eve shape.`);return s.routes.map(e=>({kind:`channel`,name:o,logicalPath:r.logicalPath,method:e.method.toUpperCase(),urlPath:e.path,sourceId:r.sourceId,sourceKind:`module`,exportName:r.exportName,adapterKind:extractAdapterKind(s.adapter)}))}function extractAdapterKind(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}export{compileChannelDefinition};
1
+ import{stripLogicalPathExtension}from"#discover/filesystem.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{normalizeChannelDefinition}from"#internal/authored-definition/channel.js";import{isDisabledRouteSentinel}from"#public/definitions/channel.js";async function compileChannelDefinition(n,r,i={}){let a=await loadModuleBackedDefinition({agentRoot:n,externalDependencies:i.externalDependencies,kind:`channel`,source:r}),o=stripLogicalPathExtension(r.logicalPath).replace(/^channels\//,``);if(isDisabledRouteSentinel(a))return{kind:`disabled`,name:o,logicalPath:r.logicalPath};let s=normalizeChannelDefinition(a,`Expected the channel export "${r.exportName??`default`}" from "${r.logicalPath}" to match the public eve shape.`);return s.routes.map(e=>({kind:`channel`,name:o,logicalPath:r.logicalPath,method:e.method.toUpperCase(),urlPath:e.path,sourceId:r.sourceId,sourceKind:`module`,exportName:r.exportName,adapterKind:extractAdapterKind(s.adapter),cors:s.cors}))}function extractAdapterKind(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}export{compileChannelDefinition};
@@ -0,0 +1,9 @@
1
+ import { ContextKey } from "#context/key.js";
2
+ import type { ConnectionRegistry } from "#runtime/connections/types.js";
3
+ /**
4
+ * Context key for the per-session connection registry.
5
+ *
6
+ * Defined separately from the provider so framework tools can read the key
7
+ * without importing connection client setup into the framework-tools bundle.
8
+ */
9
+ export declare const ConnectionRegistryKey: ContextKey<ConnectionRegistry>;
@@ -0,0 +1 @@
1
+ import{ContextKey}from"#context/key.js";const ConnectionRegistryKey=new ContextKey(`eve.connectionRegistry`);export{ConnectionRegistryKey};
@@ -1,12 +1,4 @@
1
- import { ContextKey } from "#context/key.js";
2
1
  import type { ConnectionRegistry } from "#runtime/connections/types.js";
3
2
  import type { FrameworkContextProvider } from "#context/provider.js";
4
- /**
5
- * Context key for the per-session connection registry.
6
- *
7
- * Created as a derived key (no codec) because the registry holds live
8
- * client instances that cannot be serialized across step boundaries.
9
- * The `connectionProvider` reconstructs it each step.
10
- */
11
- export declare const ConnectionRegistryKey: ContextKey<ConnectionRegistry>;
3
+ export { ConnectionRegistryKey } from "#context/providers/connection-key.js";
12
4
  export declare const connectionProvider: FrameworkContextProvider<ConnectionRegistry>;
@@ -1 +1 @@
1
- import{ContextKey}from"#context/key.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{ConnectionRegistryImpl}from"#runtime/connections/registry.js";import{getActiveRuntimeNode}from"#context/node.js";const ConnectionRegistryKey=new ContextKey(`eve.connectionRegistry`),connectionProvider={key:ConnectionRegistryKey,create(e,t){if(e.get(BundleKey)===void 0)return;let n=getActiveRuntimeNode(e).agent?.connections;if(!(!n||n.length===0))return{value:new ConnectionRegistryImpl(n)}}};export{ConnectionRegistryKey,connectionProvider};
1
+ import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{ConnectionRegistryKey,ConnectionRegistryKey as ConnectionRegistryKey$1}from"#context/providers/connection-key.js";import{ConnectionRegistryImpl}from"#runtime/connections/registry.js";import{getActiveRuntimeNode}from"#context/node.js";const connectionProvider={key:ConnectionRegistryKey$1,create(e,t){if(e.get(BundleKey)===void 0)return;let n=getActiveRuntimeNode(e).agent?.connections;if(!(!n||n.length===0))return{value:new ConnectionRegistryImpl(n)}}};export{ConnectionRegistryKey,connectionProvider};
@@ -109,9 +109,9 @@ interface StreamActionEmissionOptions {
109
109
  * Consumes the AI SDK `fullStream` and emits real-time text and reasoning
110
110
  * events.
111
111
  *
112
- * Emits local and provider tool results in source order. A result without a
113
- * streamed call resumes a call from an earlier step. `emitStepActions` emits
114
- * the remaining events.
112
+ * Emits local tool events in source order. Provider calls that arrive in one
113
+ * stream batch into one request event before their first result. A result
114
+ * without a streamed call resumes a call from an earlier step.
115
115
  */
116
116
  export declare function emitStreamContent(emitFn: HarnessEmitFn, state: HarnessEmissionState, fullStream: AsyncIterable<TextStreamPart<ToolSet>>, options?: StreamActionEmissionOptions): Promise<EmittedStreamContent>;
117
117
  export {};
@@ -1 +1 @@
1
- import{toError}from"#shared/errors.js";import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{createRuntimeActionRequestFromToolCall,resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(a,o,s,c){let l=``,u=``,d=`stop`,f,p=new Set,m=new Set,h=new Set,g=new Set,_=[],v=[],flushCurrentMessage=async()=>{u.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``)},emitActionRequest=async e=>{m.has(e.callId)||(u.trim().length>0&&await flushCurrentMessage(),m.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitProviderToolCall=async e=>{await emitActionRequest({callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName})},emitActionResult=async e=>{h.has(e.callId)||(h.add(e.callId),await a(createActionResultEvent({result:e,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(!(c===void 0||e.invalid===!0||c.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:c.tools}))}catch(e){if(e instanceof TypeError)return;throw e}};for await(let t of s)if(f===void 0)switch(t.type){case`reasoning-delta`:l+=t.text,await a(createReasoningAppendedEvent({reasoningDelta:t.text,reasoningSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:l.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``),u+=t.text,await a(createMessageAppendedEvent({messageDelta:t.text,messageSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=t;p.add(e.toolCallId),e.providerExecuted===!0?await emitProviderToolCall(e):await emitToolCall(e);break}case`tool-result`:{let e=t;if(e.preliminary===!0)break;if(e.providerExecuted===!0){await emitProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await emitActionResult(createRuntimeToolResultFromStepResult(e));break}if(p.has(t.toolCallId)){if(isInlineAuthorizationToolResult(e))break;m.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(e)),g.add(t.toolCallId));break}if(await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){g.add(t.toolCallId),_.push(e);break}await emitActionResult(createRuntimeToolResultFromStepResult(e)),g.add(t.toolCallId);let n=e.output;v.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n??null}});break}case`tool-error`:{let n=t;n.providerExecuted===!0?(await emitProviderToolCall(n),await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName}))):m.has(n.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName})),g.add(n.toolCallId));break}case`finish-step`:d=normalizeAssistantStepFinishReason(t.finishReason);break;case`error`:f=toError(t.error);break;default:break}if(f!==void 0)throw f;return l.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d!==`tool-calls`&&hasEmptyDeliverySentinel(u)?await a(createMessageCompletedEvent({finishReason:d,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):u.trim().length>0&&await a(createMessageCompletedEvent({finishReason:d,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:m,handledInlineToolResultCallIds:g,inlineAuthorizationResults:_,inlineToolResultParts:v}}function isInlineAuthorizationToolResult(e){if(isPendingAuthorizationToolOutput(e.output))return!0;let t=contextStorage.getStore();if(t===void 0)return!1;let n=readToolInterrupt(t,e.toolCallId);return n!==void 0&&isAuthorizationSignal(n)}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
1
+ import{toError}from"#shared/errors.js";import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{createRuntimeActionRequestFromToolCall,resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(a,o,s,c){let l=``,u=``,d=`stop`,f,p=new Set,m=new Set,h=new Set,g=new Set,_=createProviderStreamActionBatch({emitFn:a,state:o}),v=new Set,y=[],b=[],flushCurrentMessage=async()=>{u.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``)},emitActionRequest=async e=>{m.has(e.callId)||(u.trim().length>0&&await flushCurrentMessage(),m.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{g.has(e.toolCallId)||(g.add(e.toolCallId),!m.has(e.toolCallId)&&(m.add(e.toolCallId),u.trim().length>0&&await flushCurrentMessage(),_.observe({callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName})))},emitActionResult=async e=>{h.has(e.callId)||(h.add(e.callId),await a(createActionResultEvent({result:e,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(!(c===void 0||e.invalid===!0||c.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:c.tools}))}catch(e){if(e instanceof TypeError)return;throw e}};for await(let t of s)if(f===void 0)switch(t.type){case`reasoning-delta`:await _.flush(),l+=t.text,await a(createReasoningAppendedEvent({reasoningDelta:t.text,reasoningSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await _.flush(),l.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``),u+=t.text,await a(createMessageAppendedEvent({messageDelta:t.text,messageSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=t;p.add(e.toolCallId),e.providerExecuted===!0?await collectProviderToolCall(e):(await _.flush(),await emitToolCall(e));break}case`tool-result`:{let e=t;if(e.preliminary===!0)break;if(e.providerExecuted===!0){await collectProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await _.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(e));break}if(p.has(t.toolCallId)){if(isInlineAuthorizationToolResult(e))break;m.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId));break}if(await _.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){v.add(t.toolCallId),y.push(e);break}await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId);let n=e.output;b.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n??null}});break}case`tool-error`:{let n=t;n.providerExecuted===!0?(await collectProviderToolCall(n),await _.flush(),await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName}))):m.has(n.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName})),v.add(n.toolCallId));break}case`finish-step`:d=normalizeAssistantStepFinishReason(t.finishReason),await _.flush();break;case`error`:f=toError(t.error);break;default:break}if(await _.flush(),f!==void 0)throw f;return l.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d!==`tool-calls`&&hasEmptyDeliverySentinel(u)?await a(createMessageCompletedEvent({finishReason:d,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):u.trim().length>0&&await a(createMessageCompletedEvent({finishReason:d,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:m,handledInlineToolResultCallIds:v,inlineAuthorizationResults:y,inlineToolResultParts:b}}function isInlineAuthorizationToolResult(e){if(isPendingAuthorizationToolOutput(e.output))return!0;let t=contextStorage.getStore();if(t===void 0)return!1;let n=readToolInterrupt(t,e.toolCallId);return n!==void 0&&isAuthorizationSignal(n)}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
@@ -60,6 +60,7 @@ export declare function resolvePendingInput(input: {
60
60
  readonly stepInput?: StepInput;
61
61
  }): ResolvePendingInputResult;
62
62
  type ResolvePendingInputResult = {
63
+ readonly consumedMessage?: boolean;
63
64
  readonly deferredMessage?: boolean;
64
65
  readonly outcome: "resolved" | "continue" | "unresolved";
65
66
  readonly messages: ModelMessage[];
@@ -1 +1 @@
1
- import{parseJsonObject}from"#shared/json.js";import{coalesceTurnInputs}from"#harness/messages.js";const PENDING_INPUT_BATCH_KEY=`eve.runtime.pendingInputBatch`,APPROVED_TOOLS_KEY=`eve.runtime.hitl.approvedTools`,DEFERRED_STEP_INPUT_KEY=`eve.runtime.deferredStepInput`;function hasStepInput(e){return e===void 0?!1:e.message!==void 0||(e.inputResponses?.length??0)>0}function consumeDeferredStepInput(e){let n=getDeferredStepInput(e.session);if(n===void 0)return e;let r=clearDeferredStepInput(e.session);return e.input===void 0?{input:n,session:r}:{input:coalesceTurnInputs(n,e.input),session:r}}function hasDeferredStepInput(e){return getDeferredStepInput(e)!==void 0}function resolvePendingInput(e){let{stepInput:t}=e,n=e.session,r=[...e.history??n.history],i=getPendingInputBatch(n.state);if(i===void 0)return{outcome:`continue`,messages:r,session:n};let a=t?.inputResponses??[];if(a.length===0&&t?.message===void 0)return{outcome:`unresolved`,messages:r,session:n};if(a.length===0&&t?.message!==void 0){let e=buildToolResponseParts(i,[]),a=[...r,...i.responseMessages];e.length>0&&a.push({content:e,role:`tool`});let o=buildRejectedActionBatch(i,[]);return n=clearPendingInputBatch(n),i.requests.some(e=>isApprovalRequest(e))?(n=queueDeferredStepInput(n,{message:t.message}),{deferredMessage:!0,outcome:`resolved`,messages:a,rejectedActions:o,session:n}):{outcome:`resolved`,messages:a,rejectedActions:o,session:n}}n=recordApprovedTools({pendingBatch:i,resolveApprovalKey:e.resolveApprovalKey,responses:a,session:n});let o=buildToolResponseParts(i,a),s=[...r,...i.responseMessages];o.length>0&&s.push({content:o,role:`tool`});let c=buildRejectedActionBatch(i,a);return n=clearPendingInputBatch(n),t?.message!==void 0&&i.requests.some(e=>isApprovalRequest(e))?(n=queueDeferredStepInput(n,{message:t.message}),{deferredMessage:!0,outcome:`resolved`,messages:s,rejectedActions:c,session:n}):{outcome:`resolved`,messages:s,rejectedActions:c,session:n}}function hasPendingInputBatch(e){return getPendingInputBatch(e)!==void 0}function getPendingInputBatch(e){let t=e?.[PENDING_INPUT_BATCH_KEY];if(typeof t!=`object`||!t)return;let r=t;if(!(!Array.isArray(r.requests)||!Array.isArray(r.responseMessages)))return r}function setPendingInputBatch(e){let t={...e.session.state};return t[PENDING_INPUT_BATCH_KEY]={event:e.event,requests:[...e.requests],responseMessages:[...e.responseMessages]},{...e.session,state:t}}function clearPendingInputBatch(e){if(e.state?.[PENDING_INPUT_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_INPUT_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function getDeferredStepInput(e){return e.state?.[DEFERRED_STEP_INPUT_KEY]}function queueDeferredStepInput(e,n){let r=getDeferredStepInput(e),a=r===void 0?n:coalesceTurnInputs(r,n),o={...e.state};return o[DEFERRED_STEP_INPUT_KEY]=a,{...e,state:o}}function clearDeferredStepInput(e){if(e.state?.[DEFERRED_STEP_INPUT_KEY]===void 0)return e;let t={...e.state};return delete t[DEFERRED_STEP_INPUT_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function getApprovedTools(e){let t=e.state?.[APPROVED_TOOLS_KEY];return Array.isArray(t)?new Set(t):new Set}function recordApprovedTools(e){let t=new Set(e.responses.filter(e=>e.optionId===`approve`).map(e=>e.requestId)),n=e.pendingBatch.requests.filter(e=>t.has(e.requestId)).map(t=>e.resolveApprovalKey?.(t)??t.action.toolName);if(n.length===0)return e.session;let i=getApprovedTools(e.session),a=[...new Set([...i,...n])],o={...e.session.state};return o[APPROVED_TOOLS_KEY]=a,{...e.session,state:o}}function resolveApprovalOutcome(e){return{approved:e?.optionId===`approve`,reason:e===void 0?`Ignored because the user continued without responding.`:void 0}}function buildRejectedActionBatch(e,t){if(e.event===void 0)return;let n=new Map(t.map(e=>[e.requestId,e])),r=[];for(let t of e.requests){if(!isApprovalRequest(t))continue;let{approved:e,reason:i}=resolveApprovalOutcome(n.get(t.requestId));e||r.push({callId:t.action.callId,isError:!0,kind:`tool-result`,output:{code:`TOOL_EXECUTION_DENIED`,message:i??`Tool execution was denied.`},toolName:t.action.toolName})}return r.length>0?{event:e.event,results:r}:void 0}function buildToolResponseParts(e,t){let n=new Map(t.map(e=>[e.requestId,e])),r=[];for(let t of e.requests)r.push(...buildToolResponsePartsForRequest(t,n.get(t.requestId)));return r}function buildToolResponsePartsForRequest(e,t){if(isApprovalRequest(e)){let{approved:n,reason:r}=resolveApprovalOutcome(t),i=[{approvalId:e.requestId,approved:n,reason:r,type:`tool-approval-response`}];return n||i.push({output:{type:`execution-denied`,reason:r},toolCallId:e.action.callId,toolName:e.action.toolName,type:`tool-result`}),i}return[{output:{type:`json`,value:t===void 0?{status:`ignored`}:{optionId:t.optionId,text:t.text,status:`answered`}},toolCallId:e.action.callId,toolName:e.action.toolName,type:`tool-result`}]}function isApprovalRequest(e){return e.options?.length===2&&e.options[0]?.id===`approve`&&e.options[1]?.id===`deny`}function createRuntimeToolCallActionFromToolCall(e){return{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(t){return t==null?{}:parseJsonObject(t)}export{consumeDeferredStepInput,createRuntimeToolCallActionFromToolCall,getApprovedTools,hasDeferredStepInput,hasPendingInputBatch,hasStepInput,resolvePendingInput,setPendingInputBatch};
1
+ import{resolveTextToResponses}from"#channel/resolve-text.js";import{parseJsonObject}from"#shared/json.js";import{coalesceTurnInputs}from"#harness/messages.js";const PENDING_INPUT_BATCH_KEY=`eve.runtime.pendingInputBatch`,APPROVED_TOOLS_KEY=`eve.runtime.hitl.approvedTools`,DEFERRED_STEP_INPUT_KEY=`eve.runtime.deferredStepInput`,TOOL_EXECUTION_DENIED_MESSAGE=`Tool execution was denied.`;function hasStepInput(e){return e===void 0?!1:e.message!==void 0||(e.inputResponses?.length??0)>0}function consumeDeferredStepInput(e){let t=getDeferredStepInput(e.session);if(t===void 0)return e;let r=clearDeferredStepInput(e.session);return e.input===void 0?{input:t,session:r}:{input:coalesceTurnInputs(t,e.input),session:r}}function hasDeferredStepInput(e){return getDeferredStepInput(e)!==void 0}function resolvePendingInput(e){let{stepInput:t}=e,n=e.session,r=[...e.history??n.history],i=getPendingInputBatch(n.state);if(i===void 0)return{outcome:`continue`,messages:r,session:n};let a=resolveTextMessageInput(i,t),o=a?.inputResponses??[];if(o.length===0&&a?.message===void 0)return{outcome:`unresolved`,messages:r,session:n};if(i.requests.some(e=>isApprovalRequest(e))&&hasUnansweredApproval({pendingBatch:i,responses:o}))return n=queueDeferredStepInput(n,compactStepInput(a)),{deferredMessage:!0,outcome:`unresolved`,messages:r,session:n};if(o.length===0&&a?.message!==void 0){let e=buildToolResponseParts(i,[]),t=[...r,...i.responseMessages];e.length>0&&t.push({content:e,role:`tool`});let o=buildRejectedActionBatch(i,[]);return n=clearPendingInputBatch(n),{consumedMessage:a?.messageConsumed,outcome:`resolved`,messages:t,rejectedActions:o,session:n}}n=recordApprovedTools({pendingBatch:i,resolveApprovalKey:e.resolveApprovalKey,responses:o,session:n});let s=buildToolResponseParts(i,o),c=[...r,...i.responseMessages];s.length>0&&c.push({content:s,role:`tool`});let l=buildRejectedActionBatch(i,o);return n=clearPendingInputBatch(n),a?.message!==void 0&&i.requests.some(e=>isApprovalRequest(e))?(n=queueDeferredStepInput(n,{message:a.message}),{consumedMessage:a?.messageConsumed,deferredMessage:!0,outcome:`resolved`,messages:c,rejectedActions:l,session:n}):{consumedMessage:a?.messageConsumed,outcome:`resolved`,messages:c,rejectedActions:l,session:n}}function resolveTextMessageInput(t,n){if(typeof n?.message!=`string`||(n.inputResponses?.length??0)>0)return n;let r=resolveTextToResponses(n.message,t.requests);return r.length===0?n:compactStepInput({...n,inputResponses:r,messageConsumed:!0,message:void 0})}function compactStepInput(e){if(e===void 0)return{};let t={};return(e.context?.length??0)>0&&(t.context=e.context),(e.inputResponses?.length??0)>0&&(t.inputResponses=e.inputResponses),e.message!==void 0&&(t.message=e.message),e.messageConsumed===!0&&(t.messageConsumed=!0),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),t}function hasUnansweredApproval(e){let t=new Set(e.responses.map(e=>e.requestId));return e.pendingBatch.requests.some(e=>isApprovalRequest(e)&&!t.has(e.requestId))}function hasPendingInputBatch(e){return getPendingInputBatch(e)!==void 0}function getPendingInputBatch(e){let t=e?.[PENDING_INPUT_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.requests)||!Array.isArray(n.responseMessages)))return n}function setPendingInputBatch(e){let t={...e.session.state};return t[PENDING_INPUT_BATCH_KEY]={event:e.event,requests:[...e.requests],responseMessages:[...e.responseMessages]},{...e.session,state:t}}function clearPendingInputBatch(e){if(e.state?.[PENDING_INPUT_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_INPUT_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function getDeferredStepInput(e){return e.state?.[DEFERRED_STEP_INPUT_KEY]}function queueDeferredStepInput(e,t){let r=getDeferredStepInput(e),i=r===void 0?t:coalesceTurnInputs(r,t),o={...e.state};return o[DEFERRED_STEP_INPUT_KEY]=i,{...e,state:o}}function clearDeferredStepInput(e){if(e.state?.[DEFERRED_STEP_INPUT_KEY]===void 0)return e;let t={...e.state};return delete t[DEFERRED_STEP_INPUT_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function getApprovedTools(e){let t=e.state?.[APPROVED_TOOLS_KEY];return Array.isArray(t)?new Set(t):new Set}function recordApprovedTools(e){let t=new Set(e.responses.filter(e=>e.optionId===`approve`).map(e=>e.requestId)),n=e.pendingBatch.requests.filter(e=>t.has(e.requestId)).map(t=>e.resolveApprovalKey?.(t)??t.action.toolName);if(n.length===0)return e.session;let r=getApprovedTools(e.session),a=[...new Set([...r,...n])],o={...e.session.state};return o[APPROVED_TOOLS_KEY]=a,{...e.session,state:o}}function resolveApprovalOutcome(e){return e===void 0?{approved:!1,reason:`Ignored because the user continued without responding.`,status:`ignored`}:e.optionId===`approve`?{approved:!0,reason:void 0,status:`approved`}:e.optionId===`deny`?{approved:!1,reason:TOOL_EXECUTION_DENIED_MESSAGE,status:`denied`}:{approved:!1,reason:`Invalid approval response.`,status:`invalid`}}function buildRejectedActionBatch(e,t){if(e.event===void 0)return;let n=new Map(t.map(e=>[e.requestId,e])),r=[];for(let t of e.requests){if(!isApprovalRequest(t))continue;let{approved:e,reason:i,status:a}=resolveApprovalOutcome(n.get(t.requestId));e||r.push({callId:t.action.callId,isError:!0,kind:`tool-result`,output:{approval:{requestId:t.requestId,status:a},code:`TOOL_EXECUTION_DENIED`,message:i??TOOL_EXECUTION_DENIED_MESSAGE,tool:{result:`not_run`}},toolName:t.action.toolName})}return r.length>0?{event:e.event,results:r}:void 0}function buildToolResponseParts(e,t){let n=new Map(t.map(e=>[e.requestId,e])),r=[];for(let t of e.requests)r.push(...buildToolResponsePartsForRequest(t,n.get(t.requestId)));return r}function buildToolResponsePartsForRequest(e,t){if(isApprovalRequest(e)){let{approved:n,reason:r}=resolveApprovalOutcome(t),i=[{approvalId:e.requestId,approved:n,reason:r,type:`tool-approval-response`}];return n||i.push({output:{type:`execution-denied`,reason:r},toolCallId:e.action.callId,toolName:e.action.toolName,type:`tool-result`}),i}return[{output:{type:`json`,value:t===void 0?{status:`ignored`}:{optionId:t.optionId,text:t.text,status:`answered`}},toolCallId:e.action.callId,toolName:e.action.toolName,type:`tool-result`}]}function isApprovalRequest(e){return e.options?.length===2&&e.options[0]?.id===`approve`&&e.options[1]?.id===`deny`}function createRuntimeToolCallActionFromToolCall(e){return{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e){return e==null?{}:parseJsonObject(e)}export{consumeDeferredStepInput,createRuntimeToolCallActionFromToolCall,getApprovedTools,hasDeferredStepInput,hasPendingInputBatch,hasStepInput,resolvePendingInput,setPendingInputBatch};
@@ -0,0 +1,17 @@
1
+ import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
2
+ import type { HarnessEmitFn } from "#harness/types.js";
3
+ interface ActionEventCoordinates {
4
+ readonly sequence: number;
5
+ readonly stepIndex: number;
6
+ readonly turnId: string;
7
+ }
8
+ interface ProviderStreamActionBatch {
9
+ flush(): Promise<void>;
10
+ observe(action: RuntimeToolCallActionRequest): void;
11
+ }
12
+ /** Batches provider-managed calls that arrive in one streamed model response. */
13
+ export declare function createProviderStreamActionBatch(input: {
14
+ readonly emitFn: HarnessEmitFn;
15
+ readonly state: ActionEventCoordinates;
16
+ }): ProviderStreamActionBatch;
17
+ export {};
@@ -0,0 +1 @@
1
+ import{createActionsRequestedEvent}from"#protocol/message.js";function createProviderStreamActionBatch(t){let n=new Map,r=Promise.resolve(),i,a,o,emitPendingActions=async()=>{if(n.size===0)return;let r=[...n.values()];n.clear(),await t.emitFn(createActionsRequestedEvent({actions:r,sequence:t.state.sequence,stepIndex:t.state.stepIndex,turnId:t.state.turnId}))},scheduleFlush=()=>{if(a!==void 0)return;let e,t=new Promise(t=>{e=t});o=e,a=setTimeout(()=>{a=void 0,o=void 0,e?.()},0),r=r.then(()=>t).then(emitPendingActions).catch(e=>{i??=e})};return{observe(e){n.set(e.callId,e),scheduleFlush()},async flush(){if(a!==void 0){clearTimeout(a),a=void 0;let e=o;o=void 0,e?.()}if(await r,i!==void 0)throw i;await emitPendingActions()}}}export{createProviderStreamActionBatch};