eve 0.31.0 → 0.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/src/channel/cross-channel-receive.d.ts +1 -1
  3. package/dist/src/compiled/.vendor-stamp.json +6 -6
  4. package/dist/src/compiled/@workflow/core/_quickjs-wasi.d.ts +8 -0
  5. package/dist/src/compiled/@workflow/core/correlation-id.d.ts +109 -0
  6. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +1 -0
  7. package/dist/src/compiled/@workflow/core/index.js +2 -2
  8. package/dist/src/compiled/@workflow/core/private.d.ts +17 -1
  9. package/dist/src/compiled/@workflow/core/private.js +1 -1
  10. package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +19 -0
  11. package/dist/src/compiled/@workflow/core/runtime/deployment-guard.d.ts +99 -0
  12. package/dist/src/compiled/@workflow/core/runtime/quickjs-assets.generated.d.ts +14 -0
  13. package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +124 -0
  14. package/dist/src/compiled/@workflow/core/runtime/quickjs-runtime.d.ts +193 -0
  15. package/dist/src/compiled/@workflow/core/runtime/run.d.ts +2 -0
  16. package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +18 -1
  17. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +7 -0
  18. package/dist/src/compiled/@workflow/core/runtime/vm-mode.d.ts +44 -0
  19. package/dist/src/compiled/@workflow/core/runtime/vm-serde-bundle.generated.d.ts +14 -0
  20. package/dist/src/compiled/@workflow/core/runtime.d.ts +1 -1
  21. package/dist/src/compiled/@workflow/core/runtime.js +3 -3
  22. package/dist/src/compiled/@workflow/core/serialization/codec-devalue-vm.d.ts +9 -0
  23. package/dist/src/compiled/@workflow/core/serialization/reducers/class-vm.d.ts +20 -0
  24. package/dist/src/compiled/@workflow/core/serialization/reducers/common-vm.d.ts +15 -0
  25. package/dist/src/compiled/@workflow/core/serialization/reducers/step-function-vm.d.ts +44 -0
  26. package/dist/src/compiled/@workflow/core/serialization/vm-bundle-entry.d.ts +12 -0
  27. package/dist/src/compiled/@workflow/core/serialization/workflow-vm.d.ts +24 -0
  28. package/dist/src/compiled/@workflow/core/serialization.d.ts +2 -1
  29. package/dist/src/compiled/@workflow/core/source-map.d.ts +20 -0
  30. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +78 -0
  31. package/dist/src/compiled/@workflow/core/telemetry.d.ts +5 -0
  32. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  33. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  34. package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
  35. package/dist/src/compiled/@workflow/errors/index.d.ts +24 -0
  36. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  37. package/dist/src/compiled/@workflow/world/analytics.d.ts +2 -0
  38. package/dist/src/compiled/@workflow/world/events.d.ts +51 -1
  39. package/dist/src/compiled/@workflow/world/hooks.d.ts +1 -0
  40. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  41. package/dist/src/compiled/@workflow/world/interfaces.d.ts +28 -1
  42. package/dist/src/compiled/@workflow/world/queue.d.ts +8 -0
  43. package/dist/src/compiled/@workflow/world/runs.d.ts +83 -0
  44. package/dist/src/compiled/@workflow/world-local/index.js +5 -4
  45. package/dist/src/compiled/@workflow/world-vercel/index.js +15 -15
  46. package/dist/src/compiled/_chunks/workflow/_eve-core-quickjs-entrypoint-stub-qIV0OaFz.js +1 -0
  47. package/dist/src/compiled/_chunks/workflow/{attribute-changes-DROfGk6l.js → attribute-changes-Du5ztewf.js} +2 -2
  48. package/dist/src/compiled/_chunks/workflow/{dist-D5bR13zs.js → dist-CNXUKQCp.js} +1 -1
  49. package/dist/src/compiled/_chunks/workflow/dist-CRTn4Sg8.js +3 -0
  50. package/dist/src/compiled/_chunks/workflow/dist-tJoQXAF6.js +1 -0
  51. package/dist/src/compiled/_chunks/workflow/functions-ClJbpZhR.js +1 -0
  52. package/dist/src/compiled/_chunks/workflow/{private-BcwCGTV5.js → private-CiWVdS5v.js} +1 -1
  53. package/dist/src/compiled/_chunks/workflow/resume-hook-CT0keOww.js +1 -0
  54. package/dist/src/compiled/_chunks/workflow/run-DBheaFhH.js +1 -0
  55. package/dist/src/compiled/_chunks/workflow/signal-exit-C8vsI6zj.js +1 -0
  56. package/dist/src/compiled/_chunks/workflow/sleep-BeH4B0Cd.js +1 -0
  57. package/dist/src/compiled/_chunks/workflow/{token-hiUWkDKe.js → token-DtCUEpJs.js} +1 -1
  58. package/dist/src/compiled/_chunks/workflow/{token-util-DURSL1l8.js → token-util-DNwIAn_u.js} +9 -9
  59. package/dist/src/compiled/_chunks/workflow/undici-CUIybhQ2.js +95 -0
  60. package/dist/src/compiled/_chunks/workflow/wait-until-CMX5LUWJ.js +15 -0
  61. package/dist/src/compiler/extension-compatibility.d.ts +2 -2
  62. package/dist/src/compiler/extension-compatibility.js +1 -1
  63. package/dist/src/context/container.d.ts +3 -0
  64. package/dist/src/context/container.js +1 -1
  65. package/dist/src/discover/filesystem.js +1 -1
  66. package/dist/src/execution/parked-delivery-wait.js +1 -1
  67. package/dist/src/execution/session-command-inbox.d.ts +11 -3
  68. package/dist/src/execution/session-command-wire.d.ts +24 -0
  69. package/dist/src/execution/session-command-wire.js +1 -0
  70. package/dist/src/execution/turn-control-receiver.js +1 -1
  71. package/dist/src/execution/workflow-runtime.js +1 -1
  72. package/dist/src/execution/workflow-steps.js +1 -1
  73. package/dist/src/harness/authorization.d.ts +8 -0
  74. package/dist/src/harness/authorization.js +1 -1
  75. package/dist/src/internal/application/package.js +1 -1
  76. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  77. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  78. package/dist/src/public/definitions/tool.d.ts +18 -14
  79. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  80. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
  81. package/dist/src/setup/scaffold/create/project.js +1 -1
  82. package/docs/guides/meta.json +2 -1
  83. package/docs/guides/remote-agents.md +6 -4
  84. package/docs/guides/ucp.mdx +181 -0
  85. package/package.json +6 -6
  86. package/dist/src/compiled/_chunks/workflow/dist-B-vbuNqP.js +0 -1
  87. package/dist/src/compiled/_chunks/workflow/dist-dNxTT6nO.js +0 -3
  88. package/dist/src/compiled/_chunks/workflow/functions-CiVUVDNB.js +0 -1
  89. package/dist/src/compiled/_chunks/workflow/resume-hook-bc-OQVI0.js +0 -1
  90. package/dist/src/compiled/_chunks/workflow/run-DM3ouA3U.js +0 -1
  91. package/dist/src/compiled/_chunks/workflow/sleep-D5iWly6-.js +0 -1
  92. package/dist/src/compiled/_chunks/workflow/undici-DWL_MYmT.js +0 -95
  93. package/dist/src/compiled/_chunks/workflow/wait-until-DoW76jdb.js +0 -15
@@ -1 +1 @@
1
- import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function getHookUrl(r){let i=loadContext(),a=i.get(SessionIdKey),o=i.get(CallbackBaseUrlKey);return!a||!o?void 0:`${o}${createEveConnectionCallbackRoutePath(r,authHookToken(a))}`}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){return{...e,[PENDING_AUTHORIZATION_KEY]:t}}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(!(typeof t!=`object`||!t))return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,getAuthorizationResult,getHookUrl,getPendingAuthorization,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
1
+ import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],s=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),s.length>0&&t.set(PendingAuthorizationResultKey,s),a}function getHookUrl(r){let i=loadContext(),a=i.get(SessionIdKey),o=i.get(CallbackBaseUrlKey);return!a||!o?void 0:`${o}${createEveConnectionCallbackRoutePath(r,authHookToken(a))}`}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){return{...e,[PENDING_AUTHORIZATION_KEY]:t}}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(!(typeof t!=`object`||!t))return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,getAuthorizationResult,getHookUrl,getPendingAuthorization,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.31.0`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let n=join(e,`dist`);if(existsSync(n))return{packageBuildRoot:n,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),i=tryResolveDirectBuildLocation(n);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(n));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.31.2`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let n=join(e,`dist`);if(existsSync(n))return{packageBuildRoot:n,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),i=tryResolveDirectBuildLocation(n);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(n));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1 +1 @@
1
- import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let t of e.copyFiles)existsSync(t)&&await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotDependencyMounts(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(r){try{if((await lstat(r.sourcePath)).isDirectory()){await copySnapshotDirectory(r);return}await mkdir(dirname(r.targetPath),{recursive:!0}),await cp(r.sourcePath,r.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(e){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${r.sourcePath}" to "${r.targetPath}": ${formatErrorMessage(e)}`)}}async function copySnapshotDirectory(t){await mkdir(t.targetPath,{recursive:!0});for(let n of await readdir(t.sourcePath,{withFileTypes:!0})){let r=join(t.sourcePath,n.name);shouldSkipSnapshotSource(t.plan,r)||await cp(r,join(t.targetPath,n.name),{filter:e=>!shouldSkipSnapshotSource(t.plan,e),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e.sourceRoot,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(t,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:t})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotDependencyMounts(e){for(let t of e.dependencyMounts){let r=toSnapshotPathForPlan(e,t.mountPath),i=t.copied?toSnapshotPathForPlan(e,t.sourcePath):t.sourcePath,a=t.copied?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let t=join(e.runtimeAppRoot,`package.json`);existsSync(t)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(t,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let t=join(e.runtimeAppRoot,`package.json`);if(!existsSync(t))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${t}".`);for(let t of e.tsconfigPaths){let n=toSnapshotPathForPlan(e,t);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${n}".`);await validateSnapshotTsConfigExtends(n)}}async function validateSnapshotTsConfigExtends(e){let t=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let n of t)if(!(!isTsConfigFilePath(n)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:n}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${n}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
1
+ import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.devtools`,`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let t of e.copyFiles)existsSync(t)&&await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotDependencyMounts(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(r){try{if((await lstat(r.sourcePath)).isDirectory()){await copySnapshotDirectory(r);return}await mkdir(dirname(r.targetPath),{recursive:!0}),await cp(r.sourcePath,r.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(e){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${r.sourcePath}" to "${r.targetPath}": ${formatErrorMessage(e)}`)}}async function copySnapshotDirectory(t){await mkdir(t.targetPath,{recursive:!0});for(let n of await readdir(t.sourcePath,{withFileTypes:!0})){let r=join(t.sourcePath,n.name);shouldSkipSnapshotSource(t.plan,r)||await cp(r,join(t.targetPath,n.name),{filter:e=>!shouldSkipSnapshotSource(t.plan,e),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e.sourceRoot,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(t,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:t})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotDependencyMounts(e){for(let t of e.dependencyMounts){let r=toSnapshotPathForPlan(e,t.mountPath),i=t.copied?toSnapshotPathForPlan(e,t.sourcePath):t.sourcePath,a=t.copied?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let t=join(e.runtimeAppRoot,`package.json`);existsSync(t)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(t,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let t=join(e.runtimeAppRoot,`package.json`);if(!existsSync(t))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${t}".`);for(let t of e.tsconfigPaths){let n=toSnapshotPathForPlan(e,t);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${n}".`);await validateSnapshotTsConfigExtends(n)}}async function validateSnapshotTsConfigExtends(e){let t=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let n of t)if(!(!isTsConfigFilePath(n)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:n}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${n}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
@@ -1 +1 @@
1
- import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=0,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch$1(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:e=>shouldIgnoreWatcherPath(e,t.workspaceExtensions)}),p=waitForWatcherReady(f),rebuild=async(i,a=!1)=>{n||o>0||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t;!a&&r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:o});t=n.host,a||(n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)},forceRebuild=async(e=!1)=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0,e)};return f.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:forceRebuild,async suspend(){o+=1,i!==void 0&&(clearTimeout(i),i=void 0),await r},async resume(e){o!==0&&(--o,o===0&&await forceRebuild(e?.silent))}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(t){let n=new Set([t.compileResult.project.agentRoot,join(t.appRoot,`package.json`),join(t.appRoot,`jsconfig.json`),join(t.appRoot,`tsconfig.json`),join(t.appRoot,`tsconfig.*.json`)]),i=await resolveTsConfigWatchPaths(t.appRoot),a=await resolveDevelopmentSourceSnapshotWatchPaths(t.appRoot);for(let e of t.workspaceExtensions){n.add(e.config.sourceRoot);for(let t of e.buildConfigPaths)n.add(t)}for(let r of getDevelopmentEnvironmentFilePaths(t.appRoot))n.add(r);for(let e of a)n.add(e);for(let e of i)n.add(e);for(let e of resolveLockfileSearchDirectories(t.appRoot))for(let t of WATCHED_LOCKFILE_NAMES)n.add(join(e,t));return[...n].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let t=resolve(e),r=[t],i=t;for(;;){if(hasWatchRootMarker(i))return r;let e=dirname(i);if(e===i)return[t];i=e,r.push(i)}}function hasWatchRootMarker(e){return WATCH_ROOT_MARKER_NAMES.some(n=>existsSync(join(e,n)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e,t){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))||t.some(t=>isPathInsideOrEqual(e,t.config.outDir))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{startAuthoredSourceWatcher};
1
+ import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.devtools`,`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=0,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch$1(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:e=>shouldIgnoreWatcherPath(e,t.workspaceExtensions)}),p=waitForWatcherReady(f),rebuild=async(i,a=!1)=>{n||o>0||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t;!a&&r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:o});t=n.host,a||(n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)},forceRebuild=async(e=!1)=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0,e)};return f.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:forceRebuild,async suspend(){o+=1,i!==void 0&&(clearTimeout(i),i=void 0),await r},async resume(e){o!==0&&(--o,o===0&&await forceRebuild(e?.silent))}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(t){let n=new Set([t.compileResult.project.agentRoot,join(t.appRoot,`package.json`),join(t.appRoot,`jsconfig.json`),join(t.appRoot,`tsconfig.json`),join(t.appRoot,`tsconfig.*.json`)]),i=await resolveTsConfigWatchPaths(t.appRoot),a=await resolveDevelopmentSourceSnapshotWatchPaths(t.appRoot);for(let e of t.workspaceExtensions){n.add(e.config.sourceRoot);for(let t of e.buildConfigPaths)n.add(t)}for(let r of getDevelopmentEnvironmentFilePaths(t.appRoot))n.add(r);for(let e of a)n.add(e);for(let e of i)n.add(e);for(let e of resolveLockfileSearchDirectories(t.appRoot))for(let t of WATCHED_LOCKFILE_NAMES)n.add(join(e,t));return[...n].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let t=resolve(e),r=[t],i=t;for(;;){if(hasWatchRootMarker(i))return r;let e=dirname(i);if(e===i)return[t];i=e,r.push(i)}}function hasWatchRootMarker(e){return WATCH_ROOT_MARKER_NAMES.some(n=>existsSync(join(e,n)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e,t){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))||t.some(t=>isPathInsideOrEqual(e,t.config.outDir))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{startAuthoredSourceWatcher};
@@ -110,6 +110,10 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
110
110
  */
111
111
  toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
112
112
  }
113
+ type ToolOutputFromExecuteReturn<TReturn> = TReturn extends Promise<infer TOutput> ? TOutput : TReturn extends AsyncIterable<infer TOutput> ? TOutput : TReturn;
114
+ type ToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = ToolDefinition<TInput, TOutput> & {
115
+ execute(input: TInput, ctx: ToolContext): TReturn;
116
+ };
113
117
  /**
114
118
  * Defines a tool configuration, used both for static tools (default export
115
119
  * from `agent/tools/*.ts`) and as the entry wrapper inside `defineDynamic`
@@ -118,38 +122,38 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
118
122
  * For static tools, the runtime tool name is the filename slug. `defineTool`
119
123
  * stamps a brand that lifecycle code validates; it rejects raw object literals.
120
124
  */
121
- export declare function defineTool<TInputSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>>(definition: {
125
+ export declare function defineTool<TInputSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
122
126
  description: ToolDefinition<unknown, unknown>["description"];
123
127
  inputSchema: TInputSchema;
124
128
  outputSchema: TOutputSchema;
125
- execute(input: StandardJSONSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext): Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>;
129
+ execute(input: StandardJSONSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext): TReturn;
126
130
  approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, unknown>["approval"];
127
131
  toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
128
- }): ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, StandardJSONSchemaV1.InferOutput<TOutputSchema>>;
129
- export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutput>(definition: {
132
+ }): ToolDefinitionWithExecuteReturn<StandardJSONSchemaV1.InferOutput<TInputSchema>, StandardJSONSchemaV1.InferOutput<TOutputSchema>, TReturn>;
133
+ export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn>(definition: {
130
134
  description: ToolDefinition<unknown, unknown>["description"];
131
135
  inputSchema: TSchema;
132
136
  outputSchema?: JsonObject;
133
- execute(input: StandardJSONSchemaV1.InferOutput<TSchema>, ctx: ToolContext): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;
137
+ execute(input: StandardJSONSchemaV1.InferOutput<TSchema>, ctx: ToolContext): TReturn;
134
138
  approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, unknown>["approval"];
135
- toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];
136
- }): ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, TOutput>;
137
- export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>>(definition: {
139
+ toModelOutput?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["toModelOutput"];
140
+ }): ToolDefinitionWithExecuteReturn<StandardJSONSchemaV1.InferOutput<TSchema>, ToolOutputFromExecuteReturn<TReturn>, TReturn>;
141
+ export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
138
142
  description: ToolDefinition<unknown, unknown>["description"];
139
143
  inputSchema: JsonObject;
140
144
  outputSchema: TOutputSchema;
141
- execute(input: Record<string, unknown>, ctx: ToolContext): Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>;
145
+ execute(input: Record<string, unknown>, ctx: ToolContext): TReturn;
142
146
  approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];
143
147
  toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
144
- }): ToolDefinition<Record<string, unknown>, StandardJSONSchemaV1.InferOutput<TOutputSchema>>;
145
- export declare function defineTool<TOutput>(definition: {
148
+ }): ToolDefinitionWithExecuteReturn<Record<string, unknown>, StandardJSONSchemaV1.InferOutput<TOutputSchema>, TReturn>;
149
+ export declare function defineTool<TReturn>(definition: {
146
150
  description: ToolDefinition<unknown, unknown>["description"];
147
151
  inputSchema: JsonObject;
148
152
  outputSchema?: JsonObject;
149
- execute(input: Record<string, unknown>, ctx: ToolContext): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;
153
+ execute(input: Record<string, unknown>, ctx: ToolContext): TReturn;
150
154
  approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];
151
- toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];
152
- }): ToolDefinition<Record<string, unknown>, TOutput>;
155
+ toModelOutput?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["toModelOutput"];
156
+ }): ToolDefinitionWithExecuteReturn<Record<string, unknown>, ToolOutputFromExecuteReturn<TReturn>, TReturn>;
153
157
  export declare function defineTool<TInput = unknown, TOutput = unknown>(definition: ToolDefinition<TInput, TOutput>): ToolDefinition<TInput, TOutput>;
154
158
  /**
155
159
  * Defines a dynamic resolver evaluated at runtime from stream-event
@@ -1 +1 @@
1
- import{contextStorage,loadContext}from"#context/container.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:r,authorization:i,connection:o}=e;if(!supportsInteractiveAuthorization(i))return!1;let s=getAuthorizationResult(r);if(s===void 0)return!1;let u=i,d=loadContext(),f=resolveConnectionPrincipal(r,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,r,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:o}=e;if(!supportsInteractiveAuthorization(n))return;let s=getHookUrl(t);if(s===void 0)return;let c=n,l=resolveConnectionPrincipal(t,c),u=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:s}),{challenge:d,resume:f}=await c.startAuthorization({callbackUrl:u,connection:o,principal:l});return requestAuthorization([{challenge:stampChallengeDisplayName(d,n),hookUrl:u,name:t,resume:f}])}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
1
+ import{contextStorage,loadContext}from"#context/container.js";import{consumeAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:r,authorization:i,connection:o}=e;if(!supportsInteractiveAuthorization(i))return!1;let s=consumeAuthorizationResult(r);if(s===void 0)return!1;let u=i,d=loadContext(),f=resolveConnectionPrincipal(r,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,r,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:o}=e;if(!supportsInteractiveAuthorization(n))return;let s=getHookUrl(t);if(s===void 0)return;let c=n,l=resolveConnectionPrincipal(t,c),u=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:s}),{challenge:d,resume:f}=await c.startAuthorization({callbackUrl:u,connection:o,principal:l});return requestAuthorization([{challenge:stampChallengeDisplayName(d,n),hookUrl:u,name:t,resume:f}])}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
@@ -1,2 +1,2 @@
1
- import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{defineDynamic,defineTool}from"#public/definitions/tool.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";var __eveStepRegistrySym=Symbol.for(`@workflow/core//registeredSteps`);globalThis[__eveStepRegistrySym]||(globalThis[__eveStepRegistrySym]=new Map);var __eveStepRegistry=globalThis[__eveStepRegistrySym];const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e){let t=loadContext(),n=new Set;for(let r of e.getConnections()){let i=getAuthorizationResult(r.connectionName);if(!i)continue;let a=await resolveInteractiveAuth(e,r.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(r.connectionName,a),s=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:{url:r.url??``},principal:o,resume:i.resume,callback:i.callback});writeCachedToken(t,r.connectionName,principalKey(o),s),n.add(r.connectionName)}return n}async function executeConnectionSearch(e){let t=loadContext(),i=t.get(ConnectionRegistryKey);if(i===void 0)return[];let o=await completePendingAuthorizations(i),l=e.limit??10,d=tokenize(e.keywords),f=[],p=[],m=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections();if(e.connection&&m.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${i.getConnectionNames().join(`, `)}.`);let h=[];for(let e of m){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(o.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),p.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let r=getHookUrl(e.connectionName);if(r){let i=resolveConnectionPrincipal(e.connectionName,t),a=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:r});try{let{challenge:n,resume:r}=await t.startAuthorization({callbackUrl:a,connection:{url:e.url??``},principal:i});h.push({name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:a,resume:r})}catch(t){let r=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:r}),p.push({connection:e.connectionName,description:e.description,error:`Failed to start authorization for "${e.connectionName}": ${r.message}`});continue}}}p.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),p.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),p.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(d,n);t>0&&f.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(h.length>0)return requestAuthorization(h);let g=p.filter(e=>e.error!==void 0);if(m.length>0&&g.length===m.length)throw Error(g.map(e=>e.error).join(`
2
- `));f.sort((e,t)=>t.score-e.score);let _=f.slice(0,l).map(e=>e.item);if(_.length>0){let e=[..._,...p],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of _)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return m.map(e=>p.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}const connectionSearchDynamicDefinition=defineDynamic({events:{"step.started":async(e,t)=>{let n=loadContext().get(ConnectionRegistryKey);if(!n||n.getConnections().length===0)return null;let i=n.getConnections().map(e=>e.connectionName),o=extractDiscoveredTools(t.messages),s=loadContext().get(ConnectionSearchResultsKey)??[],c=new Map;for(let e of s)e.qualifiedName&&c.set(e.qualifiedName,e);for(let e of o)e.qualifiedName&&c.set(e.qualifiedName,e);let l=[...c.values()],u={};u.connection_search=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${i.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,execute:async e=>await __eve_dynamic_exec_0({},e),__executeStepFn:__eve_dynamic_exec_0,__closureVars:{},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});for(let e of l){let r=e.connection,i=e.tool,a=n.getConnectionApproval(r);u[qualifiedConnectionToolName(r,i)]=defineTool({description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:a,outputSchema:e.outputSchema,execute:async(e,n)=>await __eve_dynamic_exec_1({ctx:t,connectionName:r,toolName:i},e,n),__executeStepFn:__eve_dynamic_exec_1,__closureVars:{ctx:t,connectionName:r,toolName:i}})}return u}}});async function __eve_dynamic_exec_0(e,t){return executeConnectionSearch(t)}async function __eve_dynamic_exec_1(e,t,n){let{ctx:i,connectionName:s,toolName:d}=e,f=loadContext().get(ConnectionRegistryKey),p=f.getConnections().find(e=>e.connectionName===s),m=await resolveInteractiveAuth(f,s),_=!1;if(m){let e=getAuthorizationResult(s);if(e){_=!0;let t=loadContext(),n=resolveConnectionPrincipal(s,m),i=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,s,principalKey(n),i)}}try{return await f.getClient(s).executeTool(d,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(_)throw new ConnectionAuthorizationFailedError(s,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${s}" rejected the token immediately after authorization.`});let t=getHookUrl(s);if(!t)throw e;let n=resolveConnectionPrincipal(s,m),r=resolveAuthorizationCallbackUrl({authorization:m,callbackUrl:t}),{challenge:i,resume:a}=await m.startAuthorization({callbackUrl:r,connection:{url:p?.url??``},principal:n});return requestAuthorization([{name:s,challenge:stampChallengeDisplayName(i,m),hookUrl:r,resume:a}])}}__eve_dynamic_exec_0.stepId=`eve:dynamic-tool//__eve_dynamic_exec_0`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_0`,__eve_dynamic_exec_0),__eve_dynamic_exec_1.stepId=`eve:dynamic-tool//__eve_dynamic_exec_1`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_1`,__eve_dynamic_exec_1);export{connectionSearchDynamicDefinition as default,extractDiscoveredTools};
1
+ import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{consumeAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{defineDynamic,defineTool}from"#public/definitions/tool.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";var __eveStepRegistrySym=Symbol.for(`@workflow/core//registeredSteps`);globalThis[__eveStepRegistrySym]||(globalThis[__eveStepRegistrySym]=new Map);var __eveStepRegistry=globalThis[__eveStepRegistrySym];const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e,t){let n=loadContext(),i=new Set;for(let r of t){let t=consumeAuthorizationResult(r.connectionName);if(!t)continue;let a=await resolveInteractiveAuth(e,r.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(r.connectionName,a),s=await a.completeAuthorization({callbackUrl:t.hookUrl,connection:{url:r.url??``},principal:o,resume:t.resume,callback:t.callback});writeCachedToken(n,r.connectionName,principalKey(o),s),i.add(r.connectionName)}return i}async function executeConnectionSearch(e){let t=loadContext(),i=t.get(ConnectionRegistryKey);if(i===void 0)return[];let o=e.limit??10,l=tokenize(e.keywords),d=[],f=[],p=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections();if(e.connection&&p.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${i.getConnectionNames().join(`, `)}.`);let m=await completePendingAuthorizations(i,p),h=[];for(let e of p){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(m.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),f.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let r=getHookUrl(e.connectionName);if(r){let i=resolveConnectionPrincipal(e.connectionName,t),a=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:r});try{let{challenge:n,resume:r}=await t.startAuthorization({callbackUrl:a,connection:{url:e.url??``},principal:i});h.push({name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:a,resume:r})}catch(t){let r=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:r}),f.push({connection:e.connectionName,description:e.description,error:`Failed to start authorization for "${e.connectionName}": ${r.message}`});continue}}}f.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),f.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),f.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(l,n);t>0&&d.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(h.length>0)return requestAuthorization(h);let g=f.filter(e=>e.error!==void 0);if(p.length>0&&g.length===p.length)throw Error(g.map(e=>e.error).join(`
2
+ `));d.sort((e,t)=>t.score-e.score);let _=d.slice(0,o).map(e=>e.item);if(_.length>0){let e=[..._,...f],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of _)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return p.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}const connectionSearchDynamicDefinition=defineDynamic({events:{"step.started":async(e,t)=>{let n=loadContext().get(ConnectionRegistryKey);if(!n||n.getConnections().length===0)return null;let i=n.getConnections().map(e=>e.connectionName),o=extractDiscoveredTools(t.messages),s=loadContext().get(ConnectionSearchResultsKey)??[],c=new Map;for(let e of s)e.qualifiedName&&c.set(e.qualifiedName,e);for(let e of o)e.qualifiedName&&c.set(e.qualifiedName,e);let l=[...c.values()],u={};u.connection_search=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${i.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,execute:async e=>await __eve_dynamic_exec_0({},e),__executeStepFn:__eve_dynamic_exec_0,__closureVars:{},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});for(let e of l){let r=e.connection,i=e.tool,a=n.getConnectionApproval(r);u[qualifiedConnectionToolName(r,i)]=defineTool({description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:a,outputSchema:e.outputSchema,execute:async(e,n)=>await __eve_dynamic_exec_1({ctx:t,connectionName:r,toolName:i},e,n),__executeStepFn:__eve_dynamic_exec_1,__closureVars:{ctx:t,connectionName:r,toolName:i}})}return u}}});async function __eve_dynamic_exec_0(e,t){return executeConnectionSearch(t)}async function __eve_dynamic_exec_1(e,t,n){let{ctx:i,connectionName:s,toolName:d}=e,f=loadContext().get(ConnectionRegistryKey),p=f.getConnections().find(e=>e.connectionName===s),m=await resolveInteractiveAuth(f,s),_=!1;if(m){let e=consumeAuthorizationResult(s);if(e){_=!0;let t=loadContext(),n=resolveConnectionPrincipal(s,m),i=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,s,principalKey(n),i)}}try{return await f.getClient(s).executeTool(d,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(_)throw new ConnectionAuthorizationFailedError(s,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${s}" rejected the token immediately after authorization.`});let t=getHookUrl(s);if(!t)throw e;let n=resolveConnectionPrincipal(s,m),r=resolveAuthorizationCallbackUrl({authorization:m,callbackUrl:t}),{challenge:i,resume:a}=await m.startAuthorization({callbackUrl:r,connection:{url:p?.url??``},principal:n});return requestAuthorization([{name:s,challenge:stampChallengeDisplayName(i,m),hookUrl:r,resume:a}])}}__eve_dynamic_exec_0.stepId=`eve:dynamic-tool//__eve_dynamic_exec_0`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_0`,__eve_dynamic_exec_0),__eve_dynamic_exec_1.stepId=`eve:dynamic-tool//__eve_dynamic_exec_1`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_1`,__eve_dynamic_exec_1);export{connectionSearchDynamicDefinition as default,extractDiscoveredTools};
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.38`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.31.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.38`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.31.2`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -13,6 +13,7 @@
13
13
  "dev-tui",
14
14
  "acp",
15
15
  "frontend",
16
- "client"
16
+ "client",
17
+ "ucp"
17
18
  ]
18
19
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: "Remote Agents"
3
- description: "Call another eve deployment as a subagent with defineRemoteAgent: same lowered tool shape, outbound auth, durable callback dispatch."
3
+ description: "Call another eve deployment as a subagent with defineRemoteAgent: same tool call as a local subagent, outbound auth, durable callback dispatch."
4
4
  ---
5
5
 
6
6
  `defineRemoteAgent` calls a separately deployed eve agent as if it were a local subagent. Reach for it when the specialist you delegate to is a separately owned agent behind its own URL rather than a directory in your repo.
@@ -28,7 +28,7 @@ export default defineRemoteAgent({
28
28
  | `forwardPrincipal` | `boolean` | No | `false` | Forward the dispatching turn's session principal to the remote deployment (see [Forwarding the caller identity](#forwarding-the-caller-identity)). |
29
29
  | `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |
30
30
  | `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |
31
- | `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Lowered to JSON Schema at compile time and enforced by the remote like any task-mode output schema. |
31
+ | `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Enforced by the remote agent like any task-mode output schema. Set it on the definition to apply to every call, or override it per call. |
32
32
 
33
33
  ## Dynamic remote agents
34
34
 
@@ -78,9 +78,11 @@ export default defineRemoteAgent({
78
78
 
79
79
  The function may be async and must return a non-empty string. `auth` and `headers` are resolved at runtime the same way.
80
80
 
81
- ## The lowered tool
81
+ ## Calling a remote agent
82
82
 
83
- A remote agent lowers to the same `{ message, outputSchema? }` tool shape as a local subagent. The parent packs everything the remote needs into `message`. The remote never sees the parent's history. Set `outputSchema` (here or per call) and the remote runs in task mode (a single-shot delegation that returns one structured result instead of an open conversation; see [Subagents](../subagents)), returning structured output as the tool result.
83
+ To the model, a remote agent is another subagent tool. You call it the same way you call a local subagent, with a `message` and an optional `outputSchema`. The message must carry the full task, including any context the remote agent needs, because it never receives the parent's conversation history.
84
+
85
+ To get one structured result back instead of an open-ended reply, set an `outputSchema` on the agent definition or on an individual call. The remote agent then runs in task mode, a single-shot delegation that returns structured output as the tool result. See [Subagents](../subagents) for how task mode works.
84
86
 
85
87
  ## Outbound auth
86
88
 
@@ -0,0 +1,181 @@
1
+ ---
2
+ title: "Universal Commerce Protocol (UCP)"
3
+ description: "Serve a UCP profile at /.well-known/ucp from a custom eve channel."
4
+ ---
5
+
6
+ The [Universal Commerce Protocol](https://ucp.dev/) (UCP) is an open standard for agentic commerce. A business declares its UCP support by serving a JSON **profile** from the `/.well-known/ucp` path. This is a document listing the spec versions it supports, its services and capabilities, its payment handlers, and the public keys agents use to verify signed responses.
7
+
8
+ With eve, you can support UCP in three steps:
9
+
10
+ 1. [Author the profile](#author-the-profile)
11
+ 2. [Serve it from a channel](#serve-it-from-a-channel)
12
+ 3. [Add your commerce endpoints](#add-your-commerce-endpoints)
13
+
14
+ ## Author the profile
15
+
16
+ Your profile is a plain JSON object that follows the [UCP spec](https://ucp.dev/). This spec outlines the `version`, `services`, `payment_handlers` and `capabilities` of your business. It also includes `signing_keys`, the public keys agents use to verify your business's signed messages.
17
+
18
+ ```ts
19
+ // agent/ucp-profile.ts
20
+ export const profile = {
21
+ ucp: {
22
+ version: "2026-04-08",
23
+ services: {
24
+ "dev.ucp.shopping": [
25
+ {
26
+ version: "2026-04-08",
27
+ spec: "https://ucp.dev/2026-04-08/specification/overview",
28
+ transport: "rest",
29
+ schema: "https://ucp.dev/2026-04-08/services/shopping/rest.openapi.json",
30
+ endpoint: "https://your_deployment_url_here/ucp/shopping",
31
+ },
32
+ ],
33
+ },
34
+ capabilities: {
35
+ "dev.ucp.shopping.checkout": [
36
+ {
37
+ version: "2026-04-08",
38
+ spec: "https://ucp.dev/2026-04-08/specification/checkout",
39
+ schema: "https://ucp.dev/2026-04-08/schemas/shopping/checkout.json",
40
+ },
41
+ ],
42
+ },
43
+ payment_handlers: {
44
+ "dev.shopify.shop_pay": [
45
+ {
46
+ id: "shop_pay_1234",
47
+ version: "2026-04-08",
48
+ spec: "https://shopify.dev/ucp/shop-pay-handler",
49
+ schema: "https://shopify.dev/ucp/schemas/shop-pay-config.json",
50
+ available_instruments: [
51
+ {
52
+ type: "shop_pay",
53
+ },
54
+ ],
55
+ },
56
+ ],
57
+ "com.example.processor_tokenizer": [
58
+ {
59
+ id: "processor_tokenizer",
60
+ version: "2026-04-08",
61
+ spec: "https://example.com/specs/payments/processor_tokenizer-payment",
62
+ schema: "https://example.com/schemas/payments/delegate-payment.json",
63
+ available_instruments: [
64
+ {
65
+ type: "card",
66
+ constraints: {
67
+ brands: ["visa", "mastercard"],
68
+ },
69
+ },
70
+ ],
71
+ },
72
+ ],
73
+ },
74
+ },
75
+ signing_keys: [
76
+ {
77
+ kid: "business_2025",
78
+ kty: "EC",
79
+ crv: "P-256",
80
+ x: "...",
81
+ y: "...",
82
+ use: "sig",
83
+ alg: "ES256",
84
+ },
85
+ ],
86
+ };
87
+ ```
88
+
89
+ ## Serve it from a channel
90
+
91
+ Use a custom channel to serve the profile from the `/.well-known/ucp` endpoint.
92
+
93
+ ```ts
94
+ // agent/channels/ucp.ts
95
+ import { defineChannel, GET } from "eve/channels";
96
+ import { profile } from "../ucp-profile";
97
+
98
+ const body = JSON.stringify(profile);
99
+
100
+ export default defineChannel({
101
+ cors: true,
102
+ routes: [
103
+ GET("/.well-known/ucp", async () => {
104
+ return new Response(body, {
105
+ headers: {
106
+ "content-type": "application/json",
107
+ "cache-control": "public, max-age=300",
108
+ },
109
+ });
110
+ }),
111
+ ],
112
+ });
113
+ ```
114
+
115
+ - **Caching**: The spec requires `public` and a `max-age` of at least 60 seconds, and forbids `private`, `no-store`, and `no-cache`. See [Profile Requirements](https://ucp.dev/2026-04-08/specification/overview#hosting).
116
+ - **CORS**: `cors: true` suits public discovery metadata. Pass a `cors` options object to narrow origins. See [CORS](../channels/custom#cors).
117
+ - **HTTPS, no redirects**: The spec requires HTTPS and forbids 3xx responses on the profile endpoint.
118
+
119
+ ## Add your commerce endpoints
120
+
121
+ The URLs in `services[].endpoint` must point at endpoints you serve. You can use a custom channel for these endpoints:
122
+
123
+ ```ts
124
+ // agent/channels/ucp-shopping.ts
125
+ import { defineChannel, POST } from "eve/channels";
126
+
127
+ export default defineChannel({
128
+ routes: [
129
+ POST("/ucp/shopping/checkout-sessions", async (req) => {
130
+ const request = await req.json();
131
+ // Create a checkout session per your published schema. Every UCP
132
+ // response must carry the `ucp` envelope with the negotiated
133
+ // version and the capabilities active for this response.
134
+ return Response.json({
135
+ ucp: {
136
+ version: "2026-04-08",
137
+ capabilities: {
138
+ "dev.ucp.shopping.checkout": [{ version: "2026-04-08" }],
139
+ },
140
+ },
141
+ id: "checkout_123",
142
+ status: "incomplete",
143
+ // ...other checkout fields per the checkout schema
144
+ });
145
+ }),
146
+ ],
147
+ });
148
+ ```
149
+
150
+ Routes are relative to the `endpoint` base in your profile, per the service's OpenAPI schema. Keep them in sync with the paths you mount here.
151
+
152
+ ## Verify
153
+
154
+ Start the dev server with `eve dev` and fetch the well-known document locally:
155
+
156
+ ```sh
157
+ curl -i http://localhost:2000/.well-known/ucp
158
+ ```
159
+
160
+ Then fetch it from your deployment:
161
+
162
+ ```sh
163
+ curl -i https://your_deployment_url_here/.well-known/ucp
164
+ ```
165
+
166
+ Expect a `200` with the profile JSON:
167
+
168
+ ```http
169
+ HTTP/2 200
170
+ content-type: application/json
171
+ cache-control: public, max-age=300
172
+ ```
173
+
174
+ ## What's not covered
175
+
176
+ Commerce operation semantics are author-owned: the checkout, cart, and order state machines; payment-handler execution; and request signing and verification.
177
+
178
+ ## Read next
179
+
180
+ - [Channels overview](../channels/overview): The channel contract this builds on.
181
+ - [Custom channels](../channels/custom): The route helpers, CORS, and metadata this page uses.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eve",
3
- "version": "0.31.0",
3
+ "version": "0.31.2",
4
4
  "private": false,
5
5
  "description": "Filesystem-first framework for durable backend AI agents that run anywhere.",
6
6
  "keywords": [
@@ -320,13 +320,13 @@
320
320
  "@vercel/otel": "2.1.3",
321
321
  "@vercel/sandbox": "2.8.0",
322
322
  "@vercel/sdk": "1.28.8",
323
- "@workflow/core": "5.0.0-beta.39",
324
- "@workflow/errors": "5.0.0-beta.15",
323
+ "@workflow/core": "5.0.0-beta.40",
324
+ "@workflow/errors": "5.0.0-beta.16",
325
325
  "@workflow/serde": "5.0.0-beta.2",
326
326
  "@workflow/utils": "5.0.0-beta.8",
327
- "@workflow/world": "5.0.0-beta.24",
328
- "@workflow/world-local": "5.0.0-beta.33",
329
- "@workflow/world-vercel": "5.0.0-beta.35",
327
+ "@workflow/world": "5.0.0-beta.25",
328
+ "@workflow/world-local": "5.0.0-beta.34",
329
+ "@workflow/world-vercel": "5.0.0-beta.36",
330
330
  "ai": "^7.0.38",
331
331
  "autoevals": "0.0.132",
332
332
  "chat": "4.34.0",
@@ -1 +0,0 @@
1
- import{o as e,t}from"./rolldown-runtime-DaDcL9Zw.js";var n=e(t(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}}))(),1);function r(e){if(typeof e==`string`){let t=(0,n.default)(e);if(typeof t!=`number`||t<0)throw Error(`Invalid duration: "${e}". Expected a valid duration string like "1s", "1m", "1h", etc.`);return new Date(Date.now()+t)}else if(typeof e==`number`){if(e<0||!Number.isFinite(e))throw Error(`Invalid duration: ${e}. Expected a non-negative finite number of milliseconds.`);return new Date(Date.now()+e)}else if(e instanceof Date||e&&typeof e==`object`&&typeof e.getTime==`function`)return e instanceof Date?e:new Date(e.getTime());else throw Error(`Invalid duration parameter. Expected a duration string, number (milliseconds), or Date object.`)}export{r as t};
@@ -1,3 +0,0 @@
1
- import{t as e}from"./dist-B-vbuNqP.js";const t={USER_ERROR:`USER_ERROR`,RUNTIME_ERROR:`RUNTIME_ERROR`,CORRUPTED_EVENT_LOG:`CORRUPTED_EVENT_LOG`,REPLAY_DIVERGENCE:`REPLAY_DIVERGENCE`,MAX_DELIVERIES_EXCEEDED:`MAX_DELIVERIES_EXCEEDED`,MAX_EVENTS_EXCEEDED:`MAX_EVENTS_EXCEEDED`,REPLAY_TIMEOUT:`REPLAY_TIMEOUT`,WORLD_CONTRACT_ERROR:`WORLD_CONTRACT_ERROR`};function n(e){return typeof e==`object`&&!!e&&`name`in e&&`message`in e}function r(e,t){if(t.length===0)return e;let n=[e];return t.forEach((e,r)=>{let i=r===t.length-1,a=i?`╰▶ `:`├▶ `,o=i?` `:`│ `;`${e.label}: ${e.value}`.split(`
2
- `).forEach((e,t)=>{n.push(`${t===0?a:o}${e}`)})}),n.join(`
3
- `)}function i(e,t){let n=[];return e&&n.push({label:`hint`,value:e}),t&&n.push({label:`docs`,value:`https://workflow-sdk.dev/err/${t}`}),n}const a={NODE_JS_MODULE_IN_WORKFLOW:`node-js-module-in-workflow`,START_INVALID_WORKFLOW_FUNCTION:`start-invalid-workflow-function`,SERIALIZATION_FAILED:`serialization-failed`,WEBHOOK_INVALID_RESPOND_WITH_VALUE:`webhook-invalid-respond-with-value`,WEBHOOK_RESPONSE_NOT_SENT:`webhook-response-not-sent`,FETCH_IN_WORKFLOW_FUNCTION:`fetch-in-workflow`,TIMEOUT_FUNCTIONS_IN_WORKFLOW:`timeout-in-workflow`,HOOK_CONFLICT:`hook-conflict`,CORRUPTED_EVENT_LOG:`corrupted-event-log`,REPLAY_DIVERGENCE:`replay-divergence`,STEP_NOT_REGISTERED:`step-not-registered`,WORKFLOW_NOT_REGISTERED:`workflow-not-registered`,RUNTIME_DECRYPTION_FAILED:`runtime-decryption-failed`};var o=class extends Error{cause;constructor(e,t){let n=r(e,i(void 0,t?.slug));super(n,{cause:t?.cause}),t?.cause!==void 0&&(this.cause=t.cause),t?.cause instanceof Error&&(this.stack=`${this.stack}\nCaused by: ${t.cause.stack}`)}static is(e){return n(e)&&e.name===`WorkflowError`}},s=class extends o{status;code;url;retryAfter;constructor(e,t){super(e,{cause:t?.cause}),this.name=`WorkflowWorldError`,this.status=t?.status,this.code=t?.code,this.url=t?.url,this.retryAfter=t?.retryAfter}static is(e){return n(e)&&e.name===`WorkflowWorldError`}},c=class extends o{runId;errorCode;constructor(e,t,n={}){let r=t instanceof Error?t.message:typeof t==`string`?t:t&&typeof t==`object`&&`message`in t?String(t.message):`Unknown error`;super(`Workflow run "${e}" failed: ${r}`,{cause:t}),this.name=`WorkflowRunFailedError`,this.runId=e,n.errorCode!==void 0&&(this.errorCode=n.errorCode)}static is(e){return n(e)&&e.name===`WorkflowRunFailedError`}},l=class extends o{runId;status;constructor(e,t){super(`Workflow run "${e}" has not completed`,{}),this.name=`WorkflowRunNotCompletedError`,this.runId=e,this.status=t}static is(e){return n(e)&&e.name===`WorkflowRunNotCompletedError`}},u=class extends o{constructor(e,t){super(e,{...t}),this.name=`WorkflowRuntimeError`}static is(e){return n(e)&&e.name===`WorkflowRuntimeError`}},d=class extends u{constructor(e,t){super(e,{...t,slug:a.CORRUPTED_EVENT_LOG}),this.name=`CorruptedEventLogError`}static is(e){return n(e)&&e.name===`CorruptedEventLogError`}},f=class extends u{eventId;constructor(e,t){super(e,{...t,slug:a.REPLAY_DIVERGENCE}),this.name=`ReplayDivergenceError`,this.eventId=t.eventId}static is(e){return n(e)&&e.name===`ReplayDivergenceError`&&typeof e.eventId==`string`}},p=class extends o{eventCount;limit;constructor(e,t,n){super(`Workflow exceeded the maximum of ${t} events per run`,n),this.name=`MaxEventsExceededError`,this.eventCount=e,this.limit=t}static is(e){return n(e)&&e.name===`MaxEventsExceededError`}},m=class extends u{constructor(e,t){super(e,{cause:t?.cause,slug:a.RUNTIME_DECRYPTION_FAILED}),this.name=`RuntimeDecryptionError`,t?.context!==void 0&&(this.context=t.context)}static is(e){return n(e)&&e.name===`RuntimeDecryptionError`}},h=class extends o{hint;constructor(e,t){let n=r(e,i(t?.hint,void 0));super(n,{cause:t?.cause}),this.name=`WorkflowBuildError`,this.hint=t?.hint}static is(e){return n(e)&&e.name===`WorkflowBuildError`}},g=class extends o{hint;fatal=!0;constructor(e,t){let n=r(e,i(t?.hint,void 0));super(n,{cause:t?.cause}),this.name=`SerializationError`,this.hint=t?.hint}static is(e){return n(e)&&e.name===`SerializationError`}},_=class extends u{stepName;constructor(e){super(`Step "${e}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`,{slug:a.STEP_NOT_REGISTERED}),this.name=`StepNotRegisteredError`,this.stepName=e}static is(e){return n(e)&&e.name===`StepNotRegisteredError`}},v=class extends u{workflowName;constructor(e){super(`Workflow "${e}" is not registered in the current deployment. This usually means a run was started against a deployment that does not have this workflow, or there was a build/bundling issue.`,{slug:a.WORKFLOW_NOT_REGISTERED}),this.name=`WorkflowNotRegisteredError`,this.workflowName=e}static is(e){return n(e)&&e.name===`WorkflowNotRegisteredError`}},y=class extends o{runId;constructor(e){super(`Workflow run "${e}" not found`,{}),this.name=`WorkflowRunNotFoundError`,this.runId=e}static is(e){return n(e)&&e.name===`WorkflowRunNotFoundError`}},b=class extends o{token;conflictingRunId;constructor(e,t){super(`Hook token "${e}" is already in use by another workflow${t?` (run "${t}")`:``}`,{slug:a.HOOK_CONFLICT}),this.name=`HookConflictError`,this.token=e,t!==void 0&&(this.conflictingRunId=t)}static is(e){return n(e)&&e.name===`HookConflictError`}},x=class extends o{token;constructor(e){super(`Hook not found`,{}),this.name=`HookNotFoundError`,this.token=e}static is(e){return n(e)&&e.name===`HookNotFoundError`}},S=class extends s{constructor(e){super(e),this.name=`EntityConflictError`}static is(e){return n(e)&&e.name===`EntityConflictError`}},C=class extends s{constructor(e){super(e),this.name=`RunExpiredError`}static is(e){return n(e)&&e.name===`RunExpiredError`}},w=class extends s{constructor(e,t){super(e,{retryAfter:t?.retryAfter}),this.name=`TooEarlyError`}static is(e){return n(e)&&e.name===`TooEarlyError`}},T=class extends s{retryAfter;constructor(e,t){super(e),this.name=`ThrottleError`,this.retryAfter=t?.retryAfter}static is(e){return n(e)&&e.name===`ThrottleError`}},E=class extends s{details;constructor(e,t){super(e,{status:412,retryAfter:t?.retryAfter}),this.name=`PreconditionFailedError`,this.details=t?.details}static is(e){return n(e)&&e.name===`PreconditionFailedError`}},D=class extends o{runId;constructor(e){super(`Workflow run "${e}" cancelled`,{}),this.name=`WorkflowRunCancelledError`,this.runId=e}static is(e){return n(e)&&e.name===`WorkflowRunCancelledError`}},O=class extends o{runSpecVersion;worldSpecVersion;constructor(e,t){super(`Run requires spec version ${e}, but world supports version ${t}. Please upgrade 'workflow' package.`),this.name=`RunNotSupportedError`,this.runSpecVersion=e,this.worldSpecVersion=t}static is(e){return n(e)&&e.name===`RunNotSupportedError`}},k=class extends Error{fatal=!0;constructor(e){super(e),this.name=`FatalError`}static is(e){return n(e)?e.name===`FatalError`||e.fatal===!0:!1}},A=class extends Error{retryAfter;constructor(t,n={}){super(t),this.name=`RetryableError`,n.retryAfter===void 0?this.retryAfter=new Date(Date.now()+1e3):this.retryAfter=e(n.retryAfter)}static is(e){return n(e)&&e.name===`RetryableError`}};const j="Your current vercel account does not have access to this resource. Use `vercel login` or `vercel switch` to ensure you are linked to the right account.",M=Symbol.for(`@workflow/errors//FatalError`),N=Symbol.for(`@workflow/errors//RetryableError`),P=Symbol.for(`@workflow/errors//HookConflictError`),F=Symbol.for(`@workflow/errors//RuntimeDecryptionError`);typeof globalThis<`u`&&(Object.hasOwn(globalThis,M)||Object.defineProperty(globalThis,M,{value:k,writable:!1,enumerable:!1,configurable:!1}),Object.hasOwn(globalThis,N)||Object.defineProperty(globalThis,N,{value:A,writable:!1,enumerable:!1,configurable:!1}),Object.hasOwn(globalThis,P)||Object.defineProperty(globalThis,P,{value:b,writable:!1,enumerable:!1,configurable:!1}),Object.hasOwn(globalThis,F)||Object.defineProperty(globalThis,F,{value:m,writable:!1,enumerable:!1,configurable:!1}));export{c as C,s as D,u as E,t as O,D as S,y as T,w as _,b as a,o as b,E as c,C as d,O as f,T as g,_ as h,k as i,f as l,g as m,a as n,x as o,m as p,S as r,p as s,d as t,A as u,j as v,l as w,v as x,h as y};
@@ -1 +0,0 @@
1
- import{t as e}from"./rolldown-runtime-DaDcL9Zw.js";var t=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{CITY_HEADER_NAME:()=>u,COUNTRY_HEADER_NAME:()=>d,EMOJI_FLAG_UNICODE_STARTING_POSITION:()=>v,IP_HEADER_NAME:()=>f,LATITUDE_HEADER_NAME:()=>p,LONGITUDE_HEADER_NAME:()=>m,POSTAL_CODE_HEADER_NAME:()=>g,REGION_HEADER_NAME:()=>h,REQUEST_ID_HEADER_NAME:()=>_,geolocation:()=>w,ipAddress:()=>S}),t.exports=c(l);let u=`x-vercel-ip-city`,d=`x-vercel-ip-country`,f=`x-real-ip`,p=`x-vercel-ip-latitude`,m=`x-vercel-ip-longitude`,h=`x-vercel-ip-country-region`,g=`x-vercel-ip-postal-code`,_=`x-vercel-id`,v=127397;function y(e,t){return e.get(t)??void 0}function b(e,t){let n=y(e.headers,t);return n?decodeURIComponent(n):void 0}function x(e){let t=RegExp(`^[A-Z]{2}$`).test(e);if(!(!e||!t))return String.fromCodePoint(...e.split(``).map(e=>v+e.charCodeAt(0)))}function S(e){return y(`headers`in e?e.headers:e,f)}function C(e){return e?e.split(`:`)[0]:`dev1`}function w(e){return{city:b(e,u),country:y(e.headers,d),flag:x(y(e.headers,d)),countryRegion:y(e.headers,h),region:C(y(e.headers,_)),latitude:y(e.headers,p),longitude:y(e.headers,m),postalCode:y(e.headers,g)}}0&&(t.exports={CITY_HEADER_NAME:u,COUNTRY_HEADER_NAME:d,EMOJI_FLAG_UNICODE_STARTING_POSITION:v,IP_HEADER_NAME:f,LATITUDE_HEADER_NAME:p,LONGITUDE_HEADER_NAME:m,POSTAL_CODE_HEADER_NAME:g,REGION_HEADER_NAME:h,REQUEST_ID_HEADER_NAME:_,geolocation:w,ipAddress:S})})),n=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{getEnv:()=>u}),t.exports=c(l);let u=(e=process.env)=>({VERCEL:d(e,`VERCEL`),CI:d(e,`CI`),VERCEL_ENV:d(e,`VERCEL_ENV`),VERCEL_URL:d(e,`VERCEL_URL`),VERCEL_BRANCH_URL:d(e,`VERCEL_BRANCH_URL`),VERCEL_PROJECT_PRODUCTION_URL:d(e,`VERCEL_PROJECT_PRODUCTION_URL`),VERCEL_REGION:d(e,`VERCEL_REGION`),VERCEL_DEPLOYMENT_ID:d(e,`VERCEL_DEPLOYMENT_ID`),VERCEL_SKEW_PROTECTION_ENABLED:d(e,`VERCEL_SKEW_PROTECTION_ENABLED`),VERCEL_AUTOMATION_BYPASS_SECRET:d(e,`VERCEL_AUTOMATION_BYPASS_SECRET`),VERCEL_GIT_PROVIDER:d(e,`VERCEL_GIT_PROVIDER`),VERCEL_GIT_REPO_SLUG:d(e,`VERCEL_GIT_REPO_SLUG`),VERCEL_GIT_REPO_OWNER:d(e,`VERCEL_GIT_REPO_OWNER`),VERCEL_GIT_REPO_ID:d(e,`VERCEL_GIT_REPO_ID`),VERCEL_GIT_COMMIT_REF:d(e,`VERCEL_GIT_COMMIT_REF`),VERCEL_GIT_COMMIT_SHA:d(e,`VERCEL_GIT_COMMIT_SHA`),VERCEL_GIT_COMMIT_MESSAGE:d(e,`VERCEL_GIT_COMMIT_MESSAGE`),VERCEL_GIT_COMMIT_AUTHOR_LOGIN:d(e,`VERCEL_GIT_COMMIT_AUTHOR_LOGIN`),VERCEL_GIT_COMMIT_AUTHOR_NAME:d(e,`VERCEL_GIT_COMMIT_AUTHOR_NAME`),VERCEL_GIT_PREVIOUS_SHA:d(e,`VERCEL_GIT_PREVIOUS_SHA`),VERCEL_GIT_PULL_REQUEST_ID:d(e,`VERCEL_GIT_PULL_REQUEST_ID`)}),d=(e,t)=>{let n=e[t];return n===``?void 0:n};0&&(t.exports={getEnv:u})})),r=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}0&&(t.exports={SYMBOL_FOR_REQ_CONTEXT:u,getContext:d})})),i=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{waitUntil:()=>f}),t.exports=l(u);var d=r();let f=e=>{if(typeof e!=`object`||!e||typeof e.then!=`function`)throw TypeError(`waitUntil can only be called with a Promise, got ${typeof e}`);return(0,d.getContext)().waitUntil?.(e)};0&&(t.exports={waitUntil:f})})),a=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{next:()=>f,rewrite:()=>d}),t.exports=c(l);function u(e,t){if(e?.request?.headers){if(!(e.request.headers instanceof Headers))throw Error(`request.headers must be an instance of Headers`);let n=[];for(let[r,i]of e.request.headers)t.set(`x-middleware-request-`+r,i),n.push(r);t.set(`x-middleware-override-headers`,n.join(`,`))}}function d(e,t){let n=new Headers(t?.headers??{});return n.set(`x-middleware-rewrite`,String(e)),u(t,n),new Response(null,{...t,headers:n})}function f(e){let t=new Headers(e?.headers??{});return t.set(`x-middleware-next`,`1`),u(e,t),new Response(null,{...e,headers:t})}0&&(t.exports={next:f,rewrite:d})})),o=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{InMemoryCache:()=>u}),t.exports=c(l);var u=class{constructor(){this.cache={}}async get(e){let t=this.cache[e];return t?t.ttl&&t.lastModified+t.ttl*1e3<Date.now()?(await this.delete(e),null):JSON.parse(t.value):null}async set(e,t,n){let r=JSON.stringify(t??null);this.cache[e]={value:r,lastModified:Date.now(),ttl:n?.ttl,tags:new Set(n?.tags||[])}}async delete(e){delete this.cache[e]}async expireTag(e){let t=Array.isArray(e)?e:[e];for(let e in this.cache)if(Object.prototype.hasOwnProperty.call(this.cache,e)){let n=this.cache[e];t.some(e=>n.tags.has(e))&&delete this.cache[e]}}};0&&(t.exports={InMemoryCache:u})})),s=e(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},l=e=>s(n({},`__esModule`,{value:!0}),e),u={};o(u,{BuildCache:()=>f}),t.exports=l(u);var d=c(),f=class{constructor({endpoint:e,headers:t,onError:n,timeout:r=500}){this.get=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{let r=await fetch(`${this.endpoint}${e}`,{headers:this.headers,method:`GET`,signal:t.signal});if(r.status===404)return clearTimeout(n),null;if(r.status===200){if(r.headers.get(d.HEADERS_VERCEL_CACHE_STATE)!==d.PkgCacheState.Fresh)return r.body?.cancel?.(),clearTimeout(n),null;let e=await r.json();return clearTimeout(n),e}else throw clearTimeout(n),Error(`Failed to get cache: ${r.statusText}`)}catch(e){if(clearTimeout(n),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e);return null}},this.set=async(e,t,n)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),this.timeout);try{let a={};n?.ttl&&(a[d.HEADERS_VERCEL_REVALIDATE]=n.ttl.toString()),n?.tags&&n.tags.length>0&&(a[d.HEADERS_VERCEL_CACHE_TAGS]=n.tags.join(`,`)),n?.name&&(a[d.HEADERS_VERCEL_CACHE_ITEM_NAME]=n.name);let o=await fetch(`${this.endpoint}${e}`,{method:`POST`,headers:{...this.headers,...a},body:JSON.stringify(t),signal:r.signal});if(clearTimeout(i),o.status!==200)throw Error(`Failed to set cache: ${o.status} ${o.statusText}`)}catch(e){if(clearTimeout(i),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e)}},this.delete=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{let r=await fetch(`${this.endpoint}${e}`,{method:`DELETE`,headers:this.headers,signal:t.signal});if(clearTimeout(n),r.status!==200)throw Error(`Failed to delete cache: ${r.statusText}`)}catch(e){if(clearTimeout(n),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e)}},this.expireTag=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{Array.isArray(e)&&(e=e.join(`,`));let r=await fetch(`${this.endpoint}revalidate?tags=${e}`,{method:`POST`,headers:this.headers,signal:t.signal});if(clearTimeout(n),r.status!==200)throw Error(`Failed to revalidate tag: ${r.statusText}`)}catch(e){if(clearTimeout(n),e.name===`AbortError`){let t=Error(`Cache request timed out after ${this.timeout}ms`);t.stack=e.stack,this.onError?.(t)}else this.onError?.(e)}},this.endpoint=e,this.headers=t,this.onError=n,this.timeout=r}};0&&(t.exports={BuildCache:f})})),c=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},u=(e,t,r,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of a(t))!c.call(e,s)&&s!==r&&n(e,s,{get:()=>t[s],enumerable:!(o=i(t,s))||o.enumerable});return e},d=e=>u(n({},`__esModule`,{value:!0}),e),f={};l(f,{HEADERS_VERCEL_CACHE_ITEM_NAME:()=>O,HEADERS_VERCEL_CACHE_STATE:()=>T,HEADERS_VERCEL_CACHE_TAGS:()=>D,HEADERS_VERCEL_REVALIDATE:()=>E,PkgCacheState:()=>w,getCache:()=>y}),t.exports=d(f);var p=r(),m=o(),h=s();let g=e=>{let t=5381;for(let n=0;n<e.length;n++)t=t*33^e.charCodeAt(n);return(t>>>0).toString(16)},_=null,v=null,y=e=>x(()=>{let e;return e=(0,p.getContext)().cache?(0,p.getContext)().cache:C(process.env.SUSPENSE_CACHE_DEBUG===`true`),e},b(e));function b(e){let t=e?.keyHashFunction||g;return n=>{if(!e?.namespace)return t(n);let r=e.namespaceSeparator||`$`;return`${e.namespace}${r}${t(n)}`}}function x(e,t){return{get:n=>e().get(t(n)),set:(n,r,i)=>e().set(t(n),r,{...i,name:i?.name??n}),delete:n=>e().delete(t(n)),expireTag:t=>e().expireTag(t)}}let S=!1;function C(e){if(_||=new m.InMemoryCache,process.env.RUNTIME_CACHE_DISABLE_BUILD_CACHE===`true`)return e&&console.log(`Using InMemoryCache as build cache is disabled`),_;let{RUNTIME_CACHE_ENDPOINT:t,RUNTIME_CACHE_HEADERS:n}=process.env;if(e&&console.log(`Runtime cache environment variables:`,{RUNTIME_CACHE_ENDPOINT:t,RUNTIME_CACHE_HEADERS:n}),!t||!n)return S||=(console.warn(`Runtime Cache unavailable in this environment. Falling back to in-memory cache.`),!0),_;if(!v){let e={};try{e=JSON.parse(n)}catch(e){return console.error(`Failed to parse RUNTIME_CACHE_HEADERS:`,e),_}let r=500;if(process.env.RUNTIME_CACHE_TIMEOUT){let e=parseInt(process.env.RUNTIME_CACHE_TIMEOUT,10);!isNaN(e)&&e>0?r=e:console.warn(`Invalid RUNTIME_CACHE_TIMEOUT value: "${process.env.RUNTIME_CACHE_TIMEOUT}". Using default: ${r}ms`)}v=new h.BuildCache({endpoint:t,headers:e,onError:e=>console.error(e),timeout:r})}return v}var w=(e=>(e.Fresh=`fresh`,e.Stale=`stale`,e.Expired=`expired`,e.NotFound=`notFound`,e.Error=`error`,e))(w||{});let T=`x-vercel-cache-state`,E=`x-vercel-revalidate`,D=`x-vercel-cache-tags`,O=`x-vercel-cache-item-name`;0&&(t.exports={HEADERS_VERCEL_CACHE_ITEM_NAME:O,HEADERS_VERCEL_CACHE_STATE:T,HEADERS_VERCEL_CACHE_TAGS:D,HEADERS_VERCEL_REVALIDATE:E,PkgCacheState:w,getCache:y})})),l=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{attachDatabasePool:()=>v,experimental_attachDatabasePool:()=>y}),t.exports=l(u);var d=r();let f=!!process.env.DEBUG;function p(e){if(`options`in e&&e.options){if(`idleTimeoutMillis`in e.options)return typeof e.options.idleTimeoutMillis==`number`?e.options.idleTimeoutMillis:1e4;if(`maxIdleTimeMS`in e.options)return typeof e.options.maxIdleTimeMS==`number`?e.options.maxIdleTimeMS:0;if(`status`in e)return 5e3;if(`connect`in e&&`execute`in e)return 3e4}if(`config`in e&&e.config){if(`connectionConfig`in e.config&&e.config.connectionConfig)return e.config.connectionConfig.idleTimeout||6e4;if(`idleTimeout`in e.config)return typeof e.config.idleTimeout==`number`?e.config.idleTimeout:6e4}return`poolTimeout`in e?typeof e.poolTimeout==`number`?e.poolTimeout:6e4:`idleTimeout`in e?typeof e.idleTimeout==`number`?e.idleTimeout:0:1e4}let m=null,h=()=>{},g=Date.now();function _(e){if(!process.env.VERCEL_URL||!process.env.VERCEL_REGION)return;m&&(clearTimeout(m),h());let t=new Promise(e=>{h=e}),n=Math.min(p(e)+100,Math.max(100,899e3-(Date.now()-g)));m=setTimeout(()=>{h?.(),f&&console.log(`Database pool idle timeout reached. Releasing connections.`)},n);let r=(0,d.getContext)();r?.waitUntil?r.waitUntil(t):console.warn(`Pool release event triggered outside of request scope.`)}function v(e){if(m&&(h?.(),clearTimeout(m)),`on`in e&&e.on&&`options`in e&&`idleTimeoutMillis`in e.options){e.on(`release`,()=>{f&&console.log(`Client released from pool`),_(e)});return}else if(`on`in e&&e.on&&`config`in e&&e.config&&`connectionConfig`in e.config){e.on(`release`,()=>{f&&console.log(`MySQL client released from pool`),_(e)});return}else if(`on`in e&&e.on&&`config`in e&&e.config&&`idleTimeout`in e.config){e.on(`release`,()=>{f&&console.log(`MySQL2/MariaDB client released from pool`),_(e)});return}if(`on`in e&&e.on&&`options`in e&&e.options&&`maxIdleTimeMS`in e.options){e.on(`connectionCheckedOut`,()=>{f&&console.log(`MongoDB connection checked out`),_(e)});return}if(`on`in e&&e.on&&`options`in e&&e.options&&`socket`in e.options){e.on(`end`,()=>{f&&console.log(`Redis connection ended`),_(e)});return}throw Error(`Unsupported database pool type`)}let y=v;0&&(t.exports={attachDatabasePool:v,experimental_attachDatabasePool:y})})),u=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{dangerouslyDeleteBySrcImage:()=>h,dangerouslyDeleteByTag:()=>p,invalidateBySrcImage:()=>m,invalidateByTag:()=>f}),t.exports=l(u);var d=r();let f=e=>{let t=(0,d.getContext)().purge;return t?t.invalidateByTag(e):Promise.resolve()},p=(e,t)=>{let n=(0,d.getContext)().purge;return n?n.dangerouslyDeleteByTag(e,t):Promise.resolve()},m=e=>{let t=(0,d.getContext)().purge;return t?t.invalidateBySrcImage(e):Promise.resolve()},h=(e,t)=>{let n=(0,d.getContext)().purge;return n?n.dangerouslyDeleteBySrcImage(e,t):Promise.resolve()};0&&(t.exports={dangerouslyDeleteBySrcImage:h,dangerouslyDeleteByTag:p,invalidateBySrcImage:m,invalidateByTag:f})})),d=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{addCacheTag:()=>f}),t.exports=l(u);var d=r();let f=e=>{let t=(0,d.getContext)().addCacheTag;return t?t(e):Promise.resolve()};0&&(t.exports={addCacheTag:f})})),f=e(((e,t)=>{var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,r,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{experimental_upgradeWebSocket:()=>p}),t.exports=l(u);var d=r();async function f(){try{return(await import(`./wrapper-6mlyNCCb.js`)).WebSocketServer}catch{throw Error(`The "ws" package is required for experimental_upgradeWebSocket(). Install it with: npm install ws`)}}async function p(e,t={}){let n=(0,d.getContext)();if(typeof n.upgradeWebSocket!=`function`)throw Error(`experimental_upgradeWebSocket is not available in the current runtime environment. This feature requires a Vercel runtime that supports WebSocket upgrades.`);let r=await f(),{req:i,socket:a,head:o}=n.upgradeWebSocket(),s=new r({noServer:!0,maxPayload:t.maxPayload??262144}),c=await new Promise((e,t)=>{let n=()=>{a.removeListener(`error`,l),a.removeListener(`close`,u)},r=e=>{if(n(),e instanceof Error){t(e);return}let r=Error(`WebSocket upgrade failed`);r.cause=e,t(r)},c=t=>{n(),e(t)},l=e=>r(e),u=()=>r(Error(`socket closed before the WebSocket upgrade completed`));a.once(`error`,l),a.once(`close`,u);try{s.handleUpgrade(i,a,o,c)}catch(e){r(e)}});try{await e(c)}catch(e){throw c.close(1011,`WebSocket handler failed`),e}return new Response(null,{status:204})}0&&(t.exports={experimental_upgradeWebSocket:p})})),p=e(((e,r)=>{var o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,p=Object.getOwnPropertyNames,m=Object.prototype.hasOwnProperty,h=(e,t)=>{for(var n in t)o(e,n,{get:t[n],enumerable:!0})},g=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of p(t))!m.call(e,i)&&i!==n&&o(e,i,{get:()=>t[i],enumerable:!(r=s(t,i))||r.enumerable});return e},_=e=>g(o({},`__esModule`,{value:!0}),e),v={};h(v,{addCacheTag:()=>E.addCacheTag,attachDatabasePool:()=>w.attachDatabasePool,dangerouslyDeleteBySrcImage:()=>T.dangerouslyDeleteBySrcImage,dangerouslyDeleteByTag:()=>T.dangerouslyDeleteByTag,experimental_attachDatabasePool:()=>w.experimental_attachDatabasePool,experimental_upgradeWebSocket:()=>D.experimental_upgradeWebSocket,geolocation:()=>y.geolocation,getCache:()=>C.getCache,getEnv:()=>b.getEnv,invalidateBySrcImage:()=>T.invalidateBySrcImage,invalidateByTag:()=>T.invalidateByTag,ipAddress:()=>y.ipAddress,next:()=>S.next,rewrite:()=>S.rewrite,waitUntil:()=>x.waitUntil}),r.exports=_(v);var y=t(),b=n(),x=i(),S=a(),C=c(),w=l(),T=u(),E=d(),D=f();0&&(r.exports={addCacheTag,attachDatabasePool,dangerouslyDeleteBySrcImage,dangerouslyDeleteByTag,experimental_attachDatabasePool,experimental_upgradeWebSocket,geolocation,getCache,getEnv,invalidateBySrcImage,invalidateByTag,ipAddress,next,rewrite,waitUntil})}));export default p();export{};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-DaDcL9Zw.js";import{An as t,D as n,J as r,Mn as i,P as a,Sn as o,Un as s,Yn as c,a as l,en as u,ft as d,gt as f,it as p,ln as m,mt as h,n as g,nt as _,pt as v,t as y,x as b,xn as x,y as ee,yn as S}from"./wait-until-DoW76jdb.js";import{E as C,d as w,n as T,o as E,r as D}from"./dist-dNxTT6nO.js";import{j as O,o as k}from"./dist-D5bR13zs.js";import{t as A}from"./spec-version-C0hBsfu-.js";var j=e({getHookByToken:()=>R,resumeHook:()=>z,resumeWebhook:()=>V});const M=k();async function N(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function P(e){let t=e.executionContext?.workflowCoreVersion,n=e.executionContext?.traceCarrier,r=e.executionContext?.hookResumeInputVersion;return{deploymentId:e.deploymentId,workflowName:e.workflowName,runSpecVersion:e.specVersion,workflowCoreVersion:typeof t==`string`?t:void 0,traceCarrier:n&&typeof n==`object`?n:void 0,encryptionPublicKey:e.encryptionPublicKey,hookResumeInputVersion:typeof r==`number`?r:void 0}}async function F(e){if(e.resumeContext)return{resumeContext:e.resumeContext,source:`hook`};let t=await(await i()).runs.get(e.runId);return{resumeContext:P(t),source:`run_fallback`,run:t}}async function I(e,t){let n=await i(),r=t.run?await n.getEncryptionKeyForRun?.(t.run):await n.getEncryptionKeyForRun?.(e.runId,{deploymentId:t.resumeContext.deploymentId});return r?await c(r):void 0}async function L(e){let t=await i(),n=await t.hooks.getByToken(e),r;if(n.metadata!==void 0){let e=await F(n),i=e.run?await t.getEncryptionKeyForRun?.(e.run):await t.getEncryptionKeyForRun?.(n.runId,{deploymentId:e.resumeContext.deploymentId});r=i?await S(i):void 0,n.metadata=await a(n.metadata,n.runId,r)}return{hook:n,encryptionKey:r}}async function R(e){let{hook:t}=await L(e);return t}async function z(e,t,n){return B(e,t,n,!1)}async function B(e,a,s,c){return await g(()=>p(`hook.resume`,async p=>{let g=await i();try{let i=typeof e==`string`,d=i?await g.hooks.getByToken(e):e,S=i||c,C=await F(d),{resumeContext:T}=C;if(p?.setAttributes({...f(d.token),...v(d.hookId),...m(d.runId),"workflow.hook.resume_context_source":C.source}),C.run&&O(C.run.status))throw new E(d.token);let k=b(T.workflowCoreVersion),j,P=s?void 0:t(T.encryptionPublicKey);if(P)j=x(P);else{let e=s??await I(d,C);k.supportedFormats.has(o.ENCRYPTED)||(e=void 0),j=e}let L=(T.runSpecVersion??0)>=5&&k.supportedFormats.has(o.GZIP),R=[],z=A(d.specVersion),B=await n(a,d.runId,j,R,globalThis,z,k.framedByteStreams,L);y(Promise.all(R),e=>{e!==void 0&&r.warn(`Background flush of hook payload ops failed`,{workflowRunId:d.runId,hookId:d.hookId,error:e instanceof Error?e.message:String(e)})}),p?.setAttributes({...u(T.workflowName)});let V=await _(T.traceCarrier);V&&p?.addLink?.(V);let H={...z?{}:{token:d.token},payload:B},U=l(T.workflowName),W={deploymentId:T.deploymentId,specVersion:T.runSpecVersion??1},G=process.env.WORKFLOW_DISABLE_LAZY_HOOK_RESUME===`1`,K=(S?d.resumeCapabilities?.hookResumeDedupVersion??0:0)>=1||g.capabilities?.hookResumeDedup===!0,q=G?`disabled`:K?(T.hookResumeInputVersion??0)<1?`consumer_unsupported`:z?`legacy`:(T.runSpecVersion??0)<3?`non_cbor_transport`:B instanceof Uint8Array?B.byteLength>131072?`oversized`:null:`non_bytes`:`backend_unsupported`,J=q===null;p?.setAttributes({"workflow.hook.resume_strategy":J?`parallel`:`sequential`,...q?{"workflow.hook.resume_fallback_reason":q}:{}});let te=e=>E.is(e)||D.is(e)||w.is(e);if(!J){try{await g.events.create(d.runId,{eventType:`hook_received`,specVersion:5,correlationId:d.hookId,eventData:H},{v1Compat:z})}catch(e){throw te(e)?new E(d.token):e}return await g.queue(U,{runId:d.runId,traceCarrier:T.traceCarrier??void 0},W),d}let Y=M(),X=await N(B);p?.setAttributes({"workflow.hook.resume_id":Y});let[Z,Q]=await Promise.allSettled([g.events.create(d.runId,{eventType:`hook_received`,specVersion:5,correlationId:d.hookId,eventData:H},{v1Compat:z,resumeId:Y,resumePayloadDigest:X}),g.queue(U,{runId:d.runId,traceCarrier:T.traceCarrier??void 0,hookInput:{resumeId:Y,hookId:d.hookId,token:d.token,payload:B,payloadDigest:X}},W)]);if(Q.status===`rejected`)throw Q.reason;let $=!1;if(Z.status===`rejected`){let e=Z.reason;if(E.is(e)||w.is(e))throw new E(d.token);if(D.is(e)||ee(e))$=!0,p?.setAttributes({...h(!0),"workflow.hook.resume_event_write_recovered":!0,"workflow.hook.resume_event_write_error":e instanceof Error?e.name:`unknown`}),r.warn(`Hook resume event write failed, but the run was re-triggered via the queue. The hook_received event will be ensured by the queue consumer.`,{workflowRunId:d.runId,hookId:d.hookId,resumeId:Y,error:e instanceof Error?e.message:String(e)});else throw e}return $?{...d,resilientResume:!0}:d}catch(t){throw p?.setAttributes({...f(typeof e==`string`?e:e.token),...d(!1)}),t}}))}async function V(e,t){let{hook:n,encryptionKey:r}=await L(e);if(n.isWebhook===!1)throw new E(e);let i,a;if(n.metadata&&typeof n.metadata==`object`&&`respondWith`in n.metadata)if(n.metadata.respondWith===`manual`){let{readable:e,writable:n}=new TransformStream;a=e,t[s]=n}else if(n.metadata.respondWith instanceof Response)i=n.metadata.respondWith;else throw new C(`Invalid \`respondWith\` value: ${n.metadata.respondWith}`,{slug:T.WEBHOOK_INVALID_RESPOND_WITH_VALUE});else i=new Response(null,{status:202});if(await B(n,t,r,!0),a){let e=a.getReader(),t=await e.read();t.value&&(i=t.value),e.cancel()}if(!i)throw new C(`Workflow run did not send a response`,{slug:T.WEBHOOK_RESPONSE_NOT_SENT});return i}export{j as i,z as n,V as r,R as t};