eve 0.89.0 → 0.90.0

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 (81) hide show
  1. package/CHANGELOG.md +28 -9
  2. package/dist/src/channel/adapter.d.ts +12 -3
  3. package/dist/src/channel/adapter.js +1 -1
  4. package/dist/src/channel/auth/definitions.d.ts +7 -20
  5. package/dist/src/channel/auth/definitions.js +1 -1
  6. package/dist/src/channel/auth/jwt-ecdsa.js +1 -1
  7. package/dist/src/channel/auth/jwt-hmac.js +1 -1
  8. package/dist/src/channel/auth/oidc.js +1 -1
  9. package/dist/src/channel/auth/result.d.ts +2 -3
  10. package/dist/src/channel/auth/result.js +1 -1
  11. package/dist/src/channel/channel-address.d.ts +1 -1
  12. package/dist/src/channel/channel-address.js +1 -1
  13. package/dist/src/channel/schedule.js +1 -1
  14. package/dist/src/chunks/{use-eve-agent-Bbl4H5aA.js → use-eve-agent-Bwloorf8.js} +77 -63
  15. package/dist/src/chunks/{use-eve-agent-CNpxgKEH.js → use-eve-agent-XCB0-tLX.js} +77 -63
  16. package/dist/src/cli/dev/environment.js +1 -1
  17. package/dist/src/cli/dev/tui/remote-connection-probe.js +1 -1
  18. package/dist/src/cli/dev/tui/remote-connection-types.d.ts +1 -0
  19. package/dist/src/cli/dev/tui/runner.js +2 -2
  20. package/dist/src/cli/dev/tui/status-line.d.ts +2 -2
  21. package/dist/src/cli/dev/tui/status-line.js +1 -1
  22. package/dist/src/client/agent-info-schema.d.ts +341 -326
  23. package/dist/src/client/agent-info-schema.js +1 -1
  24. package/dist/src/client/agent-info-types.d.ts +13 -10
  25. package/dist/src/client/client-error.d.ts +1 -1
  26. package/dist/src/client/client.d.ts +5 -3
  27. package/dist/src/client/client.js +1 -1
  28. package/dist/src/compiled/.vendor-stamp.json +1 -1
  29. package/dist/src/evals/target.js +1 -1
  30. package/dist/src/eve-channel/auth.d.ts +19 -0
  31. package/dist/src/eve-channel/auth.js +1 -0
  32. package/dist/src/eve-channel/index.d.ts +1 -0
  33. package/dist/src/eve-channel/index.js +1 -1
  34. package/dist/src/eve-channel/types.d.ts +23 -4
  35. package/dist/src/execution/catalog/connection-entry.js +1 -1
  36. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  37. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  38. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  39. package/dist/src/internal/application/stamped-package-version.js +1 -1
  40. package/dist/src/internal/authored-module-graph.js +1 -1
  41. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +2 -2
  42. package/dist/src/protocol/routes.d.ts +7 -1
  43. package/dist/src/protocol/routes.js +1 -1
  44. package/dist/src/public/channels/github/githubChannel.js +1 -1
  45. package/dist/src/public/channels/github/state.d.ts +7 -0
  46. package/dist/src/public/channels/github/state.js +1 -1
  47. package/dist/src/public/channels/mcp.js +1 -1
  48. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  49. package/dist/src/public/connections/index.d.ts +1 -1
  50. package/dist/src/public/definitions/channel.js +1 -1
  51. package/dist/src/public/definitions/connections/tool-call.d.ts +2 -2
  52. package/dist/src/reactions/frame.js +1 -1
  53. package/dist/src/runtime/channels/registry.d.ts +2 -2
  54. package/dist/src/runtime/channels/registry.js +1 -1
  55. package/dist/src/runtime/connections/approval-scope.d.ts +9 -0
  56. package/dist/src/runtime/connections/approval-scope.js +1 -0
  57. package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
  58. package/dist/src/runtime/connections/mcp-client.js +1 -1
  59. package/dist/src/runtime/connections/provided-arguments.js +1 -1
  60. package/dist/src/runtime/subagents/workflow.js +1 -1
  61. package/dist/src/setup/scaffold/create/project.js +1 -1
  62. package/dist/src/shared/agent-info-access.d.ts +5 -0
  63. package/dist/src/shared/agent-info-access.js +1 -0
  64. package/dist/src/shared/connection-types.d.ts +21 -4
  65. package/dist/src/svelte/index.js +1 -1
  66. package/dist/src/svelte/use-eve-agent.js +1 -1
  67. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  68. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  69. package/dist/src/vue/index.js +1 -1
  70. package/dist/src/vue/use-eve-agent.js +1 -1
  71. package/docs/channels/custom.mdx +2 -0
  72. package/docs/channels/eve.mdx +4 -2
  73. package/docs/concepts/sessions-runs-and-streaming.md +6 -2
  74. package/docs/connections/overview.mdx +30 -0
  75. package/docs/evals/targets.mdx +2 -0
  76. package/docs/evals/tool-stubs.mdx +4 -4
  77. package/docs/guides/auth-and-route-protection.md +16 -3
  78. package/docs/guides/client/overview.mdx +6 -2
  79. package/docs/guides/prepare-for-1-0.md +23 -1
  80. package/docs/tools/human-in-the-loop.md +1 -1
  81. package/package.json +1 -1
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{answerSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,readSkillFileSource}from"#internal/nitro/routes/channel-route-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{interactionJsonSchema}from"#protocol/interaction-json.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions}from"#channel/auth/definitions.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{MCP_TOOL_SESSIONS_EXTENSION,createPublishedTools}from"#internal/mcp/published-tools.js";import{resolveMcpRequestPrincipals}from"#internal/mcp/forwarded-principal-header.js";import{createMcpSkillsFeature}from"#internal/mcp/skills.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t={agent:e.agent??!0,skills:e.skills??!1,tools:e.tools??!1};if(!t.agent&&!t.tools&&!t.skills)throw Error(`mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.`);let n=e.route??`/eve/v1/mcp`,r=readOAuthResourceOptions(e.auth),handle=async(n,i)=>await authenticateMcpRequest(n,i,e,r,t),i=[GET(n,handle),POST(n,handle),DELETE(n,handle)];return r!==void 0&&i.unshift(...protectedResourceMetadataRoutes(r,n)),defineChannel({routes:i})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r,i){let a=validateMcpHttpRequest(e);if(a!==void 0)return a;let o=await routeAuth(e,n.auth);if(o instanceof Response)return r===void 0?o:addResourceChallenge(o,e,r);let s=sessionAuthFromResult(o),c=await resolveMcpRequestPrincipals(e,s,n.trustedForwarders);return c instanceof Response?c:await handleMcpRequest(e,t,s,c,i)}async function handleMcpRequest(e,t,n,r,i){let a=readRouteSessionCreator(t),o=readRouteChannelName(t),s=readAgentInfoRouteResponse(t);if(o===void 0||a===void 0||s===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let c=await s();if(!c.ok)return c;let l=await c.json();if(typeof l.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let u=typeof l.agent.description==`string`?l.agent.description:void 0,d=new WorkflowAgentInvocationExecution({createSession:a,from:t.from}),f=i.agent?createInvocationTools(d,u,n.authenticator===`none`&&n.principalType===`anonymous`):[],p=i.tools||i.skills?await t.describe():void 0,m=i.tools&&p!==void 0?createPublishedTools({invokeTool:t.invokeTool,principals:r,reserved:new Set(f.map(e=>e.name)),tools:p.tools}):[],h=[];if(i.tools&&h.push({capabilities:{extensions:{[MCP_TOOL_SESSIONS_EXTENSION]:{}}},register(){}}),i.skills&&p!==void 0){let e=readSkillFileSource(t);if(e===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});h.push(createMcpSkillsFeature({files:e,skills:p.skills}))}return await createMcpStreamableHttpServer({authenticate:async()=>n,features:h,instructions:i.agent?MCP_SERVER_INSTRUCTIONS:void 0,name:l.agent.name,tools:i.agent||i.tools?[...f,...m]:void 0,version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer all non-sign-in interactions in one agent_update by interactionId; repeating accepted answers is safe.`,`For sign-in interactions, follow signIn instructions outside agent_update and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(e,t,n){let r=n?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,i=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${r}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:t===void 0?i:`${t} ${i}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1)}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(await e.create({auth:n.auth,message:t.message}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. While working, statusMessage, when present, describes the current activity. Terminal statuses are completed, failed, and cancelled. input_required includes questions, approvals, and sign-ins. Answer questions and approvals with agent_update; follow sign-in instructions and poll for sign-ins.${r}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.read({auth:n.auth,invocationId:t.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in interactions, naming it by its key as interactionId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredMutation(await e.update({auth:n.auth,invocationId:t.invocationId,responses:t.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.cancel({auth:n.auth,invocationId:t.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject({...e,status:e.status===`awaiting-input`?`input_required`:e.status});return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}const MAX_MESSAGE_BYTES=65536,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(e){let t=new TextEncoder;return z.string().refine(n=>t.encode(n).byteLength<=e,{message:`must be at most ${String(e)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=answerSchema.safeExtend({optionId:z.string().max(256).optional(),interactionId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({sessionEnded:z.boolean(),createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`),statusMessage:z.string().optional()}),AGENT_INVOCATION_BASE_SCHEMA.extend({interactions:z.record(z.string(),interactionJsonSchema),pollAfterMs:z.number().int().nonnegative().optional(),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);export{mcpChannel};
1
+ import{z}from"#compiled/zod/index.js";import{answerSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{routeAuth}from"#public/channels/auth.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,readSkillFileSource}from"#internal/nitro/routes/channel-route-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions}from"#channel/auth/definitions.js";import{interactionJsonSchema}from"#protocol/interaction-json.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{MCP_TOOL_SESSIONS_EXTENSION,createPublishedTools}from"#internal/mcp/published-tools.js";import{resolveMcpRequestPrincipals}from"#internal/mcp/forwarded-principal-header.js";import{createMcpSkillsFeature}from"#internal/mcp/skills.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t={agent:e.agent??!0,skills:e.skills??!1,tools:e.tools??!1};if(!t.agent&&!t.tools&&!t.skills)throw Error(`mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.`);let n=e.route??`/eve/v1/mcp`,r=readOAuthResourceOptions(e.auth),handle=async(n,i)=>await authenticateMcpRequest(n,i,e,r,t),i=[GET(n,handle),POST(n,handle),DELETE(n,handle)];return r!==void 0&&i.unshift(...protectedResourceMetadataRoutes(r,n)),defineChannel({routes:i})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r,i){let a=validateMcpHttpRequest(e);if(a!==void 0)return a;let o=await routeAuth(e,n.auth);if(o instanceof Response)return r===void 0?o:addResourceChallenge(o,e,r);let s=sessionAuthFromResult(o),c=await resolveMcpRequestPrincipals(e,s,n.trustedForwarders);return c instanceof Response?c:await handleMcpRequest(e,t,s,c,i)}async function handleMcpRequest(e,t,n,r,i){let a=readRouteSessionCreator(t),o=readRouteChannelName(t),s=readAgentInfoRouteResponse(t);if(o===void 0||a===void 0||s===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let c=await s();if(!c.ok)return c;let l=await c.json();if(typeof l.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let u=typeof l.agent.description==`string`?l.agent.description:void 0,d=new WorkflowAgentInvocationExecution({createSession:a,from:t.from}),f=i.agent?createInvocationTools(d,u,n.authenticator===`none`&&n.principalType===`anonymous`):[],p=i.tools||i.skills?await t.describe():void 0,m=i.tools&&p!==void 0?createPublishedTools({invokeTool:t.invokeTool,principals:r,reserved:new Set(f.map(e=>e.name)),tools:p.tools}):[],h=[];if(i.tools&&h.push({capabilities:{extensions:{[MCP_TOOL_SESSIONS_EXTENSION]:{}}},register(){}}),i.skills&&p!==void 0){let e=readSkillFileSource(t);if(e===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});h.push(createMcpSkillsFeature({files:e,skills:p.skills}))}return await createMcpStreamableHttpServer({authenticate:async()=>n,features:h,instructions:i.agent?MCP_SERVER_INSTRUCTIONS:void 0,name:l.agent.name,tools:i.agent||i.tools?[...f,...m]:void 0,version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer all non-sign-in interactions in one agent_update by interactionId; repeating accepted answers is safe.`,`For sign-in interactions, follow signIn instructions outside agent_update and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(e,t,n){let r=n?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,i=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${r}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:t===void 0?i:`${t} ${i}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1)}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(await e.create({auth:n.auth,message:t.message}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. While working, statusMessage, when present, describes the current activity. Terminal statuses are completed, failed, and cancelled. input_required includes questions, approvals, and sign-ins. Answer questions and approvals with agent_update; follow sign-in instructions and poll for sign-ins.${r}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.read({auth:n.auth,invocationId:t.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in interactions, naming it by its key as interactionId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredMutation(await e.update({auth:n.auth,invocationId:t.invocationId,responses:t.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.cancel({auth:n.auth,invocationId:t.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject({...e,status:e.status===`awaiting-input`?`input_required`:e.status});return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}const MAX_MESSAGE_BYTES=65536,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(e){let t=new TextEncoder;return z.string().refine(n=>t.encode(n).byteLength<=e,{message:`must be at most ${String(e)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=answerSchema.safeExtend({optionId:z.string().max(256).optional(),interactionId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({sessionEnded:z.boolean(),createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`),statusMessage:z.string().optional()}),AGENT_INVOCATION_BASE_SCHEMA.extend({interactions:z.record(z.string(),interactionJsonSchema),pollAfterMs:z.number().int().nonnegative().optional(),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);export{mcpChannel};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{isCompiledChannel}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{INACTIVE_REQUEST_NOTICE,respondOrRetireInactivePrompt}from"#channel/inactive-prompt.js";import{formatTelegramContextBlock,parseTelegramUpdate}from"#public/channels/telegram/inbound.js";import{answerTelegramCallbackQuery,callTelegramApi,editTelegramMessageReplyMarkup,editTelegramMessageText,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX}from"#public/channels/telegram/authorization.js";import{TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,resolveTelegramAnswers,telegramCallbackAnswer,telegramReplyAnswers,telegramResolvedPromptText}from"#public/channels/telegram/hitl.js";import{defaultEvents,defaultOnMessage,defaultTelegramAuth,isTelegramBotMentioned}from"#public/channels/telegram/defaults.js";import{dispatchTelegramAuthorizationCallback}from"#public/channels/telegram/authorization-callback.js";import{buildTelegramTurnMessage,collectTelegramFileParts,createTelegramFetchFile}from"#public/channels/telegram/attachments.js";import{initialTelegramState,stateFromTelegramCallbackQuery,stateFromTelegramMessage,telegramContinuationTokenFromState}from"#public/channels/telegram/state.js";import{verifyTelegramRequest}from"#public/channels/telegram/verify.js";import{telegramInstrumentation}from"#public/channels/telegram/audience.js";const log=createLogger(`telegram.channel`);function telegramChannel(e={}){let t=mergeUploadPolicy(e.uploadPolicy),n=e.onMessage??defaultOnMessage,r={...defaultEvents,...e.events},i=defineChannel({turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:initialTelegramState(e.botUsername),...telegramInstrumentation,fetchFile:createTelegramFetchFile({api:e.api,credentials:e.credentials,policy:t}),context(t,n){return rebuildTelegramContext(t,n,e)},routes:[POST(e.route??`/eve/v1/telegram`,async(r,{from:i,resolveSession:a,waitUntil:o})=>{let s=await verifyInbound(r,e.credentials);if(s===null)return new Response(`unauthorized`,{status:401});let c;try{c=parseJsonObject(JSON.parse(s))}catch(e){return log.warn(`inbound Telegram body is not valid JSON`,{error:e}),new Response(`ok`)}let l=parseTelegramUpdate(c);return l===null?new Response(`ok`):l.kind===`message`?(o(dispatchMessage({config:e,message:l.message,onMessage:n,uploadPolicy:t,from:i})),new Response(`ok`)):(o(dispatchCallbackQuery({config:e,query:l.callbackQuery,from:i,resolveSession:a})),new Response(`ok`))})],async receive({message:t,target:n,...r},{from:i}){let a=n,o=readChatId(a.chatId);if(o===void 0)throw Error(`telegramChannel().receive requires target.chatId.`);let s=typeof a.messageThreadId==`number`?a.messageThreadId:void 0,c=readChatId(a.conversationId),l=a.initialMessage;if(l!==void 0&&c!==void 0)throw Error("telegramChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let u={...initialTelegramState(e.botUsername),chatId:o,conversationId:c??null,messageThreadId:s??null};return l!==void 0&&await buildTelegramHandle({config:e,state:u}).sendMessage(l),i(telegramContinuationTokenFromState(u)).send(t,{...r,state:u})},events:r});return attachTelegramDeliver(i),i}function rebuildTelegramContext(e,t,n){return{state:e,telegram:buildTelegramHandle({config:n,session:t,state:e})}}function buildTelegramHandle(e){let t=e.config.api,n=e.state,r=e.config.credentials;function anchor(t){let r=n.chatType??t.chatType??null;n.chatType===null&&t.chatType!==void 0&&(n.chatType=t.chatType),t.id&&shouldAnchorTelegramConversation(r)&&(n.conversationId=t.id,n.chatId&&e.session?.continuation?.alias(telegramContinuationToken({chatId:n.chatId,conversationId:t.id,messageThreadId:n.messageThreadId??void 0})))}async function sendOne(e){let t=await sendMessage(e);return anchor(t),t}async function sendMessage(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for outbound message.`);return sendTelegramMessage({apiBaseUrl:t?.apiBaseUrl,body:{...e,message_thread_id:e.message_thread_id??n.messageThreadId??void 0},credentials:r,fetch:t?.fetch,fileBaseUrl:t?.fileBaseUrl,chatId:i})}return{botUsername:n.botUsername??e.config.botUsername,chatId:n.chatId??``,chatType:n.chatType??void 0,conversationId:n.conversationId??void 0,messageThreadId:n.messageThreadId??void 0,answerCallbackQuery(e){return answerTelegramCallbackQuery({apiBaseUrl:t?.apiBaseUrl,callbackQueryId:e.callbackQueryId,credentials:r,fetch:t?.fetch,showAlert:e.showAlert,text:e.text})},editMessageReplyMarkup(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for reply-markup edit.`);return editTelegramMessageReplyMarkup({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup})},editMessageText(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for text edit.`);return editTelegramMessageText({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup,text:e.text})},post(e){return postTelegramMessage(e,sendOne)},postEphemeral(e,t,n){return postTelegramMessage({...typeof t==`string`?{text:t}:t,ephemeral_message_parameters:{...n?.callbackQueryId===void 0?{}:{callback_query_id:n.callbackQueryId},receiver_user_id:e}},sendMessage)},request(e,n){return callTelegramApi({apiBaseUrl:t?.apiBaseUrl,body:n,botToken:r?.botToken,fetch:t?.fetch,method:e})},sendMessage(e){return postTelegramMessage(e,sendOne)},async startTyping(e=`typing`){let i=n.chatId??``;if(i)try{await sendTelegramChatAction({action:e,apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageThreadId:n.messageThreadId??void 0})}catch(e){logError(log,`Telegram typing indicator failed — swallowed`,e,{chatId:i})}}}}function shouldAnchorTelegramConversation(e){return e===`group`||e===`supergroup`}async function postTelegramMessage(e,t){let n=typeof e==`string`?{text:e}:e,r=splitTelegramMessageText(n.text),i;for(let[e,a]of r.entries()){let r=await t(e===0?{...n,text:a}:{...n.ephemeral_message_parameters===void 0?{}:{ephemeral_message_parameters:n.ephemeral_message_parameters},text:a});i===void 0&&(i=r)}return i??{id:``,raw:null}}async function verifyInbound(e,t){try{return await verifyTelegramRequest(e,{secretToken:t?.webhookVerifier?void 0:t?.webhookSecretToken,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`telegram inbound verification failed`,{error:e}),null}}async function dispatchMessage(e){if(e.message.from?.isBot===!0)return;let t=stateFromTelegramMessage(e.message,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})},r;try{r=await e.onMessage(n,e.message)}catch(e){log.error(`message handler failed`,{error:e});return}if(r==null)return;let i=collectTelegramFileParts(e.message.attachments,e.uploadPolicy),a=buildTelegramTurnMessage(e.message,i),o=formatTelegramContextBlock({botUsername:e.config.botUsername,chatId:e.message.chat.id,chatTitle:e.message.chat.title,chatType:e.message.chat.type,isMentioned:isTelegramBotMentioned(e.message,e.config.botUsername),messageId:e.message.messageId,messageThreadId:e.message.messageThreadId,userId:e.message.from?.id,username:e.message.from?.username}),s=r.context??[];try{await e.from(telegramContinuationTokenFromState(t)).send(a,{auth:r.auth,context:[o,...s],history:r.history,state:t,title:r.title})}catch(e){log.error(`message delivery failed`,{error:e})}}async function dispatchCallbackQuery(e){let t=stateFromTelegramCallbackQuery(e.query,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})};if(e.query.data?.startsWith(TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX)===!0){await dispatchTelegramAuthorizationCallback({continuationToken:telegramContinuationTokenFromState(t),query:e.query,resolveSession:e.resolveSession,state:t,telegram:n});return}if(e.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX)===!0){let r=e.query.message,i=e.query.data,a=r&&t.chatId?await respondOrRetireInactivePrompt(()=>e.from(telegramContinuationTokenFromState(t)).respond([telegramCallbackAnswer(i)],{auth:defaultTelegramAuth({...r,from:e.query.from})}),{retirePrompt:e=>retireInactivePrompt(n,r,e)},log):void 0;try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:a?.outcome===`inactive`?INACTIVE_REQUEST_NOTICE:`Answer received.`})}catch(e){log.warn(`Telegram callback-query acknowledgement failed`,{error:e})}a?.outcome===`inactive`&&await a.retirement;return}if(e.config.onCallbackQuery!==void 0){try{await e.config.onCallbackQuery(n,e.query)}catch(e){log.error(`custom callback-query handler failed`,{error:e})}return}try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:`Unsupported action.`})}catch(e){log.warn(`Telegram unsupported callback-query acknowledgement failed`,{error:e})}}async function retireInactivePrompt(e,t,n){let r={inline_keyboard:[]};if(t.text===void 0){await e.telegram.editMessageReplyMarkup({messageId:t.messageId,replyMarkup:r});return}await e.telegram.editMessageText({messageId:t.messageId,replyMarkup:r,text:telegramResolvedPromptText(t.text,n)})}function attachTelegramDeliver(e){if(!isCompiledChannel(e))return;let t=e.adapter;t.deliver=(e,t)=>{let n=e.state,r=[...e.answers??[],...telegramReplyAnswers(n?.replyToBotMessageId,e.message)];if(r.some(isTelegramSyntheticResponse)){let n=resolveTelegramAnswers(t.state,r);return n.length>0?{answers:n,context:e.context}:e.message===void 0?void 0:{message:e.message,context:e.context}}return defaultDeliverResult(e)}}function readChatId(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}export{telegramChannel};
1
+ import{createLogger,logError}from"#internal/logging.js";import{defaultDeliverResult}from"#channel/adapter.js";import{isCompiledChannel}from"#channel/compiled-channel.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{INACTIVE_REQUEST_NOTICE,respondOrRetireInactivePrompt}from"#channel/inactive-prompt.js";import{formatTelegramContextBlock,parseTelegramUpdate}from"#public/channels/telegram/inbound.js";import{answerTelegramCallbackQuery,callTelegramApi,editTelegramMessageReplyMarkup,editTelegramMessageText,sendTelegramChatAction,sendTelegramMessage,splitTelegramMessageText,telegramContinuationToken}from"#public/channels/telegram/api.js";import{TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX}from"#public/channels/telegram/authorization.js";import{TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,resolveTelegramAnswers,telegramCallbackAnswer,telegramReplyAnswers,telegramResolvedPromptText}from"#public/channels/telegram/hitl.js";import{defaultEvents,defaultOnMessage,defaultTelegramAuth,isTelegramBotMentioned}from"#public/channels/telegram/defaults.js";import{dispatchTelegramAuthorizationCallback}from"#public/channels/telegram/authorization-callback.js";import{buildTelegramTurnMessage,collectTelegramFileParts,createTelegramFetchFile}from"#public/channels/telegram/attachments.js";import{initialTelegramState,stateFromTelegramCallbackQuery,stateFromTelegramMessage,telegramContinuationTokenFromState}from"#public/channels/telegram/state.js";import{verifyTelegramRequest}from"#public/channels/telegram/verify.js";import{telegramInstrumentation}from"#public/channels/telegram/audience.js";const log=createLogger(`telegram.channel`);function telegramChannel(e={}){let t=mergeUploadPolicy(e.uploadPolicy),n=e.onMessage??defaultOnMessage,r={...defaultEvents,...e.events},i=defineChannel({turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:initialTelegramState(e.botUsername),...telegramInstrumentation,fetchFile:createTelegramFetchFile({api:e.api,credentials:e.credentials,policy:t}),context(t,n){return rebuildTelegramContext(t,n,e)},routes:[POST(e.route??`/eve/v1/telegram`,async(r,{from:i,resolveSession:a,waitUntil:o})=>{let s=await verifyInbound(r,e.credentials);if(s===null)return new Response(`unauthorized`,{status:401});let c;try{c=parseJsonObject(JSON.parse(s))}catch(e){return log.warn(`inbound Telegram body is not valid JSON`,{error:e}),new Response(`ok`)}let l=parseTelegramUpdate(c);return l===null?new Response(`ok`):l.kind===`message`?(o(dispatchMessage({config:e,message:l.message,onMessage:n,uploadPolicy:t,from:i})),new Response(`ok`)):(o(dispatchCallbackQuery({config:e,query:l.callbackQuery,from:i,resolveSession:a})),new Response(`ok`))})],async receive({message:t,target:n,...r},{from:i}){let a=n,o=readChatId(a.chatId);if(o===void 0)throw Error(`telegramChannel().receive requires target.chatId.`);let s=typeof a.messageThreadId==`number`?a.messageThreadId:void 0,c=readChatId(a.conversationId),l=a.initialMessage;if(l!==void 0&&c!==void 0)throw Error("telegramChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let u={...initialTelegramState(e.botUsername),chatId:o,conversationId:c??null,messageThreadId:s??null};return l!==void 0&&await buildTelegramHandle({config:e,state:u}).sendMessage(l),i(telegramContinuationTokenFromState(u)).send(t,{...r,state:u})},events:r});return attachTelegramDeliver(i),i}function rebuildTelegramContext(e,t,n){return{state:e,telegram:buildTelegramHandle({config:n,session:t,state:e})}}function buildTelegramHandle(e){let t=e.config.api,n=e.state,r=e.config.credentials;function anchor(t){let r=n.chatType??t.chatType??null;n.chatType===null&&t.chatType!==void 0&&(n.chatType=t.chatType),t.id&&shouldAnchorTelegramConversation(r)&&(n.conversationId=t.id,n.chatId&&e.session?.continuation?.alias(telegramContinuationToken({chatId:n.chatId,conversationId:t.id,messageThreadId:n.messageThreadId??void 0})))}async function sendOne(e){let t=await sendMessage(e);return anchor(t),t}async function sendMessage(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for outbound message.`);return sendTelegramMessage({apiBaseUrl:t?.apiBaseUrl,body:{...e,message_thread_id:e.message_thread_id??n.messageThreadId??void 0},credentials:r,fetch:t?.fetch,fileBaseUrl:t?.fileBaseUrl,chatId:i})}return{botUsername:n.botUsername??e.config.botUsername,chatId:n.chatId??``,chatType:n.chatType??void 0,conversationId:n.conversationId??void 0,messageThreadId:n.messageThreadId??void 0,answerCallbackQuery(e){return answerTelegramCallbackQuery({apiBaseUrl:t?.apiBaseUrl,callbackQueryId:e.callbackQueryId,credentials:r,fetch:t?.fetch,showAlert:e.showAlert,text:e.text})},editMessageReplyMarkup(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for reply-markup edit.`);return editTelegramMessageReplyMarkup({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup})},editMessageText(e){let i=n.chatId??``;if(!i)throw Error(`telegramChannel: missing chat id for text edit.`);return editTelegramMessageText({apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageId:e.messageId,replyMarkup:e.replyMarkup,text:e.text})},post(e){return postTelegramMessage(e,sendOne)},postEphemeral(e,t,n){return postTelegramMessage({...typeof t==`string`?{text:t}:t,ephemeral_message_parameters:{...n?.callbackQueryId===void 0?{}:{callback_query_id:n.callbackQueryId},receiver_user_id:e}},sendMessage)},request(e,n){return callTelegramApi({apiBaseUrl:t?.apiBaseUrl,body:n,botToken:r?.botToken,fetch:t?.fetch,method:e})},sendMessage(e){return postTelegramMessage(e,sendOne)},async startTyping(e=`typing`){let i=n.chatId??``;if(i)try{await sendTelegramChatAction({action:e,apiBaseUrl:t?.apiBaseUrl,chatId:i,credentials:r,fetch:t?.fetch,messageThreadId:n.messageThreadId??void 0})}catch(e){logError(log,`Telegram typing indicator failed — swallowed`,e,{chatId:i})}}}}function shouldAnchorTelegramConversation(e){return e===`group`||e===`supergroup`}async function postTelegramMessage(e,t){let n=typeof e==`string`?{text:e}:e,r=splitTelegramMessageText(n.text),i;for(let[e,a]of r.entries()){let r=await t(e===0?{...n,text:a}:{...n.ephemeral_message_parameters===void 0?{}:{ephemeral_message_parameters:n.ephemeral_message_parameters},text:a});i===void 0&&(i=r)}return i??{id:``,raw:null}}async function verifyInbound(e,t){try{return await verifyTelegramRequest(e,{secretToken:t?.webhookVerifier?void 0:t?.webhookSecretToken,webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`telegram inbound verification failed`,{error:e}),null}}async function dispatchMessage(e){if(e.message.from?.isBot===!0)return;let t=stateFromTelegramMessage(e.message,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})},r;try{r=await e.onMessage(n,e.message)}catch(e){log.error(`message handler failed`,{error:e});return}if(r==null)return;let i=collectTelegramFileParts(e.message.attachments,e.uploadPolicy),a=buildTelegramTurnMessage(e.message,i),o=formatTelegramContextBlock({botUsername:e.config.botUsername,chatId:e.message.chat.id,chatTitle:e.message.chat.title,chatType:e.message.chat.type,isMentioned:isTelegramBotMentioned(e.message,e.config.botUsername),messageId:e.message.messageId,messageThreadId:e.message.messageThreadId,userId:e.message.from?.id,username:e.message.from?.username}),s=r.context??[];try{await e.from(telegramContinuationTokenFromState(t)).send(a,{auth:r.auth,context:[o,...s],history:r.history,state:t,title:r.title})}catch(e){log.error(`message delivery failed`,{error:e})}}async function dispatchCallbackQuery(e){let t=stateFromTelegramCallbackQuery(e.query,e.config.botUsername),n={telegram:buildTelegramHandle({config:e.config,state:t})};if(e.query.data?.startsWith(TELEGRAM_AUTHORIZATION_CALLBACK_PREFIX)===!0){await dispatchTelegramAuthorizationCallback({continuationToken:telegramContinuationTokenFromState(t),query:e.query,resolveSession:e.resolveSession,state:t,telegram:n});return}if(e.query.data?.startsWith(TELEGRAM_HITL_CALLBACK_PREFIX)===!0){let r=e.query.message,i=e.query.data,a=r&&t.chatId?await respondOrRetireInactivePrompt(()=>e.from(telegramContinuationTokenFromState(t)).respond([telegramCallbackAnswer(i)],{auth:defaultTelegramAuth({...r,from:e.query.from})}),{retirePrompt:e=>retireInactivePrompt(n,r,e)},log):void 0;try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:a?.outcome===`inactive`?INACTIVE_REQUEST_NOTICE:`Answer received.`})}catch(e){log.warn(`Telegram callback-query acknowledgement failed`,{error:e})}a?.outcome===`inactive`&&await a.retirement;return}if(e.config.onCallbackQuery!==void 0){try{await e.config.onCallbackQuery(n,e.query)}catch(e){log.error(`custom callback-query handler failed`,{error:e})}return}try{await n.telegram.answerCallbackQuery({callbackQueryId:e.query.id,text:`Unsupported action.`})}catch(e){log.warn(`Telegram unsupported callback-query acknowledgement failed`,{error:e})}}async function retireInactivePrompt(e,t,n){let r={inline_keyboard:[]};if(t.text===void 0){await e.telegram.editMessageReplyMarkup({messageId:t.messageId,replyMarkup:r});return}await e.telegram.editMessageText({messageId:t.messageId,replyMarkup:r,text:telegramResolvedPromptText(t.text,n)})}function attachTelegramDeliver(e){if(!isCompiledChannel(e))return;let t=e.adapter;t.deliver=(e,t)=>{let n=e.state,r=[...e.answers??[],...telegramReplyAnswers(n?.replyToBotMessageId,e.message)];if(r.some(isTelegramSyntheticResponse)){let n=resolveTelegramAnswers(t.state,r);return n.length>0?{answers:n,context:e.context}:e.message===void 0?void 0:{message:e.message,context:e.context}}return defaultDeliverResult(e)}}function readChatId(e){if(typeof e==`string`&&e.length>0)return e;if(typeof e==`number`&&Number.isFinite(e))return String(e)}export{telegramChannel};
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Connection authoring helpers for `agent/connections/*.ts` files.
3
3
  */
4
- export type { AuthorizationCallback, AuthorizationDefinition, ConnectionAuthDefinition, ConnectionAuthResolver, ConnectionPrincipal, HeadersDefinition, InteractiveAuthorizationDefinition, NonInteractiveAuthorizationDefinition, TokenResult, ToolFilterDefinition, } from "#shared/connection-types.js";
4
+ export type { AuthorizationCallback, AuthorizationDefinition, ConnectionAuthDefinition, ConnectionCallbackContext, ConnectionAuthResolver, ConnectionPrincipal, HeadersDefinition, InteractiveAuthorizationDefinition, NonInteractiveAuthorizationDefinition, TokenResult, ToolFilterDefinition, } from "#shared/connection-types.js";
5
5
  export { defineInteractiveAuthorization } from "#shared/connection-types.js";
6
6
  export { defineDynamic, type DynamicConnectionDefinition, type DynamicConnectionResult, type DynamicConnectionSet, } from "#public/definitions/connections/dynamic.js";
7
7
  export type { DynamicContext, DynamicKey, DynamicModelContext, DynamicSentinel, DynamicTurn, Memo, Occurrence, SessionFrame, } from "#dynamic/definition.js";
@@ -1 +1 @@
1
- import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{currentView}from"#harness/session-machine/current.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,WS}from"#channel/routes.js";import{removedEventKeyMessage}from"#public/definitions/removed-event-keys.js";import{authoringEventTypes}from"#protocol/session-events/authoring.js";import{normalizeChannelCors}from"#channel/cors.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";const DISABLED_ROUTE=Symbol.for(`eve.disabled-route`);function disableRoute(){return{[DISABLED_ROUTE]:!0}}function isDisabledRouteSentinel(e){return typeof e==`object`&&!!e&&Reflect.get(e,DISABLED_ROUTE)===!0}function defineChannel(e){let t=buildAdapter(e),n=normalizeChannelCors(e.cors);return{__kind:CHANNEL_SENTINEL,routes:e.routes,adapter:t,cors:n,receive:e.receive,turnPolicy:e.turnPolicy}}const eventTypes=[...authoringEventTypes,`committed`];function buildAdapter(e){let t=e.state!=null,n=e.context!=null,r=e.fetchFile!==void 0,i=e.metadata,a=i!==void 0,o=e.audience,s=e.uploadPolicy===void 0?void 0:mergeUploadPolicy(e.uploadPolicy),c=t||n||a||s!==void 0||e.deliver!==void 0,l={},u=!1,d=e.events;for(let e of Object.keys(d??{})){let t=removedEventKeyMessage(e);if(t!==void 0)throw Error(`A channel handles ${t}`)}for(let e of eventTypes){let t=d?.[e];t&&(u=!0,l[e]=(e,n)=>{let{session:r,continuation:i,position:a,scope:o,view:s,...c}=n,l={...c,get continuation(){return n.continuation}},u={...buildCallbackContext(),channel:l,position:a??{index:0,line:0},view:snapshotOf(s??currentView())};return t(e,u)})}return!c&&!u&&!r?{kind:HTTP_ADAPTER_KIND,...o===void 0?void 0:{instrumentation:{audience:o}}}:{kind:`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,uploadPolicy:s,instrumentation:i===void 0&&o===void 0?void 0:{...i===void 0?void 0:{metadata(e){let{audience:t,...n}=i(e);return n}},...o===void 0?void 0:{audience:o}},createAdapterContext(t){let r=t.state,i={session:t.session,get continuation(){return t.continuation}};return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i.session,get continuation(){return i.continuation}}},async deliver(t,n){let r=await e.deliver?.(t,n),i=defaultDeliverResult(r??t);if(i!==void 0)return attachClientContext(attachInputText(i,readInputText(t)),readClientContext(t))},...l}}export{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,SessionNotActiveError,SessionStrandedError,WS,defineChannel,disableRoute,isDisabledRouteSentinel};
1
+ import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";import{defaultDeliverResult}from"#channel/adapter.js";import{SessionNotActiveError}from"#channel/session-not-active-error.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{currentView}from"#harness/session-machine/current.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,WS}from"#channel/routes.js";import{removedEventKeyMessage}from"#public/definitions/removed-event-keys.js";import{authoringEventTypes}from"#protocol/session-events/authoring.js";import{normalizeChannelCors}from"#channel/cors.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";const DISABLED_ROUTE=Symbol.for(`eve.disabled-route`);function disableRoute(){return{[DISABLED_ROUTE]:!0}}function isDisabledRouteSentinel(e){return typeof e==`object`&&!!e&&Reflect.get(e,DISABLED_ROUTE)===!0}function defineChannel(e){let t=buildAdapter(e),n=normalizeChannelCors(e.cors);return{__kind:CHANNEL_SENTINEL,routes:e.routes,adapter:t,cors:n,receive:e.receive,turnPolicy:e.turnPolicy}}const eventTypes=[...authoringEventTypes,`committed`];function buildAdapter(e){let t=e.state!=null,n=e.context!=null,r=e.fetchFile!==void 0,i=e.metadata,a=i!==void 0,o=e.audience,s=e.uploadPolicy===void 0?void 0:mergeUploadPolicy(e.uploadPolicy),c=t||n||a||s!==void 0||e.deliver!==void 0,l={},u=!1,d=e.events;for(let e of Object.keys(d??{})){let t=removedEventKeyMessage(e);if(t!==void 0)throw Error(`A channel handles ${t}`)}for(let e of eventTypes){let t=d?.[e];t&&(u=!0,l[e]=(e,n)=>{let{session:r,continuation:i,position:a,scope:o,view:s,...c}=n,l={...c,get continuation(){return n.continuation}},u={...buildCallbackContext(),channel:l,position:a??{index:0,line:0},view:snapshotOf(s??currentView())};return t(e,u)})}return!c&&!u&&!r?{kind:HTTP_ADAPTER_KIND,...o===void 0?void 0:{instrumentation:{audience:o}}}:{kind:`defineChannel`,state:t?{...e.state}:{},fetchFile:e.fetchFile,uploadPolicy:s,instrumentation:i===void 0&&o===void 0?void 0:{...i===void 0?void 0:{metadata(e){let{audience:t,...n}=i(e);return n}},...o===void 0?void 0:{audience:o}},createAdapterContext(t){let r=t.state,i={session:t.session,get continuation(){return t.continuation}};return{...n?e.context(r,i):{},state:r,ctx:t.ctx,session:i.session,get continuation(){return i.continuation}}},async deliver(t,n){let r=await e.deliver?.(t,n),i=defaultDeliverResult(r??t);if(i!==void 0)return attachClientContext(attachInputText(i,readInputText(t)),readClientContext(t))},...l}}export{DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,SessionNotActiveError,SessionStrandedError,WS,defineChannel,disableRoute,isDisabledRouteSentinel};
@@ -1,7 +1,7 @@
1
- import type { SessionContext } from "#public/definitions/callback-context.js";
2
1
  import type { JsonValue } from "#public/types/json.js";
2
+ import type { ConnectionCallbackContext } from "#shared/connection-types.js";
3
3
  /** Context available while resolving an application-provided connection tool argument. */
4
- export type ProvidedArgumentContext = SessionContext & {
4
+ export type ProvidedArgumentContext = ConnectionCallbackContext & {
5
5
  /** Replay-stable id of the current connection tool call. */
6
6
  readonly callId: string;
7
7
  /** Bare tool or operation name published by the remote connection. */
@@ -1 +1 @@
1
- import{readReactionsState,sessionIdOf}from"./state.js";import{latestTurn}from"./turn.js";import{normalizeInstrumentationChannelKind}from"#shared/instrumentation-channel-kind.js";import{ConversationContextKey}from"#shared/conversation-context.js";import{getAdapterKind}from"#channel/adapter.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,ParentSessionKey,SessionPredecessorKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{currentView}from"#harness/session-machine/current.js";function channelOf(e){let t=e.get(ChannelKey),n=e.get(ChannelInstrumentationKey);return{continuationToken:e.get(ContinuationTokenKey),kind:normalizeInstrumentationChannelKind(n?.kind??(t===void 0?void 0:getAdapterKind(t))),metadata:n?.metadata??{}}}function sessionFrameOf(e,t={}){let n=e.get(ConversationContextKey),r=e.get(ParentSessionKey),i=t.view??currentView(e),a=t.at??readReactionsState(e).at??i.session.startedAt;return{channel:channelOf(e),...n!==void 0&&{conversation:n},now:new Date(a??0),session:{auth:{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null},id:sessionIdOf(e),...r!==void 0&&{parent:r},predecessor:e.get(SessionPredecessorKey),schedule:readSessionSchedule(e)},turn:latestTurn(i),view:snapshotOf(i)}}export{channelOf,sessionFrameOf};
1
+ import{readReactionsState,sessionIdOf}from"./state.js";import{latestTurn}from"./turn.js";import{getAdapterKind}from"#channel/adapter.js";import{normalizeInstrumentationChannelKind}from"#shared/instrumentation-channel-kind.js";import{ConversationContextKey}from"#shared/conversation-context.js";import{snapshotOf}from"#protocol/session-projection/session-view.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,ParentSessionKey,SessionPredecessorKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{currentView}from"#harness/session-machine/current.js";function channelOf(e){let t=e.get(ChannelKey),n=e.get(ChannelInstrumentationKey);return{continuationToken:e.get(ContinuationTokenKey),kind:normalizeInstrumentationChannelKind(n?.kind??(t===void 0?void 0:getAdapterKind(t))),metadata:n?.metadata??{}}}function sessionFrameOf(e,t={}){let n=e.get(ConversationContextKey),r=e.get(ParentSessionKey),i=t.view??currentView(e),a=t.at??readReactionsState(e).at??i.session.startedAt;return{channel:channelOf(e),...n!==void 0&&{conversation:n},now:new Date(a??0),session:{auth:{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null},id:sessionIdOf(e),...r!==void 0&&{parent:r},predecessor:e.get(SessionPredecessorKey),schedule:readSessionSchedule(e)},turn:latestTurn(i),view:snapshotOf(i)}}export{channelOf,sessionFrameOf};
@@ -21,7 +21,7 @@ export declare function createRuntimeAdapterRegistry(input: {
21
21
  * Rehydrates one serialized adapter from the runtime-owned registry.
22
22
  *
23
23
  * Looks up the adapter config by `kind`, then merges the serialized state
24
- * onto it. The result is a full adapter with behavior functions and
25
- * restored state.
24
+ * onto a copy of its seed state. The result is a full adapter with behavior
25
+ * functions and restored state.
26
26
  */
27
27
  export declare function deserializeRuntimeAdapter(registry: RuntimeAdapterRegistry, data: unknown): ChannelAdapter;
@@ -1 +1 @@
1
- import{getAdapterKind}from"#channel/adapter.js";import{SCHEDULE_ADAPTER}from"#channel/schedule.js";import{HTTP_ADAPTER}from"#channel/http.js";import{SUBAGENT_ADAPTER}from"#subagents/adapter.js";import{RuntimeRegistryError}from"#internal/runtime-registry.js";const FRAMEWORK_ADAPTERS=[HTTP_ADAPTER,SUBAGENT_ADAPTER,SCHEDULE_ADAPTER],ADAPTER_NON_EVENT_FIELDS=new Set([`kind`,`state`,`deliver`,`createAdapterContext`,`fetchFile`,`instrumentation`,`uploadPolicy`]);function createRuntimeAdapterRegistry(e){let t=new Map,n=new Set;for(let e of FRAMEWORK_ADAPTERS){let r=requireAdapterKind(e);n.add(r),t.set(r,e)}for(let r of e.channels){if(r.adapter===void 0)continue;let e={logicalPath:r.logicalPath,sourceId:r.sourceId},i=r.adapter,a=requireAdapterKind(i,e);if(n.has(a)){if(carriesAdapterBehavior(i))throw new RuntimeRegistryError(`adapter`,`Channel adapter kind "${a}" is reserved by the framework. A route-declared adapter may share a framework kind only as a pass-through with no \`deliver\` hook, event handlers, \`attachments\` resolver, or \`createAdapterContext\` factory. Use a custom \`kind\` to add channel-specific behavior.`,{...e,entryName:a});continue}t.set(a,i)}return{adaptersByKind:t}}function deserializeRuntimeAdapter(e,t){let n=t,r=e.adaptersByKind.get(n.kind);if(r===void 0)throw Error(`Unknown adapter kind: "${n.kind}". Declare the adapter on the route that starts this session so the runtime can rehydrate it.`);return{...r,state:n.state}}function requireAdapterKind(e,t){let n=getAdapterKind(e);if(typeof n!=`string`||n.length===0)throw new RuntimeRegistryError(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function carriesAdapterBehavior(e){if(e.deliver!==void 0||e.fetchFile!==void 0||e.uploadPolicy!==void 0||e.createAdapterContext!==void 0)return!0;for(let[t,n]of Object.entries(e))if(!ADAPTER_NON_EVENT_FIELDS.has(t)&&typeof n==`function`)return!0;return!1}export{createRuntimeAdapterRegistry,deserializeRuntimeAdapter};
1
+ import{getAdapterKind,seedChannelState}from"#channel/adapter.js";import{SCHEDULE_ADAPTER}from"#channel/schedule.js";import{HTTP_ADAPTER}from"#channel/http.js";import{SUBAGENT_ADAPTER}from"#subagents/adapter.js";import{RuntimeRegistryError}from"#internal/runtime-registry.js";const FRAMEWORK_ADAPTERS=[HTTP_ADAPTER,SUBAGENT_ADAPTER,SCHEDULE_ADAPTER],ADAPTER_NON_EVENT_FIELDS=new Set([`kind`,`state`,`deliver`,`createAdapterContext`,`fetchFile`,`instrumentation`,`uploadPolicy`]);function createRuntimeAdapterRegistry(e){let t=new Map,n=new Set;for(let e of FRAMEWORK_ADAPTERS){let r=requireAdapterKind(e);n.add(r),t.set(r,e)}for(let r of e.channels){if(r.adapter===void 0)continue;let e={logicalPath:r.logicalPath,sourceId:r.sourceId},i=r.adapter,a=requireAdapterKind(i,e);if(n.has(a)){if(carriesAdapterBehavior(i))throw new RuntimeRegistryError(`adapter`,`Channel adapter kind "${a}" is reserved by the framework. A route-declared adapter may share a framework kind only as a pass-through with no \`deliver\` hook, event handlers, \`attachments\` resolver, or \`createAdapterContext\` factory. Use a custom \`kind\` to add channel-specific behavior.`,{...e,entryName:a});continue}t.set(a,i)}return{adaptersByKind:t}}function deserializeRuntimeAdapter(e,t){let n=t,r=e.adaptersByKind.get(n.kind);if(r===void 0)throw Error(`Unknown adapter kind: "${n.kind}". Declare the adapter on the route that starts this session so the runtime can rehydrate it.`);return{...r,state:seedChannelState(r.state,n.state)}}function requireAdapterKind(e,t){let n=getAdapterKind(e);if(typeof n!=`string`||n.length===0)throw new RuntimeRegistryError(`adapter`,"Adapters must declare a non-empty `kind` field.",{entryName:`unknown`,logicalPath:t?.logicalPath,sourceId:t?.sourceId});return n}function carriesAdapterBehavior(e){if(e.deliver!==void 0||e.fetchFile!==void 0||e.uploadPolicy!==void 0||e.createAdapterContext!==void 0)return!0;for(let[t,n]of Object.entries(e))if(!ADAPTER_NON_EVENT_FIELDS.has(t)&&typeof n==`function`)return!0;return!1}export{createRuntimeAdapterRegistry,deserializeRuntimeAdapter};
@@ -0,0 +1,9 @@
1
+ import type { SessionAuthContext } from "#channel/types.js";
2
+ import type { ConnectionCallbackContext } from "#shared/connection-types.js";
3
+ /**
4
+ * Runs one connection tool call so its `headers` and provided arguments see who approved it.
5
+ * One authorization context serves the whole call, so its inline providers share one scope.
6
+ */
7
+ export declare function withConnectionApproval<T>(connectionName: string, responder: SessionAuthContext | undefined, fn: () => T): T;
8
+ /** The session context a connection's `headers` and provided-argument callbacks receive. */
9
+ export declare function buildConnectionCallbackContext(): ConnectionCallbackContext;
@@ -0,0 +1 @@
1
+ import{contextScopeValue,withContextScopeValue}from"#context/container.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";const APPROVAL=Symbol(`eve.connectionApproval`);function withConnectionApproval(e,t,n){if(t===void 0)return n();let r=createAuthorizationContext({scope:e}),i={responder:{...t,getToken:(e,n)=>r.getResponderToken(t,e,n)}};return withContextScopeValue(APPROVAL,i,n)}function buildConnectionCallbackContext(){let e=contextScopeValue(APPROVAL);return{...buildCallbackContext(),...e!==void 0&&{approval:e}}}export{buildConnectionCallbackContext,withConnectionApproval};
@@ -80,7 +80,7 @@ export declare function passesToolFilter(names: readonly string[], filter: Reado
80
80
  * flat `Record<string, string>` for the transport layer.
81
81
  *
82
82
  * Resolves dynamic `auth` and `headers` callbacks with the active
83
- * {@link SessionContext}, then resolves the {@link ConnectionPrincipal}
83
+ * session context, then resolves the {@link ConnectionPrincipal}
84
84
  * and invokes `authorization.getToken({ principal })` to produce the bearer.
85
85
  * `getToken` may throw {@link ConnectionAuthorizationRequiredError};
86
86
  * callers catch it and it propagates as-is from here.
@@ -1 +1 @@
1
- import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{FORWARDED_PRINCIPAL_HEADER,encodeForwardedPrincipalHeader}from"#internal/mcp/forwarded-principal-header.js";import{createMcpTraceFetch,withMcpToolCallSpan,withMcpToolsListSpan}from"#runtime/connections/mcp-tracing.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{ConnectionEventActions,isEventAction}from"#runtime/connections/events/actions.js";import{readTurnPrincipals}from"#context/turn-principals.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpUnauthorizedError=class extends Error{statusCode=401;anonymous;constructor(e){super(`MCP HTTP request failed (HTTP 401).`),this.anonymous=e}};async function checkAuthorizationResponse(e,t){if(e.status===401)throw await e.body?.cancel(),new McpUnauthorizedError(t);return e}var McpConnectionClient=class{#e;#t;#n;#r;#i;eventActions;constructor(e){if(this.#i=e,e.experimental_events!==void 0){let t=new ConnectionEventActions(e,e.experimental_events,()=>resolveHeaders(e),this.#s());this.eventActions={ownsName:isEventAction,recoveryMetadata:()=>t.recoveryMetadata(),metadata:async()=>{try{return await t.metadata()}catch(e){return await this.#d(e)}},execute:async(e,n,r)=>{try{return await t.execute(e,n,r)}catch(e){return await this.#d(e)}}}}}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let{headers:e}=await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0}),t=this.#i.url,n=createMcpTraceFetch({connectionName:this.#i.connectionName,fetcher:this.#o(Object.keys(e)),getProtocolVersion:()=>this.#t?.initializeResult?.protocolVersion});try{return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{fetch:n,headers:e,type:`http`,url:t}})}catch(r){if(!isMcpHttpFallbackRetryableError(r))throw r;return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{fetch:n,headers:e,type:`sse`,url:t}})}}#o(e){let t=this.#s()??globalThis.fetch;return async(n,r)=>{let resolve=()=>resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0}),send=async i=>{let a=new Headers(r?.headers);for(let t of e)a.delete(t);for(let[e,t]of Object.entries(i.headers))a.set(e,t);return await t(n,{...r,headers:a})},i=await resolve(),a=await send(i);if(a.status!==401||i.anonymous||this.#i.authorization===void 0||r?.signal?.aborted)return await checkAuthorizationResponse(a,i.anonymous);await this.#p();let o=await resolve();return o.anonymous?await checkAuthorizationResponse(a,!0):(await a.body?.cancel(),await checkAuthorizationResponse(await send(o),o.anonymous))}}#s(){if(this.#i.forwardPrincipal!==!0)return;let e=this.#i.connectionName;return async(t,n)=>{let r=readTurnPrincipals();if(r===void 0)return await globalThis.fetch(t,n);let i=new Headers(n?.headers);return i.set(FORWARDED_PRINCIPAL_HEADER,encodeForwardedPrincipalHeader(r,e)),await globalThis.fetch(t,{...n,headers:i,redirect:`error`})}}async getToolMetadata(){return(await this.#c()).metadata}async executeTool(e,t,n){let r;try{let{tools:i}=await this.#c(),a=i[e];if(a?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let o=a.execute,s=await resolveProvidedArguments({args:t,callId:n.callId,connection:this.#i,toolName:e});r=await withMcpToolCallSpan({arguments:t,connectionName:this.#i.connectionName,execute:async()=>await o(s,{abortSignal:n.abortSignal}),protocolVersion:this.#t?.initializeResult?.protocolVersion,toolName:e})}catch(e){return await this.#d(e)}return isMcpAuthChallengeResult(r)?await this.#f(`the server asked for sign-in to call "${e}"`):r}async#c(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#l();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#l(){try{return await this.#u()}catch(e){return await this.#d(e)}}async#u(){let e=await this.connect(),t=await withMcpToolsListSpan({connectionName:this.#i.connectionName,execute:()=>e.listTools(),protocolVersion:e.initializeResult?.protocolVersion}),n=Object.keys(this.#i.toolCall?.providedArguments??{}),r=t.tools.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,n)})),i=e.toolsFromDefinitions({tools:r});return{metadata:r.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:i}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#d(e){if(!isMcpAuthRequiredError(e))throw e;let t=[...walkErrorChain(e)].find(e=>e instanceof McpUnauthorizedError)?.anonymous??(await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0})).anonymous;return await this.#f(t?`the server requires sign-in`:`the server rejected the token`,t)}async#f(e,t){throw t??=(await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0})).anonymous,t||await this.#p(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (${e}).`})}async#p(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},instanceId:this.#i.instanceId,scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}const MCP_WWW_AUTHENTICATE_META_KEY=`mcp/www_authenticate`;function isMcpAuthChallengeResult(e){if(!isObject(e)||e.isError!==!0||!isObject(e._meta))return!1;let t=e._meta[MCP_WWW_AUTHENTICATE_META_KEY];return(typeof t==`string`||Array.isArray(t))&&t.length>0}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(e){for(let t of walkErrorChain(e)){if(!isObject(t))continue;let e=readStatusField(t);if(e!==void 0)return e;let n=t.response;if(isObject(n)){let e=readStatusField(n);if(e!==void 0)return e}if(typeof t.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(t.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(e){let t=e,n=new Set;for(;t!=null&&!n.has(t);){if(n.add(t),yield t,!isObject(t)||!(`cause`in t))return;t=t.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?e.some(e=>t.allow.includes(e)):!e.some(e=>t.block.includes(e))}async function resolveHeaders(e){let{headers:t}=await resolveConnectionHeaders(e,{anonymousWhenAuthorizationRequired:!1});return t}async function resolveConnectionHeaders(e,t){let n={},r=!1,i,getCallbackContext=()=>i??=buildCallbackContext(),a=await resolveConnectionAuthorization(e,typeof e.authorization==`function`?getCallbackContext():void 0);if(a!==void 0)try{n.Authorization=`Bearer ${(await resolveToken(e,a)).token}`}catch(e){if(!t.anonymousWhenAuthorizationRequired||!isConnectionAuthorizationRequiredError(e))throw e;r=!0}if(e.headers!==void 0){let t=await resolveHeadersDefinition(e.headers,getCallbackContext);for(let[r,i]of Object.entries(t)){if(a!==void 0&&r.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);n[r]=i}}return{anonymous:r,headers:n}}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},instanceId:e.instanceId,scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{MCP_WWW_AUTHENTICATE_META_KEY,McpConnectionClient,isMcpAuthChallengeResult,isMcpAuthRequiredError,passesToolFilter,readHttpStatus,resolveHeaders};
1
+ import{isObject}from"#shared/guards.js";import{ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{buildConnectionCallbackContext}from"#runtime/connections/approval-scope.js";import{FORWARDED_PRINCIPAL_HEADER,encodeForwardedPrincipalHeader}from"#internal/mcp/forwarded-principal-header.js";import{createMcpTraceFetch,withMcpToolCallSpan,withMcpToolsListSpan}from"#runtime/connections/mcp-tracing.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{ConnectionEventActions,isEventAction}from"#runtime/connections/events/actions.js";import{readTurnPrincipals}from"#context/turn-principals.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpUnauthorizedError=class extends Error{statusCode=401;anonymous;constructor(e){super(`MCP HTTP request failed (HTTP 401).`),this.anonymous=e}};async function checkAuthorizationResponse(e,t){if(e.status===401)throw await e.body?.cancel(),new McpUnauthorizedError(t);return e}var McpConnectionClient=class{#e;#t;#n;#r;#i;eventActions;constructor(e){if(this.#i=e,e.experimental_events!==void 0){let t=new ConnectionEventActions(e,e.experimental_events,()=>resolveHeaders(e),this.#s());this.eventActions={ownsName:isEventAction,recoveryMetadata:()=>t.recoveryMetadata(),metadata:async()=>{try{return await t.metadata()}catch(e){return await this.#d(e)}},execute:async(e,n,r)=>{try{return await t.execute(e,n,r)}catch(e){return await this.#d(e)}}}}}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let{headers:e}=await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0}),t=this.#i.url,n=createMcpTraceFetch({connectionName:this.#i.connectionName,fetcher:this.#o(Object.keys(e)),getProtocolVersion:()=>this.#t?.initializeResult?.protocolVersion});try{return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{fetch:n,headers:e,type:`http`,url:t}})}catch(r){if(!isMcpHttpFallbackRetryableError(r))throw r;return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{fetch:n,headers:e,type:`sse`,url:t}})}}#o(e){let t=this.#s()??globalThis.fetch;return async(n,r)=>{let resolve=()=>resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0}),send=async i=>{let a=new Headers(r?.headers);for(let t of e)a.delete(t);for(let[e,t]of Object.entries(i.headers))a.set(e,t);return await t(n,{...r,headers:a})},i=await resolve(),a=await send(i);if(a.status!==401||i.anonymous||this.#i.authorization===void 0||r?.signal?.aborted)return await checkAuthorizationResponse(a,i.anonymous);await this.#p();let o=await resolve();return o.anonymous?await checkAuthorizationResponse(a,!0):(await a.body?.cancel(),await checkAuthorizationResponse(await send(o),o.anonymous))}}#s(){if(this.#i.forwardPrincipal!==!0)return;let e=this.#i.connectionName;return async(t,n)=>{let r=readTurnPrincipals();if(r===void 0)return await globalThis.fetch(t,n);let i=new Headers(n?.headers);return i.set(FORWARDED_PRINCIPAL_HEADER,encodeForwardedPrincipalHeader(r,e)),await globalThis.fetch(t,{...n,headers:i,redirect:`error`})}}async getToolMetadata(){return(await this.#c()).metadata}async executeTool(e,t,n){let r;try{let{tools:i}=await this.#c(),a=i[e];if(a?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let o=a.execute,s=await resolveProvidedArguments({args:t,callId:n.callId,connection:this.#i,toolName:e});r=await withMcpToolCallSpan({arguments:t,connectionName:this.#i.connectionName,execute:async()=>await o(s,{abortSignal:n.abortSignal}),protocolVersion:this.#t?.initializeResult?.protocolVersion,toolName:e})}catch(e){return await this.#d(e)}return isMcpAuthChallengeResult(r)?await this.#f(`the server asked for sign-in to call "${e}"`):r}async#c(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#l();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#l(){try{return await this.#u()}catch(e){return await this.#d(e)}}async#u(){let e=await this.connect(),t=await withMcpToolsListSpan({connectionName:this.#i.connectionName,execute:()=>e.listTools(),protocolVersion:e.initializeResult?.protocolVersion}),n=Object.keys(this.#i.toolCall?.providedArguments??{}),r=t.tools.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,n)})),i=e.toolsFromDefinitions({tools:r});return{metadata:r.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:i}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#d(e){if(!isMcpAuthRequiredError(e))throw e;let t=[...walkErrorChain(e)].find(e=>e instanceof McpUnauthorizedError)?.anonymous??(await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0})).anonymous;return await this.#f(t?`the server requires sign-in`:`the server rejected the token`,t)}async#f(e,t){throw t??=(await resolveConnectionHeaders(this.#i,{anonymousWhenAuthorizationRequired:!0})).anonymous,t||await this.#p(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (${e}).`})}async#p(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},instanceId:this.#i.instanceId,scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}const MCP_WWW_AUTHENTICATE_META_KEY=`mcp/www_authenticate`;function isMcpAuthChallengeResult(e){if(!isObject(e)||e.isError!==!0||!isObject(e._meta))return!1;let t=e._meta[MCP_WWW_AUTHENTICATE_META_KEY];return(typeof t==`string`||Array.isArray(t))&&t.length>0}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(e){for(let t of walkErrorChain(e)){if(!isObject(t))continue;let e=readStatusField(t);if(e!==void 0)return e;let n=t.response;if(isObject(n)){let e=readStatusField(n);if(e!==void 0)return e}if(typeof t.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(t.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(e){let t=e,n=new Set;for(;t!=null&&!n.has(t);){if(n.add(t),yield t,!isObject(t)||!(`cause`in t))return;t=t.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?e.some(e=>t.allow.includes(e)):!e.some(e=>t.block.includes(e))}async function resolveHeaders(e){let{headers:t}=await resolveConnectionHeaders(e,{anonymousWhenAuthorizationRequired:!1});return t}async function resolveConnectionHeaders(e,t){let n={},r=!1,i=await resolveConnectionAuthorization(e);if(i!==void 0)try{n.Authorization=`Bearer ${(await resolveToken(e,i)).token}`}catch(e){if(!t.anonymousWhenAuthorizationRequired||!isConnectionAuthorizationRequiredError(e))throw e;r=!0}if(e.headers!==void 0){let t,r=await resolveHeadersDefinition(e.headers,()=>t??=buildConnectionCallbackContext());for(let[t,a]of Object.entries(r)){if(i!==void 0&&t.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);n[t]=a}}return{anonymous:r,headers:n}}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},instanceId:e.instanceId,scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{MCP_WWW_AUTHENTICATE_META_KEY,McpConnectionClient,isMcpAuthChallengeResult,isMcpAuthRequiredError,passesToolFilter,readHttpStatus,resolveHeaders};
@@ -1 +1 @@
1
- import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{buildCallbackContext}from"#context/build-callback-context.js";async function resolveProvidedArguments(e){if(!isObject(e.args))throw Error(`Tool "${e.toolName}" in connection "${e.connection.connectionName}" expected object arguments.`);let t=e.connection.toolCall?.providedArguments;if(t===void 0||Object.keys(t).length===0)return e.args;let n,getContext=()=>n??={...buildCallbackContext(),callId:e.callId,toolName:e.toolName},r={};for(let[n,i]of Object.entries(t)){let t=typeof i==`function`?await i(getContext()):await i;try{r[n]=parseJsonValue(t)}catch{throw Error(`Connection "${e.connection.connectionName}" provided argument "${n}" must resolve to a JSON-serializable value.`)}}return{...e.args,...r}}function omitProvidedArgumentsFromSchema(e,t){if(t.length===0)return e;let n=new Set(t),r={...e};return isObject(e.properties)&&(r.properties=Object.fromEntries(Object.entries(e.properties).filter(([e])=>!n.has(e)))),Array.isArray(e.required)&&(r.required=e.required.filter(e=>typeof e!=`string`||!n.has(e))),r}export{omitProvidedArgumentsFromSchema,resolveProvidedArguments};
1
+ import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{buildConnectionCallbackContext}from"#runtime/connections/approval-scope.js";async function resolveProvidedArguments(e){if(!isObject(e.args))throw Error(`Tool "${e.toolName}" in connection "${e.connection.connectionName}" expected object arguments.`);let t=e.connection.toolCall?.providedArguments;if(t===void 0||Object.keys(t).length===0)return e.args;let n,getContext=()=>n??={...buildConnectionCallbackContext(),callId:e.callId,toolName:e.toolName},r={};for(let[n,i]of Object.entries(t)){let t=typeof i==`function`?await i(getContext()):await i;try{r[n]=parseJsonValue(t)}catch{throw Error(`Connection "${e.connection.connectionName}" provided argument "${n}" must resolve to a JSON-serializable value.`)}}return{...e.args,...r}}function omitProvidedArgumentsFromSchema(e,t){if(t.length===0)return e;let n=new Set(t),r={...e};return isObject(e.properties)&&(r.properties=Object.fromEntries(Object.entries(e.properties).filter(([e])=>!n.has(e)))),Array.isArray(e.required)&&(r.required=e.required.filter(e=>typeof e!=`string`||!n.has(e))),r}export{omitProvidedArgumentsFromSchema,resolveProvidedArguments};
@@ -1 +1 @@
1
- async function agentToolServeWorkflow(e,t){"use workflow";let n=t.agent(t.toolName),r=sendToAgent(n,await e()),i=e();for(;;){let a=await nextCallOrResult(i,r);if(a.kind===`call`){r=await forwardCall(n,r,a.call),i=e();continue}if(!r.signal.aborted){if(a.result.status===`failed`)throw Error(`The agent's turn failed: ${a.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let o=e();if(o!==i){r=sendToAgent(n,await i),i=o;continue}t.reply(a.result.reply??``)}r=sendToAgent(n,await i),i=e()}}async function agentWithModelServeWorkflow(e,t){"use workflow";let n=await e(),r=n.input.model.trim();if(r===``)throw TypeError(`agent model must not be empty.`);let i=t.agent(`agent`,{model:r}),a=sendToModelAgent(i,n,r),o=e();for(;;){let n=await nextModelCallOrResult(o,a);if(n.kind===`call`){a=await forwardModelCall(i,a,n.call,r),o=e();continue}if(!a.signal.aborted){if(n.result.status===`failed`)throw Error(`The agent's turn failed: ${n.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let s=e();if(s!==o){a=sendToModelAgent(i,await o,r),o=s;continue}t.reply(n.result.reply??``)}a=sendToModelAgent(i,await o,r),o=e()}}function sendToAgent(e,t){return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}function sendToModelAgent(e,t,n){if(t.input.model!==n)throw Error(`An agent task keeps the model it started with. This task has ended; start a new task to use another model.`);return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}async function nextCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function nextModelCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function forwardCall(e,t,n){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToAgent(e,n)}async function forwardModelCall(e,t,n,r){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToModelAgent(e,n,r)}agentToolServeWorkflow.workflowId=`workflow//eve//agentToolServeWorkflow`,agentWithModelServeWorkflow.workflowId=`workflow//eve@0.89.0//agentWithModelServeWorkflow`;export{agentToolServeWorkflow,agentWithModelServeWorkflow};
1
+ async function agentToolServeWorkflow(e,t){"use workflow";let n=t.agent(t.toolName),r=sendToAgent(n,await e()),i=e();for(;;){let a=await nextCallOrResult(i,r);if(a.kind===`call`){r=await forwardCall(n,r,a.call),i=e();continue}if(!r.signal.aborted){if(a.result.status===`failed`)throw Error(`The agent's turn failed: ${a.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let o=e();if(o!==i){r=sendToAgent(n,await i),i=o;continue}t.reply(a.result.reply??``)}r=sendToAgent(n,await i),i=e()}}async function agentWithModelServeWorkflow(e,t){"use workflow";let n=await e(),r=n.input.model.trim();if(r===``)throw TypeError(`agent model must not be empty.`);let i=t.agent(`agent`,{model:r}),a=sendToModelAgent(i,n,r),o=e();for(;;){let n=await nextModelCallOrResult(o,a);if(n.kind===`call`){a=await forwardModelCall(i,a,n.call,r),o=e();continue}if(!a.signal.aborted){if(n.result.status===`failed`)throw Error(`The agent's turn failed: ${n.result.error.message}\nThis task has ended; to retry, call ${t.toolName} without taskId.`);let s=e();if(s!==o){a=sendToModelAgent(i,await o,r),o=s;continue}t.reply(n.result.reply??``)}a=sendToModelAgent(i,await o,r),o=e()}}function sendToAgent(e,t){return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}function sendToModelAgent(e,t,n){if(t.input.model!==n)throw Error(`An agent task keeps the model it started with. This task has ended; start a new task to use another model.`);return{result:e.send(t.input.message,{signal:t.abortSignal}).then(e=>e.result()),signal:t.abortSignal}}async function nextCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function nextModelCallOrResult(e,t){return await Promise.race([t.result.then(e=>({kind:`result`,result:e})),e.then(e=>({call:e,kind:`call`}))])}async function forwardCall(e,t,n){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToAgent(e,n)}async function forwardModelCall(e,t,n,r){return t.signal.aborted&&await t.result.catch(()=>void 0),sendToModelAgent(e,n,r)}agentToolServeWorkflow.workflowId=`workflow//eve//agentToolServeWorkflow`,agentWithModelServeWorkflow.workflowId=`workflow//eve@0.90.0//agentWithModelServeWorkflow`;export{agentToolServeWorkflow,agentWithModelServeWorkflow};
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.137`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.89.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{[SCAFFOLDED_AGENT_PATHS.config]:renderAgentTemplate(e,t),[SCAFFOLDED_AGENT_PATHS.channel]:WEB_CHANNEL_TEMPLATES.default,[SCAFFOLDED_AGENT_PATHS.instructions]:AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.137`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.90.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{[SCAFFOLDED_AGENT_PATHS.config]:renderAgentTemplate(e,t),[SCAFFOLDED_AGENT_PATHS.channel]:WEB_CHANNEL_TEMPLATES.default,[SCAFFOLDED_AGENT_PATHS.instructions]:AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -0,0 +1,5 @@
1
+ import { ClientError } from "#client/client-error.js";
2
+ /** Whether a client error is the info route refusing the caller's credential. */
3
+ export declare function isAgentInfoForbidden(error: unknown): error is ClientError;
4
+ /** Says which credential `GET /eve/v1/info` accepts, for callers it refused. */
5
+ export declare function formatAgentInfoForbiddenMessage(target: string): string;
@@ -0,0 +1 @@
1
+ import{AGENT_INFO_FORBIDDEN_CODE,AGENT_INFO_FORBIDDEN_MESSAGE}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";function isAgentInfoForbidden(e){return e instanceof ClientError&&e.status===403&&e.code===AGENT_INFO_FORBIDDEN_CODE}function formatAgentInfoForbiddenMessage(e){return`${e} refused GET /eve/v1/info. ${AGENT_INFO_FORBIDDEN_MESSAGE}`}export{formatAgentInfoForbiddenMessage,isAgentInfoForbidden};
@@ -7,6 +7,7 @@ import type { ConnectionEventsBackend } from "#shared/connection-events.js";
7
7
  */
8
8
  import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";
9
9
  import type { SessionContext } from "#context/session-context.js";
10
+ import type { ApprovedCall } from "#tools/definition.js";
10
11
  import type { JsonValue } from "#shared/json.js";
11
12
  /**
12
13
  * Credential returned by a connection's `getToken` or
@@ -37,18 +38,34 @@ export interface TokenResult {
37
38
  * client implementation. Never authored directly.
38
39
  */
39
40
  export type ConnectionProtocol = "mcp" | "openapi";
41
+ /**
42
+ * Context passed to a connection's `headers` and `toolCall.providedArguments`
43
+ * callbacks.
44
+ */
45
+ export interface ConnectionCallbackContext extends SessionContext {
46
+ /**
47
+ * Who approved the tool call these values are for. Present only while a
48
+ * connection tool call runs after a person approved it. The call still runs
49
+ * as the requester, `session.auth.current`, and its `auth` token is still
50
+ * the requester's. `approval.responder.getToken(provider)` resolves the
51
+ * approver's token as it does in a `defineTool` tool, so a callback can send
52
+ * the approver's credentials where the server should act for them.
53
+ */
54
+ readonly approval?: ApprovedCall;
55
+ }
40
56
  /** A single header value, supporting static strings and per-caller resolution. */
41
- export type HeaderValue = string | Promise<string> | ((ctx: SessionContext) => string | Promise<string>);
57
+ export type HeaderValue = string | Promise<string> | ((ctx: ConnectionCallbackContext) => string | Promise<string>);
42
58
  /**
43
59
  * Arbitrary HTTP headers sent with every request to a connection server.
44
60
  *
45
61
  * Static form: key-value pairs where each value may be a string, Promise,
46
62
  * or callback. Function form: a callback returning the full headers map,
47
63
  * useful when multiple headers must be resolved together. Header callbacks
48
- * receive the active {@link SessionContext}, so credentials and routing
49
- * metadata can be selected from the current caller.
64
+ * receive the active {@link ConnectionCallbackContext}, so credentials and
65
+ * routing metadata can be selected from the current caller, or from the
66
+ * approver of an approved tool call.
50
67
  */
51
- export type HeadersDefinition = Readonly<Record<string, HeaderValue>> | ((ctx: SessionContext) => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>);
68
+ export type HeadersDefinition = Readonly<Record<string, HeaderValue>> | ((ctx: ConnectionCallbackContext) => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>);
52
69
  /**
53
70
  * Client-side tool filter applied after `listTools()`.
54
71
  *
@@ -1,3 +1,3 @@
1
- import { n as signInEnding, t as useEveAgent } from "../chunks/use-eve-agent-CNpxgKEH.js";
1
+ import { n as signInEnding, t as useEveAgent } from "../chunks/use-eve-agent-XCB0-tLX.js";
2
2
 
3
3
  export { signInEnding, useEveAgent };
@@ -1,3 +1,3 @@
1
- import { t as useEveAgent } from "../chunks/use-eve-agent-CNpxgKEH.js";
1
+ import { t as useEveAgent } from "../chunks/use-eve-agent-XCB0-tLX.js";
2
2
 
3
3
  export { useEveAgent };
@@ -1 +1 @@
1
- async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){switch(e.status){case`answered`:return{answer:e.optionId??e.text??``,status:`answered`};case`cancelled`:return{interrupted:!0};case`unavailable`:return{status:`unavailable`}}}executeAskQuestionTool.workflowId=`workflow//eve@0.89.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
1
+ async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){switch(e.status){case`answered`:return{answer:e.optionId??e.text??``,status:`answered`};case`cancelled`:return{interrupted:!0};case`unavailable`:return{status:`unavailable`}}}executeAskQuestionTool.workflowId=`workflow//eve@0.90.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
@@ -1 +1 @@
1
- import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e,t){"use workflow";if(t.abortSignal.aborted)return{interrupted:!0};let n=new Promise(e=>t.abortSignal.addEventListener(`abort`,()=>e(`interrupted`),{once:!0})),r=sleep(Math.ceil(e.seconds*1e3)).then(()=>`elapsed`);return await Promise.race([r,n])===`elapsed`?{waitedSeconds:e.seconds}:{interrupted:!0}}executeSleepTool.workflowId=`workflow//eve@0.89.0//executeSleepTool`;export{executeSleepTool};
1
+ import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e,t){"use workflow";if(t.abortSignal.aborted)return{interrupted:!0};let n=new Promise(e=>t.abortSignal.addEventListener(`abort`,()=>e(`interrupted`),{once:!0})),r=sleep(Math.ceil(e.seconds*1e3)).then(()=>`elapsed`);return await Promise.race([r,n])===`elapsed`?{waitedSeconds:e.seconds}:{interrupted:!0}}executeSleepTool.workflowId=`workflow//eve@0.90.0//executeSleepTool`;export{executeSleepTool};
@@ -1,3 +1,3 @@
1
- import { n as signInEnding, t as useEveAgent } from "../chunks/use-eve-agent-Bbl4H5aA.js";
1
+ import { n as signInEnding, t as useEveAgent } from "../chunks/use-eve-agent-Bwloorf8.js";
2
2
 
3
3
  export { signInEnding, useEveAgent };
@@ -1,3 +1,3 @@
1
- import { t as useEveAgent } from "../chunks/use-eve-agent-Bbl4H5aA.js";
1
+ import { t as useEveAgent } from "../chunks/use-eve-agent-Bwloorf8.js";
2
2
 
3
3
  export { useEveAgent };
@@ -200,6 +200,8 @@ A sent delivery can interrupt generation before your `deliver` hook runs. If the
200
200
 
201
201
  Every `send()` and `respond()` delivery passes its `state` option to your channel's `deliver(payload, channel)` hook as `payload.state`, including deliveries to an existing session. Use it for values that belong to one delivery, such as the author of a message. The hook decides what to merge into `channel.state`; eve seeds `channel.state` from `state` only when `send()` creates the session.
202
202
 
203
+ The `state` you pass to `defineChannel(...)` is the seed for every session's `channel.state`, and must be plain JSON-like data. At each step boundary, eve restores any top-level seed field missing from the session's state, so a field you add to the seed in a later deploy holds its seed value in older sessions too, including in `context(state)` and event handlers. A field you `delete` is restored the same way; to clear one, set it to `null` (or `undefined`). eve doesn't merge nested objects: a stored object replaces the seed's object whole.
204
+
203
205
  The payload is `ChannelDelivery<TState>` from `eve/channels`: `message`, `answers`, `context`, `outputSchema`, and `state?: Partial<TState>`. Return a replacement with `message`, `answers`, `context`, or `outputSchema` to change the delivery, or return nothing to keep it unchanged. Change durable state through `channel.state`, not a `state` field on the replacement. To ignore a delivery, return `{}`. The hook does not return a harness input or accept arbitrary extra fields.
204
206
 
205
207
  ```ts
@@ -108,7 +108,7 @@ has completed. Idle preparation preserves the session ID, stream, history, and e
108
108
  active work is not interrupted. See the [frontend guide](../guides/frontend/use-eve-agent#prewarming)
109
109
  for client usage and deployment routing.
110
110
 
111
- `GET /eve/v1/health` is public and returns `{ ok: true, status: "ready", workflowId: string }`. `GET /eve/v1/info` uses the channel's auth policy and returns agent-info version 6. The TypeScript client validates both successful payloads: malformed health JSON throws `HealthResponseError`, malformed inspection JSON throws `AgentInfoResponseError`, and a non-success response from either route throws `ClientError`.
111
+ `GET /eve/v1/health` is public and returns `{ ok: true, status: "ready", workflowId: string }`. `GET /eve/v1/info` uses the channel's auth policy, then serves only operator principals: `service` and `runtime` principals and, when the channel's auth includes `localDev()`, any caller it admits on a development server. Other callers the channel admits, such as `user` or `anonymous` principals, get `403` with code `info_forbidden`, because the payload includes authored instructions, skill and schedule markdown, and server paths. The route returns agent-info version 5. The TypeScript client validates both successful payloads: malformed health JSON throws `HealthResponseError`, malformed inspection JSON throws `AgentInfoResponseError`, and a non-success response from either route throws `ClientError`.
112
112
 
113
113
  ### Request validation
114
114
 
@@ -305,7 +305,7 @@ export default eveChannel({
305
305
 
306
306
  ## Authentication
307
307
 
308
- The `auth` option decides who can call `/eve/v1/info` and the session routes. The built-in helpers cover development and trusted infrastructure:
308
+ The `auth` option decides who can call `/eve/v1/info` and the session routes. `/eve/v1/info` additionally requires an operator principal (`service`, `runtime`, or `local-dev`). The built-in helpers cover development and trusted infrastructure:
309
309
 
310
310
  - `localDev()` accepts requests during local development.
311
311
  - `vercelOidc()` lets the local CLI reach a deployed agent, and lets other internal deployments from your team call it.
@@ -314,6 +314,8 @@ Neither admits browser users or external clients in production. For a public app
314
314
 
315
315
  `eve init` scaffolds an `agent/channels/eve.ts` with a production placeholder so you replace it before going live. The generated channel checks Vercel OIDC before falling back to localhost access, and includes `placeholderAuth()`, which returns a setup-focused 401 in production until you swap it for real auth. Delete the file and eve selects its default channel source with `[vercelOidc(), localDev(), placeholderAuth()]`, which rejects all production traffic.
316
316
 
317
+ To let your own operator credential read `/eve/v1/info`, have its `AuthFn` return `principalType: "service"` (as `jwtHmac()` and `jwtEcdsa()` do), or return `allowAgentInfo: true` from an `EveAuthFn`; see [Agent info access](../guides/auth-and-route-protection#agent-info-access). Keep end-user strategies returning `"user"` without the grant so they cannot read it.
318
+
317
319
  For the full auth model and helper list, see [Auth & route protection](../guides/auth-and-route-protection).
318
320
 
319
321
  ## Audience
@@ -452,9 +452,13 @@ A read reflects events that are already durable. A hook runs after its line is w
452
452
 
453
453
  ## Inspect the agent over HTTP
454
454
 
455
- `GET /eve/v1/info` returns agent-info version 6, a JSON inspection snapshot of the effective compiled agent. It reports the selected config; active tools, instructions, memory slots, skills, channels, schedules, sandbox, connections, hooks, and instrumentation with explicit source ownership; dynamic resolvers separately from their session-specific output; local and remote agents in separate collections; prepared built-in effects; and shadowed or disabled source diagnostics. Memory tool wrappers include their selected memory-source dependency. Channel routes appear in the same effective order used by the HTTP host. Static instructions remain an ordered array whose entries expose `content` and `role`. Sandbox inspection exposes the opaque `revisionHash` that identifies its compiler-discovered environment inputs.
455
+ `GET /eve/v1/info` returns agent-info version 5, a JSON inspection snapshot of the effective compiled agent. It reports the selected config; active tools, instructions, memory slots, skills, channels, schedules, sandbox, connections, hooks, and instrumentation with explicit source ownership; dynamic resolvers separately from their session-specific output; local and remote agents in separate collections; prepared built-in effects; and shadowed or disabled source diagnostics. Memory tool wrappers include their selected memory-source dependency. Channel routes appear in the same effective order used by the HTTP host. Static instructions remain an ordered array whose entries expose `content` and `role`. Sandbox inspection exposes the opaque `revisionHash` that identifies its compiler-discovered environment inputs.
456
456
 
457
- The info route belongs to the selected `channels/eve.ts` source and uses its resolved auth policy. Without an authored replacement, eve selects the default channel source with Vercel OIDC, local development access, and the production placeholder. Replacing or disabling that source replaces or removes the info route too; no native fallback serves it.
457
+ Because the payload includes authored text and server paths, the route serves only operator principals: `service` and `runtime` principals and, when the channel's auth includes `localDev()`, any caller it admits on a development server. Any other principal the channel admits, such as a `user` or `anonymous` principal, gets `403` with `{ "code": "info_forbidden", "ok": false }` and an `error` message. To give another credential access, return `principalType: "service"` or `allowAgentInfo: true` from its authenticator; see [Agent info access](../guides/auth-and-route-protection#agent-info-access).
458
+
459
+ The version changes only for breaking reshapes. New fields and new enum values are added within a version, so readers should ignore unknown fields and tolerate unknown enum values. `kind` discriminants, such as an owner's, a model endpoint's, or a module's backing `kind`, are closed: a new variant comes with a version bump.
460
+
461
+ The info route belongs to the selected `channels/eve.ts` source and uses its resolved auth policy before the operator check. Without an authored replacement, eve selects the default channel source with Vercel OIDC, local development access, and the production placeholder. Replacing or disabling that source replaces or removes the info route too; no native fallback serves it.
458
462
 
459
463
  ```bash
460
464
  curl http://127.0.0.1:2000/eve/v1/info
@@ -213,6 +213,36 @@ export default defineMcpClientConnection({
213
213
 
214
214
  For connection tools that can create, modify, delete, transmit, purchase, message, or access sensitive data, use approval, allow-lists, or other safeguards appropriate to the action.
215
215
 
216
+ ### Send the approver to the server
217
+
218
+ [Approval is consent only](/docs/human-in-the-loop): it never changes who the turn runs as. An approved connection call keeps the requester's identity, so `ctx.session.auth.current` and the connection's `auth` token stay the requester's, and later calls in the turn are unaffected. While an approved call runs, its `headers` and `toolCall.providedArguments` callbacks also receive `ctx.approval.responder`, the person who approved it, with access to their credentials. That's a separate identity your code explicitly sends to the server, not a replacement for the requester:
219
+
220
+ ```ts title="agent/connections/gateway.ts"
221
+ import { defineMcpClientConnection } from "eve/connections";
222
+ import { always } from "eve/tools/approval";
223
+
224
+ export default defineMcpClientConnection({
225
+ url: "https://gateway.example.com/mcp",
226
+ description: "Internal systems through the MCP gateway.",
227
+ approval: {
228
+ request: always(),
229
+ response: ({ response }) =>
230
+ admins.includes(response.principal.principalId)
231
+ ? { status: "allowed" }
232
+ : { status: "rejected", reason: "Only admins can approve gateway calls." },
233
+ },
234
+ auth: gatewayAuth,
235
+ headers: async (ctx) => {
236
+ const approver = await ctx.approval?.responder.getToken(gatewayApproverAuth);
237
+ return approver === undefined ? {} : { "X-Approver-Token": approver.token };
238
+ },
239
+ });
240
+ ```
241
+
242
+ `ctx.approval.responder.getToken(provider)` resolves the approver's token as it does in a [`defineTool` tool](/docs/human-in-the-loop): it never starts a sign-in, and throws a `ConnectionAuthorizationFailedError` with `reason: "approver_authorization_required"` when the approver has no token. `headers` can't set `Authorization` when the connection also sets `auth`, so send the approver's token in another header, or omit `auth` and set `Authorization` yourself.
243
+
244
+ `ctx.approval` is absent for calls that needed no approval, and while eve connects to the server and lists its tools. The approver's identity reaches only the requests of the call they approved. Pair it with an `approval.response` policy so only people whose access the call may use can approve it.
245
+
216
246
  ## Interactive OAuth via Vercel Connect
217
247
 
218
248
  When the server uses OAuth and you want each end-user to sign in through their own browser, turn on interactive authorization with [Vercel Connect](https://vercel.com/docs/connect). The `connect()` helper from `@vercel/connect/eve` handles consent, encrypted token storage, and refresh, then hooks all of that into eve's authorization flow.
@@ -51,6 +51,8 @@ After verification, eve sends the available Vercel credentials:
51
51
 
52
52
  `EVE_EVAL_AUTH_TOKEN` is an explicit bearer override for targets whose auth is not Vercel OIDC. Credential-bearing clients do not follow redirects, so those headers cannot be forwarded to another origin.
53
53
 
54
+ `/eve/v1/info` serves only operator principals, so the credential must authenticate as a service principal, for example through Vercel OIDC, `jwtHmac()`, `jwtEcdsa()`, or a custom `AuthFn` that returns `principalType: "service"`. When the target answers `403`, the run fails before any eval starts and names the credential it needs.
55
+
54
56
  `t.target.fetch(path, init)` carries these same credentials, so channel and webhook ingress you exercise through it authenticates the same way the session protocol does.
55
57
 
56
58
  ## What to read next
@@ -156,15 +156,15 @@ Parallel calls consume responses in arrival order, which can vary. Use separate
156
156
 
157
157
  ## Permit tool replacement
158
158
 
159
- Tool replacement is denied by default, including in development. With [Vercel OIDC](../guides/auth-and-route-protection#verceloidc), put the permission on the eval runner's verified subject:
159
+ Tool replacement is denied by default, including in development. With [Vercel OIDC](../guides/auth-and-route-protection#verceloidc), use `eveVercelOidc` and put the permission on the eval runner's verified subject:
160
160
 
161
161
  ```ts title="agent/channels/eve.ts"
162
- import { vercelOidc, vercelSubject } from "eve/channels/auth";
163
- import { eveChannel } from "eve/channels/eve";
162
+ import { vercelSubject } from "eve/channels/auth";
163
+ import { eveChannel, eveVercelOidc } from "eve/channels/eve";
164
164
 
165
165
  export default eveChannel({
166
166
  auth: [
167
- vercelOidc({
167
+ eveVercelOidc({
168
168
  subjects: [
169
169
  vercelSubject({ teamSlug: "acme", projectName: "app" }),
170
170
  {
@@ -117,7 +117,7 @@ Verifies a bearer JWT against the [Vercel OIDC issuer](https://vercel.com/docs/o
117
117
 
118
118
  Auth fails closed: routes reject unauthenticated traffic by default, and the OIDC user branch verifies `external_sub` against `VERCEL_PROJECT_ID` and the deployment environment, returning `false` when either is unset. An external-subject token cannot authenticate on a deployment that hasn't pinned its project.
119
119
 
120
- Subject entries can also be objects: `{ subject: vercelSubject({ teamSlug: "acme", projectName: "eval-runner" }), allowToolStubs: true }`. This explicitly permits that verified service/runtime caller to create [stubbed eval sessions](../evals/tool-stubs). Plain subject strings and implicit current-project acceptance grant ordinary access only. Custom authenticators can return the same permission in their authentication result; it is not part of persisted or forwarded session identity.
120
+ To also permit [stubbed eval sessions](../evals/tool-stubs), use `eveVercelOidc` from `eve/channels/eve`. It takes the same options, and its subject entries can grant [tool replacement permission](#tool-replacement-permission).
121
121
 
122
122
  #### `subjects` patterns and `vercelSubject(...)`
123
123
 
@@ -307,9 +307,9 @@ Route auth does not enforce session ownership. If multiple users or tenants can
307
307
 
308
308
  ## Tool replacement permission
309
309
 
310
- Creating a [stubbed eval session](../evals/tool-stubs) requires an explicit `allowToolStubs: true` in the verified route authentication result. The target's server configuration grants permission; request JSON cannot. With `vercelOidc`, put the grant on a `subjects` entry as shown above. Any matching entry with the grant permits replacement; other entries do not revoke it. Implicit current-project acceptance and user principals do not inherit project grants.
310
+ Creating a [stubbed eval session](../evals/tool-stubs) requires an explicit `allowToolStubs: true` in the verified route authentication result. The target's server configuration grants permission; request JSON cannot. With `eveVercelOidc`, put the grant on a `subjects` entry, as in the [tool stubs example](../evals/tool-stubs#permit-tool-replacement). Any matching entry with the grant permits replacement; other entries do not revoke it. Implicit current-project acceptance and user principals do not inherit project grants.
311
311
 
312
- Custom authenticators return the same grant after verifying their caller. For example, this alternative channel permits stubs only in local development:
312
+ Custom authenticators return the same grant after verifying their caller; type standalone callbacks as `EveAuthFn` from `eve/channels/eve`. For example, this alternative channel permits stubs only in local development:
313
313
 
314
314
  ```ts
315
315
  import { localDev } from "eve/channels/auth";
@@ -328,6 +328,19 @@ The channel checks the grant before forwarded-principal handling or `onMessage`
328
328
 
329
329
  Later messages, approvals, controls, and result reads use normal channel authentication. There is no additional creator-only rule or replacement-permission recheck. Anyone your channel admits to an existing session can use its configured stubs; apply the same application-specific session-access policy you need for ordinary sessions.
330
330
 
331
+ ## Agent info access
332
+
333
+ `GET /eve/v1/info` returns authored instructions and server paths, so it serves only operators by default: `service` and `runtime` principals, plus callers `localDev()` admits when the channel's `auth` includes it. Other callers get `403` with code `info_forbidden`. An eve-channel authenticator can decide for its caller instead: `allowAgentInfo: true` grants access, and `false` denies it even to an operator. Like `allowToolStubs`, the flag applies only to the current request and is never persisted or forwarded.
334
+
335
+ ```ts
336
+ import type { EveAuthFn } from "eve/channels/eve";
337
+
338
+ const authenticateStaff: EveAuthFn = async (request) => {
339
+ const staff = await verifyStaffSession(request);
340
+ return staff ? { ...staff, allowAgentInfo: true } : null;
341
+ };
342
+ ```
343
+
331
344
  ## Tool and connection auth
332
345
 
333
346
  Tool and connection auth is how your agent reaches an external service that wants an interactive sign-in, like an OAuth MCP server. Connections declare `auth` on the connection definition. Tools should resolve providers inline with `ctx.getToken(provider)` and call `ctx.requireAuth(provider)` only when a downstream service rejects a token; eve drives the sign-in, caches the token per step, and re-runs the call once the caller authorizes.