eve 0.83.1 → 0.83.3

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 (133) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/src/channel/types.d.ts +3 -2
  3. package/dist/src/chunks/{use-eve-agent-ZY7NQ2VW.js → use-eve-agent-BE2_zd5q.js} +17 -12
  4. package/dist/src/chunks/{use-eve-agent-DnbG9c7c.js → use-eve-agent-e8a5vcFO.js} +17 -12
  5. package/dist/src/client/optimistic-message-submissions.d.ts +2 -3
  6. package/dist/src/client/optimistic-message-submissions.js +1 -1
  7. package/dist/src/compiled/.vendor-stamp.json +1 -1
  8. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  9. package/dist/src/evals/assertions/run.js +1 -1
  10. package/dist/src/evals/runner/derive-run-facts.d.ts +13 -0
  11. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  12. package/dist/src/evals/session.js +2 -2
  13. package/dist/src/evals/types.d.ts +1 -1
  14. package/dist/src/eve-channel/request.js +1 -1
  15. package/dist/src/execution/cancelled-model-call-batch.js +1 -1
  16. package/dist/src/execution/catalog/connection-auth.js +1 -1
  17. package/dist/src/execution/catalog/connection-entry.js +1 -1
  18. package/dist/src/execution/catalog/rank.js +1 -1
  19. package/dist/src/execution/connections/callback-route.d.ts +3 -2
  20. package/dist/src/execution/connections/callback-route.js +1 -1
  21. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  22. package/dist/src/execution/legacy-session/prepare-step.js +1 -1
  23. package/dist/src/execution/node-step.d.ts +1 -0
  24. package/dist/src/execution/node-step.js +1 -1
  25. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  26. package/dist/src/execution/sandbox/multiplexed-command.d.ts +9 -3
  27. package/dist/src/execution/sandbox/multiplexed-command.js +1 -1
  28. package/dist/src/execution/sandbox/read-file.js +1 -1
  29. package/dist/src/execution/session/handoff-steps.d.ts +1 -0
  30. package/dist/src/execution/session/handoff-steps.js +1 -1
  31. package/dist/src/execution/session/handoff.d.ts +1 -0
  32. package/dist/src/execution/session/handoff.js +1 -1
  33. package/dist/src/execution/session/program.js +1 -1
  34. package/dist/src/execution/session/turn-step.js +1 -1
  35. package/dist/src/execution/session-event-stream.d.ts +6 -0
  36. package/dist/src/execution/session-event-stream.js +1 -1
  37. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  38. package/dist/src/execution/web-fetch/html.js +3 -4
  39. package/dist/src/execution/workflow-runtime.js +1 -1
  40. package/dist/src/extensions/git/extension/lib/gh-tool.d.ts +11 -2
  41. package/dist/src/extensions/git/extension/lib/gh-tool.js +1 -1
  42. package/dist/src/harness/attachment-staging.js +1 -1
  43. package/dist/src/harness/compaction/engine.js +2 -2
  44. package/dist/src/harness/compaction/over-limit-error.d.ts +7 -0
  45. package/dist/src/harness/compaction/over-limit-error.js +1 -0
  46. package/dist/src/harness/compaction/prompt.js +1 -1
  47. package/dist/src/harness/compaction/step.d.ts +16 -1
  48. package/dist/src/harness/compaction/step.js +1 -1
  49. package/dist/src/harness/emission.d.ts +8 -3
  50. package/dist/src/harness/emission.js +1 -1
  51. package/dist/src/harness/hitl/approvals.d.ts +2 -0
  52. package/dist/src/harness/hitl/approvals.js +1 -1
  53. package/dist/src/harness/hitl/delivery.d.ts +1 -0
  54. package/dist/src/harness/hitl/delivery.js +1 -1
  55. package/dist/src/harness/hitl/intake.js +1 -1
  56. package/dist/src/harness/model-call/call.d.ts +8 -2
  57. package/dist/src/harness/model-call/call.js +1 -1
  58. package/dist/src/harness/model-call/failure.d.ts +7 -0
  59. package/dist/src/harness/model-call/failure.js +1 -1
  60. package/dist/src/harness/model-call/request.d.ts +2 -1
  61. package/dist/src/harness/model-call/run.js +1 -1
  62. package/dist/src/harness/model-call/usage.js +1 -1
  63. package/dist/src/harness/session-machine/current.d.ts +8 -0
  64. package/dist/src/harness/session-machine/current.js +1 -1
  65. package/dist/src/harness/token-estimate.js +1 -1
  66. package/dist/src/harness/types.d.ts +6 -0
  67. package/dist/src/internal/application/stamped-package-version.js +1 -1
  68. package/dist/src/internal/attachments/media-metadata.d.ts +0 -2
  69. package/dist/src/internal/attachments/media-metadata.js +1 -1
  70. package/dist/src/internal/attachments/read-media-metadata.d.ts +7 -0
  71. package/dist/src/internal/attachments/read-media-metadata.js +2 -0
  72. package/dist/src/internal/authored-asset-import-plugin.d.ts +11 -3
  73. package/dist/src/internal/authored-asset-import-plugin.js +1 -1
  74. package/dist/src/internal/authored-module-build-options.js +1 -1
  75. package/dist/src/internal/authored-module-graph.js +1 -1
  76. package/dist/src/internal/authored-module-loader.d.ts +0 -1
  77. package/dist/src/internal/authored-module-loader.js +1 -1
  78. package/dist/src/internal/authored-package-boundary.d.ts +3 -0
  79. package/dist/src/internal/authored-package-boundary.js +1 -1
  80. package/dist/src/internal/input-text.d.ts +2 -1
  81. package/dist/src/internal/nitro/dev-client-address.d.ts +12 -0
  82. package/dist/src/internal/nitro/dev-client-address.js +1 -1
  83. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  84. package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +6 -3
  85. package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
  86. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  87. package/dist/src/public/channels/auth.d.ts +14 -0
  88. package/dist/src/public/channels/auth.js +1 -1
  89. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +6 -1
  90. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
  91. package/dist/src/public/channels/slack/reply-delivery.d.ts +1 -7
  92. package/dist/src/public/channels/slack/reply-delivery.js +1 -1
  93. package/dist/src/public/channels/slack/slackChannel.d.ts +2 -6
  94. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  95. package/dist/src/public/channels/undelivered-reply.d.ts +30 -0
  96. package/dist/src/public/channels/undelivered-reply.js +1 -0
  97. package/dist/src/runtime/connections/authorization-complete-page.d.ts +14 -2
  98. package/dist/src/runtime/connections/authorization-complete-page.js +5 -5
  99. package/dist/src/runtime/connections/mcp-client.d.ts +5 -2
  100. package/dist/src/runtime/connections/mcp-client.js +1 -1
  101. package/dist/src/runtime/connections/openapi-client.js +1 -1
  102. package/dist/src/runtime/connections/openapi-operations.d.ts +4 -0
  103. package/dist/src/runtime/connections/openapi-operations.js +1 -1
  104. package/dist/src/runtime/connections/openapi-schema.d.ts +19 -14
  105. package/dist/src/runtime/connections/openapi-schema.js +1 -1
  106. package/dist/src/runtime/local-dev-capability.d.ts +2 -2
  107. package/dist/src/runtime/local-dev-capability.js +1 -1
  108. package/dist/src/runtime/subagents/workflow.js +1 -1
  109. package/dist/src/setup/scaffold/create/project.js +1 -1
  110. package/dist/src/shared/connection-types.d.ts +5 -0
  111. package/dist/src/svelte/index.js +1 -1
  112. package/dist/src/svelte/use-eve-agent.js +1 -1
  113. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  114. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  115. package/dist/src/tools/schema.d.ts +2 -0
  116. package/dist/src/tools/schema.js +1 -1
  117. package/dist/src/tools/signature.js +1 -1
  118. package/dist/src/vue/index.js +1 -1
  119. package/dist/src/vue/use-eve-agent.js +1 -1
  120. package/docs/channels/chat-sdk.mdx +1 -1
  121. package/docs/channels/custom.mdx +4 -0
  122. package/docs/channels/slack.mdx +3 -1
  123. package/docs/concepts/built-in-tools.md +1 -1
  124. package/docs/concepts/default-harness.md +1 -1
  125. package/docs/concepts/sessions-runs-and-streaming.md +1 -1
  126. package/docs/connections/mcp.mdx +1 -1
  127. package/docs/connections/openapi.mdx +1 -1
  128. package/docs/guides/auth-and-route-protection.md +4 -0
  129. package/docs/reference/cli.md +3 -1
  130. package/docs/reference/typescript-api.md +3 -1
  131. package/docs/tools/human-in-the-loop.md +3 -1
  132. package/docs/tools/tasks.md +2 -2
  133. package/package.json +6 -2
@@ -1 +1 @@
1
- import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-build-options.js";import{createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createPseudoPackagePlugin}from"#internal/bundler/pseudo-packages.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{hasVercelScheduleCollections,usesLocalVercelSchedules}from"#internal/schedules/consumer-route.js";import{configureInstrumentationEntry}from"#internal/nitro/host/instrumentation-entry.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{prepareSkillServerAssets}from"#internal/nitro/host/skill-server-assets.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createExternalDependencyOutputCheckPlugin}from"#internal/nitro/host/external-dependency-output-check-plugin.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),EVE_NITRO_BUILDER=`rolldown`,LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=collectConfiguredExternalDependencies(e.compileResult.manifest);return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectConfiguredExternalDependencies(e){return[...e.config.build?.externalDependencies??[],...e.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let{preset:n}=t,r=collectConfiguredSandboxProviderNames(e.compileResult.manifest),i=shouldPruneLocalSandboxProviders({configuredBackendNames:r,preset:n})?createCompiledSandboxProviderPrunePlugin():null,a=[],o=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(r.has(e)?a:o).push(t);let s=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,mountId:e.mountId})))),c=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),l=[createPseudoPackagePlugin(),t.development?null:createDevelopmentRuntimePrunePlugin(),i,createOptionalEngineDependencyPlugin(o),createExtensionExternalDependencyPlugin(c),t.development?null:createExternalDependencyOutputCheckPlugin({appRoot:e.appRoot,externalDependencies:collectConfiguredExternalDependencies(e.compileResult.manifest)}),createExtensionMountPlugin(c,extensionOverridePaths(e.compileResult.manifest)),s].filter(e=>e!==null);return{nitroRolldownConfig:{output:{sourcemapIgnoreList:/node_modules/},tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(l),tracedAppDependencies:collectHostedTraceDependencies(e,a),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(c)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){t.compiledArtifacts.instrumentationPluginPath!==void 0&&configureInstrumentationEntry(e,t.compiledArtifacts.instrumentationPluginPath),addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,{development:!0,preset:void 0}),r=createApplicationNitroPlugins(e);usesLocalVercelSchedules(e.compileResult.manifest)&&r.push(resolvePackageSourceFilePath(`src/internal/nitro/host/local-schedules-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},builder:EVE_NITRO_BUILDER,buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,{development:!1,preset:n}),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let{manifest:a,paths:o}=e.compileResult,s=await prepareSkillServerAssets({stagingDirectory:join(t.buildDir,`eve-skill-assets`),skills:a.skills.map(e=>e.name),skillsRoot:join(o.compileDirectoryPath,a.workspaceResourceRoot.logicalPath,`skills`)}),c=await createNitro({_cli:{command:`build`},builder:EVE_NITRO_BUILDER,buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},logging:{compressedSizes:!1},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:{...r.nitroRolldownConfig,experimental:{attachDebugInfo:`none`}},rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverAssets:s,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,hasVercelScheduleCollections:hasVercelScheduleCollections(e.compileResult.manifest),publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),c.options.serverAssets=c.options.serverAssets.filter(e=>e.baseName!==`server`),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(c);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(c,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(c,e),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
1
+ import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{extensionOverridePaths}from"#compiler/extension-mount-bindings.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{findAuthoredPackageRoot}from"#internal/authored-package-boundary.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{resolveAuthoredTsConfigPath}from"#internal/authored-module-build-options.js";import{createExtensionMountPlugin}from"#internal/bundler/extension-mount-plugin.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createPseudoPackagePlugin}from"#internal/bundler/pseudo-packages.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{hasVercelScheduleCollections,usesLocalVercelSchedules}from"#internal/schedules/consumer-route.js";import{configureInstrumentationEntry}from"#internal/nitro/host/instrumentation-entry.js";import{createCompiledSandboxProviderPrunePlugin}from"#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";import{createDevelopmentRuntimePrunePlugin}from"#internal/nitro/host/development-runtime-prune-plugin.js";import{prepareSkillServerAssets}from"#internal/nitro/host/skill-server-assets.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createExternalDependencyOutputCheckPlugin}from"#internal/nitro/host/external-dependency-output-check-plugin.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],INSTRUMENTATION_ALIAS_PATHS={"eve/instrumentation":`src/public/instrumentation/index.ts`,"eve/instrumentation/otel":`src/public/instrumentation/otel.ts`},WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),EVE_NITRO_BUILDER=`rolldown`,LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestHasWorkflowProgram(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.tools.some(e=>e.workflowProgram!==void 0))}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=collectConfiguredExternalDependencies(e.compileResult.manifest);return[...new Set([...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectConfiguredExternalDependencies(e){return[...e.config.build?.externalDependencies??[],...e.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxProviderNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.providerName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxProviders(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,t,n){return t.startsWith(`workflow`)?resolveWorkflowModulePath(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?resolveNitroModuleComparisonPath(n===void 0?e:dirname(resolveNitroModuleComparisonPath(e,n)),t):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=r.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(r.length+1);if(o===a)return`.`;let s=relative(r,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,o=`${r}/src/`,s=`${t}/dist/src/`,c=`${r}/dist/src/`;if(i.startsWith(o))return`src/${n.slice(a.length)}`;if(i.startsWith(c))return`src/${n.slice(s.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(n,r){let i=resolveNitroImportPath(e.options.rootDir,n,r);return i===null||!(await t()).has(normalizeStepTransformComparisonPath(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){e.hooks.hook(`rollup:before`,(n,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({async transform(n,r){let i=await t(),a=resolveNitroModuleComparisonPath(e.options.rootDir,r);return i.has(normalizeStepTransformComparisonPath(a))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,a),n,`step`,a,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let{preset:n}=t,r=collectConfiguredSandboxProviderNames(e.compileResult.manifest),i=shouldPruneLocalSandboxProviders({configuredBackendNames:r,preset:n})?createCompiledSandboxProviderPrunePlugin():null,a=[],o=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(r.has(e)?a:o).push(t);let s=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,mountId:e.mountId})))),c=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),l=[createPseudoPackagePlugin(),t.development?null:createDevelopmentRuntimePrunePlugin(),i,createOptionalEngineDependencyPlugin(o),createExtensionExternalDependencyPlugin(c),t.development?null:createExternalDependencyOutputCheckPlugin({appRoot:e.appRoot,externalDependencies:collectConfiguredExternalDependencies(e.compileResult.manifest)}),createExtensionMountPlugin(c,extensionOverridePaths(e.compileResult.manifest)),s,createAuthoredAssetImportPlugin({authoredSourceOnly:!0,packageRoot:findAuthoredPackageRoot(e.appRoot)??e.appRoot})].filter(e=>e!==null);return{nitroRolldownConfig:{output:{sourcemapIgnoreList:/node_modules/},tsconfig:resolveAuthoredTsConfigPath(e.appRoot)},nitroRollupConfig:createNitroBundlerConfig(l),tracedAppDependencies:collectHostedTraceDependencies(e,a),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(c)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestHasWorkflowProgram(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){t.compiledArtifacts.instrumentationPluginPath!==void 0&&configureInstrumentationEntry(e,t.compiledArtifacts.instrumentationPluginPath),addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;for(let[t,n]of Object.entries(INSTRUMENTATION_ALIAS_PATHS))e.options.alias[t]=resolvePackageSourceFilePath(n);addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){let n,getTargets=()=>n??=collectNitroStepTransformTargets(t,e.options.rootDir),invalidate=()=>{n=void 0};return e.hooks.hook(`build:before`,invalidate),addNitroStepModuleSideEffectsPlugin(e,getTargets),addNitroStepTransformPlugin(e,getTargets),[invalidate]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,{development:!0,preset:void 0}),r=createApplicationNitroPlugins(e);usesLocalVercelSchedules(e.compileResult.manifest)&&r.push(resolvePackageSourceFilePath(`src/internal/nitro/host/local-schedules-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath===void 0&&r.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let i=await createNitro({_cli:{command:`dev`},builder:EVE_NITRO_BUILDER,buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:r,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let a=join(i.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(i,e);let o=configureNitroStepPlugins(i,a);return i.hooks.hook(`dev:reload`,()=>{for(let e of o)e()}),externalizeDevelopmentWorkflowBundle(i,e),await configureDevelopmentNitroRoutes(i,e),await addNitroStepNoExternals(i,a),i}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),r=createApplicationNitroBundlerConfiguration(e,{development:!1,preset:n}),i=createApplicationNitroPlugins(e);i.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let{manifest:a,paths:o}=e.compileResult,s=await prepareSkillServerAssets({stagingDirectory:join(t.buildDir,`eve-skill-assets`),skills:a.skills.map(e=>e.name),skillsRoot:join(o.compileDirectoryPath,a.workspaceResourceRoot.logicalPath,`skills`)}),c=await createNitro({_cli:{command:`build`},builder:EVE_NITRO_BUILDER,buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},logging:{compressedSizes:!1},output:{dir:t.outputDir},preset:n,plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:{...r.nitroRolldownConfig,experimental:{attachDebugInfo:`none`}},rollupConfig:r.nitroRollupConfig,rootDir:e.appRoot,serverAssets:s,serverDir:!1,traceDeps:r.tracedAppDependencies,traceOpts:{nft:{paths:r.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,hasVercelScheduleCollections:hasVercelScheduleCollections(e.compileResult.manifest),publicRoutePrefix:t.publicRoutePrefix,workspaceMember:t.workspaceMember})});if(await writeEveVersionedCacheMetadata(t.buildDir),c.options.serverAssets=c.options.serverAssets.filter(e=>e.baseName!==`server`),configureSharedApplicationNitro(c,e),configureNitroStepPlugins(c,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0){applyEveCronHandlerRoute(c);let t=createProductionNitroArtifactsConfig(e.appRoot);registerScheduleTaskHandlers(c,{artifactsConfig:t,dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})}return await configureProductionNitroRoutes(c,e),await addNitroStepNoExternals(c,join(e.workflowBuildDir,`steps.mjs`)),c}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxProviders};
@@ -6,9 +6,12 @@ export interface ChannelRequestTrace {
6
6
  channelKind?: string;
7
7
  }): void;
8
8
  }
9
- /** The request lifetime ends at handler return, not response-body consumption. */
10
- export declare function traceChannelRequest<T extends Response>(input: {
9
+ /**
10
+ * The request span ends when the response body finishes, errors, or is
11
+ * cancelled, not when the handler returns.
12
+ */
13
+ export declare function traceChannelRequest(input: {
11
14
  readonly request: Request;
12
15
  readonly routeKey: string;
13
- }, handler: (operation: ChannelRequestTrace | undefined) => Promise<T>): Promise<T>;
16
+ }, handler: (operation: ChannelRequestTrace | undefined) => Promise<Response>): Promise<Response>;
14
17
  export declare function traceConnectionEventRequest(request: Request, handler: (span: Span | undefined) => Promise<Response>): Promise<Response>;
@@ -1 +1 @@
1
- import{SpanKind,SpanStatusCode,context,propagation,trace}from"#compiled/@opentelemetry/api/index.js";import{getInstrumentationRuntime}from"#instrumentation/runtime.js";import{markAgentTraceContext}from"#tracing/eve/agent-trace-context.js";import{withErrorContent}from"#compiled/@vercel/agent-runs/otel.js";import{connectionEventDestination}from"#runtime/connections/events/path.js";const headersGetter={get:(e,t)=>e.get(t)??void 0,keys:e=>[...e.keys()]};async function traceChannelRequest(e,t){return traceRequest({...e,spanName:`agent.channel.request`},e=>t(e===void 0?void 0:{reference:e.spanContext(),channel(t){t.channelName!==void 0&&(e.setAttribute(`agent.channel.name`,t.channelName),e.setAttribute(`eve.channel.name`,t.channelName)),t.channelKind!==void 0&&(e.setAttribute(`agent.channel.kind`,t.channelKind),e.setAttribute(`eve.channel.kind`,t.channelKind))}}))}async function traceConnectionEventRequest(e,t){return traceRequest({request:e,routeKey:`POST ${connectionEventDestination(`:connectionName`).replace(`%3AconnectionName`,`:connectionName`)}`,spanName:`agent.connection.event.request`},t)}async function traceRequest(e,t){if(getInstrumentationRuntime()?.otelSettings?.traceChannelRequests!==!0)return t(void 0);let{request:n,routeKey:r}=e,i=propagation.extract(context.active(),n.headers,headersGetter),a=r.indexOf(` `),o;try{o=new URL(n.url)}catch{}let s=trace.getTracer(`eve.channel`).startSpan(e.spanName,{kind:SpanKind.SERVER,attributes:{"operation.name":e.spanName,"resource.name":e.spanName,"http.request.method":n.method,"http.route":a===-1?r:r.slice(a+1),"url.scheme":o?.protocol.replace(/:$/,``),"server.address":o?.hostname}},i);try{let e=await context.with(markAgentTraceContext(withErrorContent(trace.setSpan(i,s),!1)),()=>t(s));return s.setAttribute(`http.response.status_code`,e.status),e.status>=500&&s.setStatus({code:SpanStatusCode.ERROR}),e}catch(e){throw s.setStatus({code:SpanStatusCode.ERROR}),e}finally{s.end()}}export{traceChannelRequest,traceConnectionEventRequest};
1
+ import{SpanKind,SpanStatusCode,context,propagation,trace}from"#compiled/@opentelemetry/api/index.js";import{getInstrumentationRuntime}from"#instrumentation/runtime.js";import{markAgentTraceContext}from"#tracing/eve/agent-trace-context.js";import{withErrorContent}from"#compiled/@vercel/agent-runs/otel.js";import{connectionEventDestination}from"#runtime/connections/events/path.js";const headersGetter={get:(e,t)=>e.get(t)??void 0,keys:e=>[...e.keys()]};async function traceChannelRequest(e,t){return traceRequest({...e,spanName:`agent.channel.request`},e=>t(e===void 0?void 0:{reference:e.spanContext(),channel(t){t.channelName!==void 0&&(e.setAttribute(`agent.channel.name`,t.channelName),e.setAttribute(`eve.channel.name`,t.channelName)),t.channelKind!==void 0&&(e.setAttribute(`agent.channel.kind`,t.channelKind),e.setAttribute(`eve.channel.kind`,t.channelKind))}}))}async function traceConnectionEventRequest(e,t){return traceRequest({request:e,routeKey:`POST ${connectionEventDestination(`:connectionName`).replace(`%3AconnectionName`,`:connectionName`)}`,spanName:`agent.connection.event.request`},t)}async function traceRequest(e,t){if(getInstrumentationRuntime()?.otelSettings?.traceChannelRequests!==!0)return t(void 0);let{request:n,routeKey:r}=e,i=propagation.extract(context.active(),n.headers,headersGetter),a=r.indexOf(` `),o;try{o=new URL(n.url)}catch{}let s=trace.getTracer(`eve.channel`).startSpan(e.spanName,{kind:SpanKind.SERVER,attributes:{"operation.name":e.spanName,"resource.name":e.spanName,"http.request.method":n.method,"http.route":a===-1?r:r.slice(a+1),"url.scheme":o?.protocol.replace(/:$/,``),"server.address":o?.hostname}},i);try{let e=await context.with(markAgentTraceContext(withErrorContent(trace.setSpan(i,s),!1)),()=>t(s));return s.setAttribute(`http.response.status_code`,e.status),e.status>=500&&s.setStatus({code:SpanStatusCode.ERROR}),endWithBody(e,()=>s.end())}catch(e){throw s.setStatus({code:SpanStatusCode.ERROR}),s.end(),e}}function endWithBody(e,t){if(e.body===null)return t(),e;let{readable:n,writable:r}=new TransformStream;return e.body.pipeTo(r).then(t,t),new Response(n,e)}export{traceChannelRequest,traceConnectionEventRequest};
@@ -1,2 +1,2 @@
1
- import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{findWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{mapConcurrent}from"#shared/map-concurrent.js";import{onVendoredDependencyLog}from"#internal/bundler/vendored-dependency-log.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,mergeWorkflowManifest}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;constructor(e){let t=[resolvePackageSourceDirectoryPath(`src/execution`),resolvePackageSourceDirectoryPath(`src/runtime/subagents`),resolvePackageSourceDirectoryPath(`src/runtime/connections/events`),resolvePackageSourceDirectoryPath(`src/subagents`),resolvePackageSourceDirectoryPath(`src/tools/provided`)];e.includeTestFixtures===!0&&t.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:t,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.authoredWorkflowModules??{directiveModules:[],workflowModules:[]},this.#t=e.compiledArtifactsBootstrapPath,this.#n=e.outDir,this.#r=deriveEveWorkflowQueueNamespace(e.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#i(e))}async#i(e){await prepareEveVersionedCacheDirectory(this.#n);let t=await this.#o();if(t.length===0)throw Error(`Expected framework workflow source files under eve's execution, runtime/subagents, subagents, or tools/provided source directories.`);let n=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let r=await this.discoverEntries(t),i=this.#e,a=mergeStepEntries(r,i),o=join(this.#n,`steps.mjs`),s=join(this.#n,`workflows.mjs`),c=e.nitroStepOutfile,l=e.nitroWorkflowOutfile,writeStepEntry=(e,t)=>writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:a,outfile:e,precomputedManifest:t,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),u=await writeStepEntry(o);c!==void 0&&c!==o&&await writeStepEntry(c,u);let{manifest:d}=await this.createWorkflowsBundle({additionalOutputs:l===void 0||l===s?[]:[{outfile:l,stepRegistrationsPath:c??o}],appWorkflowFiles:i.workflowModules,frameworkSerdeFiles:r.discoveredSerdeFiles,frameworkWorkflowFiles:r.discoveredWorkflows,outfile:s,stepRegistrationsPath:o,tsconfigPath:n});await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...u.steps,...d.steps},workflows:{...u.workflows,...d.workflows},classes:{...u.classes,...d.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.transformProjectRoot;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e){let t={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]},n=await mapConcurrent(e,async e=>{let t=await readFile(e,`utf8`);return{filePath:e,patterns:await findWorkflowPatterns(e,t)}});for(let{filePath:e,patterns:r}of n)r.hasUseStep&&t.discoveredSteps.push(e),r.hasUseWorkflow&&t.discoveredWorkflows.push(e),r.hasSerde&&t.discoveredSerdeFiles.push(e);return t}async createWorkflowsBundle({additionalOutputs:e=[],appWorkflowFiles:t,frameworkSerdeFiles:n,frameworkWorkflowFiles:r,outfile:i,stepRegistrationsPath:a,tsconfigPath:o}){let s={},c=await mapConcurrent([{label:`framework`,serdeFiles:n,workflowFiles:r},{label:`app`,serdeFiles:[],workflowFiles:t}],async e=>{let t={};return{code:await this.#a({...e,manifest:t,tsconfigPath:o}),manifest:t}});for(let e of c)mergeWorkflowManifest(s,e.manifest);let l=composeWorkflowDriverCode(c.map(e=>e.code));return await Promise.all([{outfile:i,stepRegistrationsPath:a},...e].map(e=>bundleFinalWorkflowOutput({code:l,outfile:e.outfile,queueNamespace:this.#r,stepRegistrationsPath:e.stepRegistrationsPath}))),{manifest:s}}async#a(e){let t=[...e.workflowFiles].sort(),n=new Set(t),r=[...e.serdeFiles].sort().filter(e=>!n.has(e));if(t.length===0&&r.length===0)return``;let i=[...t.map(e=>createWorkflowImport(e,this.config.workingDir)),...r.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
- `);return(await buildSingleRolldownChunk(`${e.label} workflow driver chunk`,{cwd:this.config.workingDir,onLog(e,t,n){if(e===`warn`&&t.code===`UNRESOLVED_IMPORT`)throw Error(`Cannot build workflow bundle: ${t.message}`);onVendoredDependencyLog(e,t,n)},input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(i),createWorkflowDriverAliasPlugin(this.config.workingDir),createAuthoredRelativeExtensionResolverPlugin({extensions:WORKFLOW_SOURCE_EXTENSIONS}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:this.transformProjectRoot,extensions:WORKFLOW_SOURCE_EXTENSIONS}),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:e.manifest,projectRoot:this.transformProjectRoot,sideEffectFiles:[...t,...r],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`],extensions:WORKFLOW_SOURCE_EXTENSIONS,mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`cjs`,sourcemap:`inline`}})).code}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},r=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),r),r}async#o(){return await this.getInputFiles()}};function mergeStepEntries(e,t){return{discoveredSerdeFiles:e.discoveredSerdeFiles,discoveredSteps:[...new Set([...e.discoveredSteps,...t.directiveModules])]}}export{WorkflowBundleBuilder};
1
+ import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceDirectoryPath,resolveWorkflowModulePath}from"#internal/application/package.js";import{findAuthoredPackageRoot}from"#internal/authored-package-boundary.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{findWorkflowPatterns}from"#internal/workflow-bundle/workflow-builders.js";import{mapConcurrent}from"#shared/map-concurrent.js";import{onVendoredDependencyLog}from"#internal/bundler/vendored-dependency-log.js";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WORKFLOW_BUILDER_DEFERRED_PACKAGES,WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";import{deriveEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{runQueuedWorkflowBuild}from"#internal/workflow-bundle/build-queue.js";import{WORKFLOW_SOURCE_EXTENSIONS,WORKFLOW_VIRTUAL_ENTRY_ID,bundleFinalWorkflowOutput,collectWorkflowInputFiles,composeWorkflowDriverCode,convertClassesManifest,convertStepsManifest,convertWorkflowsManifest,createEvePackageImportsPlugin,createWorkflowDriverAliasPlugin,createWorkflowImport,createWorkflowNodeBuiltinGuardPlugin,createWorkflowTransformPlugin,createWorkflowVirtualEntryPlugin,mergeWorkflowManifest}from"#internal/workflow-bundle/builder-support.js";import{writeNitroStepEntrypoint}from"#internal/workflow-bundle/nitro-step-entry.js";var WorkflowBundleBuilder=class{#e;#t;#n;#r;config;constructor(e){let t=[resolvePackageSourceDirectoryPath(`src/execution`),resolvePackageSourceDirectoryPath(`src/runtime/subagents`),resolvePackageSourceDirectoryPath(`src/runtime/connections/events`),resolvePackageSourceDirectoryPath(`src/subagents`),resolvePackageSourceDirectoryPath(`src/tools/provided`)];e.includeTestFixtures===!0&&t.push(resolvePackageSourceDirectoryPath(`src/internal/testing`)),this.config={buildTarget:`standalone`,dirs:t,externalPackages:[...WORKFLOW_STEP_EXTERNAL_PACKAGES,...WORKFLOW_BUILDER_DEFERRED_PACKAGES],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.authoredWorkflowModules??{directiveModules:[],workflowModules:[]},this.#t=e.compiledArtifactsBootstrapPath,this.#n=e.outDir,this.#r=deriveEveWorkflowQueueNamespace(e.agentName)}async build(e={}){await runQueuedWorkflowBuild(this.#n,async()=>this.#i(e))}async#i(e){await prepareEveVersionedCacheDirectory(this.#n);let t=await this.#o();if(t.length===0)throw Error(`Expected framework workflow source files under eve's execution, runtime/subagents, subagents, or tools/provided source directories.`);let n=await this.findTsConfigPath();await mkdir(this.#n,{recursive:!0});let r=await this.discoverEntries(t),i=this.#e,a=mergeStepEntries(r,i),o=join(this.#n,`steps.mjs`),s=join(this.#n,`workflows.mjs`),c=e.nitroStepOutfile,l=e.nitroWorkflowOutfile,writeStepEntry=(e,t)=>writeNitroStepEntrypoint({builtinsPath:resolveWorkflowModulePath(`workflow/internal/builtins`),discoveredEntries:a,outfile:e,precomputedManifest:t,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,sideEffectFiles:[this.#t],workingDir:this.config.workingDir}),u=await writeStepEntry(o);c!==void 0&&c!==o&&await writeStepEntry(c,u);let{manifest:d}=await this.createWorkflowsBundle({additionalOutputs:l===void 0||l===s?[]:[{outfile:l,stepRegistrationsPath:c??o}],appWorkflowFiles:i.workflowModules,frameworkSerdeFiles:r.discoveredSerdeFiles,frameworkWorkflowFiles:r.discoveredWorkflows,outfile:s,stepRegistrationsPath:o,tsconfigPath:n});await this.createManifest({workflowBundlePath:join(this.#n,`workflows.mjs`),manifestDir:this.#n,manifest:{steps:{...u.steps,...d.steps},workflows:{...u.workflows,...d.workflows},classes:{...u.classes,...d.classes}}}),await writeEveVersionedCacheMetadata(this.#n)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.transformProjectRoot;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);try{return await readFile(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=dirname(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>resolve(this.config.workingDir,e));return(await Promise.all(e.map(e=>collectWorkflowInputFiles(e)))).flat()}async discoverEntries(e){let t={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]},n=await mapConcurrent(e,async e=>{let t=await readFile(e,`utf8`);return{filePath:e,patterns:await findWorkflowPatterns(e,t)}});for(let{filePath:e,patterns:r}of n)r.hasUseStep&&t.discoveredSteps.push(e),r.hasUseWorkflow&&t.discoveredWorkflows.push(e),r.hasSerde&&t.discoveredSerdeFiles.push(e);return t}async createWorkflowsBundle({additionalOutputs:e=[],appWorkflowFiles:t,frameworkSerdeFiles:n,frameworkWorkflowFiles:r,outfile:i,stepRegistrationsPath:a,tsconfigPath:o}){let s={},c=await mapConcurrent([{label:`framework`,serdeFiles:n,workflowFiles:r},{label:`app`,serdeFiles:[],workflowFiles:t}],async e=>{let t={};return{code:await this.#a({...e,manifest:t,tsconfigPath:o}),manifest:t}});for(let e of c)mergeWorkflowManifest(s,e.manifest);let l=composeWorkflowDriverCode(c.map(e=>e.code));return await Promise.all([{outfile:i,stepRegistrationsPath:a},...e].map(e=>bundleFinalWorkflowOutput({code:l,outfile:e.outfile,queueNamespace:this.#r,stepRegistrationsPath:e.stepRegistrationsPath}))),{manifest:s}}async#a(e){let t=[...e.workflowFiles].sort(),n=new Set(t),r=[...e.serdeFiles].sort().filter(e=>!n.has(e));if(t.length===0&&r.length===0)return``;let i=[...t.map(e=>createWorkflowImport(e,this.config.workingDir)),...r.map(e=>createWorkflowImport(e,this.config.workingDir))].join(`
2
+ `);return(await buildSingleRolldownChunk(`${e.label} workflow driver chunk`,{cwd:this.config.workingDir,onLog(e,t,n){if(e===`warn`&&t.code===`UNRESOLVED_IMPORT`)throw Error(`Cannot build workflow bundle: ${t.message}`);onVendoredDependencyLog(e,t,n)},input:WORKFLOW_VIRTUAL_ENTRY_ID,platform:`neutral`,plugins:[createWorkflowVirtualEntryPlugin(i),createWorkflowDriverAliasPlugin(this.config.workingDir),createAuthoredRelativeExtensionResolverPlugin({extensions:WORKFLOW_SOURCE_EXTENSIONS}),createAuthoredAssetImportPlugin({authoredSourceOnly:!0,packageRoot:findAuthoredPackageRoot(this.transformProjectRoot)??this.transformProjectRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:this.transformProjectRoot,extensions:WORKFLOW_SOURCE_EXTENSIONS}),createEvePackageImportsPlugin(this.config.workingDir,{workflowCondition:!0}),createWorkflowTransformPlugin({manifest:e.manifest,projectRoot:this.transformProjectRoot,sideEffectFiles:[...t,...r],workingDir:this.config.workingDir}),createWorkflowNodeBuiltinGuardPlugin()],resolve:{conditionNames:[`eve-source`,`workflow`],extensions:WORKFLOW_SOURCE_EXTENSIONS,mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`cjs`,sourcemap:`inline`}})).code}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:convertStepsManifest(e.steps),workflows:convertWorkflowsManifest(e.workflows),classes:convertClassesManifest(e.classes)},r=JSON.stringify(n,null,2);return await mkdir(t,{recursive:!0}),await writeFile(join(t,`manifest.json`),r),r}async#o(){return await this.getInputFiles()}};function mergeStepEntries(e,t){return{discoveredSerdeFiles:e.discoveredSerdeFiles,discoveredSteps:[...new Set([...e.discoveredSteps,...t.directiveModules])]}}export{WorkflowBundleBuilder};
@@ -347,6 +347,20 @@ export declare function none<TEvent = unknown>(): AuthFn<TEvent>;
347
347
  * deployment (`eve start`, a Vercel deployment, or any container host) sets
348
348
  * neither flag, so `localDev()` authenticates nothing there. Layer a real
349
349
  * authenticator on those hosts.
350
+ *
351
+ * On a development server, `localDev()` also refuses requests a browser sent
352
+ * on behalf of another site: a request addressed to a host that is neither
353
+ * loopback nor one of this machine's addresses, or one whose `Origin` is not. Browsers set both themselves and
354
+ * send `Origin` on every cross-origin request that can change state, so a web
355
+ * page cannot use the developer's browser to reach the local agent, including
356
+ * through DNS rebinding. Frontends on any loopback host and port, or on this
357
+ * machine's own address, still authenticate.
358
+ *
359
+ * On `eve dev`, `localDev()` also refuses callers whose connection comes from
360
+ * another machine, such as LAN clients of a server started with
361
+ * `--host 0.0.0.0`. A tunnel or reverse proxy on this machine still forwards
362
+ * its callers as `local-dev`, so expose a development server that way only
363
+ * behind an authenticator that runs before `localDev()`.
350
364
  */
351
365
  export declare function localDev(): AuthFn<Request>;
352
366
  /**
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{areTokenClaimMatchersSatisfied}from"#channel/auth/token-claims.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{ANONYMOUS_SESSION_AUTH_CONTEXT}from"#channel/principal-identity.js";import{resolveVercelOidcCurrentProject}from"#channel/auth/vercel-oidc-project.js";import{authenticateHttpBasicStrategy}from"#channel/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#channel/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#channel/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#channel/auth/oidc.js";import{createRuntimeSessionAuthContext}from"#channel/auth/types.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#channel/ip-allow-list.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let n=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtHmacStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtEcdsaStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1,currentVercelProject:void 0});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){if(e===null||e.length===0)return{kind:`not-authenticated`};let n={acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=t.currentVercelProject===void 0?n:{...n,currentVercelProject:t.currentVercelProject};return await authenticateOidcStrategy({strategy:r,token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e!==null&&isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeAuthChallengeParameter(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeAuthChallengeParameter(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function isValidOAuthIdentifierUrl(e){try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`&&isLoopbackHostname(t.hostname))&&t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0}catch{return!1}}function isValidMetadataPath(e){if(!e.startsWith(`/`)||e.startsWith(`//`))return!1;let t=new URL(e,`https://eve.invalid`);return t.origin===`https://eve.invalid`&&t.search.length===0&&t.hash.length===0}var UnauthenticatedError=class extends Error{response;constructor(e={}){super(e.message??`Authorization is required for this route.`),this.name=`UnauthenticatedError`,this.response=createUnauthorizedResponse({...e,status:401})}},ForbiddenError=class extends Error{response;constructor(e={}){super(e.message??`Forbidden.`),this.name=`ForbiddenError`,this.response=createUnauthorizedResponse({...e,status:403})}};const OAUTH_RESOURCE_SYMBOL=Symbol.for(`eve.channels.auth.oauthResource`);function oauthResource(e,t){let n=t.issuer===void 0?t.authorizationServers:[t.issuer];if(n.length===0||n.some(e=>!isValidOAuthIdentifierUrl(e)))throw Error(`oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).`);if(t.resource!==void 0&&!isValidOAuthIdentifierUrl(t.resource))throw Error(`oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).`);if(t.metadataPath!==void 0&&!isValidMetadataPath(t.metadataPath))throw Error(`oauthResource metadataPath must be an absolute path without a host, query, or fragment.`);let r=Array.isArray(e)?e:[e],composed=async e=>{for(let t of r){let n=await t(e);if(n)return n}return null},i=collectDeclaredChallenges(r),a=withAuthChallenges(composed,i.length>0?i:[{scheme:`Bearer`}]);return Object.defineProperty(a,OAUTH_RESOURCE_SYMBOL,{enumerable:!1,value:t}),a}function readOAuthResourceOptions(e){if(!Array.isArray(e))return e[OAUTH_RESOURCE_SYMBOL]}const AUTH_CHALLENGES_SYMBOL=Symbol.for(`eve.channels.auth.challenges`);function withAuthChallenges(e,t){let wrapped=t=>e(t);return Object.defineProperty(wrapped,AUTH_CHALLENGES_SYMBOL,{value:t}),wrapped}function getDeclaredChallenges(e){return e[AUTH_CHALLENGES_SYMBOL]}function collectDeclaredChallenges(e){let t=new Set,n=[];for(let r of e)for(let e of getDeclaredChallenges(r)??[]){let r=formatChallenge(e);t.has(r)||(t.add(r),n.push(e))}return n}async function routeAuth(e,t){let n=Array.isArray(t)?t:[t];try{for(let t of n){let n=await t(e);if(n)return n}}catch(e){if(typeof e==`object`&&e&&`response`in e&&e.response instanceof Response)return e.response;throw e}let r=collectDeclaredChallenges(n);return createUnauthorizedResponse({challenges:r.length>0?addInvalidBearerTokenError(e,r):[{scheme:`Bearer`}]})}function addInvalidBearerTokenError(e,t){let n=e.headers.get(`authorization`);return n===null||!/^Bearer(?:\s|$)/i.test(n.trim())||!t.some(e=>e.scheme===`Bearer`)?t:t.map(e=>e.scheme!==`Bearer`||e.parameters?.error!==void 0?e:{...e,parameters:{...e.parameters,error:`invalid_token`}})}function placeholderAuth(){return()=>{if(process.env.VERCEL_ENV!==`production`)return null;throw new UnauthenticatedError({code:`eve_production_auth_not_configured`,message:`Production auth is not configured. Replace placeholderAuth() in agent/channels/eve.ts with your app's auth provider.`})}}function none(){return()=>ANONYMOUS_SESSION_AUTH_CONTEXT}function localDev(){return()=>isLocalDevelopmentServer()?LOCAL_DEV_SESSION_AUTH_CONTEXT:null}function isLocalDevelopmentServer(){return process.env.VERCEL&&process.env.VERCEL_ENV===`development`?!0:isEveDevEnvironment()}const LOCAL_DEV_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`local-dev`,principalId:`local-dev`,principalType:`local-dev`};async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!isVercelOidcIssuer(n.issuer))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};if(!n.audiences.some(e=>e.startsWith(`https://vercel.com/`)))return vercelOidcLog.debug(`Rejected token whose audience is not a Vercel audience.`,{audiences:n.audiences,issuer:n.issuer}),{ok:!1};let r=resolveCurrentVercelProject(t),i=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,currentVercelProject:r,issuer:n.issuer,subjects:t.subjects??[]});return i.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:i.principal.principalType,subject:i.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(i.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:i.kind,subjectsConfigured:(t.subjects??[]).length>0,...i.kind===`misconfigured`?{detail:i.message}:{}}),{ok:!1})}function resolveCurrentVercelProject(e){if(e.currentVercelProject!==void 0)return e.currentVercelProject;let t=process.env.VERCEL_PROJECT_ID?.trim();if(t===void 0||t.length===0)return;let n=process.env.VERCEL_TARGET_ENV?.trim()||process.env.VERCEL_ENV?.trim();return n===void 0||n.length===0?{projectId:t}:{environment:n,projectId:t}}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){let{subjects:t,...n}=e,r={...n,subjects:t?.map(e=>typeof e==`string`?e:e.subject)};return withAuthChallenges(async n=>{let i=extractBearerToken(n.headers.get(`authorization`)),a=e.currentVercelProject??(i!==null&&isLocalDevelopmentVercelOidc()?await resolveVercelOidcCurrentProject(n):void 0),o=await verifyVercelOidc(i,a===void 0?r:{...r,currentVercelProject:a});if(!o.ok)return null;let s=o.sessionAuth;return(s.principalType===`service`||s.principalType===`runtime`)&&t?.some(e=>typeof e!=`string`&&e.allowToolStubs===!0&&areTokenClaimMatchersSatisfied({sub:s.subject},{subjects:[e.subject]}))?{...s,allowToolStubs:!0}:s},[{scheme:`Bearer`}])}function isLocalDevelopmentVercelOidc(){return process.env.VERCEL_ENV===`development`?!0:process.env.VERCEL_ENV===`preview`||process.env.VERCEL_ENV===`production`?!1:isEveDevEnvironment()}function httpBasic(e,t){return withAuthChallenges(t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null},[{parameters:{realm:t?.realm??`eve`,charset:`UTF-8`},scheme:`Basic`}])}function jwtHmac(e){return withAuthChallenges(async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function jwtEcdsa(e){return withAuthChallenges(async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function oidc(e){return withAuthChallenges(async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function decodeUnverifiedJwtClaims(e){let t;try{t=decodeJwt(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}export{ForbiddenError,UnauthenticatedError,createIpAllowList,createUnauthorizedResponse,escapeAuthChallengeParameter,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,localDev,none,oauthResource,oidc,placeholderAuth,readOAuthResourceOptions,routeAuth,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc,withAuthChallenges};
1
+ import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{areTokenClaimMatchersSatisfied}from"#channel/auth/token-claims.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{ANONYMOUS_SESSION_AUTH_CONTEXT}from"#channel/principal-identity.js";import{isLocalMachineAddress,readTrustedDevelopmentPeer}from"#internal/nitro/dev-client-address.js";import{resolveVercelOidcCurrentProject}from"#channel/auth/vercel-oidc-project.js";import{authenticateHttpBasicStrategy}from"#channel/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#channel/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#channel/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#channel/auth/oidc.js";import{createRuntimeSessionAuthContext}from"#channel/auth/types.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#channel/ip-allow-list.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let n=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtHmacStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtEcdsaStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1,currentVercelProject:void 0});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){if(e===null||e.length===0)return{kind:`not-authenticated`};let n={acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=t.currentVercelProject===void 0?n:{...n,currentVercelProject:t.currentVercelProject};return await authenticateOidcStrategy({strategy:r,token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e!==null&&isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeAuthChallengeParameter(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeAuthChallengeParameter(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function isValidOAuthIdentifierUrl(e){try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`&&isLoopbackHostname(t.hostname))&&t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0}catch{return!1}}function isValidMetadataPath(e){if(!e.startsWith(`/`)||e.startsWith(`//`))return!1;let t=new URL(e,`https://eve.invalid`);return t.origin===`https://eve.invalid`&&t.search.length===0&&t.hash.length===0}var UnauthenticatedError=class extends Error{response;constructor(e={}){super(e.message??`Authorization is required for this route.`),this.name=`UnauthenticatedError`,this.response=createUnauthorizedResponse({...e,status:401})}},ForbiddenError=class extends Error{response;constructor(e={}){super(e.message??`Forbidden.`),this.name=`ForbiddenError`,this.response=createUnauthorizedResponse({...e,status:403})}};const OAUTH_RESOURCE_SYMBOL=Symbol.for(`eve.channels.auth.oauthResource`);function oauthResource(e,t){let n=t.issuer===void 0?t.authorizationServers:[t.issuer];if(n.length===0||n.some(e=>!isValidOAuthIdentifierUrl(e)))throw Error(`oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).`);if(t.resource!==void 0&&!isValidOAuthIdentifierUrl(t.resource))throw Error(`oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).`);if(t.metadataPath!==void 0&&!isValidMetadataPath(t.metadataPath))throw Error(`oauthResource metadataPath must be an absolute path without a host, query, or fragment.`);let r=Array.isArray(e)?e:[e],composed=async e=>{for(let t of r){let n=await t(e);if(n)return n}return null},i=collectDeclaredChallenges(r),a=withAuthChallenges(composed,i.length>0?i:[{scheme:`Bearer`}]);return Object.defineProperty(a,OAUTH_RESOURCE_SYMBOL,{enumerable:!1,value:t}),a}function readOAuthResourceOptions(e){if(!Array.isArray(e))return e[OAUTH_RESOURCE_SYMBOL]}const AUTH_CHALLENGES_SYMBOL=Symbol.for(`eve.channels.auth.challenges`);function withAuthChallenges(e,t){let wrapped=t=>e(t);return Object.defineProperty(wrapped,AUTH_CHALLENGES_SYMBOL,{value:t}),wrapped}function getDeclaredChallenges(e){return e[AUTH_CHALLENGES_SYMBOL]}function collectDeclaredChallenges(e){let t=new Set,n=[];for(let r of e)for(let e of getDeclaredChallenges(r)??[]){let r=formatChallenge(e);t.has(r)||(t.add(r),n.push(e))}return n}async function routeAuth(e,t){let n=Array.isArray(t)?t:[t];try{for(let t of n){let n=await t(e);if(n)return n}}catch(e){if(typeof e==`object`&&e&&`response`in e&&e.response instanceof Response)return e.response;throw e}let r=collectDeclaredChallenges(n);return createUnauthorizedResponse({challenges:r.length>0?addInvalidBearerTokenError(e,r):[{scheme:`Bearer`}]})}function addInvalidBearerTokenError(e,t){let n=e.headers.get(`authorization`);return n===null||!/^Bearer(?:\s|$)/i.test(n.trim())||!t.some(e=>e.scheme===`Bearer`)?t:t.map(e=>e.scheme!==`Bearer`||e.parameters?.error!==void 0?e:{...e,parameters:{...e.parameters,error:`invalid_token`}})}function placeholderAuth(){return()=>{if(process.env.VERCEL_ENV!==`production`)return null;throw new UnauthenticatedError({code:`eve_production_auth_not_configured`,message:`Production auth is not configured. Replace placeholderAuth() in agent/channels/eve.ts with your app's auth provider.`})}}function none(){return()=>ANONYMOUS_SESSION_AUTH_CONTEXT}function localDev(){return e=>isLocalDevelopmentServer()&&!isCrossSiteBrowserRequest(e)&&!isFromRemotePeer(e)?LOCAL_DEV_SESSION_AUTH_CONTEXT:null}function isCrossSiteBrowserRequest(e){if(!isLocalMachineAddress(new URL(e.url).hostname))return!0;let t=e.headers.get(`origin`);if(t===null)return!1;let n=URL.parse(t)?.hostname;return n===void 0||!isLocalMachineAddress(n)}function isFromRemotePeer(e){return readTrustedDevelopmentPeer(e.headers)===`remote`}function isLocalDevelopmentServer(){return process.env.VERCEL&&process.env.VERCEL_ENV===`development`?!0:isEveDevEnvironment()}const LOCAL_DEV_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`local-dev`,principalId:`local-dev`,principalType:`local-dev`};async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!isVercelOidcIssuer(n.issuer))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};if(!n.audiences.some(e=>e.startsWith(`https://vercel.com/`)))return vercelOidcLog.debug(`Rejected token whose audience is not a Vercel audience.`,{audiences:n.audiences,issuer:n.issuer}),{ok:!1};let r=resolveCurrentVercelProject(t),i=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,currentVercelProject:r,issuer:n.issuer,subjects:t.subjects??[]});return i.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:i.principal.principalType,subject:i.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(i.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:i.kind,subjectsConfigured:(t.subjects??[]).length>0,...i.kind===`misconfigured`?{detail:i.message}:{}}),{ok:!1})}function resolveCurrentVercelProject(e){if(e.currentVercelProject!==void 0)return e.currentVercelProject;let t=process.env.VERCEL_PROJECT_ID?.trim();if(t===void 0||t.length===0)return;let n=process.env.VERCEL_TARGET_ENV?.trim()||process.env.VERCEL_ENV?.trim();return n===void 0||n.length===0?{projectId:t}:{environment:n,projectId:t}}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){let{subjects:t,...n}=e,r={...n,subjects:t?.map(e=>typeof e==`string`?e:e.subject)};return withAuthChallenges(async n=>{let i=extractBearerToken(n.headers.get(`authorization`)),a=e.currentVercelProject??(i!==null&&isLocalDevelopmentVercelOidc()?await resolveVercelOidcCurrentProject(n):void 0),o=await verifyVercelOidc(i,a===void 0?r:{...r,currentVercelProject:a});if(!o.ok)return null;let s=o.sessionAuth;return(s.principalType===`service`||s.principalType===`runtime`)&&t?.some(e=>typeof e!=`string`&&e.allowToolStubs===!0&&areTokenClaimMatchersSatisfied({sub:s.subject},{subjects:[e.subject]}))?{...s,allowToolStubs:!0}:s},[{scheme:`Bearer`}])}function isLocalDevelopmentVercelOidc(){return process.env.VERCEL_ENV===`development`?!0:process.env.VERCEL_ENV===`preview`||process.env.VERCEL_ENV===`production`?!1:isEveDevEnvironment()}function httpBasic(e,t){return withAuthChallenges(t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null},[{parameters:{realm:t?.realm??`eve`,charset:`UTF-8`},scheme:`Basic`}])}function jwtHmac(e){return withAuthChallenges(async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function jwtEcdsa(e){return withAuthChallenges(async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function oidc(e){return withAuthChallenges(async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function decodeUnverifiedJwtClaims(e){let t;try{t=decodeJwt(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}export{ForbiddenError,UnauthenticatedError,createIpAllowList,createUnauthorizedResponse,escapeAuthChallengeParameter,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,localDev,none,oauthResource,oidc,placeholderAuth,readOAuthResourceOptions,routeAuth,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc,withAuthChallenges};
@@ -7,13 +7,18 @@ import type { InputRequest } from "#shared/input.js";
7
7
  import { type InputResponse, type StrictInputResponses } from "#shared/input.js";
8
8
  import type { ActionEvent, Adapter, ChatConfig, SerializedThread, Thread, WebhookOptions } from "#compiled/chat/index.js";
9
9
  import { Chat } from "#compiled/chat/index.js";
10
+ import { type UndeliveredReplyState } from "#public/channels/undelivered-reply.js";
10
11
  import { type Channel, type ChannelEvents, type ChannelContinuationOps, type Session } from "#public/definitions/channel.js";
11
12
  type ChatSdkAdapters = Record<string, Adapter>;
12
13
  /** Durable Chat SDK thread state plus default-handler streaming bookkeeping. */
13
- export interface ChatSdkChannelState extends Record<string, unknown>, PromptQueueState {
14
+ export interface ChatSdkChannelState extends Record<string, unknown>, PromptQueueState, UndeliveredReplyState {
14
15
  thread: SerializedThread | null;
15
16
  /** Message id of the in-flight streamed assistant post (edit fallback). */
16
17
  anchorMessageId?: string | null;
18
+ /** Text streamed for the anchor so far, including deltas no throttled edit has shown yet. */
19
+ streamText?: string | null;
20
+ /** Text the anchor showed after its last successful post or edit. */
21
+ shownText?: string | null;
17
22
  /**
18
23
  * Whether `adapter.editMessage` works for this session. Set to `false` once
19
24
  * an edit throws {@link isNotImplemented}, which disables streaming edits for
@@ -1,3 +1,3 @@
1
- import{actionLabel,visibleActions}from"#shared/action-label.js";import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{parseInputResponses}from"#shared/input.js";import{defaultDeliverResult}from"#channel/adapter.js";import{ContextContainer,contextStorage}from"#context/container.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import{ContextKey}from"#context/key.js";import{DEFAULT_UPLOAD_POLICY}from"#public/channels/upload-policy.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{assertWithinLimit}from"#internal/attachments/limited-read.js";import{isNotImplemented}from"#public/channels/chat-sdk/notImplemented.js";import{promptQueueEvents}from"#channel/prompt-queue.js";import{INACTIVE_REQUEST_NOTICE,respondOrRetireInactivePrompt}from"#channel/inactive-prompt.js";import{Chat,Message,ThreadImpl}from"#compiled/chat/index.js";import{defaultAuthorizationEvents}from"#public/channels/chat-sdk/authorization.js";import{parseChatSdkFileRef}from"#public/channels/chat-sdk/attachment-refs.js";import{decodeInputAction,renderInputRequests,renderRetiredInputRequest}from"#public/channels/chat-sdk/input-actions.js";import{chatSdkInstrumentation}from"#public/channels/chat-sdk/audience.js";const log=createLogger(`chat-sdk.channel`),streamTextByState=new WeakMap,ActiveWebhookKey=new ContextKey(`chat-sdk.active-webhook`);function chatSdkChannel(e){let t=new Chat(e),n=e.inputActionPrefix??`eve_input:`,r=e.streaming??!0,i=e.streamingEditIntervalMs??1e3,a={...defaultEvents(n),...e.events};return t.onAction(async r=>{let i=decodeInputAction(r.actionId,n,r.value);if(!i)return;let{thread:a}=r;if(!a)throw Error(`chatSdkChannel input actions require a thread on the Chat SDK action event.`);let o=e.resolveInputAuth?await e.resolveInputAuth(r):null,s=await respondOrRetireInactivePrompt(()=>bridgeRespond(t,[i],{auth:o,thread:a.toJSON()}),{retirePrompt:e=>retireInputCard(a,r.messageId,e)},log);if(s.outcome===`failed`)throw s.error;s.outcome!==`delivered`&&await Promise.all([s.retirement,a.postEphemeral(r.user,{markdown:INACTIVE_REQUEST_NOTICE},{fallbackToDM:!0}).catch(e=>log.error(`inactive prompt notice failed`,{error:e}))])}),{bot:t,channel:defineChannel({kindHint:`chat-sdk`,turnPolicy:e.turnPolicy,fetchFile:e=>fetchAttachment(t,e),state:initialState(),...chatSdkInstrumentation,context(e){return{bot:t,state:e,streaming:r,streamingEditIntervalMs:i,thread:threadFromState(t,e)}},routes:adapterNames(e.adapters).flatMap(n=>{let r=routeForAdapter(n,e),handler=async(r,i)=>{let a=t.webhooks[n],o=new ContextContainer;return o.setVirtualContext(ActiveWebhookKey,{from:i.from}),contextStorage.run(o,()=>a(r,{...e.webhook,waitUntil(e){i.waitUntil(e)}}))};return[GET(r,handler),POST(r,handler)]}),async receive(e,{from:n}){let r=serializeReceiveTarget(t,e.target);return n(r.id).send(e.message,{auth:e.auth,state:{thread:r}})},deliver(e,t){recordPrincipalUser(t.state,t.session.auth.current,e),recordLatestMessage(t.state,e);let n=resolveInputAnswer(t.state,e);return n===void 0?defaultDeliverResult(e):{context:e.context,inputResponses:parseInputResponses([n])}},events:a}),send(e,n){return bridgeSend(t,e,n)},respond(e,n){return bridgeRespond(t,e,n)}}}function defaultEvents(e){async function showPrompt(t,n){if(!t.thread)return!1;let r=await t.thread.post(renderInputRequests([n],e));r.id&&(t.state.pendingInputCards={...t.state.pendingInputCards,[r.id]:{requests:[n],resolved:{}}})}async function clearAnsweredCards(t,n){let r=n.thread;if(r)for(let[i,a]of Object.entries(n.state.pendingInputCards??{})){let o=t.resolutions.filter(e=>a.requests.some(t=>t.requestId===e.requestId));if(o.length===0)continue;let s={...a.resolved,...Object.fromEntries(o.map(e=>[e.requestId,e]))},{[i]:c,...l}=n.state.pendingInputCards??{};if(n.state.pendingInputCards=a.requests.every(e=>s[e.requestId]!==void 0)?l:{...l,[i]:{requests:a.requests,resolved:s}},n.state.editSupported!==!1)try{await r.adapter.editMessage(r.id,i,renderInputRequests(a.requests,e,s))}catch(e){if(!isNotImplemented(e)){log.warn(`answered input card edit failed`,{error:e,messageId:i});continue}n.state.editSupported=!1}}}let t=promptQueueEvents(showPrompt);return{...defaultAuthorizationEvents(),async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,clearStream(t.state),await safeStartTyping(t.thread,`Working...`)},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await safeStartTyping(t.thread,truncate(r));return}let i=visibleActions(e.actions).map(t=>actionLabel(t,e.presentation));i.length!==0&&await safeStartTyping(t.thread,truncate(`${i.join(`, `)}...`))},async"message.appended"(e,t,n){if(!t.thread||!canStream(t))return;let r=((t.state.streamStepIndex===e.stepIndex?streamTextByState.get(t.state):void 0)??``)+e.messageDelta;if(!r)return;streamTextByState.set(t.state,r);let i=t.state.anchorMessageId;if(!i||t.state.streamStepIndex!==e.stepIndex){let n=await t.thread.post({markdown:r});t.state.anchorMessageId=n.id,t.state.streamStepIndex=e.stepIndex,t.state.lastEditAtMs=Date.now();return}let a=t.state.lastEditAtMs??0;if(!(Date.now()-a<t.streamingEditIntervalMs))try{await editMessage(t.thread,i,r),t.state.lastEditAtMs=Date.now()}catch(e){if(!isNotImplemented(e))throw e;t.state.editSupported=!1,clearStream(t.state)}},...t,async"input.resolved"(e,n,r){await clearAnsweredCards(e,n),await t[`input.resolved`](e,n)},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null,e.message?await finalizeStreamedMessage(t,e.message,!1):clearStream(t.state);return}if(t.state.pendingToolCallMessage=null,!e.message){clearStream(t.state);return}await finalizeStreamedMessage(t,e.message,!0)},async"turn.failed"(e,t,n){e.terminal||await postFailure(t.thread,`I hit an error while handling your request`,`Please try again, rephrase, or reach out if it keeps failing.`,e)},async"session.failed"(e,t){await postFailure(t.thread,`This session could not recover from an error`,`Start a new conversation to continue.`,e)}}}async function safeStartTyping(e,t){if(e)try{await e.startTyping(t)}catch(e){if(!isNotImplemented(e))throw e}}async function editMessage(e,t,n){await e.adapter.editMessage(e.id,t,{markdown:n})}async function retireInputCard(e,t,n){try{await e.adapter.editMessage(e.id,t,renderRetiredInputRequest(n))}catch(e){if(!isNotImplemented(e))throw e}}async function finalizeStreamedMessage(e,t,n){let r=e.thread;if(!r){clearStream(e.state);return}let i=e.state.anchorMessageId;if(canStream(e)&&i)try{await editMessage(r,i,t)}catch(i){if(!isNotImplemented(i))throw i;e.state.editSupported=!1,n&&await r.post({markdown:t})}else n&&await r.post({markdown:t});clearStream(e.state)}function canStream(e){return e.streaming&&e.state.editSupported!==!1}function clearStream(e){e.anchorMessageId=null,e.lastEditAtMs=null,e.streamStepIndex=null,streamTextByState.delete(e)}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}function truncate(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}async function postFailure(e,t,n,r){if(!e)return;let i=formatErrorHint(r),a=extractErrorId(r.details);await e.post([`${t}${i}.`,n,...a?[`Error id: ${a}`]:[]].join(`
1
+ import{actionLabel,visibleActions}from"#shared/action-label.js";import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{parseInputResponses}from"#shared/input.js";import{defaultDeliverResult}from"#channel/adapter.js";import{ContextContainer,contextStorage}from"#context/container.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import{ContextKey}from"#context/key.js";import{DEFAULT_UPLOAD_POLICY}from"#public/channels/upload-policy.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{assertWithinLimit}from"#internal/attachments/limited-read.js";import{isNotImplemented}from"#public/channels/chat-sdk/notImplemented.js";import{promptQueueEvents}from"#channel/prompt-queue.js";import{INACTIVE_REQUEST_NOTICE,respondOrRetireInactivePrompt}from"#channel/inactive-prompt.js";import{Chat,Message,ThreadImpl}from"#compiled/chat/index.js";import{defaultAuthorizationEvents}from"#public/channels/chat-sdk/authorization.js";import{parseChatSdkFileRef}from"#public/channels/chat-sdk/attachment-refs.js";import{decodeInputAction,renderInputRequests,renderRetiredInputRequest}from"#public/channels/chat-sdk/input-actions.js";import{reportUndeliveredReply,withUndeliveredReplyNote}from"#public/channels/undelivered-reply.js";import{chatSdkInstrumentation}from"#public/channels/chat-sdk/audience.js";const log=createLogger(`chat-sdk.channel`),SURFACE_NAME=`this chat`,ActiveWebhookKey=new ContextKey(`chat-sdk.active-webhook`);function chatSdkChannel(e){let t=new Chat(e),n=e.inputActionPrefix??`eve_input:`,r=e.streaming??!0,i=e.streamingEditIntervalMs??1e3,a={...defaultEvents(n),...e.events};return t.onAction(async r=>{let i=decodeInputAction(r.actionId,n,r.value);if(!i)return;let{thread:a}=r;if(!a)throw Error(`chatSdkChannel input actions require a thread on the Chat SDK action event.`);let o=e.resolveInputAuth?await e.resolveInputAuth(r):null,s=await respondOrRetireInactivePrompt(()=>bridgeRespond(t,[i],{auth:o,thread:a.toJSON()}),{retirePrompt:e=>retireInputCard(a,r.messageId,e)},log);if(s.outcome===`failed`)throw s.error;s.outcome!==`delivered`&&await Promise.all([s.retirement,a.postEphemeral(r.user,{markdown:INACTIVE_REQUEST_NOTICE},{fallbackToDM:!0}).catch(e=>log.error(`inactive prompt notice failed`,{error:e}))])}),{bot:t,channel:defineChannel({kindHint:`chat-sdk`,turnPolicy:e.turnPolicy,fetchFile:e=>fetchAttachment(t,e),state:initialState(),...chatSdkInstrumentation,context(e){return{bot:t,state:e,streaming:r,streamingEditIntervalMs:i,thread:threadFromState(t,e)}},routes:adapterNames(e.adapters).flatMap(n=>{let r=routeForAdapter(n,e),handler=async(r,i)=>{let a=t.webhooks[n],o=new ContextContainer;return o.setVirtualContext(ActiveWebhookKey,{from:i.from}),contextStorage.run(o,()=>a(r,{...e.webhook,waitUntil(e){i.waitUntil(e)}}))};return[GET(r,handler),POST(r,handler)]}),async receive(e,{from:n}){let r=serializeReceiveTarget(t,e.target);return n(r.id).send(e.message,{auth:e.auth,state:{thread:r}})},deliver(e,t){recordPrincipalUser(t.state,t.session.auth.current,e),recordLatestMessage(t.state,e);let n=resolveInputAnswer(t.state,e);return n===void 0?defaultDeliverResult(withUndeliveredReplyNote(t.state,e,SURFACE_NAME)):{context:e.context,inputResponses:parseInputResponses([n])}},events:a}),send(e,n){return bridgeSend(t,e,n)},respond(e,n){return bridgeRespond(t,e,n)}}}function defaultEvents(e){async function showPrompt(t,n){if(!t.thread)return!1;let r=await t.thread.post(renderInputRequests([n],e));r.id&&(t.state.pendingInputCards={...t.state.pendingInputCards,[r.id]:{requests:[n],resolved:{}}})}async function clearAnsweredCards(t,n){let r=n.thread;if(r)for(let[i,a]of Object.entries(n.state.pendingInputCards??{})){let o=t.resolutions.filter(e=>a.requests.some(t=>t.requestId===e.requestId));if(o.length===0)continue;let s={...a.resolved,...Object.fromEntries(o.map(e=>[e.requestId,e]))},{[i]:c,...l}=n.state.pendingInputCards??{};if(n.state.pendingInputCards=a.requests.every(e=>s[e.requestId]!==void 0)?l:{...l,[i]:{requests:a.requests,resolved:s}},n.state.editSupported!==!1)try{await r.adapter.editMessage(r.id,i,renderInputRequests(a.requests,e,s))}catch(e){if(!isNotImplemented(e)){log.warn(`answered input card edit failed`,{error:e,messageId:i});continue}n.state.editSupported=!1}}}let t=promptQueueEvents(showPrompt);return{...defaultAuthorizationEvents(),async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,clearStream(t.state),await safeStartTyping(t.thread,`Working...`)},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await safeStartTyping(t.thread,truncate(r));return}let i=visibleActions(e.actions).map(t=>actionLabel(t,e.presentation));i.length!==0&&await safeStartTyping(t.thread,truncate(`${i.join(`, `)}...`))},async"message.appended"(e,t,n){if(!t.thread||!canStream(t))return;let r=((t.state.streamStepIndex===e.stepIndex?t.state.streamText:null)??``)+e.messageDelta;if(!r)return;t.state.streamText=r;let i=t.state.anchorMessageId;if(!i||t.state.streamStepIndex!==e.stepIndex){let n=await t.thread.post({markdown:r});t.state.shownText=r,t.state.anchorMessageId=n.id,t.state.streamStepIndex=e.stepIndex,t.state.lastEditAtMs=Date.now();return}let a=t.state.lastEditAtMs??0;if(!(Date.now()-a<t.streamingEditIntervalMs))try{await editMessage(t.thread,i,r),t.state.shownText=r,t.state.lastEditAtMs=Date.now()}catch(e){if(!isNotImplemented(e))throw e;t.state.editSupported=!1}},...t,async"input.resolved"(e,n,r){await clearAnsweredCards(e,n),await t[`input.resolved`](e,n)},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){if(t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null,e.message)try{await finalizeStreamedMessage(t,e.message,!1)}catch(e){if(!isNotImplemented(e))throw e}else clearStream(t.state);return}if(t.state.pendingToolCallMessage=null,!e.message){clearStream(t.state);return}try{await finalizeStreamedMessage(t,e.message,!0)}catch(n){await reportUndeliveredReply({log,name:SURFACE_NAME,post:async e=>t.thread?.post(e),state:t.state},e.turnId,n)}},async"turn.failed"(e,t,n){e.terminal||await postFailure(t.thread,`I hit an error while handling your request`,`Please try again, rephrase, or reach out if it keeps failing.`,e)},async"session.failed"(e,t){await postFailure(t.thread,`This session could not recover from an error`,`Start a new conversation to continue.`,e)}}}async function safeStartTyping(e,t){if(e)try{await e.startTyping(t)}catch(e){if(!isNotImplemented(e))throw e}}async function editMessage(e,t,n){await e.adapter.editMessage(e.id,t,{markdown:n})}async function retireInputCard(e,t,n){try{await e.adapter.editMessage(e.id,t,renderRetiredInputRequest(n))}catch(e){if(!isNotImplemented(e))throw e}}async function finalizeStreamedMessage(e,t,n){let{anchorMessageId:r,shownText:i}=e.state;clearStream(e.state);let a=e.thread;if(a){if(!r){n&&await a.post({markdown:t});return}if(i!==t)try{await editMessage(a,r,t)}catch(t){throw isNotImplemented(t)&&(e.state.editSupported=!1),t}}}function canStream(e){return e.streaming&&e.state.editSupported!==!1}function clearStream(e){e.anchorMessageId=null,e.lastEditAtMs=null,e.streamStepIndex=null,e.streamText=null,e.shownText=null}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}function truncate(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}async function postFailure(e,t,n,r){if(!e)return;let i=formatErrorHint(r),a=extractErrorId(r.details);await e.post([`${t}${i}.`,n,...a?[`Error id: ${a}`]:[]].join(`
2
2
 
3
3
  `))}async function bridgeSend(e,t,n){let r=activeFrom(`send`),{adapterName:i,auth:a,inputAnswer:o,thread:s,...c}=n,l=serializeThread(e,s,i),u={thread:l};return o!==void 0&&(u.inputAnswer=o),r(l.id).send(t,{...c,auth:a??null,state:u})}async function bridgeRespond(e,t,n){let r=activeFrom(`respond`),{adapterName:i,auth:a,thread:o,...s}=n;return r(serializeThread(e,o,i).id).respond(parseInputResponses(t),{...s,auth:a??null})}function recordPrincipalUser(e,t,n){if(t===null)return;let r=(n.state?.thread)?.currentMessage?.author;if(r===void 0||r.isBot===!0||r.isMe)return;let i=e.usersByPrincipal?.[t.principalId];i!==r.userId&&i!==null&&(e.usersByPrincipal={...e.usersByPrincipal,[t.principalId]:i===void 0?r.userId:null})}function recordLatestMessage(e,t){let n=t.state?.thread?.currentMessage;n===void 0||n.author.isMe||(e.latestMessageId=n.id)}function resolveInputAnswer(e,t){let n=t.state?.inputAnswer;if(n===void 0)return;let r=e.pendingInputCards?.[n.messageId],i=r?.requests.find(e=>r.resolved[e.requestId]===void 0&&e.options?.some(e=>e.id===n.optionId)===!0);return i===void 0?void 0:{optionId:n.optionId,requestId:i.requestId}}function activeFrom(e){let t=contextStorage.getStore()?.get(ActiveWebhookKey);if(!t)throw Error(`chatSdkChannel().${e} can only run during a Chat SDK webhook handler for this bridge.`);return t.from}function initialState(){return{pendingAuthMessageIds:{},thread:null}}async function fetchAttachment(e,t){let n=parseChatSdkFileRef(new URL(t));if(n===null)return null;await e.initialize();let r=e.getAdapter(n.adapter).rehydrateAttachment?.(n.attachment);if(r?.fetchData===void 0)throw new EveAttachmentError({adapterKind:`chat-sdk`,kind:`resolver-threw`,message:`the ${n.adapter} adapter can't download it after the webhook returns.`});let i;try{i=await r.fetchData()}catch(e){throw e instanceof EveAttachmentError?e:new EveAttachmentError({adapterKind:`chat-sdk`,cause:e,kind:`resolver-threw`,message:`the ${n.adapter} download failed.`})}let a=Buffer.isBuffer(i)?i:Buffer.from(i);return assertWithinLimit(a,DEFAULT_UPLOAD_POLICY.maxBytes,`chat-sdk`),{bytes:a,mediaType:n.attachment.mimeType}}function threadFromState(e,t){if(!t.thread)return null;try{let n=t.thread;return new ThreadImpl({adapter:e.getAdapter(n.adapterName),channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Message.fromJSON(n.currentMessage):void 0,id:n.id,isDM:n.isDM,stateAdapter:e.getState()})}catch(e){return log.warn(`failed to rebuild Chat SDK thread from channel state`,{error:e}),null}}function serializeReceiveTarget(e,t){if(t.thread)return t.thread;if(!t.threadId)throw Error(`chatSdkChannel().receive requires target.thread or target.threadId.`);return serializeThread(e,t.threadId,t.adapterName)}function serializeThread(e,t,n){if(typeof t==`string`){let r=n??inferAdapterName(t),i=e.getAdapter(r);return{_type:`chat:Thread`,adapterName:r,channelId:i.channelIdFromThreadId(t),channelVisibility:i.getChannelVisibility?.(t),id:t,isDM:!1}}return isSerializedThread(t)?t:t.toJSON()}function isSerializedThread(e){return`_type`in e&&e._type===`chat:Thread`}function inferAdapterName(e){let t=e.indexOf(`:`);if(t<=0)throw Error(`chatSdkChannel string thread references require options.adapterName.`);return e.slice(0,t)}function adapterNames(e){return Object.keys(e)}function routeForAdapter(e,t){return t.routes?.[e]||`${(t.route??`/eve/v1`).replace(/\/$/u,``)}/${e}`}export{chatSdkChannel};
@@ -1,5 +1,4 @@
1
- import type { DeliverPayload } from "#channel/types.js";
2
- import type { SlackChannelInternalEvents, SlackChannelState, SlackContext } from "#public/channels/slack/slackChannel.js";
1
+ import type { SlackChannelInternalEvents, SlackContext } from "#public/channels/slack/slackChannel.js";
3
2
  type MessageCompletedHandler = NonNullable<SlackChannelInternalEvents["message.completed"]>;
4
3
  /**
5
4
  * A completed reply for {@link postCompletedSlackReply}: Markdown alone, or
@@ -69,9 +68,4 @@ export declare function deliverCompletedSlackReply(channel: SlackContext, reply:
69
68
  * Steps that end in tool calls and empty replies pass through.
70
69
  */
71
70
  export declare function withFinalReplyDelivery(render: MessageCompletedHandler | undefined): MessageCompletedHandler;
72
- /**
73
- * Tells the model, ahead of the next message, that its previous reply never
74
- * reached Slack, so it does not assume the user read that reply.
75
- */
76
- export declare function withUndeliveredReplyNote<T extends DeliverPayload>(state: SlackChannelState, payload: T): T;
77
71
  export {};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{SLACK_MARKDOWN_TEXT_MAX_LENGTH,truncateMessageText}from"#public/channels/slack/limits.js";const log=createLogger(`slack.reply`),LONG_RESPONSE_NOTICE=`Here's a snippet with the full response.`,FALLBACK_LOG=`Slack refused the final reply; delivering it with a fallback`,REFUSED_PAYLOAD_ERRORS=new Set([`invalid_blocks`,`invalid_blocks_format`,`msg_blocks_too_long`,`msg_blocks_too_many`,`msg_too_long`]);async function postCompletedSlackReply(e,t){await deliverCompletedSlackReply(e,t,{})}async function deliverCompletedSlackReply(e,t,n){let{blocks:r,markdown:i,text:a}=typeof t==`string`?{markdown:t}:t;if(await threadRootIsGone(e)){log.warn(`Slack thread root was deleted; dropping the final reply`,n);return}let o;if(r!==void 0)try{await e.thread.post({blocks:r,text:a??truncateMessageText(i)});return}catch(e){if(o=refusedPayloadError(e),o===void 0)throw e}if(i.length<=SLACK_MARKDOWN_TEXT_MAX_LENGTH){o!==void 0&&log.warn(FALLBACK_LOG,{fallback:`inline`,slackError:o,...n});try{await e.thread.post(i);return}catch(e){if(o=refusedPayloadError(e),o===void 0)throw e}}o!==void 0&&log.warn(FALLBACK_LOG,{fallback:`snippet`,slackError:o,...n}),await uploadReplySnippet(e,i)}async function threadRootIsGone(e){let{channelId:t,threadTs:n}=e.slack;if(!t||!n||e.state?.postedInThread===!0)return!1;try{let r=await e.slack.request(`chat.getPermalink`,{channel:t,message_ts:n});return r.ok!==!0&&r.error===`message_not_found`}catch{return!1}}async function uploadReplySnippet(e,t){let n={data:new Blob([t],{type:`text/markdown`}),filename:`eve-response.md`,mimeType:`text/markdown`},r=e.slack.threadTs.length>0;if(!r&&(!(await e.thread.post(LONG_RESPONSE_NOTICE)).id||e.slack.threadTs.length===0))throw Error(`Slack did not return a thread timestamp for the long response notice.`);await e.slack.uploadFiles([n],{initialComment:r?LONG_RESPONSE_NOTICE:void 0,snippetType:`markdown`})}function refusedPayloadError(e){let t=e;for(let e=0;e<5&&typeof t==`object`&&t;e++){let e=t,n=e.response?.error??e.data?.error;if(typeof n==`string`&&REFUSED_PAYLOAD_ERRORS.has(n))return n;t=e.cause}}function withFinalReplyDelivery(e){return async(t,n,r)=>{if(t.finishReason===`tool-calls`||!t.message){await e?.(t,n,r);return}try{await e?.(t,n,r)}catch(e){await reportUndeliveredReply(n,t.turnId,e)}}}async function reportUndeliveredReply(e,t,n){let r=logError(log,`final reply was not delivered to Slack`,n,{turnId:t});e.state.undeliveredReplyErrorId=r;try{await e.thread.post(`I finished, but couldn't deliver my answer in Slack (error id \`${r}\`). Please ask me to resend it.`)}catch(e){logError(log,`undelivered reply notice failed`,e,{errorId:r,turnId:t})}}function withUndeliveredReplyNote(e,t){let n=e.undeliveredReplyErrorId;if(!n||t.message===void 0)return t;e.undeliveredReplyErrorId=null;let r=[`Your previous reply was not delivered to Slack (error id ${n}).`,`The user has not seen it. Do not assume they read it; send the answer again if they ask for it.`].join(` `);return{...t,context:[r,...t.context??[]]}}export{deliverCompletedSlackReply,postCompletedSlackReply,withFinalReplyDelivery,withUndeliveredReplyNote};
1
+ import{createLogger}from"#internal/logging.js";import{reportUndeliveredReply}from"#public/channels/undelivered-reply.js";import{SLACK_MARKDOWN_TEXT_MAX_LENGTH,truncateMessageText}from"#public/channels/slack/limits.js";const log=createLogger(`slack.reply`),LONG_RESPONSE_NOTICE=`Here's a snippet with the full response.`,FALLBACK_LOG=`Slack refused the final reply; delivering it with a fallback`,REFUSED_PAYLOAD_ERRORS=new Set([`invalid_blocks`,`invalid_blocks_format`,`msg_blocks_too_long`,`msg_blocks_too_many`,`msg_too_long`]);async function postCompletedSlackReply(e,t){await deliverCompletedSlackReply(e,t,{})}async function deliverCompletedSlackReply(e,t,n){let{blocks:r,markdown:i,text:a}=typeof t==`string`?{markdown:t}:t;if(await threadRootIsGone(e)){log.warn(`Slack thread root was deleted; dropping the final reply`,n);return}let o;if(r!==void 0)try{await e.thread.post({blocks:r,text:a??truncateMessageText(i)});return}catch(e){if(o=refusedPayloadError(e),o===void 0)throw e}if(i.length<=SLACK_MARKDOWN_TEXT_MAX_LENGTH){o!==void 0&&log.warn(FALLBACK_LOG,{fallback:`inline`,slackError:o,...n});try{await e.thread.post(i);return}catch(e){if(o=refusedPayloadError(e),o===void 0)throw e}}o!==void 0&&log.warn(FALLBACK_LOG,{fallback:`snippet`,slackError:o,...n}),await uploadReplySnippet(e,i)}async function threadRootIsGone(e){let{channelId:t,threadTs:n}=e.slack;if(!t||!n||e.state?.postedInThread===!0)return!1;try{let r=await e.slack.request(`chat.getPermalink`,{channel:t,message_ts:n});return r.ok!==!0&&r.error===`message_not_found`}catch{return!1}}async function uploadReplySnippet(e,t){let n={data:new Blob([t],{type:`text/markdown`}),filename:`eve-response.md`,mimeType:`text/markdown`},r=e.slack.threadTs.length>0;if(!r&&(!(await e.thread.post(LONG_RESPONSE_NOTICE)).id||e.slack.threadTs.length===0))throw Error(`Slack did not return a thread timestamp for the long response notice.`);await e.slack.uploadFiles([n],{initialComment:r?LONG_RESPONSE_NOTICE:void 0,snippetType:`markdown`})}function refusedPayloadError(e){let t=e;for(let e=0;e<5&&typeof t==`object`&&t;e++){let e=t,n=e.response?.error??e.data?.error;if(typeof n==`string`&&REFUSED_PAYLOAD_ERRORS.has(n))return n;t=e.cause}}function withFinalReplyDelivery(e){return async(t,n,r)=>{if(t.finishReason===`tool-calls`||!t.message){await e?.(t,n,r);return}try{await e?.(t,n,r)}catch(e){await reportUndeliveredReply({log,name:`Slack`,post:e=>n.thread.post(e),state:n.state},t.turnId,e)}}}export{deliverCompletedSlackReply,postCompletedSlackReply,withFinalReplyDelivery};
@@ -19,6 +19,7 @@ import { type LoadThreadContextMessagesOptions } from "#public/channels/slack/th
19
19
  import { type SlackSessionOperations } from "#public/channels/slack/session-operations.js";
20
20
  import { type UploadPolicyInput } from "#public/channels/upload-policy.js";
21
21
  import { type SlackWebhookVerifier } from "#public/channels/slack/verify.js";
22
+ import { type UndeliveredReplyState } from "#public/channels/undelivered-reply.js";
22
23
  import { type Channel } from "#public/definitions/channel.js";
23
24
  import { type ChannelAudience } from "#shared/channel-audience.js";
24
25
  export type { SlackRespondOptions, SlackSendOptions, SlackSessionOperations, } from "#public/channels/slack/session-operations.js";
@@ -101,7 +102,7 @@ export interface SlackPendingApprovalCard {
101
102
  readonly messageBlocks: readonly unknown[];
102
103
  readonly messageTs: string;
103
104
  }
104
- export interface SlackChannelState {
105
+ export interface SlackChannelState extends UndeliveredReplyState {
105
106
  /** Audience classification captured before the session is dispatched. */
106
107
  audience?: ChannelAudience;
107
108
  /** Slack channel id seeded by the inbound mention. */
@@ -162,11 +163,6 @@ export interface SlackChannelState {
162
163
  * `authorization.required` and approval events.
163
164
  */
164
165
  slackUsersByPrincipal?: Record<string, string>;
165
- /**
166
- * Error id of a final reply that never reached Slack. The next delivered
167
- * message tells the model the reply was not seen, then clears it.
168
- */
169
- undeliveredReplyErrorId?: string | null;
170
166
  /**
171
167
  * Whether eve has posted in this thread. Once it has, deleting the root
172
168
  * leaves a tombstone that keeps the thread, so the final reply skips the
@@ -1 +1 @@
1
- import{markEventHandled}from"./utils.js";import{attachInputText}from"#internal/input-text.js";import{createLogger,logError}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{setChannelBuildMetadata}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{maxBytesOf}from"#internal/attachments/limited-read.js";import{resolveSlackTransportOptions}from"#public/channels/slack/transport.js";import{buildSlackAuthContext,slackUserIdFromAuthContext}from"#public/channels/slack/auth.js";import{buildSlackBinding,buildSlackWorkspaceHandle,fetchSlackThreadWindow,slackContinuationToken}from"#public/channels/slack/api.js";import{parseMessageEvent,parseSlackEventEnvelope,slackEventBotUserId,slackEventInstallationTeamId,slackEventReceivingBotUserId,slackMessageFromWebhookPayload}from"#public/channels/slack/inbound.js";import{defaultInputRequestedHandler}from"#public/channels/slack/approval-cards.js";import{withFinalReplyDelivery,withUndeliveredReplyNote}from"#public/channels/slack/reply-delivery.js";import{defaultEvents,defaultOnMessage,defaultReceived}from"#public/channels/slack/defaults.js";import{composeSlackRenderers}from"#public/channels/slack/renderers.js";import{loadThreadContextMessages}from"#public/channels/slack/thread.js";import{parseSlackWebhookBody}from"#compiled/@chat-adapter/slack/webhook.js";import{bindSlackSessionOperations,withSlackResponder}from"#public/channels/slack/session-operations.js";import{buildSlackTurnMessage,collectInboundFileParts,createSlackFetchFile}from"#public/channels/slack/attachments.js";import{renderDefaultSlackTaskCard,withTaskCards}from"#public/channels/slack/task-card.js";import{formatSlackInboundMessage,formatSlackThreadContext,slackThreadSessionHistory}from"#public/channels/slack/model-context.js";import{isPrivateSlackConversation}from"#public/channels/slack/privacy.js";import{SLACK_CHANNEL_DEFAULT_ROUTE}from"#public/channels/slack/constants.js";import{defineSlackAppManifest}from"#public/channels/slack/app-manifest.js";import{handleInteractionPost}from"#public/channels/slack/interactions.js";import{verifySlackRequest as verifySlackRequest$1}from"#public/channels/slack/verify.js";const log=createLogger(`slack.channel`);function rebuildSlackContext(e,t,n,r){let{thread:i,slack:a}=buildSlackBinding({api:n,botToken:r?.botToken,channelId:e.channelId??``,threadTs:e.threadTs??``,installationTeamId:e.installationTeamId??void 0,teamId:e.teamId??void 0,onThreadTsChanged(n){e.threadTs=n,e.channelId&&t.continuation?.alias(slackContinuationToken(e.channelId,n))},onPosted(){e.postedInThread=!0}});return{thread:i,slack:a,state:e}}function slackChannel(e={}){let t=resolveSlackTransportOptions(e.api),n=mergeUploadPolicy(e.uploadPolicy),r=createSlackFetchFile({api:t,botToken:e.credentials?.botToken,maxBytes:maxBytesOf(n)}),i=e.onInputResponse??defaultOnInputResponse,a=composeSlackRenderers(e.renderers??[],{events:{...defaultEvents,"input.requested":defaultInputRequestedHandler(e.approvalChannel)},received:defaultReceived,taskCard:renderDefaultSlackTaskCard}),o=a.events[`turn.started`],s=withTaskCards({...a.events,"message.completed":withFinalReplyDelivery(a.events[`message.completed`]),async"turn.started"(e,t,n){let r=slackUserIdFromAuthContext(n.session.auth.current);r!==void 0&&(t.state.triggeringUserId=r),await o?.(e,t,n)}},a.taskCard),c=new Set,l=defineChannel({kindHint:`slack`,turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:{channelId:null,threadTs:null,teamId:null,installationTeamId:null,triggeringUserId:null,triggeringMessageTs:null,pendingToolCallMessage:null,pendingAuthMessageTs:{},pendingApprovalCards:{},slackUsersByPrincipal:{}},fetchFile:r,metadata(e){return{channelId:e.channelId,teamId:e.teamId,threadTs:e.threadTs,triggeringUserId:e.triggeringUserId??null}},audience:({state:e})=>e.audience??`unknown`,context(n,r){return rebuildSlackContext(n,r,t,e.credentials)},deliver(e,t){return recordSlackPrincipal(t.state,t.session.auth.current,e),defaultDeliverResult(withUndeliveredReplyNote(t.state,e))},routes:[POST(e.route??SLACK_CHANNEL_DEFAULT_ROUTE,async(r,o)=>{let{waitUntil:s}=o,{from:l,resolveSession:u}=o,d=await verifyInbound(r,e.credentials);return d===null?new Response(`unauthorized`,{status:401}):shouldDropSlackHttpTimeoutRetry(r.headers)?new Response(`ok`):(r.headers.get(`content-type`)??``).includes(`application/x-www-form-urlencoded`)?handleInteractionPost(d,{from:l,resolveSession:u,waitUntil:s},{api:t,config:e,onInputResponse:i}):handleEventPost({api:t,body:d,from:l,resolveSession:u,waitUntil:s,config:e,received:a.received,uploadPolicy:n,handledEvents:c,headers:r.headers})})],receive(n,{from:r}){return receiveOnSlack(n,{from:r,api:t,credentials:e.credentials})},events:s}),u=e.credentials,d=defineSlackAppManifest({botName:e.botName});return setChannelBuildMetadata(l,e=>({externalCredentials:u?.vercelConnect,manifest:d.build(e)})),l}function defaultOnInputResponse(e){return{auth:e.defaultAuth}}async function receiveOnSlack(e,t){let n=e.target,r=n.channelId;if(!r||typeof r!=`string`)throw Error(`slackChannel().receive requires target.channelId.`);let i=typeof n.threadTs==`string`?n.threadTs:``,a=typeof n.installationTeamId==`string`?n.installationTeamId:t.installationTeamId,o=n.initialMessage;if(o&&i.length>0)throw Error("slackChannel().receive: `threadTs` and `initialMessage` are mutually exclusive.");let s=i;if(o){let{thread:e}=buildSlackBinding({api:t.api,botToken:t.credentials?.botToken,channelId:r,threadTs:``,installationTeamId:a,teamId:t.teamId}),n={card:o.card};o.fallbackText!==void 0&&(n.fallbackText=o.fallbackText),s=(await e.post(n)).id}let c=s||crypto.randomUUID(),l=n.audience===void 0?void 0:normalizeChannelAudience(n.audience),u={channelId:r,installationTeamId:a??null,threadTs:s||null,teamId:t.teamId??null,triggeringUserId:t.triggeringUserId??null};return l!==void 0&&(u.audience=l),t.from(slackContinuationToken(r,c)).send(e.message,{auth:e.auth,history:e.history,state:u,title:e.title})}function shouldDropSlackHttpTimeoutRetry(e){return Number(e.get(`x-slack-retry-num`)??`0`)>=1&&e.get(`x-slack-retry-reason`)===`http_timeout`}async function handleEventPost(e){let{config:t}=e,n,r;try{n=parseSlackWebhookBody(e.body,{headers:e.headers}),r=parseSlackEventEnvelope(e.body)}catch(e){return log.warn(`inbound webhook body is not valid JSON`,{error:e}),new Response(`ok`)}if(n.kind===`url_verification`)return new Response(n.challenge,{status:200,headers:{"content-type":`text/plain`}});if(r===null)return new Response(`ok`);let i=typeof r.api_app_id==`string`?r.api_app_id:void 0,a=slackEventBotUserId(r),o=slackEventReceivingBotUserId(r),s=slackEventInstallationTeamId(r),dispatch=null,c=null,dispatchMessage=(n,r,c)=>()=>dispatchSlackMessage({api:e.api,appId:i,botUserId:a,receivingBotUserId:o,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,handler:c,installationTeamId:s,kind:n,message:r,received:e.received,resolvesTypedInput:t.onInputResponse===void 0&&t.approvalChannel===void 0,threadContext:t.threadContext,uploadPolicy:e.uploadPolicy});if(n.kind===`app_mention`||n.kind===`direct_message`){let e=n.kind,r=slackMessageFromWebhookPayload(n,s);if(r!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},r)){let n=(e===`app_mention`?t.onAppMention:t.onDirectMessage)??t.onMessage;n===void 0?c=dispatchMessage(e,r,defaultOnMessage):dispatch=dispatchMessage(e,r,n)}}let l=t.onMessage;if(dispatch===null&&l!==void 0){let e=parseMessageEvent(r);e!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},e)&&(a===void 0||!e.text.includes(`<@${a}`))&&(dispatch=dispatchMessage(`channel_message`,e,l))}let u=t.onEvent;if(dispatch===null&&u!==void 0&&(dispatch=()=>dispatchSlackEvent({api:e.api,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,envelope:r,handler:u,installationTeamId:s})),dispatch??=c,dispatch===null)return new Response(`ok`);let d=r.event_id;if(d){if(e.handledEvents.has(d))return log.warn(`received a duplicate event`,{event_id:d,event_time:r.event_time,retry_num:n.retry?.num??`(null)`,retry_reason:n.retry?.reason??`(null)`}),new Response(`ok`);markEventHandled(d,e.handledEvents)}return e.waitUntil(dispatch()),new Response(`ok`)}function isSelfAuthoredSlackMessage(e,t){return e.botUserId!==void 0&&t.author?.userId===e.botUserId||e.appId!==void 0&&t.raw.app_id===e.appId}async function dispatchSlackMessage(e){let t=slackContinuationToken(e.message.channelId,e.message.threadTs),{thread:n,slack:r}=buildSlackBinding({api:e.api,appId:e.appId,botToken:e.credentials?.botToken,botUserId:e.botUserId,channelId:e.message.channelId,threadTs:e.message.threadTs,threadHasReplies:e.message.threadTs!==e.message.ts,installationTeamId:e.installationTeamId,teamId:e.message.teamId}),i=e.message.author,a={channelId:e.message.channelId,installationTeamId:e.installationTeamId??null,teamId:e.message.teamId??null,threadTs:e.message.threadTs,triggeringMessageTs:e.message.ts,triggeringUserId:i?.userId??null},o=bindSlackSessionOperations({address:t,defaultAuth:i===void 0?null:buildSlackAuthContext({channelId:e.message.channelId,fullName:i.fullName,installationTeamId:e.installationTeamId,isBot:i.isBot,teamId:e.message.teamId,threadTs:e.message.threadTs,userId:i.userId,userName:i.userName}),from:e.from,resolveSession:e.resolveSession,state:a}),s,isDMOrPrivateChannel=()=>s??=isPrivateSlackConversation({channelId:e.message.channelId,raw:e.message.raw,request:r.request}),c=e.kind===`app_mention`||e.botUserId!==void 0&&e.message.text.includes(`<@${e.botUserId}`),l={...o,isBotMentioned:()=>c,isDMOrPrivateChannel,isSubscribed:async()=>await o.resolveSession()!==void 0,slack:r,thread:n},u=e.kind===`channel_message`?void 0:acknowledgeMessage(e.received,e.message,{slack:r,thread:n}),d;try{d=await e.handler(l,e.message)}catch(t){logError(log,`${e.kind} handler failed`,t,{channelId:e.message.channelId})}if(d==null){u!==void 0&&(await u,await n.startTyping());return}await(u??acknowledgeMessage(e.received,e.message,{slack:r,thread:n}));let f=await isDMOrPrivateChannel();a.audience=e.kind===`direct_message`||f?`private`:`public`,await deliverSlackMessage({botUserId:e.receivingBotUserId,credentials:e.credentials,kind:e.kind,isPrivateConversation:f,isMentioned:c,message:e.message,resolvesTypedInput:e.resolvesTypedInput,result:d,sessionOperations:o,thread:n,threadContext:e.threadContext,uploadPolicy:e.uploadPolicy})}async function acknowledgeMessage(e,t,n){try{await e(t,n)}catch(e){logError(log,`received renderer failed`,e,{channelId:t.channelId})}}async function dispatchSlackEvent(e){let t=e.envelope.event.team_id,n=typeof t==`string`?t:typeof e.envelope.team_id==`string`?e.envelope.team_id:void 0,r=[],sourceFor=t=>e.from(slackContinuationToken(t.channelId,t.threadTs)),i={cancel:({target:e,turnId:t})=>sourceFor(e).cancel({turnId:t}),clear:({target:e})=>sourceFor(e).clear(),compact:({target:e})=>sourceFor(e).compact(),envelope:e.envelope,reset:({reason:e,target:t})=>sourceFor(t).reset({reason:e}),resolveSession:({target:t})=>e.resolveSession(slackContinuationToken(t.channelId,t.threadTs)),respond:(t,{auth:n,target:r})=>sourceFor(r).respond(t,{auth:n,state:withSlackResponder(void 0,typeof e.envelope.event.user==`string`?e.envelope.event.user:void 0)}),send:(t,{auth:r,history:i,target:a,title:o})=>receiveOnSlack({auth:r,history:i,message:t,target:a,title:o},{from:e.from,api:e.api,credentials:e.credentials,installationTeamId:e.installationTeamId,teamId:n,...typeof e.envelope.event.user==`string`?{triggeringUserId:e.envelope.event.user}:{}}),slack:buildSlackWorkspaceHandle({api:e.api,botToken:e.credentials?.botToken,installationTeamId:e.installationTeamId,teamId:n}),waitUntil(e){r.push(e)}};try{await e.handler(i,e.envelope.event)}catch(t){logError(log,`event handler failed`,t,{eventId:e.envelope.event_id,eventType:e.envelope.event.type})}await Promise.allSettled(r)}async function verifyInbound(e,t){try{return await verifySlackRequest$1(e,{signingSecret:t?.signingSecret??(t?.webhookVerifier?void 0:process.env.SLACK_SIGNING_SECRET),webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`slack inbound verification failed`,{error:e}),null}}async function deliverSlackMessage(e){let{message:t,thread:n}=e;try{let r=e.threadContext===void 0?[]:await loadThreadContextMessages(n,t,e.threadContext),i=r.length>0&&e.result.history===void 0&&await e.sessionOperations.resolveSession()===void 0,a=i?void 0:formatSlackThreadContext(r),o=e.result.history??(i?slackThreadSessionHistory(r):void 0),s=await collectInboundFileParts({botUserId:e.botUserId,fetchThreadWindow:(e,t)=>fetchSlackThreadWindow(n,e,t),isMentioned:e.kind===`app_mention`,mention:t,thread:n,policy:e.uploadPolicy}),c={botUserId:e.botUserId,channelId:t.channelId,fullName:t.author?.fullName,isMentioned:e.isMentioned,teamId:t.teamId,threadTs:t.threadTs,userId:t.author?.userId??``,userName:t.author?.userName},l=formatSlackInboundMessage(c,t),u=buildSlackTurnMessage(a===void 0?l:`${a}\n\n${l}`,s),d=e.result.context??[],f=e.isPrivateConversation?`Private message`:e.result.title??t.markdown,p=attachInputText({auth:e.result.auth,title:f,...d.length>0&&{context:d},...o!==void 0&&{history:o}},e.resolvesTypedInput&&s.length===0?slackTypedText(t.text,e.botUserId):void 0);await e.sessionOperations.send(u,p)}catch(n){logError(log,`${e.kind} delivery failed`,n,{channelId:t.channelId})}}function slackTypedText(e,t){return t===void 0?e:e.replace(RegExp(`<@${t}(?:\\|[^>]*)?>`,`gu`),``).trim()}function recordSlackPrincipal(e,t,n){if(t===null)return;let r=n.state?.triggeringUserId,i=slackUserIdFromAuthContext(t)??(typeof r==`string`?r:void 0);i!==void 0&&(e.slackUsersByPrincipal={...e.slackUsersByPrincipal,[t.principalId]:i})}export{slackChannel};
1
+ import{markEventHandled}from"./utils.js";import{attachInputText}from"#internal/input-text.js";import{createLogger,logError}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{setChannelBuildMetadata}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{POST,defineChannel}from"#public/definitions/channel.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{maxBytesOf}from"#internal/attachments/limited-read.js";import{withUndeliveredReplyNote}from"#public/channels/undelivered-reply.js";import{resolveSlackTransportOptions}from"#public/channels/slack/transport.js";import{buildSlackAuthContext,slackUserIdFromAuthContext}from"#public/channels/slack/auth.js";import{buildSlackBinding,buildSlackWorkspaceHandle,fetchSlackThreadWindow,slackContinuationToken}from"#public/channels/slack/api.js";import{parseMessageEvent,parseSlackEventEnvelope,slackEventBotUserId,slackEventInstallationTeamId,slackEventReceivingBotUserId,slackMessageFromWebhookPayload}from"#public/channels/slack/inbound.js";import{defaultInputRequestedHandler}from"#public/channels/slack/approval-cards.js";import{withFinalReplyDelivery}from"#public/channels/slack/reply-delivery.js";import{defaultEvents,defaultOnMessage,defaultReceived}from"#public/channels/slack/defaults.js";import{composeSlackRenderers}from"#public/channels/slack/renderers.js";import{loadThreadContextMessages}from"#public/channels/slack/thread.js";import{parseSlackWebhookBody}from"#compiled/@chat-adapter/slack/webhook.js";import{bindSlackSessionOperations,withSlackResponder}from"#public/channels/slack/session-operations.js";import{buildSlackTurnMessage,collectInboundFileParts,createSlackFetchFile}from"#public/channels/slack/attachments.js";import{renderDefaultSlackTaskCard,withTaskCards}from"#public/channels/slack/task-card.js";import{formatSlackInboundMessage,formatSlackThreadContext,slackThreadSessionHistory}from"#public/channels/slack/model-context.js";import{isPrivateSlackConversation}from"#public/channels/slack/privacy.js";import{SLACK_CHANNEL_DEFAULT_ROUTE}from"#public/channels/slack/constants.js";import{defineSlackAppManifest}from"#public/channels/slack/app-manifest.js";import{handleInteractionPost}from"#public/channels/slack/interactions.js";import{verifySlackRequest as verifySlackRequest$1}from"#public/channels/slack/verify.js";const log=createLogger(`slack.channel`);function rebuildSlackContext(e,t,n,r){let{thread:i,slack:a}=buildSlackBinding({api:n,botToken:r?.botToken,channelId:e.channelId??``,threadTs:e.threadTs??``,installationTeamId:e.installationTeamId??void 0,teamId:e.teamId??void 0,onThreadTsChanged(n){e.threadTs=n,e.channelId&&t.continuation?.alias(slackContinuationToken(e.channelId,n))},onPosted(){e.postedInThread=!0}});return{thread:i,slack:a,state:e}}function slackChannel(e={}){let t=resolveSlackTransportOptions(e.api),n=mergeUploadPolicy(e.uploadPolicy),r=createSlackFetchFile({api:t,botToken:e.credentials?.botToken,maxBytes:maxBytesOf(n)}),i=e.onInputResponse??defaultOnInputResponse,a=composeSlackRenderers(e.renderers??[],{events:{...defaultEvents,"input.requested":defaultInputRequestedHandler(e.approvalChannel)},received:defaultReceived,taskCard:renderDefaultSlackTaskCard}),o=a.events[`turn.started`],s=withTaskCards({...a.events,"message.completed":withFinalReplyDelivery(a.events[`message.completed`]),async"turn.started"(e,t,n){let r=slackUserIdFromAuthContext(n.session.auth.current);r!==void 0&&(t.state.triggeringUserId=r),await o?.(e,t,n)}},a.taskCard),c=new Set,l=defineChannel({kindHint:`slack`,turnPolicy:e.turnPolicy,uploadPolicy:e.uploadPolicy,state:{channelId:null,threadTs:null,teamId:null,installationTeamId:null,triggeringUserId:null,triggeringMessageTs:null,pendingToolCallMessage:null,pendingAuthMessageTs:{},pendingApprovalCards:{},slackUsersByPrincipal:{}},fetchFile:r,metadata(e){return{channelId:e.channelId,teamId:e.teamId,threadTs:e.threadTs,triggeringUserId:e.triggeringUserId??null}},audience:({state:e})=>e.audience??`unknown`,context(n,r){return rebuildSlackContext(n,r,t,e.credentials)},deliver(e,t){return recordSlackPrincipal(t.state,t.session.auth.current,e),defaultDeliverResult(withUndeliveredReplyNote(t.state,e,`Slack`))},routes:[POST(e.route??SLACK_CHANNEL_DEFAULT_ROUTE,async(r,o)=>{let{waitUntil:s}=o,{from:l,resolveSession:u}=o,d=await verifyInbound(r,e.credentials);return d===null?new Response(`unauthorized`,{status:401}):shouldDropSlackHttpTimeoutRetry(r.headers)?new Response(`ok`):(r.headers.get(`content-type`)??``).includes(`application/x-www-form-urlencoded`)?handleInteractionPost(d,{from:l,resolveSession:u,waitUntil:s},{api:t,config:e,onInputResponse:i}):handleEventPost({api:t,body:d,from:l,resolveSession:u,waitUntil:s,config:e,received:a.received,uploadPolicy:n,handledEvents:c,headers:r.headers})})],receive(n,{from:r}){return receiveOnSlack(n,{from:r,api:t,credentials:e.credentials})},events:s}),u=e.credentials,d=defineSlackAppManifest({botName:e.botName});return setChannelBuildMetadata(l,e=>({externalCredentials:u?.vercelConnect,manifest:d.build(e)})),l}function defaultOnInputResponse(e){return{auth:e.defaultAuth}}async function receiveOnSlack(e,t){let n=e.target,r=n.channelId;if(!r||typeof r!=`string`)throw Error(`slackChannel().receive requires target.channelId.`);let i=typeof n.threadTs==`string`?n.threadTs:``,a=typeof n.installationTeamId==`string`?n.installationTeamId:t.installationTeamId,o=n.initialMessage;if(o&&i.length>0)throw Error("slackChannel().receive: `threadTs` and `initialMessage` are mutually exclusive.");let s=i;if(o){let{thread:e}=buildSlackBinding({api:t.api,botToken:t.credentials?.botToken,channelId:r,threadTs:``,installationTeamId:a,teamId:t.teamId}),n={card:o.card};o.fallbackText!==void 0&&(n.fallbackText=o.fallbackText),s=(await e.post(n)).id}let c=s||crypto.randomUUID(),l=n.audience===void 0?void 0:normalizeChannelAudience(n.audience),u={channelId:r,installationTeamId:a??null,threadTs:s||null,teamId:t.teamId??null,triggeringUserId:t.triggeringUserId??null};return l!==void 0&&(u.audience=l),t.from(slackContinuationToken(r,c)).send(e.message,{auth:e.auth,history:e.history,state:u,title:e.title})}function shouldDropSlackHttpTimeoutRetry(e){return Number(e.get(`x-slack-retry-num`)??`0`)>=1&&e.get(`x-slack-retry-reason`)===`http_timeout`}async function handleEventPost(e){let{config:t}=e,n,r;try{n=parseSlackWebhookBody(e.body,{headers:e.headers}),r=parseSlackEventEnvelope(e.body)}catch(e){return log.warn(`inbound webhook body is not valid JSON`,{error:e}),new Response(`ok`)}if(n.kind===`url_verification`)return new Response(n.challenge,{status:200,headers:{"content-type":`text/plain`}});if(r===null)return new Response(`ok`);let i=typeof r.api_app_id==`string`?r.api_app_id:void 0,a=slackEventBotUserId(r),o=slackEventReceivingBotUserId(r),s=slackEventInstallationTeamId(r),dispatch=null,c=null,dispatchMessage=(n,r,c)=>()=>dispatchSlackMessage({api:e.api,appId:i,botUserId:a,receivingBotUserId:o,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,handler:c,installationTeamId:s,kind:n,message:r,received:e.received,resolvesTypedInput:t.onInputResponse===void 0&&t.approvalChannel===void 0,threadContext:t.threadContext,uploadPolicy:e.uploadPolicy});if(n.kind===`app_mention`||n.kind===`direct_message`){let e=n.kind,r=slackMessageFromWebhookPayload(n,s);if(r!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},r)){let n=(e===`app_mention`?t.onAppMention:t.onDirectMessage)??t.onMessage;n===void 0?c=dispatchMessage(e,r,defaultOnMessage):dispatch=dispatchMessage(e,r,n)}}let l=t.onMessage;if(dispatch===null&&l!==void 0){let e=parseMessageEvent(r);e!==null&&!isSelfAuthoredSlackMessage({appId:i,botUserId:a},e)&&(a===void 0||!e.text.includes(`<@${a}`))&&(dispatch=dispatchMessage(`channel_message`,e,l))}let u=t.onEvent;if(dispatch===null&&u!==void 0&&(dispatch=()=>dispatchSlackEvent({api:e.api,from:e.from,resolveSession:e.resolveSession,credentials:t.credentials,envelope:r,handler:u,installationTeamId:s})),dispatch??=c,dispatch===null)return new Response(`ok`);let d=r.event_id;if(d){if(e.handledEvents.has(d))return log.warn(`received a duplicate event`,{event_id:d,event_time:r.event_time,retry_num:n.retry?.num??`(null)`,retry_reason:n.retry?.reason??`(null)`}),new Response(`ok`);markEventHandled(d,e.handledEvents)}return e.waitUntil(dispatch()),new Response(`ok`)}function isSelfAuthoredSlackMessage(e,t){return e.botUserId!==void 0&&t.author?.userId===e.botUserId||e.appId!==void 0&&t.raw.app_id===e.appId}async function dispatchSlackMessage(e){let t=slackContinuationToken(e.message.channelId,e.message.threadTs),{thread:n,slack:r}=buildSlackBinding({api:e.api,appId:e.appId,botToken:e.credentials?.botToken,botUserId:e.botUserId,channelId:e.message.channelId,threadTs:e.message.threadTs,threadHasReplies:e.message.threadTs!==e.message.ts,installationTeamId:e.installationTeamId,teamId:e.message.teamId}),i=e.message.author,a={channelId:e.message.channelId,installationTeamId:e.installationTeamId??null,teamId:e.message.teamId??null,threadTs:e.message.threadTs,triggeringMessageTs:e.message.ts,triggeringUserId:i?.userId??null},o=bindSlackSessionOperations({address:t,defaultAuth:i===void 0?null:buildSlackAuthContext({channelId:e.message.channelId,fullName:i.fullName,installationTeamId:e.installationTeamId,isBot:i.isBot,teamId:e.message.teamId,threadTs:e.message.threadTs,userId:i.userId,userName:i.userName}),from:e.from,resolveSession:e.resolveSession,state:a}),s,isDMOrPrivateChannel=()=>s??=isPrivateSlackConversation({channelId:e.message.channelId,raw:e.message.raw,request:r.request}),c=e.kind===`app_mention`||e.botUserId!==void 0&&e.message.text.includes(`<@${e.botUserId}`),l={...o,isBotMentioned:()=>c,isDMOrPrivateChannel,isSubscribed:async()=>await o.resolveSession()!==void 0,slack:r,thread:n},u=e.kind===`channel_message`?void 0:acknowledgeMessage(e.received,e.message,{slack:r,thread:n}),d;try{d=await e.handler(l,e.message)}catch(t){logError(log,`${e.kind} handler failed`,t,{channelId:e.message.channelId})}if(d==null){u!==void 0&&(await u,await n.startTyping());return}await(u??acknowledgeMessage(e.received,e.message,{slack:r,thread:n}));let f=await isDMOrPrivateChannel();a.audience=e.kind===`direct_message`||f?`private`:`public`,await deliverSlackMessage({botUserId:e.receivingBotUserId,credentials:e.credentials,kind:e.kind,isPrivateConversation:f,isMentioned:c,message:e.message,resolvesTypedInput:e.resolvesTypedInput,result:d,sessionOperations:o,thread:n,threadContext:e.threadContext,uploadPolicy:e.uploadPolicy})}async function acknowledgeMessage(e,t,n){try{await e(t,n)}catch(e){logError(log,`received renderer failed`,e,{channelId:t.channelId})}}async function dispatchSlackEvent(e){let t=e.envelope.event.team_id,n=typeof t==`string`?t:typeof e.envelope.team_id==`string`?e.envelope.team_id:void 0,r=[],sourceFor=t=>e.from(slackContinuationToken(t.channelId,t.threadTs)),i={cancel:({target:e,turnId:t})=>sourceFor(e).cancel({turnId:t}),clear:({target:e})=>sourceFor(e).clear(),compact:({target:e})=>sourceFor(e).compact(),envelope:e.envelope,reset:({reason:e,target:t})=>sourceFor(t).reset({reason:e}),resolveSession:({target:t})=>e.resolveSession(slackContinuationToken(t.channelId,t.threadTs)),respond:(t,{auth:n,target:r})=>sourceFor(r).respond(t,{auth:n,state:withSlackResponder(void 0,typeof e.envelope.event.user==`string`?e.envelope.event.user:void 0)}),send:(t,{auth:r,history:i,target:a,title:o})=>receiveOnSlack({auth:r,history:i,message:t,target:a,title:o},{from:e.from,api:e.api,credentials:e.credentials,installationTeamId:e.installationTeamId,teamId:n,...typeof e.envelope.event.user==`string`?{triggeringUserId:e.envelope.event.user}:{}}),slack:buildSlackWorkspaceHandle({api:e.api,botToken:e.credentials?.botToken,installationTeamId:e.installationTeamId,teamId:n}),waitUntil(e){r.push(e)}};try{await e.handler(i,e.envelope.event)}catch(t){logError(log,`event handler failed`,t,{eventId:e.envelope.event_id,eventType:e.envelope.event.type})}await Promise.allSettled(r)}async function verifyInbound(e,t){try{return await verifySlackRequest$1(e,{signingSecret:t?.signingSecret??(t?.webhookVerifier?void 0:process.env.SLACK_SIGNING_SECRET),webhookVerifier:t?.webhookVerifier})}catch(e){return log.warn(`slack inbound verification failed`,{error:e}),null}}async function deliverSlackMessage(e){let{message:t,thread:n}=e;try{let r=e.threadContext===void 0?[]:await loadThreadContextMessages(n,t,e.threadContext),i=r.length>0&&e.result.history===void 0&&await e.sessionOperations.resolveSession()===void 0,a=i?void 0:formatSlackThreadContext(r),o=e.result.history??(i?slackThreadSessionHistory(r):void 0),s=await collectInboundFileParts({botUserId:e.botUserId,fetchThreadWindow:(e,t)=>fetchSlackThreadWindow(n,e,t),isMentioned:e.kind===`app_mention`,mention:t,thread:n,policy:e.uploadPolicy}),c={botUserId:e.botUserId,channelId:t.channelId,fullName:t.author?.fullName,isMentioned:e.isMentioned,teamId:t.teamId,threadTs:t.threadTs,userId:t.author?.userId??``,userName:t.author?.userName},l=formatSlackInboundMessage(c,t),u=buildSlackTurnMessage(a===void 0?l:`${a}\n\n${l}`,s),d=e.result.context??[],f=e.isPrivateConversation?`Private message`:e.result.title??t.markdown,p=e.resolvesTypedInput?slackTypedText(t.text,e.botUserId):``,m=attachInputText({auth:e.result.auth,title:f,...d.length>0&&{context:d},...o!==void 0&&{history:o}},s.length===0?p:void 0);await e.sessionOperations.send(u,m)}catch(n){logError(log,`${e.kind} delivery failed`,n,{channelId:t.channelId})}}function slackTypedText(e,t){return t===void 0?e:e.replace(RegExp(`<@${t}(?:\\|[^>]*)?>`,`gu`),``).trim()}function recordSlackPrincipal(e,t,n){if(t===null)return;let r=n.state?.triggeringUserId,i=slackUserIdFromAuthContext(t)??(typeof r==`string`?r:void 0);i!==void 0&&(e.slackUsersByPrincipal={...e.slackUsersByPrincipal,[t.principalId]:i})}export{slackChannel};
@@ -0,0 +1,30 @@
1
+ import type { DeliverPayload } from "#channel/types.js";
2
+ import { type Logger } from "#internal/logging.js";
3
+ /** Channel state that remembers a final reply the user never saw. */
4
+ export interface UndeliveredReplyState {
5
+ /**
6
+ * Error id of a final reply that never reached the user. The next delivered
7
+ * message tells the model the reply was not seen, then clears it.
8
+ */
9
+ undeliveredReplyErrorId?: string | null;
10
+ }
11
+ /** Where a channel's final reply failed, and how to post a notice there. */
12
+ export interface UndeliveredReplySurface {
13
+ readonly log: Logger;
14
+ /** The surface as the user and the model know it, e.g. `"Slack"`. */
15
+ readonly name: string;
16
+ readonly post: (notice: string) => Promise<unknown>;
17
+ readonly state: UndeliveredReplyState;
18
+ }
19
+ /**
20
+ * Records a final reply that failed to reach the user: logs `error` at error
21
+ * level, remembers its error id for {@link withUndeliveredReplyNote}, and
22
+ * posts a notice that names the id without repeating the reply. A failed
23
+ * notice is logged, not thrown.
24
+ */
25
+ export declare function reportUndeliveredReply(surface: UndeliveredReplySurface, turnId: string, error: unknown): Promise<void>;
26
+ /**
27
+ * Tells the model, ahead of the next message, that its previous reply never
28
+ * reached `surfaceName`, so it does not assume the user read that reply.
29
+ */
30
+ export declare function withUndeliveredReplyNote<T extends DeliverPayload>(state: UndeliveredReplyState, payload: T, surfaceName: string): T;
@@ -0,0 +1 @@
1
+ import{logError}from"#internal/logging.js";async function reportUndeliveredReply(e,t,n){let r=logError(e.log,`final reply was not delivered to ${e.name}`,n,{turnId:t});e.state.undeliveredReplyErrorId=r;try{await e.post(`I finished, but couldn't deliver my answer in ${e.name} (error id \`${r}\`). Please ask me to resend it.`)}catch(n){logError(e.log,`undelivered reply notice failed`,n,{errorId:r,turnId:t})}}function withUndeliveredReplyNote(e,t,n){let r=e.undeliveredReplyErrorId;if(!r||t.message===void 0)return t;e.undeliveredReplyErrorId=null;let i=[`Your previous reply was not delivered to ${n} (error id ${r}).`,`The user has not seen it. Do not assume they read it; send the answer again if they ask for it.`].join(` `);return{...t,context:[i,...t.context??[]]}}export{reportUndeliveredReply,withUndeliveredReplyNote};
@@ -1,11 +1,23 @@
1
+ declare const PAGES: {
2
+ readonly authorized: {
3
+ readonly title: "Authorization complete";
4
+ readonly icon: "M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0m-4.47-1.47.53-.53L11 4.94l-.53.53L6.5 9.44l-.97-.97L5 7.94 3.94 9l.53.53 1.5 1.5c.3.3.77.3 1.06 0z";
5
+ };
6
+ readonly failed: {
7
+ readonly title: "Authorization not completed";
8
+ readonly icon: "M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0M8 6.94l2.47-2.47 1.06 1.06L9.06 8l2.47 2.47-1.06 1.06L8 9.06l-2.47 2.47-1.06-1.06L6.94 8 4.47 5.53l1.06-1.06z";
9
+ };
10
+ };
1
11
  /**
2
12
  * Renders the static HTML landing page that the user's browser sees
3
13
  * after an OAuth IdP redirects back to the framework's connection
4
- * callback route.
14
+ * callback route. `failed` covers callbacks where the IdP reported an
15
+ * error, such as the user declining consent.
5
16
  *
6
17
  * The framework would otherwise respond with an empty `202 Accepted`
7
18
  * body, which looks broken. This helper is intentionally self-contained:
8
19
  * no external assets, no script, so it renders identically regardless
9
20
  * of where the runtime serves the callback from.
10
21
  */
11
- export declare function buildAuthorizationCompletePage(): Response;
22
+ export declare function buildAuthorizationCompletePage(outcome: keyof typeof PAGES): Response;
23
+ export {};
@@ -1,9 +1,9 @@
1
- function buildAuthorizationCompletePage(){return new Response(`<!doctype html>
1
+ const PAGES={authorized:{title:`Authorization complete`,icon:`M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0m-4.47-1.47.53-.53L11 4.94l-.53.53L6.5 9.44l-.97-.97L5 7.94 3.94 9l.53.53 1.5 1.5c.3.3.77.3 1.06 0z`},failed:{title:`Authorization not completed`,icon:`M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0M8 6.94l2.47-2.47 1.06 1.06L9.06 8l2.47 2.47-1.06 1.06L8 9.06l-2.47 2.47-1.06-1.06L6.94 8 4.47 5.53l1.06-1.06z`}};function buildAuthorizationCompletePage(e){let t=PAGES[e],n=`<!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <title>Authorization complete</title>
6
+ <title>${t.title}</title>
7
7
  <style>
8
8
  :root {
9
9
  color-scheme: light dark;
@@ -80,10 +80,10 @@ function buildAuthorizationCompletePage(){return new Response(`<!doctype html>
80
80
  <main class="screen" aria-labelledby="authorization-title">
81
81
  <div class="content">
82
82
  <div class="header">
83
- <h1 id="authorization-title">Authorization complete</h1>
83
+ <h1 id="authorization-title">${t.title}</h1>
84
84
  <div class="icon" aria-hidden="true">
85
85
  <svg viewBox="0 0 16 16" fill="none">
86
- <path fill="currentColor" fill-rule="evenodd" d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0m-4.47-1.47.53-.53L11 4.94l-.53.53L6.5 9.44l-.97-.97L5 7.94 3.94 9l.53.53 1.5 1.5c.3.3.77.3 1.06 0z" clip-rule="evenodd" />
86
+ <path fill="currentColor" fill-rule="evenodd" d="${t.icon}" clip-rule="evenodd" />
87
87
  </svg>
88
88
  </div>
89
89
  </div>
@@ -92,4 +92,4 @@ function buildAuthorizationCompletePage(){return new Response(`<!doctype html>
92
92
  </div>
93
93
  </main>
94
94
  </body>
95
- </html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}export{buildAuthorizationCompletePage};
95
+ </html>`;return new Response(n,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}export{buildAuthorizationCompletePage};
@@ -69,9 +69,12 @@ export declare const MCP_WWW_AUTHENTICATE_META_KEY = "mcp/www_authenticate";
69
69
  export declare function isMcpAuthChallengeResult(result: unknown): boolean;
70
70
  export declare function readHttpStatus(error: unknown): number | undefined;
71
71
  /**
72
- * Returns `true` when a tool name passes the configured filter.
72
+ * Returns `true` when a tool passes the configured filter. A tool may be known
73
+ * by more than one name, such as an OpenAPI tool's name and the `operationId`
74
+ * it was derived from; `allow` admits it when any name is listed, and `block`
75
+ * hides it when any name is listed.
73
76
  */
74
- export declare function passesToolFilter(toolName: string, filter: Readonly<ToolFilterDefinition> | undefined): boolean;
77
+ export declare function passesToolFilter(names: readonly string[], filter: Readonly<ToolFilterDefinition> | undefined): boolean;
75
78
  /**
76
79
  * Merges `authorization` (Bearer token) and `headers` into one
77
80
  * flat `Record<string, string>` for the transport layer.