eve 0.51.1 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/src/cli/dev/boot-progress.d.ts +3 -0
  3. package/dist/src/cli/dev/boot-progress.js +1 -0
  4. package/dist/src/cli/run.d.ts +4 -0
  5. package/dist/src/cli/run.js +3 -3
  6. package/dist/src/cli/telemetry/command.d.ts +9 -0
  7. package/dist/src/cli/telemetry/command.js +1 -0
  8. package/dist/src/cli/telemetry/flush.d.ts +2 -0
  9. package/dist/src/cli/telemetry/flush.js +1 -0
  10. package/dist/src/cli/telemetry/identity.d.ts +13 -0
  11. package/dist/src/cli/telemetry/identity.js +1 -0
  12. package/dist/src/cli/telemetry/index.d.ts +25 -0
  13. package/dist/src/cli/telemetry/index.js +3 -0
  14. package/dist/src/cli/telemetry/preference.d.ts +9 -0
  15. package/dist/src/cli/telemetry/preference.js +1 -0
  16. package/dist/src/client/types.d.ts +3 -2
  17. package/dist/src/compiled/.vendor-stamp.json +2 -2
  18. package/dist/src/compiled/@eve/catalog/index.js +1 -1
  19. package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +1 -0
  20. package/dist/src/compiler/extension-compatibility.d.ts +22 -4
  21. package/dist/src/compiler/extension-compatibility.js +1 -1
  22. package/dist/src/compiler/manifest.js +1 -1
  23. package/dist/src/compiler/normalize-channel.js +1 -1
  24. package/dist/src/compiler/normalize-schedule.js +1 -1
  25. package/dist/src/compiler/normalize-tool.js +1 -1
  26. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  27. package/dist/src/execution/activity-collector.js +1 -1
  28. package/dist/src/execution/continuation-conflict-step.js +1 -1
  29. package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -2
  30. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  31. package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -1
  32. package/dist/src/execution/inline-turn.d.ts +2 -2
  33. package/dist/src/execution/inline-turn.js +1 -1
  34. package/dist/src/execution/tasks/child/steps.d.ts +11 -1
  35. package/dist/src/execution/tasks/child/steps.js +1 -1
  36. package/dist/src/execution/tasks/child/workflow.js +1 -1
  37. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  38. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  39. package/dist/src/execution/tools/subagent/invoke-agent.d.ts +1 -7
  40. package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
  41. package/dist/src/execution/tools/workflow/ask.d.ts +1 -2
  42. package/dist/src/execution/tools/workflow/ask.js +1 -1
  43. package/dist/src/execution/tools/workflow/body.d.ts +6 -1
  44. package/dist/src/execution/tools/workflow/body.js +1 -1
  45. package/dist/src/execution/tools/workflow/cancel.js +1 -1
  46. package/dist/src/execution/tools/workflow/messages.d.ts +9 -8
  47. package/dist/src/execution/tools/workflow/messages.js +1 -1
  48. package/dist/src/execution/tools/workflow/owner-inbox.d.ts +2 -2
  49. package/dist/src/execution/tools/workflow/owner-inbox.js +1 -1
  50. package/dist/src/execution/tools/workflow/owner.d.ts +5 -11
  51. package/dist/src/execution/tools/workflow/owner.js +1 -1
  52. package/dist/src/execution/tools/workflow/run-control.d.ts +0 -4
  53. package/dist/src/execution/tools/workflow/run-control.js +1 -1
  54. package/dist/src/execution/tools/workflow/start.d.ts +5 -14
  55. package/dist/src/execution/tools/workflow/start.js +1 -1
  56. package/dist/src/execution/tools/workflow/workflow.d.ts +1 -1
  57. package/dist/src/execution/tools/workflow/workflow.js +1 -1
  58. package/dist/src/execution/turn-dispatch.js +1 -1
  59. package/dist/src/execution/turn-workflow-tool-run.d.ts +2 -8
  60. package/dist/src/execution/turn-workflow-tool-run.js +1 -1
  61. package/dist/src/execution/turn-workflow.d.ts +1 -0
  62. package/dist/src/execution/turn-workflow.js +1 -1
  63. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  64. package/dist/src/execution/workflow-runtime.js +1 -1
  65. package/dist/src/execution/workflow-steps.js +1 -1
  66. package/dist/src/harness/emission-state.js +1 -1
  67. package/dist/src/harness/tool-loop.js +2 -2
  68. package/dist/src/harness/turn-client-context.d.ts +9 -0
  69. package/dist/src/harness/turn-client-context.js +1 -0
  70. package/dist/src/harness/workflow-tool-runs.d.ts +0 -1
  71. package/dist/src/harness/workflow-tool-runs.js +1 -1
  72. package/dist/src/internal/application/package.js +1 -1
  73. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  74. package/dist/src/internal/invocation/workflow-execution.js +1 -1
  75. package/dist/src/internal/mcp/streamable-http-server.d.ts +29 -1
  76. package/dist/src/internal/mcp/streamable-http-server.js +1 -1
  77. package/dist/src/internal/nitro/host/build-application.js +1 -1
  78. package/dist/src/internal/workflow/runtime.d.ts +6 -0
  79. package/dist/src/internal/workflow/runtime.js +1 -1
  80. package/dist/src/internal/workflow-bundle/authored-workflow-directives.d.ts +1 -3
  81. package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
  82. package/dist/src/internal/workflow-bundle/authored-workflow-modules.d.ts +1 -2
  83. package/dist/src/internal/workflow-bundle/authored-workflow-modules.js +1 -1
  84. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
  85. package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +0 -2
  86. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  87. package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
  88. package/dist/src/protocol/message.d.ts +3 -2
  89. package/dist/src/public/channels/mcp.js +1 -1
  90. package/dist/src/public/models/openai/chatgpt/model.js +2 -2
  91. package/dist/src/public/models/openai/chatgpt/transport.js +1 -1
  92. package/dist/src/public/tools/index.d.ts +3 -1
  93. package/dist/src/public/tools/index.js +1 -1
  94. package/dist/src/setup/scaffold/create/project.js +1 -1
  95. package/dist/src/shared/workflow-tool-context.d.ts +2 -0
  96. package/dist/src/shared/workflow-tool-context.js +1 -0
  97. package/dist/src/tasks/types.d.ts +17 -1
  98. package/dist/src/tasks/types.js +1 -1
  99. package/dist/src/tools/behavior.d.ts +5 -0
  100. package/dist/src/tools/definition.d.ts +16 -12
  101. package/dist/src/tools/definition.js +1 -1
  102. package/dist/src/tools/dynamic.d.ts +2 -2
  103. package/dist/src/tools/provided/sleep.d.ts +2 -2
  104. package/dist/src/tools/provided/sleep.js +1 -1
  105. package/dist/src/tools/task.d.ts +28 -80
  106. package/dist/src/tools/task.js +1 -1
  107. package/dist/src/tools/workflow-definition.d.ts +60 -0
  108. package/dist/src/tools/workflow-definition.js +1 -0
  109. package/docs/channels/mcp.mdx +25 -3
  110. package/docs/concepts/execution-model-and-durability.mdx +13 -2
  111. package/docs/guides/client/messages.mdx +1 -1
  112. package/docs/guides/deployment/vercel.mdx +2 -0
  113. package/docs/guides/frontend/overview.mdx +1 -1
  114. package/docs/memory/overview.mdx +40 -11
  115. package/docs/reference/cli.md +31 -33
  116. package/docs/reference/meta.json +1 -4
  117. package/docs/reference/telemetry.md +56 -0
  118. package/docs/reference/typescript-api.md +38 -35
  119. package/docs/tools/overview.mdx +59 -18
  120. package/docs/tools/workflows.mdx +146 -70
  121. package/package.json +1 -7
  122. package/dist/src/public/workflow/index.d.ts +0 -5
  123. package/dist/src/public/workflow/index.js +0 -1
@@ -1,6 +1,5 @@
1
1
  import type { HarnessSession, SessionStateMap } from "#harness/types.js";
2
2
  import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
3
- export declare function workflowToolRunAnswerToken(runId: string, seq: number): string;
4
3
  /** A workflow tool run the active turn waits on. Background runs live in the task index. */
5
4
  export interface WorkflowToolRunRecord {
6
5
  readonly callId: string;
@@ -1 +1 @@
1
- const WORKFLOW_TOOL_RUNS_STATE_KEY=`eve.runtime.workflowToolRuns`;function workflowToolRunAnswerToken(e,t){return`eve:workflow-tool-run-answer:${e}:${t}`}function getWorkflowToolRuns(t){let n=t?.[WORKFLOW_TOOL_RUNS_STATE_KEY];return Array.isArray(n)?n:[]}function findWorkflowToolRun(e,t){return getWorkflowToolRuns(e).find(e=>e.callId===t)}function recordWorkflowToolRun(e,t){return writeWorkflowToolRuns(e,[...getWorkflowToolRuns(e.state).filter(e=>e.callId!==t.callId),t])}function removeWorkflowToolRun(e,t){let n=getWorkflowToolRuns(e.state),r=n.filter(e=>e.callId!==t);return r.length===n.length?e:writeWorkflowToolRuns(e,r)}function clearWorkflowToolRuns(e){return getWorkflowToolRuns(e.state).length===0?e:writeWorkflowToolRuns(e,[])}function isInboxToolResultFromRecordedWorkflowToolRun(e,t){let n=findWorkflowToolRun(e,t.callId);return n!==void 0&&n.resultKind!==`subagent`&&n.toolName===t.toolName}function isInboxSubagentResultFromRecordedWorkflowToolRun(e,t){let n=findWorkflowToolRun(e,t.callId);return n?.resultKind===`subagent`&&n.toolName===t.subagentName}function writeWorkflowToolRuns(t,n){let r={...t.state};return n.length===0?delete r[WORKFLOW_TOOL_RUNS_STATE_KEY]:r[WORKFLOW_TOOL_RUNS_STATE_KEY]=n,{...t,state:Object.keys(r).length>0?r:void 0}}export{clearWorkflowToolRuns,findWorkflowToolRun,getWorkflowToolRuns,isInboxSubagentResultFromRecordedWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun,recordWorkflowToolRun,removeWorkflowToolRun,workflowToolRunAnswerToken};
1
+ const WORKFLOW_TOOL_RUNS_STATE_KEY=`eve.runtime.workflowToolRuns`;function getWorkflowToolRuns(t){let n=t?.[WORKFLOW_TOOL_RUNS_STATE_KEY];return Array.isArray(n)?n:[]}function findWorkflowToolRun(e,t){return getWorkflowToolRuns(e).find(e=>e.callId===t)}function recordWorkflowToolRun(e,t){return writeWorkflowToolRuns(e,[...getWorkflowToolRuns(e.state).filter(e=>e.callId!==t.callId),t])}function removeWorkflowToolRun(e,t){let n=getWorkflowToolRuns(e.state),r=n.filter(e=>e.callId!==t);return r.length===n.length?e:writeWorkflowToolRuns(e,r)}function clearWorkflowToolRuns(e){return getWorkflowToolRuns(e.state).length===0?e:writeWorkflowToolRuns(e,[])}function isInboxToolResultFromRecordedWorkflowToolRun(e,t){let n=findWorkflowToolRun(e,t.callId);return n!==void 0&&n.resultKind!==`subagent`&&n.toolName===t.toolName}function isInboxSubagentResultFromRecordedWorkflowToolRun(e,t){let n=findWorkflowToolRun(e,t.callId);return n?.resultKind===`subagent`&&n.toolName===t.subagentName}function writeWorkflowToolRuns(t,n){let r={...t.state};return n.length===0?delete r[WORKFLOW_TOOL_RUNS_STATE_KEY]:r[WORKFLOW_TOOL_RUNS_STATE_KEY]=n,{...t,state:Object.keys(r).length>0?r:void 0}}export{clearWorkflowToolRuns,findWorkflowToolRun,getWorkflowToolRuns,isInboxSubagentResultFromRecordedWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun,recordWorkflowToolRun,removeWorkflowToolRun};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.51.1`,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 i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=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 t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}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 n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}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{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.52.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 i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=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 t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}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 n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}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{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectPositiveInteger,expectString}from"#internal/authored-module.js";import{serializeInputSchema,serializeOutputSchema}from"#tools/schema.js";import{isDisabledToolSentinel}from"#tools/definition.js";import{assertResolverOnlyDynamicSentinel,isDynamicSentinel}from"#dynamic/definition.js";import{shouldRebindDynamicCallbacks}from"#internal/dynamic-tool-rebind.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{isExperimentalWorkflowToolDefinition}from"#tools/workflow.js";import{isWebSearchToolDefinition}from"#tools/provided/web-search.js";import{readToolBehavior}from"#tools/behavior.js";function normalizeToolDefinition(n,r){if(isDynamicSentinel(n))return assertResolverOnlyDynamicSentinel(n,r),{kind:`dynamic-tool`,eventNames:Object.keys(n.events),rebindMissingCallbacks:shouldRebindDynamicCallbacks(n)};if(isDisabledToolSentinel(n))return{kind:`disabled`};if(isExperimentalWorkflowToolDefinition(n)){let e=expectObjectRecord(n,r);return expectOnlyKnownKeys(e,[`kind`,`maxSubagents`],r),{kind:`workflow-tool`,maxSubagents:e.maxSubagents===void 0?void 0:expectPositiveInteger(e.maxSubagents,r)}}if(isWebSearchToolDefinition(n)){let e=expectObjectRecord(n,r);expectOnlyKnownKeys(e,[`kind`,`provider`],r);let t=expectString(e.provider,r);if(t!==`exa`&&t!==`parallel`)throw Error(`${r} Expected "provider" to be one of: exa, parallel.`);return{kind:`web-search-tool`,provider:t}}let i=expectObjectRecord(n,r);expectOnlyKnownKeys(i,[`auth`,`description`,`execute`,`execution`,`inputSchema`,`approval`,`outputSchema`,`toModelOutput`],r);let a=i.inputSchema===void 0?null:serializeInputSchema(i.inputSchema),o=serializeOutputSchema(i.outputSchema),s=readToolBehavior(n),c=i.execute!==void 0;!c&&s?.handling?.kind!==`dispatch`&&s?.handling?.kind!==`request-input`&&expectFunction(i.execute,r);let l={description:expectString(i.description,r),hasApproval:i.approval!==void 0,hasExecute:c,hasModelOutputProjection:i.toModelOutput!==void 0,inputSchema:a};if(s!==void 0&&(l.behavior=s),c&&(l.execute=expectFunction(i.execute,r)),i.execution!==void 0){if(!c)throw Error(`${r} Execute-less native tools cannot use background execution.`);let e=expectString(i.execution,r);if(e!==`background`)throw Error(`${r} Expected "execution" to be "background".`);l.execution=e}return o!==void 0&&(l.outputSchema=o),i.approval!==void 0&&normalizeApproval(i.approval,r),i.toModelOutput!==void 0&&expectFunction(i.toModelOutput,r),i.auth!==void 0&&expectFunction(expectObjectRecord(i.auth,r).getToken,r),{kind:`tool`,definition:l}}export{normalizeToolDefinition};
1
+ import{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectPositiveInteger,expectString}from"#internal/authored-module.js";import{serializeInputSchema,serializeOutputSchema}from"#tools/schema.js";import{isDisabledToolSentinel}from"#tools/definition.js";import{readWorkflowFunctionId}from"#internal/workflow/reference.js";import{assertResolverOnlyDynamicSentinel,isDynamicSentinel}from"#dynamic/definition.js";import{isWorkflowToolDefinition}from"#tools/workflow-definition.js";import{shouldRebindDynamicCallbacks}from"#internal/dynamic-tool-rebind.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{isExperimentalWorkflowToolDefinition}from"#tools/workflow.js";import{isWebSearchToolDefinition}from"#tools/provided/web-search.js";import{readToolBehavior}from"#tools/behavior.js";function normalizeToolDefinition(n,r){if(isDynamicSentinel(n))return assertResolverOnlyDynamicSentinel(n,r),{kind:`dynamic-tool`,eventNames:Object.keys(n.events),rebindMissingCallbacks:shouldRebindDynamicCallbacks(n)};if(isDisabledToolSentinel(n))return{kind:`disabled`};if(isExperimentalWorkflowToolDefinition(n)){let e=expectObjectRecord(n,r);return expectOnlyKnownKeys(e,[`kind`,`maxSubagents`],r),{kind:`workflow-tool`,maxSubagents:e.maxSubagents===void 0?void 0:expectPositiveInteger(e.maxSubagents,r)}}if(isWebSearchToolDefinition(n)){let e=expectObjectRecord(n,r);expectOnlyKnownKeys(e,[`kind`,`provider`],r);let t=expectString(e.provider,r);if(t!==`exa`&&t!==`parallel`)throw Error(`${r} Expected "provider" to be one of: exa, parallel.`);return{kind:`web-search-tool`,provider:t}}let i=expectObjectRecord(n,r),a=readWorkflowFunctionId(i.execute);if(isWorkflowToolDefinition(n)){if(a===void 0)throw Error(`${r} defineWorkflowTool() requires a compiled workflow executor. Start execute with "use workflow" and export defineWorkflowTool() as the default export of a static tool module.`)}else if(a!==void 0)throw Error(`${r} Workflow executors require defineWorkflowTool() from "eve/tools". Replace defineTool() or the bare tool object with defineWorkflowTool().`);expectOnlyKnownKeys(i,[`auth`,`description`,`execute`,`execution`,`inputSchema`,`approval`,`outputSchema`,`toModelOutput`],r);let o=i.inputSchema===void 0?null:serializeInputSchema(i.inputSchema),s=serializeOutputSchema(i.outputSchema),c=readToolBehavior(n),l=i.execute!==void 0;!l&&c?.handling?.kind!==`dispatch`&&c?.handling?.kind!==`request-input`&&expectFunction(i.execute,r);let u={description:expectString(i.description,r),hasApproval:i.approval!==void 0,hasExecute:l,hasModelOutputProjection:i.toModelOutput!==void 0,inputSchema:o};if(c!==void 0&&(u.behavior=c),l&&(u.execute=expectFunction(i.execute,r)),i.execution!==void 0){if(!l)throw Error(`${r} Execute-less native tools cannot use background execution.`);let e=expectString(i.execution,r);if(e!==`background`)throw Error(`${r} Expected "execution" to be "background".`);u.execution=e}return s!==void 0&&(u.outputSchema=s),i.approval!==void 0&&normalizeApproval(i.approval,r),i.toModelOutput!==void 0&&expectFunction(i.toModelOutput,r),i.auth!==void 0&&expectFunction(expectObjectRecord(i.auth,r).getToken,r),{kind:`tool`,definition:u}}export{normalizeToolDefinition};
@@ -1 +1 @@
1
- import{INTERNAL_CHANNEL_DELIVER}from"#channel/channel-operations.js";import{parseJsonValue}from"#shared/json.js";import{getRun,getWorld}from"#internal/workflow/runtime.js";import{RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{INVOCATION_OWNER_ATTRIBUTE,INVOCATION_TOKEN_ATTRIBUTE,invocationInputRequestId,invocationOwnerKey}from"#internal/invocation/metadata.js";var WorkflowAgentInvocationExecution=class{#e;#t;constructor(e){this.#e=e.createSession,this.#t=e.from}async create(e){let t=`invocation:${crypto.randomUUID()}`,n=await this.#e({auth:e.auth,capabilities:{requestInput:!0},continuationToken:t,externalInvocation:{continuationToken:t,ownerKey:invocationOwnerKey(e.auth)},input:{message:e.message,outputSchema:e.outputSchema},mode:`task`}),r=await this.#n(n.sessionId,e.auth);if(r===void 0)throw Error(`Invocation run was unavailable after durable creation.`);return workingInvocation(n.sessionId,r.createdAt.toISOString(),r.expiredAt?.toISOString())}async read(e){let t=await this.#n(e.invocationId,e.auth);if(t===void 0)return;if(isTerminalRunStatus(t.status))return await terminalInvocation(t,t.status===`failed`?await readRecentPersistedEvents(e.invocationId):[]);let n=await readRecentPersistedEvents(e.invocationId);return projectNonterminal(t.runId,t.createdAt.toISOString(),t.expiredAt?.toISOString(),n)}async update(t){let n=await this.read(t);if(n===void 0)return{type:`not_found`};if(n.status!==`input_required`)return conflict(`Invocation is not waiting for input.`);let r=await this.#n(t.invocationId,t.auth);if(r===void 0)return{type:`not_found`};let a=latestPendingInputBatch(await readRecentPersistedEvents(t.invocationId));if(a===void 0)return conflict(`Invocation input changed before the update could be applied.`);let o=new Set,s=[];for(let e of t.responses){let t=a.rawRequestIds[e.requestId];if(t===void 0)return conflict(`Unknown input request: ${e.requestId}`);o.add(e.requestId),s.push({...e,requestId:t})}if(o.size!==t.responses.length||o.size!==Object.keys(a.requests).length)return conflict(`Responses must answer the complete pending input batch exactly once.`);let l=r.attributes[INVOCATION_TOKEN_ATTRIBUTE];if(l===void 0)return{type:`not_found`};try{await this.#t(l)[INTERNAL_CHANNEL_DELIVER]({inputResponses:s},{auth:t.auth})}catch(e){if(RunExpiredError.is(e))return{type:`not_found`};throw e}return{invocation:workingInvocation(t.invocationId,n.createdAt,n.expiresAt),type:`success`}}async cancel(e){let t=await this.read(e);if(t===void 0||isTerminal(t.status))return t;try{await getRun(e.invocationId).cancel()}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}return await this.read(e)}async#n(e,t){let n=await getWorld();try{let r=await n.runs.get(e);return r.attributes[INVOCATION_TOKEN_ATTRIBUTE]===void 0?void 0:r.attributes[INVOCATION_OWNER_ATTRIBUTE]===invocationOwnerKey(t)?r:void 0}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}}};async function readRecentPersistedEvents(e){let t=getRun(e).getReadable({startIndex:-64}),r=await t.getTailIndex();if(r<0)return await t.cancel(`invocation event stream is empty`).catch(()=>{}),[];let i=Math.min(r+1,64),a=parseNdjsonStream(()=>t).getReader(),s=[];try{for(;s.length<i;){let{done:e,value:t}=await a.read();if(e)break;s.push(t)}}finally{await a.cancel(`invocation event window read complete`).catch(()=>{}),a.releaseLock()}return s}function pendingInputBatch(e){let t={},n={};for(let r of e.data.requests){let i=invocationInputRequestId(e.meta.id,r.requestId);t[i]=r.requestId,n[i]={...r,requestId:i}}return{id:e.meta.id,rawRequestIds:t,requests:n}}function latestPendingInputBatch(e){let t;for(let n of e)n.type===`input.requested`?t=pendingInputBatch(n):n.type===`turn.started`&&(t=void 0);return t}function projectNonterminal(e,t,n,r){let i=new Map,a,o;for(let e of r)if(e.type===`input.requested`)a=pendingInputBatch(e);else if(e.type===`turn.started`)i.clear(),a=void 0,o=void 0;else if(e.type===`authorization.required`){let t={description:e.data.description,name:e.data.name};e.data.authorization!==void 0&&(t.authorization=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),i.set(e.data.name,t)}else e.type===`authorization.completed`?i.delete(e.data.name):e.type===`message.completed`&&e.data.finishReason!==`tool-calls`&&e.data.message!==null&&(o=safeJson(e.data.message));let s=[...i.values()],c={createdAt:t,expiresAt:n,invocationId:e,result:o};return s.length>0?{...c,authorizations:s,pollAfterMs:1e3,status:`authorization_required`}:a===void 0?{...c,pollAfterMs:1e3,status:`working`}:{...c,inputRequests:a.requests,status:`input_required`}}async function terminalInvocation(e,t){let r={createdAt:e.createdAt.toISOString(),expiresAt:e.expiredAt?.toISOString(),invocationId:e.runId};if(e.status===`cancelled`)return{...r,status:`cancelled`};if(e.status===`failed`)return{...r,error:publicInvocationFailure(e.runId,t),status:`failed`};let i=await getRun(e.runId).returnValue;return{...r,result:safeJson(i.output),status:`completed`}}function workingInvocation(e,t,n){return{createdAt:t,expiresAt:n,invocationId:e,pollAfterMs:1e3,status:`working`}}function safeJson(e){try{return parseJsonValue(e)}catch{return String(e)}}function publicInvocationFailure(e,t){let n=[...t].reverse().find(e=>e.type===`session.failed`),r={runId:e};n!==void 0&&(r.eveCode=n.data.code);let i=vercelDeploymentId();i!==void 0&&(r.vercelDeploymentId=i),typeof n?.data.details?.errorId==`string`&&(r.errorId=n.data.details.errorId);let a=n===void 0?null:semanticFailure(n.data);if(a===null){let e=n===void 0?null:fallbackFailure(n.data);return e===null?{code:-32603,data:r,message:`Invocation failed.`}:(e.name!==void 0&&(r.name=e.name),{code:-32603,data:r,message:e.message})}return r.semanticErrorId=a.id,r.name=a.name,a.hint!==void 0&&(r.hint=a.hint),{code:-32603,data:r,message:a.message}}function semanticFailure(e){let t=e.details;if(typeof t?.semanticErrorId!=`string`||t.semanticErrorId.trim().length===0||typeof t.name!=`string`||t.name.trim().length===0)return null;let n=typeof t.message==`string`&&t.message.trim().length>0?t.message.trim():e.message.trim();if(n.length===0)return null;let r=typeof t.hint==`string`&&t.hint.trim().length>0?t.hint.trim():void 0,i={id:t.semanticErrorId,message:n,name:t.name};return r!==void 0&&(i.hint=r),i}function fallbackFailure(e){let t=e.message.trim(),n=typeof e.details?.name==`string`?e.details.name.trim():``;if(t.length===0&&n.length===0)return null;let r={message:t.length===0?n:truncateForDisplay(t)};return n.length>0&&(r.name=n),r}function truncateForDisplay(e,t=160){return e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`}function vercelDeploymentId(){if(process.env.VERCEL!==`1`)return;let e=process.env.VERCEL_DEPLOYMENT_ID?.trim();return e&&e.length>0?e:void 0}function conflict(e){return{message:e,type:`conflict`}}function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}function isTerminalRunStatus(e){return e===`completed`||e===`failed`||e===`cancelled`}export{WorkflowAgentInvocationExecution};
1
+ import{INTERNAL_CHANNEL_DELIVER}from"#channel/channel-operations.js";import{parseJsonValue}from"#shared/json.js";import{getRun,getWorld}from"#internal/workflow/runtime.js";import{RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{INVOCATION_OWNER_ATTRIBUTE,INVOCATION_TOKEN_ATTRIBUTE,invocationInputRequestId,invocationOwnerKey}from"#internal/invocation/metadata.js";var WorkflowAgentInvocationExecution=class{#e;#t;constructor(e){this.#e=e.createSession,this.#t=e.from}async create(e){let t=`invocation:${crypto.randomUUID()}`,n=await this.#e({auth:e.auth,capabilities:{requestInput:!0},continuationToken:t,externalInvocation:{continuationToken:t,ownerKey:invocationOwnerKey(e.auth)},input:{message:e.message,outputSchema:e.outputSchema},mode:`task`}),r=await this.#n(n.sessionId,e.auth);if(r===void 0)throw Error(`Invocation run was unavailable after durable creation.`);return workingInvocation(n.sessionId,r.createdAt.toISOString(),r.expiredAt?.toISOString())}async read(e){let t=await this.#n(e.invocationId,e.auth);if(t===void 0)return;if(isTerminalRunStatus(t.status))return await terminalInvocation(t,t.status===`failed`?await readRecentPersistedEvents(e.invocationId):[]);let n=await readRecentPersistedEvents(e.invocationId);return projectNonterminal(t.runId,t.createdAt.toISOString(),t.expiredAt?.toISOString(),n)}async update(t){let n=await this.read(t);if(n===void 0)return{type:`not_found`};if(n.status!==`input_required`)return replaysResolvedBatch(await readRecentPersistedEvents(t.invocationId),t.responses)?{invocation:n,type:`success`}:conflict(`Invocation is not waiting for input.`);let r=await this.#n(t.invocationId,t.auth);if(r===void 0)return{type:`not_found`};let a=latestPendingInputBatch(await readRecentPersistedEvents(t.invocationId));if(a===void 0)return conflict(`Invocation input changed before the update could be applied.`);let o=new Set,s=[];for(let e of t.responses){let t=a.rawRequestIds[e.requestId];if(t===void 0)return conflict(`Unknown input request: ${e.requestId}`);o.add(e.requestId),s.push({...e,requestId:t})}if(o.size!==t.responses.length||o.size!==Object.keys(a.requests).length)return conflict(`Responses must answer the complete pending input batch exactly once.`);let l=r.attributes[INVOCATION_TOKEN_ATTRIBUTE];if(l===void 0)return{type:`not_found`};try{await this.#t(l)[INTERNAL_CHANNEL_DELIVER]({inputResponses:s},{auth:t.auth})}catch(e){if(RunExpiredError.is(e))return{type:`not_found`};throw e}return{invocation:workingInvocation(t.invocationId,n.createdAt,n.expiresAt),type:`success`}}async cancel(e){let t=await this.read(e);if(t===void 0||isTerminal(t.status))return t;try{await getRun(e.invocationId).cancel()}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}return await this.read(e)}async#n(e,t){let n=await getWorld();try{let r=await n.runs.get(e);return r.attributes[INVOCATION_TOKEN_ATTRIBUTE]===void 0?void 0:r.attributes[INVOCATION_OWNER_ATTRIBUTE]===invocationOwnerKey(t)?r:void 0}catch(e){if(WorkflowRunNotFoundError.is(e)||RunExpiredError.is(e))return;throw e}}};async function readRecentPersistedEvents(e){let t=getRun(e).getReadable({startIndex:-64}),r=await t.getTailIndex();if(r<0)return await t.cancel(`invocation event stream is empty`).catch(()=>{}),[];let i=Math.min(r+1,64),a=parseNdjsonStream(()=>t).getReader(),s=[];try{for(;s.length<i;){let{done:e,value:t}=await a.read();if(e)break;s.push(t)}}finally{await a.cancel(`invocation event window read complete`).catch(()=>{}),a.releaseLock()}return s}function pendingInputBatch(e){let t={},n={};for(let r of e.data.requests){let i=invocationInputRequestId(e.meta.id,r.requestId);t[i]=r.requestId,n[i]={...r,requestId:i}}return{id:e.meta.id,rawRequestIds:t,requests:n}}function withoutResolved(e,t){let n=new Set(t.map(e=>e.requestId)),r={},i={};for(let[t,a]of Object.entries(e.rawRequestIds)){if(n.has(a))continue;r[t]=a;let o=e.requests[t];o!==void 0&&(i[t]=o)}return Object.keys(r).length===0?void 0:{id:e.id,rawRequestIds:r,requests:i}}function foldInputBatches(e){let t,n,r;for(let i of e)if(i.type===`input.requested`)n=pendingInputBatch(i),t=n;else if(i.type===`input.resolved`){if(n===void 0)continue;let e=new Map;for(let t of i.data.resolutions)e.set(t.requestId,t.response);r={batch:n,responses:e},t!==void 0&&(t=withoutResolved(t,i.data.resolutions))}else i.type===`turn.started`&&(t=void 0);return{pending:t,resolved:r}}function latestPendingInputBatch(e){return foldInputBatches(e).pending}function replaysResolvedBatch(e,t){let n=foldInputBatches(e).resolved;if(n===void 0||t.length!==n.responses.size)return!1;let r=new Set;for(let e of t){let t=n.batch.rawRequestIds[e.requestId];if(t===void 0||r.has(t)||(r.add(t),!n.responses.has(t)))return!1;let i=n.responses.get(t);if(i?.optionId!==e.optionId||i?.text!==e.text)return!1}return!0}function projectNonterminal(e,t,n,r){let i=new Map,a,o;for(let e of r)if(e.type===`input.requested`)a=pendingInputBatch(e);else if(e.type===`input.resolved`)a!==void 0&&(a=withoutResolved(a,e.data.resolutions));else if(e.type===`turn.started`)i.clear(),a=void 0,o=void 0;else if(e.type===`authorization.required`){let t={description:e.data.description,name:e.data.name};e.data.authorization!==void 0&&(t.authorization=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),i.set(e.data.name,t)}else e.type===`authorization.completed`?i.delete(e.data.name):e.type===`message.completed`&&e.data.finishReason!==`tool-calls`&&e.data.message!==null&&(o=safeJson(e.data.message));let s=[...i.values()],c={createdAt:t,expiresAt:n,invocationId:e,result:o};return s.length>0?{...c,authorizations:s,pollAfterMs:1e3,status:`authorization_required`}:a===void 0?{...c,pollAfterMs:1e3,status:`working`}:{...c,inputRequests:a.requests,status:`input_required`}}async function terminalInvocation(e,t){let r={createdAt:e.createdAt.toISOString(),expiresAt:e.expiredAt?.toISOString(),invocationId:e.runId};if(e.status===`cancelled`)return{...r,status:`cancelled`};if(e.status===`failed`)return{...r,error:publicInvocationFailure(e.runId,t),status:`failed`};let i=await getRun(e.runId).returnValue;return{...r,result:safeJson(i.output),status:`completed`}}function workingInvocation(e,t,n){return{createdAt:t,expiresAt:n,invocationId:e,pollAfterMs:1e3,status:`working`}}function safeJson(e){try{return parseJsonValue(e)}catch{return String(e)}}function publicInvocationFailure(e,t){let n=[...t].reverse().find(e=>e.type===`session.failed`),r={runId:e};n!==void 0&&(r.eveCode=n.data.code);let i=vercelDeploymentId();i!==void 0&&(r.vercelDeploymentId=i),typeof n?.data.details?.errorId==`string`&&(r.errorId=n.data.details.errorId);let a=n===void 0?null:semanticFailure(n.data);if(a===null){let e=n===void 0?null:fallbackFailure(n.data);return e===null?{code:-32603,data:r,message:`Invocation failed.`}:(e.name!==void 0&&(r.name=e.name),{code:-32603,data:r,message:e.message})}return r.semanticErrorId=a.id,r.name=a.name,a.hint!==void 0&&(r.hint=a.hint),{code:-32603,data:r,message:a.message}}function semanticFailure(e){let t=e.details;if(typeof t?.semanticErrorId!=`string`||t.semanticErrorId.trim().length===0||typeof t.name!=`string`||t.name.trim().length===0)return null;let n=typeof t.message==`string`&&t.message.trim().length>0?t.message.trim():e.message.trim();if(n.length===0)return null;let r=typeof t.hint==`string`&&t.hint.trim().length>0?t.hint.trim():void 0,i={id:t.semanticErrorId,message:n,name:t.name};return r!==void 0&&(i.hint=r),i}function fallbackFailure(e){let t=e.message.trim(),n=typeof e.details?.name==`string`?e.details.name.trim():``;if(t.length===0&&n.length===0)return null;let r={message:t.length===0?n:truncateForDisplay(t)};return n.length>0&&(r.name=n),r}function truncateForDisplay(e,t=160){return e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`}function vercelDeploymentId(){if(process.env.VERCEL!==`1`)return;let e=process.env.VERCEL_DEPLOYMENT_ID?.trim();return e&&e.length>0?e:void 0}function conflict(e){return{message:e,type:`conflict`}}function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}function isTerminalRunStatus(e){return e===`completed`||e===`failed`||e===`cancelled`}export{WorkflowAgentInvocationExecution};
@@ -2,6 +2,11 @@ import { McpServer, type McpToolAnnotations, type StandardSchemaWithJSON } from
2
2
  import type { SessionAuthContext } from "#channel/types.js";
3
3
  export declare const MCP_PROTOCOL_VERSION = "2026-07-28";
4
4
  export declare const MCP_LEGACY_PROTOCOL_VERSION = "2025-11-25";
5
+ /**
6
+ * Upper bound for any MCP POST body. Tool arguments are small JSON; the
7
+ * largest legitimate payload is an `outputSchema`, itself capped at 64 KiB.
8
+ */
9
+ export declare const MCP_REQUEST_BODY_MAX_BYTES: number;
5
10
  export interface McpToolDefinition<TInputSchema extends StandardSchemaWithJSON = StandardSchemaWithJSON> {
6
11
  readonly name: string;
7
12
  readonly description?: string;
@@ -12,7 +17,10 @@ export interface McpToolDefinition<TInputSchema extends StandardSchemaWithJSON =
12
17
  export interface McpCallToolResult<TStructured extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>> {
13
18
  readonly content: readonly McpContent[];
14
19
  readonly isError?: boolean;
15
- readonly structuredContent?: TStructured;
20
+ readonly structuredContent?: TStructured | McpToolOperationErrorEnvelope;
21
+ }
22
+ export interface McpToolOperationErrorEnvelope {
23
+ readonly error: McpToolOperationErrorData;
16
24
  }
17
25
  export type McpContent = {
18
26
  readonly type: "text";
@@ -22,6 +30,24 @@ export type McpContent = {
22
30
  readonly name: string;
23
31
  readonly uri: string;
24
32
  };
33
+ /**
34
+ * Stable, client-actionable reason a tool call was rejected before it could
35
+ * return a result. `invalid_input` and `conflict` mean the caller should
36
+ * change or re-read something; `not_found` means stop; `internal` means the
37
+ * server failed and `errorId` correlates with its logs.
38
+ */
39
+ export type McpToolOperationErrorCode = "invalid_input" | "not_found" | "conflict" | "internal";
40
+ export interface McpToolOperationErrorData {
41
+ readonly code: McpToolOperationErrorCode;
42
+ readonly errorId?: string;
43
+ readonly message: string;
44
+ readonly retryable: boolean;
45
+ }
46
+ /** Thrown by tool handlers to produce a structured `isError` result. */
47
+ export declare class McpToolOperationError extends Error {
48
+ readonly code: McpToolOperationErrorCode;
49
+ constructor(code: McpToolOperationErrorCode, message: string);
50
+ }
25
51
  export interface McpServerTool {
26
52
  readonly name: string;
27
53
  register(server: McpServer, auth: SessionAuthContext | null): void;
@@ -38,6 +64,8 @@ export declare function defineMcpTool<const TInputSchema extends StandardSchemaW
38
64
  export interface McpStreamableHttpServerOptions {
39
65
  readonly name: string;
40
66
  readonly version: string;
67
+ /** Server-level usage guidance returned from `initialize` and `server/discover`. */
68
+ readonly instructions?: string;
41
69
  readonly tools: readonly McpServerTool[];
42
70
  authenticate(request: Request): Promise<SessionAuthContext | null | Response>;
43
71
  }
@@ -1 +1 @@
1
- import{McpServer,createMcpHandler}from"#compiled/@modelcontextprotocol/server/index.js";const MCP_PROTOCOL_VERSION=`2026-07-28`,MCP_LEGACY_PROTOCOL_VERSION=`2025-11-25`;function defineMcpTool(e){return{name:e.definition.name,register(t,n){t.registerTool(e.definition.name,{...e.definition.annotations===void 0?{}:{annotations:e.definition.annotations},...e.definition.description===void 0?{}:{description:e.definition.description},inputSchema:e.definition.inputSchema,...e.definition.outputSchema===void 0?{}:{outputSchema:e.definition.outputSchema}},async(t,r)=>await callTool(e.call,t,r.mcpReq.signal,n))}}}function createMcpStreamableHttpServer(e){let n=new Map(e.tools.map(e=>[e.name,e]));if(n.size!==e.tools.length)throw Error(`MCP tool names must be unique.`);return async r=>{let i=await e.authenticate(r);if(i instanceof Response)return i;let a=await preflightModernRequest(r);return a.response===void 0?await createMcpHandler(()=>createServer(e,n,i),{legacy:`stateless`}).fetch(r,a.parsedBody===void 0?void 0:{parsedBody:a.parsedBody}):a.response}}async function preflightModernRequest(e){if(e.method.toUpperCase()!==`POST`||e.headers.has(`mcp-protocol-version`))return{};let t=await inspectRequestBody(e);if(t.tooLarge)return{response:requestBodyTooLargeResponse()};if(t.invalidJson)return{response:invalidJsonResponse()};let n=t.value;if(n===void 0)return{};if(!claimsCurrentProtocolVersion(n))return{parsedBody:n};let r=await probeEarlierValidationFailure(e,n);return r===void 0?{parsedBody:n,response:headerMismatchResponse(n)}:{parsedBody:n,response:r}}async function inspectRequestBody(e){let t=e.body;if(t===null)return{tooLarge:!1};let n=t.getReader(),r=[],i=0;try{for(;;){let e=await n.read();if(e.done)break;if(i+=e.value.byteLength,i>4194304)return await n.cancel(),{tooLarge:!0};r.push(e.value)}let e=new Uint8Array(i),t=0;for(let n of r)e.set(n,t),t+=n.byteLength;return{tooLarge:!1,value:JSON.parse(new TextDecoder().decode(e))}}catch{return{invalidJson:!0,tooLarge:!1}}}function invalidJsonResponse(){return Response.json({error:{code:-32700,message:`Parse error`},id:null,jsonrpc:`2.0`},{status:400})}function requestBodyTooLargeResponse(){return Response.json({error:{code:-32e3,message:`Request body too large`},id:null,jsonrpc:`2.0`},{status:413,statusText:`Request Entity Too Large`})}function claimsCurrentProtocolVersion(e){return isPlainRecord(e)&&isPlainRecord(e.params)&&isPlainRecord(e.params._meta)&&e.params._meta[`io.modelcontextprotocol/protocolVersion`]===`2026-07-28`}function isPlainRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function probeEarlierValidationFailure(r,i){let a=new Headers(r.headers);a.set(`mcp-protocol-version`,MCP_PROTOCOL_VERSION);let o=new Request(r.url,{body:JSON.stringify(i),headers:a,method:r.method}),s=createMcpHandler(()=>new McpServer({name:`eve-mcp-preflight`,version:`0`}),{legacy:`reject`});try{let e=await s.fetch(o,{parsedBody:i});if(e.status===406||e.status===415)return e;if(e.status===400){let t=await e.clone().json().catch(()=>void 0);if(t?.error?.code===-32700||t?.error?.code===-32600||t?.error?.code===-32602||t?.error?.code===-32022)return e}await e.body?.cancel();return}finally{await s.close().catch(()=>{})}}function headerMismatchResponse(e){let t=`the body carries a modern MCP envelope but the required MCP-Protocol-Version header is absent`;return Response.json({error:{code:-32020,data:{mismatch:{body:t,header:`(missing)`}},message:`Bad Request: the request headers and body disagree: ${t}`},id:readJsonRpcRequestId(e),jsonrpc:`2.0`},{status:400})}function readJsonRpcRequestId(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`id`);return typeof t==`string`||typeof t==`number`?t:null}function createServer(t,n,r){let i=new McpServer({name:t.name,version:t.version},{capabilities:{tools:{listChanged:!1}}});for(let e of n.values())e.register(i,r);return i}async function callTool(e,t,n,r){try{return await e(t,{auth:r,signal:n})}catch(e){return toolError(e instanceof Error?e.message:`Tool call failed.`)}}function toolError(e){return{content:[{type:`text`,text:e}],isError:!0}}export{MCP_LEGACY_PROTOCOL_VERSION,MCP_PROTOCOL_VERSION,createMcpStreamableHttpServer,defineMcpTool};
1
+ import{createLogger,logError}from"#internal/logging.js";import{McpServer,createMcpHandler}from"#compiled/@modelcontextprotocol/server/index.js";const log=createLogger(`mcp.server`),MCP_PROTOCOL_VERSION=`2026-07-28`,MCP_LEGACY_PROTOCOL_VERSION=`2025-11-25`,MCP_REQUEST_BODY_MAX_BYTES=1024*1024;var McpToolOperationError=class extends Error{code;constructor(e,t){super(t),this.name=`McpToolOperationError`,this.code=e}};const RETRYABLE_CODES=new Set([`conflict`]);function defineMcpTool(e){return{name:e.definition.name,register(t,n){t.registerTool(e.definition.name,{...e.definition.annotations===void 0?{}:{annotations:e.definition.annotations},...e.definition.description===void 0?{}:{description:e.definition.description},inputSchema:e.definition.inputSchema,...e.definition.outputSchema===void 0?{}:{outputSchema:e.definition.outputSchema}},async(t,r)=>await callTool(e.call,t,r.mcpReq.signal,n))}}}function createMcpStreamableHttpServer(e){let t=new Map(e.tools.map(e=>[e.name,e]));if(t.size!==e.tools.length)throw Error(`MCP tool names must be unique.`);return async n=>{let i=await e.authenticate(n);if(i instanceof Response)return i;let a=createMcpHandler(()=>createServer(e,t,i),{legacy:`stateless`});if(n.method.toUpperCase()!==`POST`)return await a.fetch(n);let o=await inspectRequestBody(n);if(o.tooLarge)return requestBodyTooLargeResponse();if(o.invalidJson)return invalidJsonResponse();let s=o.value;if(s===void 0)return await a.fetch(n);let c=await preflightModernRequest(n,s);return c===void 0?await a.fetch(n,{parsedBody:s}):c}}async function preflightModernRequest(e,t){return e.headers.has(`mcp-protocol-version`)||!claimsCurrentProtocolVersion(t)?void 0:await probeEarlierValidationFailure(e,t)??headerMismatchResponse(t)}async function inspectRequestBody(e){let t=e.body;if(t===null)return{tooLarge:!1};let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>1048576)return await t.cancel().catch(()=>{}),{tooLarge:!0};let r=t.getReader(),i=[],a=0;try{for(;;){let e=await r.read();if(e.done)break;if(a+=e.value.byteLength,a>1048576)return await r.cancel(),{tooLarge:!0};i.push(e.value)}let e=new Uint8Array(a),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;return{tooLarge:!1,value:JSON.parse(new TextDecoder().decode(e))}}catch{return{invalidJson:!0,tooLarge:!1}}}function invalidJsonResponse(){return Response.json({error:{code:-32700,message:`Parse error`},id:null,jsonrpc:`2.0`},{status:400})}function requestBodyTooLargeResponse(){return Response.json({error:{code:-32e3,message:`Request body too large`},id:null,jsonrpc:`2.0`},{status:413,statusText:`Request Entity Too Large`})}function claimsCurrentProtocolVersion(e){return isPlainRecord(e)&&isPlainRecord(e.params)&&isPlainRecord(e.params._meta)&&e.params._meta[`io.modelcontextprotocol/protocolVersion`]===`2026-07-28`}function isPlainRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function probeEarlierValidationFailure(e,t){let i=new Headers(e.headers);i.set(`mcp-protocol-version`,MCP_PROTOCOL_VERSION);let o=new Request(e.url,{body:JSON.stringify(t),headers:i,method:e.method}),s=createMcpHandler(()=>new McpServer({name:`eve-mcp-preflight`,version:`0`}),{legacy:`reject`});try{let e=await s.fetch(o,{parsedBody:t});if(e.status===406||e.status===415)return e;if(e.status===400){let t=await e.clone().json().catch(()=>void 0);if(t?.error?.code===-32700||t?.error?.code===-32600||t?.error?.code===-32602||t?.error?.code===-32022)return e}await e.body?.cancel();return}finally{await s.close().catch(()=>{})}}function headerMismatchResponse(e){let t=`the body carries a modern MCP envelope but the required MCP-Protocol-Version header is absent`;return Response.json({error:{code:-32020,data:{mismatch:{body:t,header:`(missing)`}},message:`Bad Request: the request headers and body disagree: ${t}`},id:readJsonRpcRequestId(e),jsonrpc:`2.0`},{status:400})}function readJsonRpcRequestId(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`id`);return typeof t==`string`||typeof t==`number`?t:null}function createServer(e,t,r){let i={capabilities:{tools:{listChanged:!1}}};e.instructions!==void 0&&(i.instructions=e.instructions);let a=new McpServer({name:e.name,version:e.version},i);for(let e of t.values())e.register(a,r);return a}async function callTool(e,n,r,a){try{return await e(n,{auth:a,signal:r})}catch(e){return e instanceof McpToolOperationError?toolError({code:e.code,message:e.message,retryable:RETRYABLE_CODES.has(e.code)}):toolError({code:`internal`,errorId:logError(log,`MCP tool call failed`,e),message:`The server could not complete this tool call.`,retryable:!1})}}function toolError(e){return{content:[{type:`text`,text:e.errorId===void 0?e.message:`${e.message} (errorId: ${e.errorId})`}],isError:!0,structuredContent:{error:e}}}export{MCP_LEGACY_PROTOCOL_VERSION,MCP_PROTOCOL_VERSION,MCP_REQUEST_BODY_MAX_BYTES,McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool};
@@ -1 +1 @@
1
- import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{resolveDiscoveryProject}from"#discover/project.js";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{isObject}from"#shared/guards.js";import{toErrorMessage}from"#shared/errors.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{materializeVercelWorkflowFunctionOutput,normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{normalizeVercelServiceCrons}from"#internal/nitro/host/normalize-vercel-service-crons.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";import{resolveEveServicePrefixByRoot}from"#internal/vercel/vercel-service-config-operations.js";import{parseVercelServicesConfig}from"#internal/vercel/vercel-services-config.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let r=relative(e,t);return r.length===0||!r.startsWith(`..${sep}`)&&r!==`..`&&!isAbsolute(r)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}async function resolveEveServicePrefixForVercelFunctionOutput(n,i){let o=Array.from(new Set([resolve(n),resolve(i)])),s=await findClosestVercelOutputDirectory(n);if(s!==void 0)try{let t=join(s,`config.json`),n=parseVercelServicesConfig(JSON.parse(await readFile(t,`utf8`)),t),i=resolveEveServicePrefixByRoot({appRoots:o,configRoot:await resolveVercelOutputConfigRoot(s),config:n});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=n;for(;;){for(let n of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let r=parseVercelServicesConfig(JSON.parse(await readFile(n,`utf8`)),n),i=resolveEveServicePrefixByRoot({appRoots:o,configRoot:n.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(n)),config:r});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let n=dirname(c);if(n===c)return;c=n}}async function resolveVercelOutputConfigRoot(n){let i=dirname(dirname(n));try{let t=JSON.parse(await readFile(join(i,`.vercel`,`project.json`),`utf8`));if(isObject(t)&&isObject(t.settings)){let e=t.settings.rootDirectory;if(typeof e==`string`&&e.trim().length>0)return resolve(i,e)}}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return i}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let o=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),c=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(o.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),u=!1,d;try{d=await buildApplicationInWorkspace(c,t,r)}catch(e){throw u=e instanceof RecoverablePublicationError,e}finally{u||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(c))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({outputDirectory:d,profileOutputPath:n,profiler:r}),d}async function buildApplicationInWorkspace(e,t,n){let r=await measureBuildPhase(n,`host.prepare`,()=>prepareProductionApplicationHost(e)),i=!!process.env.VERCEL,a=i?await measureBuildPhase(n,`vercel.service-prefix.resolve`,()=>resolveEveServicePrefixForVercelFunctionOutput(r.appRoot,r.compileResult.project.agentRoot)):void 0;if(t.publicRoutePrefix!==void 0&&a!==void 0&&t.publicRoutePrefix!==a)throw Error(`EVE_PUBLIC_ROUTE_PREFIX ${JSON.stringify(t.publicRoutePrefix)} conflicts with the configured Vercel service prefix ${JSON.stringify(a)}.`);let o=t.publicRoutePrefix??a,s=await measureBuildPhase(n,`nitro.create`,()=>createProductionApplicationNitro(r,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,publicRoutePrefix:o,workspaceMember:t.workspaceMember}));try{i&&!t.skipVercelSandboxPrewarm&&await measureBuildPhase(n,`sandbox.prewarm`,()=>runVercelBuildPrewarm({appRoot:r.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:r.appRoot}),log(e){console.log(e)}})),await buildNitroOutput(s,n,`nitro`),i&&await measureBuildPhase(n,`vercel.workflow-function.materialize`,()=>materializeVercelWorkflowFunctionOutput(e.publication.output.stagedDir)),a!==void 0&&await measureBuildPhase(n,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}));let l=t.vercelServiceOutput;l!==void 0&&(await measureBuildPhase(n,`vercel.service-crons.normalize`,()=>normalizeVercelServiceCrons({publicRoutePrefix:o,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(n,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:l.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}))),await measureBuildPhase(n,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:r.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),i||await measureBuildPhase(n,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(n,`nitro.close`,()=>s.close())}return await measureBuildPhase(n,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
1
+ import{readFile}from"node:fs/promises";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{resolveDiscoveryProject}from"#discover/project.js";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{isObject}from"#shared/guards.js";import{toErrorMessage}from"#shared/errors.js";import{createDiskRuntimeCompiledArtifactsSource}from"#runtime/compiled-artifacts-source.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createApplicationBuildWorkspace,removeApplicationBuildWorkspace}from"#internal/application/build-workspace.js";import{ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile}from"#internal/application/build-profile.js";import{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{materializeVercelWorkflowFunctionOutput,normalizeEveVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createProductionApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{copyHostMiddlewareFunctions}from"#internal/nitro/host/copy-host-middleware.js";import{normalizeVercelServiceCrons}from"#internal/nitro/host/normalize-vercel-service-crons.js";import{prepareProductionApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";import{resolveEveServicePrefixByRoot}from"#internal/vercel/vercel-service-config-operations.js";import{parseVercelServicesConfig}from"#internal/vercel/vercel-services-config.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}async function measureBuildPhase(e,t,n){return e===void 0?n():e.measure(t,n)}function isPathInside(e,t){let n=relative(e,t);return n.length===0||!n.startsWith(`..${sep}`)&&n!==`..`&&!isAbsolute(n)}function assertProfileOutputOutsideBuildOutput(e,t){if(e!==void 0&&isPathInside(t,e))throw Error(`Build profile path ${e} must be outside the published output directory ${t}.`)}async function writeOptionalApplicationBuildProfile(e){try{assertProfileOutputOutsideBuildOutput(e.profileOutputPath,e.outputDirectory);let t=e.profiler.finish(),n=await measureApplicationBuildOutput(e.outputDirectory);await writeApplicationBuildProfile(e.profileOutputPath,createApplicationBuildProfile({output:n,target:process.env.VERCEL?`vercel`:`local`,timing:t}))}catch(t){console.warn(`eve: failed to write optional build profile to ${e.profileOutputPath}; continuing with the published build output: ${toErrorMessage(t)}`)}}async function resolveEveServicePrefixForVercelFunctionOutput(t,r){let a=Array.from(new Set([resolve(t),resolve(r)])),s=await findClosestVercelOutputDirectory(t);if(s!==void 0)try{let t=join(s,`config.json`),n=parseVercelServicesConfig(JSON.parse(await readFile(t,`utf8`)),t),r=resolveEveServicePrefixByRoot({appRoots:a,configRoot:await resolveVercelOutputConfigRoot(s),config:n});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=t;for(;;){for(let t of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let r=parseVercelServicesConfig(JSON.parse(await readFile(t,`utf8`)),t),i=resolveEveServicePrefixByRoot({appRoots:a,configRoot:t.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(t)),config:r});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=dirname(c);if(t===c)return;c=t}}async function resolveVercelOutputConfigRoot(t){let r=dirname(dirname(t));try{let t=JSON.parse(await readFile(join(r,`.vercel`,`project.json`),`utf8`));if(isObject(t)&&isObject(t.settings)){let e=t.settings.rootDirectory;if(typeof e==`string`&&e.trim().length>0)return resolve(r,e)}}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return r}async function buildNitroOutput(e,t,n){let r=trimTrailingSlash(e.options.output.dir);return await measureBuildPhase(t,`${n}.cache.prepare`,()=>prepareEveVersionedCacheDirectory(r)),await measureBuildPhase(t,`${n}.prepare`,()=>prepare(e)),await measureBuildPhase(t,`${n}.public-assets`,()=>copyPublicAssets(e)),await measureBuildPhase(t,`${n}.prerender`,()=>prerender(e)),await measureBuildPhase(t,`${n}.bundle`,()=>build(e)),await measureBuildPhase(t,`${n}.cache.write`,()=>writeEveVersionedCacheMetadata(r)),r}async function buildApplication(e,t){let n=t.profileOutputPath===void 0?void 0:resolve(t.profileOutputPath),r=n===void 0?void 0:new ApplicationBuildProfiler,i=await measureBuildPhase(r,`extension.check`,()=>tryReadExtensionBuildConfig(e));if(i!==null)throw Error(`Package "${i.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let a=await measureBuildPhase(r,`project.resolve`,()=>resolveDiscoveryProject(e)),s=await measureBuildPhase(r,`workspace.create`,()=>createApplicationBuildWorkspace(a.appRoot,t.vercelServiceOutput?.serviceOutputDirectory)),l=!1,u;try{u=await buildApplicationInWorkspace(s,t,r)}catch(e){throw l=e instanceof RecoverablePublicationError,e}finally{l||await measureBuildPhase(r,`workspace.remove`,()=>removeApplicationBuildWorkspace(s))}return r!==void 0&&n!==void 0&&await writeOptionalApplicationBuildProfile({outputDirectory:u,profileOutputPath:n,profiler:r}),u}async function buildApplicationInWorkspace(e,n,r){let i=await measureBuildPhase(r,`host.prepare`,()=>prepareProductionApplicationHost(e)),a=!!process.env.VERCEL,o=a?await measureBuildPhase(r,`vercel.service-prefix.resolve`,()=>resolveEveServicePrefixForVercelFunctionOutput(i.appRoot,i.compileResult.project.agentRoot)):void 0,s=normalizePublicRoutePrefix(o),c=s===EVE_ROUTE_PREFIX?void 0:s;if(n.publicRoutePrefix!==void 0&&c!==void 0&&n.publicRoutePrefix!==c)throw Error(`EVE_PUBLIC_ROUTE_PREFIX ${JSON.stringify(n.publicRoutePrefix)} conflicts with the configured Vercel service prefix ${JSON.stringify(o)}.`);let d=n.publicRoutePrefix??c,f=await measureBuildPhase(r,`nitro.create`,()=>createProductionApplicationNitro(i,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,publicRoutePrefix:d,workspaceMember:n.workspaceMember}));try{a&&!n.skipVercelSandboxPrewarm&&await measureBuildPhase(r,`sandbox.prewarm`,()=>runVercelBuildPrewarm({appRoot:i.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:i.appRoot}),log(e){console.log(e)}})),await buildNitroOutput(f,r,`nitro`),a&&await measureBuildPhase(r,`vercel.workflow-function.materialize`,()=>materializeVercelWorkflowFunctionOutput(e.publication.output.stagedDir)),o!==void 0&&await measureBuildPhase(r,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:o}));let t=n.vercelServiceOutput;t!==void 0&&(await measureBuildPhase(r,`vercel.service-crons.normalize`,()=>normalizeVercelServiceCrons({publicRoutePrefix:d,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(r,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:t.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}))),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),a||await measureBuildPhase(r,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(r,`nitro.close`,()=>f.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}async function publishCompletedApplicationBuild(e){await publishApplicationBuildArtifacts({appRoot:e.appRoot,finalOutputDir:e.publication.output.finalDir,finalSummaryPath:e.publication.summary.finalPath,scratchDir:e.rootDir,stagedOutputDir:e.publication.output.stagedDir,stagedSummaryPath:e.publication.summary.stagedPath})}export{buildApplication};
@@ -1,4 +1,10 @@
1
+ import type { Hook } from "#compiled/@workflow/world/index.js";
1
2
  export * from "#compiled/@workflow/core/runtime.js";
2
3
  export type { StartOptionsWithoutDeploymentId, WorkflowFunction, WorkflowMetadata, } from "#compiled/@workflow/core/runtime/start.js";
4
+ /**
5
+ * Reads a hook without decrypting metadata or resolving an encryption key.
6
+ * Metadata is excluded from the return type; use `getHookByToken` to read it.
7
+ */
8
+ export declare function getRawHookByToken(token: string): Promise<Omit<Hook, "metadata">>;
3
9
  /** Installs a World across source and vendored Workflow package identities. */
4
10
  export declare function setWorld(world: unknown): void;
@@ -1 +1 @@
1
- import*as workflowRuntime from"#compiled/@workflow/core/runtime.js";export*from"#compiled/@workflow/core/runtime.js";function setWorld(e){workflowRuntime.setWorld(e)}export{setWorld};
1
+ import*as workflowRuntime from"#compiled/@workflow/core/runtime.js";export*from"#compiled/@workflow/core/runtime.js";async function getRawHookByToken(e){return await(await workflowRuntime.getWorld()).hooks.getByToken(e)}function setWorld(e){workflowRuntime.setWorld(e)}export{getRawHookByToken,setWorld};
@@ -1,13 +1,11 @@
1
1
  export interface AuthoredWorkflowDirectiveSource {
2
- /** Name of the top-level `"use workflow"` function the default export's `execute` is or references. */
3
- readonly executeWorkflow?: string;
4
2
  readonly hasDirectives: boolean;
5
3
  readonly hasWorkflowDirective: boolean;
6
4
  readonly source: string;
7
5
  }
8
6
  /**
9
7
  * The directive transform understands one shape: a top-level `async function`
10
- * whose first statement is the directive. A tool's `execute` method is hoisted
8
+ * whose first statement is the directive. A marked `defineWorkflowTool` executor is hoisted
11
9
  * into that shape here; every other placement is a build error, because an
12
10
  * ignored directive would run side effects inline in a replayed body.
13
11
  */
@@ -1 +1 @@
1
- import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{detectWorkflowPatterns}from"#compiled/@workflow/builders/index.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const HOISTED_EXECUTE_NAME=`execute`;async function prepareAuthoredWorkflowDirectives(i){let a=await parseWithNitroRolldownAst(i.filePath,i.source),o=a.body??[];for(let e of o){if(typeof e.directive!=`string`)break;let t=readWorkflowDirective(e);if(t!==void 0)throw Error(`${JSON.stringify(t)} in "${i.filePath}" is a module-level directive. Put it as the first statement of the function it marks: a top-level "async function" declaration or, for "use workflow", the "execute" method of the module's default export.`)}let s=new Set;for(let e of o){let t=e.type===`FunctionDeclaration`?e:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`?e.declaration:void 0;t!==void 0&&s.add(t)}let c=findDefaultExportExecuteProperty(o),l=c!==void 0&&isAstNode(c.value)&&isFunctionLike(c.value)?c.value:void 0;l!==void 0&&s.add(l);let u=collectDirectiveFunctions(a);if(u.length===0)return{hasDirectives:!1,hasWorkflowDirective:!1,source:i.source};let d=u.some(e=>e.directive===`use workflow`),f=detectWorkflowPatterns(i.source).hasDirective;for(let e of u){if(!f)throw Error(`${JSON.stringify(e.directive)} in "${i.filePath}" is not on its own line. Write it as the first statement of the function body, on a line by itself.`);if(!s.has(e.fn))throw Error(`${JSON.stringify(e.directive)} in "${i.filePath}" marks ${describeFunction(e.fn)}. Workflow directives must mark a top-level "async function" declaration or, for "use workflow", the "execute" method of the module's default export.`);if(e.fn.async!==!0)throw Error(`${JSON.stringify(e.directive)} in "${i.filePath}" marks ${describeFunction(e.fn)}, which is not async. Declare it with "async function".`);if(e.fn===l&&e.directive!==`use workflow`)throw Error(`"use step" in "${i.filePath}" marks the default export's "execute" method. A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`)}let p=u.find(e=>e.fn===l);if(p===void 0||c===void 0){let e={hasDirectives:!0,hasWorkflowDirective:d,source:i.source},t=readExecuteReference(c,u);return t===void 0?e:{...e,executeWorkflow:t}}if(declaresTopLevelBinding(o,HOISTED_EXECUTE_NAME))throw Error(`"use workflow" in "${i.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`);return{executeWorkflow:HOISTED_EXECUTE_NAME,hasDirectives:!0,hasWorkflowDirective:d,source:hoistExecuteMethod(i.source,c,p.fn)}}function readExecuteReference(e,t){let n=e?.value;if(!isAstNode(n)||n.type!==`Identifier`||typeof n.name!=`string`)return;let r=n.name;return t.find(e=>e.directive===`use workflow`&&e.fn.id?.name===r)===void 0?void 0:r}function findDefaultExportExecuteProperty(e){let t=e.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration,n=t?.type===`CallExpression`?t.arguments?.[0]:t;if(n?.type===`ObjectExpression`)return n.properties?.find(e=>e.type===`Property`&&e.kind===`init`&&e.computed!==!0&&readPropertyName(e.key)===HOISTED_EXECUTE_NAME)}function hoistExecuteMethod(e,t,n){if(t.start===void 0||t.end===void 0||!isAstNode(n.body)||n.body.start===void 0||n.body.end===void 0)throw Error(`Cannot hoist an execute method without source ranges.`);let i=n.params??[],a=i[0],o=i[i.length-1],s=a?.start===void 0||o?.end===void 0?``:e.slice(a.start,o.end),c=sliceNode(e,n.typeParameters),l=sliceNode(e,n.returnType),u=e.slice(n.body.start,n.body.end),d=`async function${n.generator===!0?`*`:``} ${HOISTED_EXECUTE_NAME}${c}(${s})${l} ${u}`;return`${e.slice(0,t.start)}${HOISTED_EXECUTE_NAME}${e.slice(t.end)}\n${d}\n`}function sliceNode(e,t){return t==null||t.start===void 0||t.end===void 0?``:e.slice(t.start,t.end)}function declaresTopLevelBinding(e,t){for(let n of e){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e!=null){if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.name===t)return!0;if(e.type===`VariableDeclaration`){for(let n of e.declarations??[])if(n.id?.name===t)return!0}if(e.type===`ImportDeclaration`){for(let n of e.specifiers??[])if(n.local?.name===t)return!0}}}return!1}function collectDirectiveFunctions(e){let t=[];return visit(e,e=>{if(!isFunctionLike(e))return;let n=readLeadingDirective(e);n!==void 0&&t.push({directive:n,fn:e})}),t}function readLeadingDirective(e){if(!(!isAstNode(e.body)||e.body.type!==`BlockStatement`||!Array.isArray(e.body.body)))return readWorkflowDirective(e.body.body[0])}function describeFunction(e){return e.type===`FunctionDeclaration`?e.id?.name===void 0?`a nested function declaration`:`the nested function "${e.id.name}"`:e.type===`ArrowFunctionExpression`?`an arrow function`:e.id?.name===void 0?`a function expression`:`the function "${e.id.name}"`}function readPropertyName(e){if(e!=null){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`&&typeof e.value==`string`)return e.value}}function isFunctionLike(e){return e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`}function visit(e,t){if(!e.type?.startsWith(`TS`)){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visit(e,t);else isAstNode(n)&&visit(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}export{prepareAuthoredWorkflowDirectives};
1
+ import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const HOISTED_EXECUTE_NAME=`execute`;async function prepareAuthoredWorkflowDirectives(r){let i=await parseWithNitroRolldownAst(/\.[cm]?js$/.test(r.filePath)?`${r.filePath}.jsx`:r.filePath,r.source),a=i.body??[];if(a.some(e=>e.source?.value===`eve/workflow`))throw Error(`${r.filePath}: "eve/workflow" has been removed. Use defineWorkflowTool() from "eve/tools" and call ctx.agent(input) or ctx.ask(request) in its executor.`);for(let e of a){if(typeof e.directive!=`string`)break;let n=readWorkflowDirective(e);if(n!==void 0)throw Error(`${JSON.stringify(n)} in "${r.filePath}" is a module-level directive. Put it as the first statement of the function it marks: a top-level "async function" declaration or the "execute" method of a default-exported defineWorkflowTool().`)}let o=new Set;for(let e of a){let t=e.type===`FunctionDeclaration`?e:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`?e.declaration:void 0;t!==void 0&&o.add(t)}let s=findDefaultExportExecuteProperty(a),c=s!==void 0&&isAstNode(s.value)&&isFunctionLike(s.value)?s.value:void 0;c!==void 0&&o.add(c);let l=collectDirectiveFunctions(i);if(l.length===0)return{hasDirectives:!1,hasWorkflowDirective:!1,source:r.source};let u=l.some(e=>e.directive===`use workflow`);for(let e of l){if(!o.has(e.fn))throw Error(`${JSON.stringify(e.directive)} in "${r.filePath}" marks ${describeFunction(e.fn)}. Workflow directives must mark a top-level "async function" declaration or the "execute" method of a default-exported defineWorkflowTool().`);if(e.fn.async!==!0)throw Error(`${JSON.stringify(e.directive)} in "${r.filePath}" marks ${describeFunction(e.fn)}, which is not async. Declare it with "async function".`);if(e.fn===c&&e.directive!==`use workflow`)throw Error(`"use step" in "${r.filePath}" marks the default export's "execute" method. A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`)}let d=l.find(e=>e.fn===c);if(d===void 0||s===void 0)return{hasDirectives:!0,hasWorkflowDirective:u,source:r.source};if(declaresTopLevelBinding(a,HOISTED_EXECUTE_NAME))throw Error(`"use workflow" in "${r.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`);return{hasDirectives:!0,hasWorkflowDirective:u,source:hoistExecuteMethod(r.source,s,d.fn)}}function findDefaultExportExecuteProperty(e){let t=e.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration,r=t?.type===`CallExpression`?t.arguments?.[0]:t;if(r?.type===`ObjectExpression`)return r.properties?.find(e=>e.type===`Property`&&e.kind===`init`&&e.computed!==!0&&readPropertyName(e.key)===HOISTED_EXECUTE_NAME)}function hoistExecuteMethod(e,t,r){if(t.start===void 0||t.end===void 0||!isAstNode(r.body)||r.body.start===void 0||r.body.end===void 0)throw Error(`Cannot hoist an execute method without source ranges.`);let i=r.params??[],a=i[0],o=i[i.length-1],s=a?.start===void 0||o?.end===void 0?``:e.slice(a.start,o.end),c=sliceNode(e,r.typeParameters),l=sliceNode(e,r.returnType),u=e.slice(r.body.start,r.body.end),d=`async function${r.generator===!0?`*`:``} ${HOISTED_EXECUTE_NAME}${c}(${s})${l} ${u}`;return`${e.slice(0,t.start)}${HOISTED_EXECUTE_NAME}${e.slice(t.end)}\n${d}\n`}function sliceNode(e,t){return t==null||t.start===void 0||t.end===void 0?``:e.slice(t.start,t.end)}function declaresTopLevelBinding(e,t){for(let n of e){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e!=null){if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.name===t)return!0;if(e.type===`VariableDeclaration`){for(let n of e.declarations??[])if(n.id?.name===t)return!0}if(e.type===`ImportDeclaration`){for(let n of e.specifiers??[])if(n.local?.name===t)return!0}}}return!1}function collectDirectiveFunctions(e){let t=[];return visit(e,e=>{if(!isFunctionLike(e))return;let n=readLeadingDirective(e);n!==void 0&&t.push({directive:n,fn:e})}),t}function readLeadingDirective(e){if(!(!isAstNode(e.body)||e.body.type!==`BlockStatement`||!Array.isArray(e.body.body)))return readWorkflowDirective(e.body.body[0])}function describeFunction(e){return e.type===`FunctionDeclaration`?e.id?.name===void 0?`a nested function declaration`:`the nested function "${e.id.name}"`:e.type===`ArrowFunctionExpression`?`an arrow function`:e.id?.name===void 0?`a function expression`:`the function "${e.id.name}"`}function readPropertyName(e){if(e!=null){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`&&typeof e.value==`string`)return e.value}}function isFunctionLike(e){return e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`}function visit(e,t){if(!e.type?.startsWith(`TS`)){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visit(e,t);else isAstNode(n)&&visit(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}export{prepareAuthoredWorkflowDirectives};
@@ -4,7 +4,6 @@ export interface AuthoredWorkflowModules {
4
4
  }
5
5
  /**
6
6
  * Scans the whole application root, as the SDK's bundler integrations do, so a
7
- * step helper can live wherever the tool imports it from. The SDK's pre-scan
8
- * picks the files worth parsing.
7
+ * step helper can live wherever the tool imports it from.
9
8
  */
10
9
  export declare function discoverAuthoredWorkflowModules(appRoot: string): Promise<AuthoredWorkflowModules>;
@@ -1 +1 @@
1
- import{prepareAuthoredWorkflowDirectives}from"./authored-workflow-directives.js";import{isWorkflowSourceFile}from"./builder-support.js";import{isAuthoredApplicationModule,isAuthoredApplicationRoot}from"./workflow-builders.js";import{readFile,readdir}from"node:fs/promises";import{join}from"node:path";import{detectWorkflowPatterns,isGeneratedWorkflowFile}from"#compiled/@workflow/builders/index.js";const IGNORED_DIRECTORIES=new Set([`.cache`,`.eve`,`.git`,`.next`,`.nitro`,`.nuxt`,`.output`,`.pnpm-store`,`.svelte-kit`,`.swc`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.yarn`,`coverage`,`dist`,`node_modules`]);function isIgnoredDirectory(e){return IGNORED_DIRECTORIES.has(e)||e.startsWith(`.output.`)}async function discoverAuthoredWorkflowModules(t){let a=[],o=[];if(!isAuthoredApplicationRoot(t))return{directiveModules:a,workflowModules:o};let s=await collectSourceFiles(t);for(let r of s.sort()){if(!isAuthoredApplicationModule(r,t)||isGeneratedWorkflowFile(r))continue;let s=await readFile(r,`utf8`);if(!detectWorkflowPatterns(s).hasDirective)continue;let c=await prepareAuthoredWorkflowDirectives({filePath:r,source:s});c.hasDirectives&&(a.push(r),c.hasWorkflowDirective&&o.push(r))}return{directiveModules:a,workflowModules:o}}async function collectSourceFiles(e){let n=[];async function visit(e){let r;try{r=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let i of r){let r=join(e,i.name);if(i.isDirectory()){isIgnoredDirectory(i.name)||await visit(r);continue}i.isFile()&&isWorkflowSourceFile(i.name)&&n.push(r)}}return await visit(e),n}export{discoverAuthoredWorkflowModules};
1
+ import{prepareAuthoredWorkflowDirectives}from"./authored-workflow-directives.js";import{isWorkflowSourceFile}from"./builder-support.js";import{isAuthoredApplicationModule,isAuthoredApplicationRoot}from"./workflow-builders.js";import{readFile,readdir}from"node:fs/promises";import{join}from"node:path";import{isGeneratedWorkflowFile}from"#compiled/@workflow/builders/index.js";const IGNORED_DIRECTORIES=new Set([`.cache`,`.eve`,`.git`,`.next`,`.nitro`,`.nuxt`,`.output`,`.pnpm-store`,`.svelte-kit`,`.swc`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.yarn`,`coverage`,`dist`,`node_modules`]);function isIgnoredDirectory(e){return IGNORED_DIRECTORIES.has(e)||e.startsWith(`.output.`)}async function discoverAuthoredWorkflowModules(t){let a=[],o=[];if(!isAuthoredApplicationRoot(t))return{directiveModules:a,workflowModules:o};let s=await collectSourceFiles(t);for(let r of s.sort()){if(!isAuthoredApplicationModule(r,t)||isGeneratedWorkflowFile(r))continue;let s=await readFile(r,`utf8`);if(!s.includes(`use workflow`)&&!s.includes(`use step`))continue;let c=await prepareAuthoredWorkflowDirectives({filePath:r,source:s});c.hasDirectives&&(a.push(r),c.hasWorkflowDirective&&o.push(r))}return{directiveModules:a,workflowModules:o}}async function collectSourceFiles(e){let n=[];async function visit(e){let r;try{r=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let i of r){let r=join(e,i.name);if(i.isDirectory()){isIgnoredDirectory(i.name)||await visit(r);continue}i.isFile()&&isWorkflowSourceFile(i.name)&&n.push(r)}}return await visit(e),n}export{discoverAuthoredWorkflowModules};
@@ -1,3 +1,3 @@
1
- import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{collectReferencedIdentifierNames,findProperty,walkNode}from"#internal/workflow-bundle/dynamic-tool-ast-references.js";async function transformDynamicToolExecute(t,n,r=NO_WORKFLOW_FUNCTIONS){if(!n.includes(`defineTool`))return null;let a=await parseWithNitroRolldownAst(t,n),o=findDefineToolAliases(a);if(o.size===0)return null;let s=[];return walkForCallbacks(n,a,s,[],{defineToolAliases:o,workflowFunctions:r}),s.length===0?null:applyTransform(n,s)}const NO_WORKFLOW_FUNCTIONS=new Set;function findDefineToolAliases(e){let t=new Set;return walkNode(e,e=>{if(e.type!==`ImportDeclaration`)return!0;let n=e.source?.value;if(typeof n!=`string`||n!==`eve`&&!n.startsWith(`eve/`))return!1;for(let n of e.specifiers??[])n.type===`ImportSpecifier`&&(n.imported?.name??n.imported?.value)===`defineTool`&&n.local?.name&&t.add(n.local.name);return!1}),t}function walkForCallbacks(e,t,n,r,i){if(t){if(isFunction(t)){let a=t.body;if(!a)return;walkForCallbacks(e,a,n,[...r,{params:extractParamNames(t),vars:collectScopeVarDeclarations(a)}],i);return}if(t.type===`CallExpression`&&t.callee?.type===`Identifier`&&t.callee.name!==void 0&&i.defineToolAliases.has(t.callee.name)&&t.arguments?.length===1&&t.arguments[0]?.type===`ObjectExpression`){collectToolCallbacks(e,t.arguments[0],n,r,i);return}for(let a of Object.values(t))if(Array.isArray(a))for(let t of a)isAstNode(t)&&walkForCallbacks(e,t,n,r,i);else isAstNode(a)&&walkForCallbacks(e,a,n,r,i)}}function isWorkflowExecute(e,t){let n=e?.value;return n?.type===`Identifier`&&n.name!==void 0&&t.workflowFunctions.has(n.name)}function collectToolCallbacks(e,t,r,i,a){let o=findProperty(t,`execute`);isWorkflowExecute(o,a)||collectCallbackProperty(e,o,`execute`,`execute`,r,i),collectCallbackProperty(e,findProperty(t,`toModelOutput`),`toModelOutput`,`toModelOutput`,r,i);let s=findProperty(t,`approval`),c=s?.value;c?.type===`ObjectExpression`?(collectCallbackProperty(e,findProperty(c,`request`),`approvalRequest`,`request`,r,i),collectCallbackProperty(e,findProperty(c,`response`),`approvalResponse`,`response`,r,i)):collectCallbackProperty(e,s,`approvalRequest`,`approval`,r,i)}function collectCallbackProperty(e,t,n,r,i,a){if(t?.type!==`Property`||t.start===void 0||t.end===void 0)return;let o=t.value;if(!(!o||o.start===void 0||o.end===void 0)){if(isFunction(o)||t.method===!0){let s=o.body;if(!s)return;i.push({body:extractFnBody(e,o),bodyNode:s,isAsync:o.async===!0,isGenerator:o.generator===!0,isReference:!1,nestedScopes:a,params:extractFnParams(e,o),phase:n,propertyName:r,propEnd:t.end,propStart:t.start});return}o.type===`Identifier`&&i.push({body:`{ return ${e.slice(o.start,o.end)}(...__args); }`,bodyNode:o,isAsync:!1,isGenerator:!1,isReference:!0,nestedScopes:a,params:`...__args`,phase:n,propertyName:r,propEnd:t.end,propStart:t.start})}}function applyTransform(e,n){let r=[],i=[];for(let[e,a]of n.entries()){let n=collectReferencedIdentifierNames(a.bodyNode),o=a.nestedScopes.flatMap(e=>[...e.params,...e.vars]),s=extractCallbackParamNames(a.params),c=dedupeShadowed(o).filter(e=>!s.has(e)&&n.has(e)),l=c.length>0?`{ ${c.join(`, `)} }`:`{}`,u=a.phase.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`),d=a.phase===`execute`?`__eve_dynamic_exec_${e}`:`__eve_dynamic_${u}_${e}`,f=a.params,p=f?`__vars, ${f}`:`__vars`,m=c.length>0?`const ${l} = __vars;\n `:``,h=a.body.slice(1,-1).trim(),g=a.isAsync?`async `:``,_=a.isGenerator?`*`:``;i.push(`${g}function${_} ${d}(${p}) {\n ${m}${h}\n}`);let v=`__eveStampDynamicCallback(${createLiveWrapper(a,d,l)}, ${d}, ${l})`;r.push({end:a.propEnd,start:a.propStart,text:`${a.propertyName}: ${v}`})}let a=e;for(let e of r.sort((e,t)=>t.start-e.start))a=a.slice(0,e.start)+e.text+a.slice(e.end);return{code:`${[`var __eveDurableCallbackSym = Symbol.for("eve:durable-dynamic-callback");`,`function __eveStampDynamicCallback(callback, impl, closure) {`,` Object.defineProperty(callback, __eveDurableCallbackSym, { configurable: true, value: { callback: impl, closure } });`,` return callback;`,`}`].join(`
1
+ import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{collectReferencedIdentifierNames,findProperty,walkNode}from"#internal/workflow-bundle/dynamic-tool-ast-references.js";async function transformDynamicToolExecute(t,n,r=NO_WORKFLOW_FUNCTIONS){if(!n.includes(`defineTool`)&&!n.includes(`defineWorkflowTool`))return null;let a=await parseWithNitroRolldownAst(t,n),o=findDefineToolAliases(a);if(o.size===0)return null;let s=[];return walkForCallbacks(n,a,s,[],{defineToolAliases:o,workflowFunctions:r}),s.length===0?null:applyTransform(n,s)}const NO_WORKFLOW_FUNCTIONS=new Set;function findDefineToolAliases(e){let t=new Set;return walkNode(e,e=>{if(e.type!==`ImportDeclaration`)return!0;let n=e.source?.value;if(typeof n!=`string`||n!==`eve`&&!n.startsWith(`eve/`))return!1;for(let n of e.specifiers??[])n.type===`ImportNamespaceSpecifier`&&n.local?.name&&t.add(`${n.local.name}.defineWorkflowTool`),n.type===`ImportSpecifier`&&[`defineTool`,`defineWorkflowTool`].includes(String(n.imported?.name??n.imported?.value))&&n.local?.name&&t.add(n.local.name);return!1}),t}function readDefinerName(e){if(e?.type===`Identifier`)return e.name;if(e?.type!==`MemberExpression`||e.object?.type!==`Identifier`)return;let t=e.computed?e.property?.value:e.property?.name;return typeof t==`string`?`${e.object.name}.${t}`:void 0}function walkForCallbacks(e,t,n,r,i){if(t){if(isFunction(t)){let a=t.body;if(!a)return;walkForCallbacks(e,a,n,[...r,{params:extractParamNames(t),vars:collectScopeVarDeclarations(a)}],i);return}if(t.type===`CallExpression`&&i.defineToolAliases.has(readDefinerName(t.callee)??``)&&t.arguments?.length===1&&t.arguments[0]?.type===`ObjectExpression`){collectToolCallbacks(e,t.arguments[0],n,r,i);return}for(let a of Object.values(t))if(Array.isArray(a))for(let t of a)isAstNode(t)&&walkForCallbacks(e,t,n,r,i);else isAstNode(a)&&walkForCallbacks(e,a,n,r,i)}}function isWorkflowExecute(e,t){let n=e?.value;return n?.type===`Identifier`&&n.name!==void 0&&t.workflowFunctions.has(n.name)}function collectToolCallbacks(e,t,r,i,a){let o=findProperty(t,`execute`);isWorkflowExecute(o,a)||collectCallbackProperty(e,o,`execute`,`execute`,r,i),collectCallbackProperty(e,findProperty(t,`toModelOutput`),`toModelOutput`,`toModelOutput`,r,i);let s=findProperty(t,`approval`),c=s?.value;c?.type===`ObjectExpression`?(collectCallbackProperty(e,findProperty(c,`request`),`approvalRequest`,`request`,r,i),collectCallbackProperty(e,findProperty(c,`response`),`approvalResponse`,`response`,r,i)):collectCallbackProperty(e,s,`approvalRequest`,`approval`,r,i)}function collectCallbackProperty(e,t,n,r,i,a){if(t?.type!==`Property`||t.start===void 0||t.end===void 0)return;let o=t.value;if(!(!o||o.start===void 0||o.end===void 0)){if(isFunction(o)||t.method===!0){let s=o.body;if(!s)return;i.push({body:extractFnBody(e,o),bodyNode:s,isAsync:o.async===!0,isGenerator:o.generator===!0,isReference:!1,nestedScopes:a,params:extractFnParams(e,o),phase:n,propertyName:r,propEnd:t.end,propStart:t.start});return}o.type===`Identifier`&&i.push({body:`{ return ${e.slice(o.start,o.end)}(...__args); }`,bodyNode:o,isAsync:!1,isGenerator:!1,isReference:!0,nestedScopes:a,params:`...__args`,phase:n,propertyName:r,propEnd:t.end,propStart:t.start})}}function applyTransform(e,n){let r=[],i=[];for(let[e,a]of n.entries()){let n=collectReferencedIdentifierNames(a.bodyNode),o=a.nestedScopes.flatMap(e=>[...e.params,...e.vars]),s=extractCallbackParamNames(a.params),c=dedupeShadowed(o).filter(e=>!s.has(e)&&n.has(e)),l=c.length>0?`{ ${c.join(`, `)} }`:`{}`,u=a.phase.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`),d=a.phase===`execute`?`__eve_dynamic_exec_${e}`:`__eve_dynamic_${u}_${e}`,f=a.params,p=f?`__vars, ${f}`:`__vars`,m=c.length>0?`const ${l} = __vars;\n `:``,h=a.body.slice(1,-1).trim(),g=a.isAsync?`async `:``,_=a.isGenerator?`*`:``;i.push(`${g}function${_} ${d}(${p}) {\n ${m}${h}\n}`);let v=`__eveStampDynamicCallback(${createLiveWrapper(a,d,l)}, ${d}, ${l})`;r.push({end:a.propEnd,start:a.propStart,text:`${a.propertyName}: ${v}`})}let a=e;for(let e of r.sort((e,t)=>t.start-e.start))a=a.slice(0,e.start)+e.text+a.slice(e.end);return{code:`${[`var __eveDurableCallbackSym = Symbol.for("eve:durable-dynamic-callback");`,`function __eveStampDynamicCallback(callback, impl, closure) {`,` Object.defineProperty(callback, __eveDurableCallbackSym, { configurable: true, value: { callback: impl, closure } });`,` return callback;`,`}`].join(`
2
2
  `)}\n${a}\n\n${i.join(`
3
3
  `)}\n`}}function createLiveWrapper(e,t,n){if(e.isReference)return`(...__args) => ${t}(${n}, ...__args)`;let r=e.isAsync?`async `:``;return e.isGenerator?`${r}function* (...__args) { yield* ${t}(${n}, ...__args); }`:`${r}(...__args) => ${e.isAsync?`await `:``}${t}(${n}, ...__args)`}function dedupeShadowed(e){let t=new Set,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];t.has(i)||(t.add(i),n.unshift(i))}return n}function collectScopeVarDeclarations(e){let t=[];return walkNode(e,n=>n!==e&&isFunction(n)?!1:(n.type===`VariableDeclarator`&&collectPatternNames(n.id,t),n.type===`FunctionDeclaration`&&n.id?.name&&t.push(n.id.name),!0)),t}function collectPatternNames(e,t){if(e){if(e.type===`Identifier`&&e.name){t.push(e.name);return}if(e.type===`ObjectPattern`)for(let n of e.properties??[])collectPatternNames(n.type===`RestElement`?n.argument:n.value,t);if(e.type===`ArrayPattern`)for(let n of e.elements??[])collectPatternNames(n,t);e.type===`AssignmentPattern`&&collectPatternNames(e.left,t)}}function extractParamNames(e){let t=[];for(let n of e.params??[])collectPatternNames(n,t);return t}function extractFnParams(e,t){if(!t.params||t.params.length===0)return``;let n=t.params[0],r=t.params[t.params.length-1];return n.start===void 0||r.end===void 0?``:e.slice(n.start,r.end)}function extractFnBody(e,t){let n=t.body;if(!n||n.start===void 0||n.end===void 0)return`{}`;let r=e.slice(n.start,n.end);return t.type===`ArrowFunctionExpression`&&n.type!==`BlockStatement`?`{ return ${r}; }`:r}function splitParamsTopLevel(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i];a===`<`||a===`(`||a===`[`||a===`{`?n++:a===`>`||a===`)`||a===`]`||a===`}`?n--:a===`,`&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function extractParamBindingName(e){let t=e.trim(),n=0;for(let e=0;e<t.length;e++){let r=t[e];if(r===`<`||r===`(`||r===`[`||r===`{`)n++;else if(r===`>`||r===`)`||r===`]`||r===`}`)n--;else if(n===0&&(r===`:`||r===`=`))return t.slice(0,e).trim()}return t}function extractCallbackParamNames(e){let t=[];if(!e)return new Set;for(let n of splitParamsTopLevel(e)){let e=extractParamBindingName(n);e.startsWith(`...`)?t.push(e.slice(3)):t.push(e)}return new Set(t)}function isFunction(e){return e.type===`ArrowFunctionExpression`||e.type===`FunctionDeclaration`||e.type===`FunctionExpression`}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}export{transformDynamicToolExecute as transformDynamicToolAwait,transformDynamicToolExecute};
@@ -26,8 +26,6 @@ export declare function applyWorkflowTransform(filename: string, source: string,
26
26
  workflowManifest: WorkflowManifest;
27
27
  }>;
28
28
  export declare function isAuthoredApplicationModule(absolutePath: string, appRoot: string): boolean;
29
- /** The id the transform mints for an authored `"use workflow"` function. */
30
- export declare function authoredWorkflowId(absolutePath: string, appRoot: string, functionName: string): string;
31
29
  export declare function isAuthoredApplicationRoot(appRoot: string): boolean;
32
30
  export declare function findWorkflowPatterns(filename: string, source: string): Promise<{
33
31
  hasSerde: boolean;
@@ -1 +1 @@
1
- import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{STABLE_WORKFLOW_NAMES}from"#execution/stable-workflow-names.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME}from"#runtime/subagents/workflow-reference.js";import{createWorkflowId,findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives}from"#internal/workflow-bundle/workflow-transformer.js";const packageJsonCache=new Map,projectDepsCache=new Map;async function applyWorkflowTransform(e,t,i,a,o,s=new Set([...STABLE_WORKFLOW_NAMES,SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME])){let c=o??process.cwd(),{moduleSpecifier:l,stableModuleSpecifier:u}=resolveModuleSpecifier(a===void 0?isAbsolute(e)?e:join(c,e):a,c,i===`metadata`);if(a!==void 0&&isAuthoredApplicationModule(a,c)){let e=i===!1?void 0:await prepareAuthoredWorkflowDirectives({filePath:a,source:t});return transformWorkflowDirectives({authored:!0,filename:authoredRelativePath(a,c),mode:e?.hasDirectives===!0&&i,moduleSpecifier:authoredModuleIdBase(a,c),source:e?.source??t,stableModuleSpecifier:void 0,stableWorkflowNames:s})}return transformWorkflowDirectives({filename:e,mode:i,moduleSpecifier:l,source:t,stableModuleSpecifier:u,stableWorkflowNames:s})}function isAuthoredApplicationModule(e,t){let n=toRealPath(t).replace(/\\/g,`/`).replace(/\/$/,``),r=toRealPath(e).replace(/\\/g,`/`);return!r.startsWith(`${n}/`)||isInNodeModules(r)?!1:findPackageJson(r)?.name!==EVE_PACKAGE_NAME}function authoredRelativePath(e,t){return toRelativeImportPath(toRealPath(e),toRealPath(t)).replace(/^\.\//,``)}function authoredModuleIdBase(e,t){return`./${stripJavaScriptExtension(authoredRelativePath(e,t))}`}function authoredWorkflowId(e,t,n){return createWorkflowId(authoredModuleIdBase(e,t),n)}function toRealPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isAuthoredApplicationRoot(e){let t=join(e,`package.json`);if(!existsSync(t))return!1;try{return JSON.parse(readFileSync(t,`utf8`)).name!==EVE_PACKAGE_NAME}catch{return!1}}async function findWorkflowPatterns(e,t){let n=await findWorkflowDirectiveFunctions(e,t);return{hasSerde:t.includes(`workflow.serde`)||t.includes(`@serde`)||t.includes(`workflowSerde`)||t.includes(`__workflow_serde`),hasUseStep:n.some(e=>e.directive===`use step`),hasUseWorkflow:n.some(e=>e.directive===`use workflow`)}}function getImportPath(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t);if(n||r){let n=findPackageJson(e);if(n!==null){let i=getProjectDependencies(t).has(n.name);if(!(r||i))return{importPath:toRelativeImportPath(e,t),isPackage:!1};let a=resolveExportSubpath(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:isRootEntrypointFile(e,n)?{importPath:n.name,isPackage:!0}:{importPath:toRelativeImportPath(e,t),isPackage:!1}}}return{importPath:toRelativeImportPath(e,t),isPackage:!1}}function resolveModuleSpecifier(e,t,n=!1){let r=isInNodeModules(e),i=!r&&isWorkspacePackage(e,t),a=findPackageJson(e);if(n&&a!==null)return{moduleSpecifier:`${a.name}@${a.version}`,stableModuleSpecifier:a.name};if(!r&&!i)return{moduleSpecifier:void 0,stableModuleSpecifier:a?.name===EVE_PACKAGE_NAME?EVE_PACKAGE_NAME:void 0};if(a===null)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let o=resolveExportSubpath(e,a),s=o?`${a.name}${o}`:a.name;return{moduleSpecifier:`${s}@${a.version}`,stableModuleSpecifier:s}}function findPackageJson(e){let n=dirname(e),i=[];for(;n!==dirname(n);){let e=packageJsonCache.get(n);if(e!==void 0){for(let t of i)packageJsonCache.set(t,e);return e}i.push(n);let a=join(n,`package.json`);if(existsSync(a))try{let e=JSON.parse(readFileSync(a,`utf8`));if(typeof e.name==`string`&&typeof e.version==`string`){let t={dir:n,exports:e.exports,main:e.main,module:e.module,name:e.name,version:e.version};packageJsonCache.set(n,t);for(let e of i)packageJsonCache.set(e,t);return t}}catch{}n=dirname(n)}for(let e of i)packageJsonCache.set(e,null);return null}function resolveExportSubpath(e,t){if(t.exports===null||typeof t.exports!=`object`||Array.isArray(t.exports))return``;let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`),i=n.startsWith(`${r}/`)?`./${n.substring(r.length+1)}`:null;if(i===null)return``;for(let[e,n]of Object.entries(t.exports)){let t=resolveExportTarget(n);if(t!==null&&normalizeExportPath(t)===i)return e===`.`?``:e.substring(1)}return``}function resolveExportTarget(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=resolveExportTarget(t);if(e!==null)return e}return null}if(typeof e==`object`&&e)for(let t of[`workflow`,`default`,`require`,`import`,`node`]){let n=e[t],r=resolveExportTarget(n);if(r!==null)return r}return null}function normalizeExportPath(e){return e.startsWith(`./`)?e:`./${e}`}function isInNodeModules(e){return e.split(sep).join(`/`).includes(`/node_modules/`)}function getProjectDependencies(e){let t=projectDepsCache.get(e);if(t!==void 0)return t;let n=new Set,i=join(e,`package.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let r=e[t];if(typeof r==`object`&&r&&!Array.isArray(r))for(let e of Object.keys(r))n.add(e)}}catch{}return projectDepsCache.set(e,n),n}function isWorkspacePackage(e,t){if(isInNodeModules(e))return!1;let n=findPackageJson(e);return n===null||resolve(n.dir)===resolve(t)?!1:getProjectDependencies(t).has(n.name)}function toRelativeImportPath(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),a=r.startsWith(`${n}/`)?r.substring(n.length+1):relative(t,e).replace(/\\/g,`/`);return a.startsWith(`.`)||(a=`./${a}`),a}function hasRootExport(e){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>!e.startsWith(`.`))?!0:`.`in e}function normalizePackageTargetPath(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function isRootEntrypointFile(e,t){let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`);if(!n.startsWith(`${r}/`))return!1;let i=n.substring(r.length+1);if(t.exports!==void 0){let e;if(t.exports!==null&&typeof t.exports==`object`&&`.`in t.exports)e=t.exports[`.`];else if(hasRootExport(t.exports))e=t.exports;else return!1;let n=resolveExportTarget(e);return n!==null&&normalizePackageTargetPath(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[normalizePackageTargetPath(e)]:[]).includes(i)}async function readSourceFile(t){return await readFile(t,`utf8`)}export{applyWorkflowTransform,authoredWorkflowId,findWorkflowPatterns,getImportPath,isAuthoredApplicationModule,isAuthoredApplicationRoot,readSourceFile};
1
+ import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{STABLE_WORKFLOW_NAMES}from"#execution/stable-workflow-names.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME}from"#runtime/subagents/workflow-reference.js";import{findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives}from"#internal/workflow-bundle/workflow-transformer.js";const packageJsonCache=new Map,projectDepsCache=new Map;async function applyWorkflowTransform(e,t,i,a,o,s=new Set([...STABLE_WORKFLOW_NAMES,SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME])){let c=o??process.cwd(),{moduleSpecifier:l,stableModuleSpecifier:u}=resolveModuleSpecifier(a===void 0?isAbsolute(e)?e:join(c,e):a,c,i===`metadata`);if(a!==void 0&&isAuthoredApplicationModule(a,c)){let e=i===!1?void 0:await prepareAuthoredWorkflowDirectives({filePath:a,source:t});return transformWorkflowDirectives({authored:!0,filename:authoredRelativePath(a,c),mode:e?.hasDirectives===!0&&i,moduleSpecifier:authoredModuleIdBase(a,c),source:e?.source??t,stableModuleSpecifier:void 0,stableWorkflowNames:s})}return transformWorkflowDirectives({filename:e,mode:i,moduleSpecifier:l,source:t,stableModuleSpecifier:u,stableWorkflowNames:s})}function isAuthoredApplicationModule(e,t){let n=toRealPath(t).replace(/\\/g,`/`).replace(/\/$/,``),r=toRealPath(e).replace(/\\/g,`/`);return!r.startsWith(`${n}/`)||isInNodeModules(r)?!1:findPackageJson(r)?.name!==EVE_PACKAGE_NAME}function authoredRelativePath(e,t){return toRelativeImportPath(toRealPath(e),toRealPath(t)).replace(/^\.\//,``)}function authoredModuleIdBase(e,t){return`./${stripJavaScriptExtension(authoredRelativePath(e,t))}`}function toRealPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isAuthoredApplicationRoot(e){let t=join(e,`package.json`);if(!existsSync(t))return!1;try{return JSON.parse(readFileSync(t,`utf8`)).name!==EVE_PACKAGE_NAME}catch{return!1}}async function findWorkflowPatterns(e,t){let n=await findWorkflowDirectiveFunctions(e,t);return{hasSerde:t.includes(`workflow.serde`)||t.includes(`@serde`)||t.includes(`workflowSerde`)||t.includes(`__workflow_serde`),hasUseStep:n.some(e=>e.directive===`use step`),hasUseWorkflow:n.some(e=>e.directive===`use workflow`)}}function getImportPath(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t);if(n||r){let n=findPackageJson(e);if(n!==null){let i=getProjectDependencies(t).has(n.name);if(!(r||i))return{importPath:toRelativeImportPath(e,t),isPackage:!1};let a=resolveExportSubpath(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:isRootEntrypointFile(e,n)?{importPath:n.name,isPackage:!0}:{importPath:toRelativeImportPath(e,t),isPackage:!1}}}return{importPath:toRelativeImportPath(e,t),isPackage:!1}}function resolveModuleSpecifier(e,t,n=!1){let r=isInNodeModules(e),i=!r&&isWorkspacePackage(e,t),a=findPackageJson(e);if(n&&a!==null)return{moduleSpecifier:`${a.name}@${a.version}`,stableModuleSpecifier:a.name};if(!r&&!i)return{moduleSpecifier:void 0,stableModuleSpecifier:a?.name===EVE_PACKAGE_NAME?EVE_PACKAGE_NAME:void 0};if(a===null)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let o=resolveExportSubpath(e,a),s=o?`${a.name}${o}`:a.name;return{moduleSpecifier:`${s}@${a.version}`,stableModuleSpecifier:s}}function findPackageJson(e){let n=dirname(e),i=[];for(;n!==dirname(n);){let e=packageJsonCache.get(n);if(e!==void 0){for(let t of i)packageJsonCache.set(t,e);return e}i.push(n);let a=join(n,`package.json`);if(existsSync(a))try{let e=JSON.parse(readFileSync(a,`utf8`));if(typeof e.name==`string`&&typeof e.version==`string`){let t={dir:n,exports:e.exports,main:e.main,module:e.module,name:e.name,version:e.version};packageJsonCache.set(n,t);for(let e of i)packageJsonCache.set(e,t);return t}}catch{}n=dirname(n)}for(let e of i)packageJsonCache.set(e,null);return null}function resolveExportSubpath(e,t){if(t.exports===null||typeof t.exports!=`object`||Array.isArray(t.exports))return``;let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`),i=n.startsWith(`${r}/`)?`./${n.substring(r.length+1)}`:null;if(i===null)return``;for(let[e,n]of Object.entries(t.exports)){let t=resolveExportTarget(n);if(t!==null&&normalizeExportPath(t)===i)return e===`.`?``:e.substring(1)}return``}function resolveExportTarget(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=resolveExportTarget(t);if(e!==null)return e}return null}if(typeof e==`object`&&e)for(let t of[`workflow`,`default`,`require`,`import`,`node`]){let n=e[t],r=resolveExportTarget(n);if(r!==null)return r}return null}function normalizeExportPath(e){return e.startsWith(`./`)?e:`./${e}`}function isInNodeModules(e){return e.split(sep).join(`/`).includes(`/node_modules/`)}function getProjectDependencies(e){let t=projectDepsCache.get(e);if(t!==void 0)return t;let n=new Set,i=join(e,`package.json`);if(existsSync(i))try{let e=JSON.parse(readFileSync(i,`utf8`));for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let r=e[t];if(typeof r==`object`&&r&&!Array.isArray(r))for(let e of Object.keys(r))n.add(e)}}catch{}return projectDepsCache.set(e,n),n}function isWorkspacePackage(e,t){if(isInNodeModules(e))return!1;let n=findPackageJson(e);return n===null||resolve(n.dir)===resolve(t)?!1:getProjectDependencies(t).has(n.name)}function toRelativeImportPath(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),a=r.startsWith(`${n}/`)?r.substring(n.length+1):relative(t,e).replace(/\\/g,`/`);return a.startsWith(`.`)||(a=`./${a}`),a}function hasRootExport(e){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>!e.startsWith(`.`))?!0:`.`in e}function normalizePackageTargetPath(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function isRootEntrypointFile(e,t){let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`);if(!n.startsWith(`${r}/`))return!1;let i=n.substring(r.length+1);if(t.exports!==void 0){let e;if(t.exports!==null&&typeof t.exports==`object`&&`.`in t.exports)e=t.exports[`.`];else if(hasRootExport(t.exports))e=t.exports;else return!1;let n=resolveExportTarget(e);return n!==null&&normalizePackageTargetPath(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[normalizePackageTargetPath(e)]:[]).includes(i)}async function readSourceFile(t){return await readFile(t,`utf8`)}export{applyWorkflowTransform,findWorkflowPatterns,getImportPath,isAuthoredApplicationModule,isAuthoredApplicationRoot,readSourceFile};
@@ -1,5 +1,5 @@
1
1
  import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const BUILTIN_STEP_NAMES=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`,`__builtin_set_attributes`]);async function findWorkflowDirectiveFunctions(e,t){return findDirectiveFunctions(await parseWorkflowSource(e,t)).map(e=>({directive:e.directive,name:e.name}))}async function transformWorkflowDirectives(t){if(t.mode===!1)return{code:t.source,workflowManifest:{}};let n=await parseWorkflowSource(t.filename,t.source),r=findDirectiveFunctions(n);if(r.length===0)return{code:t.source,workflowManifest:{}};let i=t.moduleSpecifier??`./${stripJavaScriptExtension(t.filename)}`,a=t.stableModuleSpecifier??i,o={},s=[],c=[],l=!1;for(let n of r){if(n.directive===`use step`){let e=createStepId(i,n.name);o.steps??={};let r=o.steps[t.filename]??={};if(r[n.name]={stepId:e},t.mode===`workflow`){let t=n.exportPrefix.length>0?`export `:``;s.push({end:n.rangeEnd,start:n.rangeStart,text:`${t}var ${n.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(e)});`})}else if(t.mode===`metadata`)continue;else s.push({end:n.directiveEnd,start:n.directiveStart,text:``}),t.mode===`step`?(l=!0,c.push(`registerStepFunction(${JSON.stringify(e)}, ${n.name});`)):c.push(`${n.name}.stepId = ${JSON.stringify(e)};`);continue}let r=createWorkflowId(t.stableWorkflowNames?.has(n.name)===!0?a:i,n.name);o.workflows??={};let u=o.workflows[t.filename]??={};u[n.name]={workflowId:r},t.mode===`workflow`?(s.push({end:n.directiveEnd,start:n.directiveStart,text:``}),c.push(`${n.name}.workflowId = ${JSON.stringify(r)};`),c.push(`globalThis.${WORKFLOW_REGISTRY_GLOBAL}.set(${JSON.stringify(r)}, ${n.name});`)):(t.mode===`metadata`||s.push({end:n.directiveEnd,start:n.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${n.name} function directly. To start a workflow, use start(${n.name}) from workflow/api`)});`}),c.push(`${n.name}.workflowId = ${JSON.stringify(r)};`))}let u=`/**__internal_workflows${JSON.stringify(o)}*/;`,d=r.some(e=>e.directive===`use workflow`);if(t.mode===`workflow`&&!d&&t.authored!==!0)return{code:`${u}\n${createWorkflowStepProxySource(t.source,n,r,i)}`,workflowManifest:o};t.mode===`workflow`&&t.authored===!0&&s.push(...removeEveDefinerDefaultExport(n));let f=applySourceReplacements(t.source,s),p=t.mode===`workflow`?await stripUnusedValueImports(t.filename,f):f;return{code:`${l?`import { registerStepFunction } from "workflow/internal/private";\n${u}\n`:`${u}\n`}${p}${c.length>0?`\n${c.join(`
2
2
  `)}\n`:``}`,workflowManifest:o}}async function parseWorkflowSource(e,n){return await parseWithNitroRolldownAst(e,n)}function createWorkflowStepProxySource(e,t,n,r){let i=findExportedLiteralValueDeclarations(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exported?`export `:``,n=createStepId(r,e.name);return`${t}var ${e.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`}),o=[...i,...a];return o.length>0?`${o.join(`
3
- `)}\n`:``}function findDirectiveFunctions(e){let t=[],n=collectLocalNamesReExportedAtModuleLevel(e);for(let r of e.body??[]){let e=readTopLevelFunctionDeclaration(r);if(e===null)continue;let i=e.fn,a=i.id?.name,o=readBlockStatements(i.body);if(i.async!==!0||a===void 0||o===void 0)continue;let s=readFunctionDirective(o[0]);s!==null&&t.push({directive:s.value,directiveEnd:s.end,directiveStart:s.start,exportPrefix:e.exported?`export `:``,exported:e.exported||n.has(a),name:a,rangeEnd:e.end,rangeStart:e.start})}return t}function collectLocalNamesReExportedAtModuleLevel(e){let t=new Set;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&!(n.source!==void 0&&n.source!==null)&&!(n.declaration!==void 0&&n.declaration!==null))for(let e of n.specifiers??[]){let n=e.local?.name;n!==void 0&&t.add(n)}return t}function readTopLevelFunctionDeclaration(e){return e.type===`FunctionDeclaration`?readFunctionDeclarationRange(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:readFunctionDeclarationRange(e.declaration,!0,e)}function readFunctionDeclarationRange(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function readBlockStatements(e){return e===void 0||Array.isArray(e)?e:e.body}function readFunctionDirective(e){let t=readWorkflowDirective(e);return t===void 0||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function applySourceReplacements(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}function removeEveDefinerDefaultExport(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source?.value;if(!(typeof e!=`string`||!/^eve(?:\/|$)/.test(e)))for(let e of n.specifiers??[]){if(e.importKind===`type`)continue;let n=e.local?.name;n!==void 0&&t.add(n)}}let n=[];for(let r of e.body??[]){if(r.type!==`ExportDefaultDeclaration`||r.start===void 0)continue;let e=r.declaration;if(e?.type!==`CallExpression`||r.end===void 0)continue;let i=e.callee;i?.type!==`Identifier`||!t.has(i.name??``)||n.push({end:r.end,start:r.start,text:``})}return n}async function stripUnusedValueImports(e,t){let n=await parseWorkflowSource(e,t),r=collectReferencedIdentifiers(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=readValueImportBindings(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:extendRemovalEnd(t,e.end),start:e.start,text:``})}return i.length>0?applySourceReplacements(t,i):t}function findExportedLiteralValueDeclarations(e,t){let n=[],r=collectLocalReExportAliases(t);for(let i of t.body??[]){if(i.type===`ExportNamedDeclaration`&&i.declaration?.type===`VariableDeclaration`&&i.declaration.kind===`const`&&i.start!==void 0&&i.end!==void 0&&(i.declaration.declarations??[]).every(isLiteralValueDeclarator)){n.push(e.slice(i.start,i.end).trim());continue}if(i.type===`VariableDeclaration`&&(i.kind===`const`||i.kind===`var`||i.kind===`let`))for(let t of i.declarations??[]){if(!isLiteralValueDeclarator(t)||t.start===void 0||t.end===void 0)continue;let a=t.id?.name;if(a===void 0)continue;let o=r.get(a);if(o===void 0||o.length===0)continue;let s=e.slice(t.start,t.end).trim(),c=o.map(e=>e===a?a:`${a} as ${e}`);n.push(`${i.kind} ${s};\nexport { ${c.join(`, `)} };`)}}return n}function collectLocalReExportAliases(e){let t=new Map;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&!(n.source!==void 0&&n.source!==null)&&!(n.declaration!==void 0&&n.declaration!==null))for(let e of n.specifiers??[]){let n=e.local?.name,r=e.exported?.name??n;if(n!==void 0&&r!==void 0){let e=t.get(n)??[];e.push(r),t.set(n,e)}}return t}function isLiteralValueDeclarator(e){return isLiteralValueExpression(e.init)}function isLiteralValueExpression(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TemplateLiteral`&&(e.expressions??[]).length===0?!0:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?isLiteralValueExpression(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`&&typeof e.argument.value==`number`}function readValueImportBindings(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function collectReferencedIdentifiers(e){let t=new Set;return visitAstNode(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function visitAstNode(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visitAstNode(e,t);else isAstNode(n)&&visitAstNode(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function extendRemovalEnd(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
3
+ `)}\n`:``}function findDirectiveFunctions(e){let t=[],n=collectLocalNamesReExportedAtModuleLevel(e);for(let r of e.body??[]){let e=readTopLevelFunctionDeclaration(r);if(e===null)continue;let i=e.fn,a=i.id?.name,o=readBlockStatements(i.body);if(i.async!==!0||a===void 0||o===void 0)continue;let s=readFunctionDirective(o[0]);s!==null&&t.push({directive:s.value,directiveEnd:s.end,directiveStart:s.start,exportPrefix:e.exported?`export `:``,exported:e.exported||n.has(a),name:a,rangeEnd:e.end,rangeStart:e.start})}return t}function collectLocalNamesReExportedAtModuleLevel(e){let t=new Set;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&!(n.source!==void 0&&n.source!==null)&&!(n.declaration!==void 0&&n.declaration!==null))for(let e of n.specifiers??[]){let n=e.local?.name;n!==void 0&&t.add(n)}return t}function readTopLevelFunctionDeclaration(e){return e.type===`FunctionDeclaration`?readFunctionDeclarationRange(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:readFunctionDeclarationRange(e.declaration,!0,e)}function readFunctionDeclarationRange(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function readBlockStatements(e){return e===void 0||Array.isArray(e)?e:e.body}function readFunctionDirective(e){let t=readWorkflowDirective(e);return t===void 0||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function applySourceReplacements(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}function removeEveDefinerDefaultExport(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source?.value;if(!(typeof e!=`string`||!/^eve(?:\/|$)/.test(e)))for(let e of n.specifiers??[]){if(e.importKind===`type`)continue;let n=e.local?.name;n!==void 0&&t.add(n)}}let n=[];for(let r of e.body??[]){if(r.type!==`ExportDefaultDeclaration`||r.start===void 0)continue;let e=r.declaration;if(e?.type!==`CallExpression`||r.end===void 0)continue;let i=e.callee,a=i?.type===`MemberExpression`?i.object:i;a?.type!==`Identifier`||!t.has(a.name??``)||n.push({end:r.end,start:r.start,text:``})}return n}async function stripUnusedValueImports(e,t){let n=await parseWorkflowSource(e,t),r=collectReferencedIdentifiers(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=readValueImportBindings(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:extendRemovalEnd(t,e.end),start:e.start,text:``})}return i.length>0?applySourceReplacements(t,i):t}function findExportedLiteralValueDeclarations(e,t){let n=[],r=collectLocalReExportAliases(t);for(let i of t.body??[]){if(i.type===`ExportNamedDeclaration`&&i.declaration?.type===`VariableDeclaration`&&i.declaration.kind===`const`&&i.start!==void 0&&i.end!==void 0&&(i.declaration.declarations??[]).every(isLiteralValueDeclarator)){n.push(e.slice(i.start,i.end).trim());continue}if(i.type===`VariableDeclaration`&&(i.kind===`const`||i.kind===`var`||i.kind===`let`))for(let t of i.declarations??[]){if(!isLiteralValueDeclarator(t)||t.start===void 0||t.end===void 0)continue;let a=t.id?.name;if(a===void 0)continue;let o=r.get(a);if(o===void 0||o.length===0)continue;let s=e.slice(t.start,t.end).trim(),c=o.map(e=>e===a?a:`${a} as ${e}`);n.push(`${i.kind} ${s};\nexport { ${c.join(`, `)} };`)}}return n}function collectLocalReExportAliases(e){let t=new Map;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&!(n.source!==void 0&&n.source!==null)&&!(n.declaration!==void 0&&n.declaration!==null))for(let e of n.specifiers??[]){let n=e.local?.name,r=e.exported?.name??n;if(n!==void 0&&r!==void 0){let e=t.get(n)??[];e.push(r),t.set(n,e)}}return t}function isLiteralValueDeclarator(e){return isLiteralValueExpression(e.init)}function isLiteralValueExpression(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TemplateLiteral`&&(e.expressions??[]).length===0?!0:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?isLiteralValueExpression(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`&&typeof e.argument.value==`number`}function readValueImportBindings(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function collectReferencedIdentifiers(e){let t=new Set;return visitAstNode(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function visitAstNode(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visitAstNode(e,t);else isAstNode(n)&&visitAstNode(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function extendRemovalEnd(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
4
4
  `?n+2:e[n]===`
5
5
  `?n+1:n}function stripJavaScriptExtension(e){return e.replace(/\.(?:[cm]?[jt]sx?)$/,``)}function createWorkflowId(e,t){return`workflow//${e}//${t}`}function createStepId(e,t){return BUILTIN_STEP_NAMES.has(t)?t:`step//${e}//${t}`}export{createWorkflowId,findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives};
@@ -106,8 +106,9 @@ export interface RuntimeTraceContext {
106
106
  * `message` is either a plain text string or an AI SDK `UserContent`
107
107
  * array (mixing `text`, `image`, and `file` parts). Clients pass
108
108
  * multimodal attachments with the same shape AI SDK's `useChat`
109
- * `sendMessage({ files })` produces. `clientContext` is one-turn
110
- * client/page context; the channel converts it into internal model context.
109
+ * `sendMessage({ files })` produces. `clientContext` is turn-scoped
110
+ * client/page context; the channel converts it into internal model context
111
+ * for every model call in that turn.
111
112
  */
112
113
  export type HandleMessageRequestBody = {
113
114
  readonly inputResponses?: never;
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{inputRequestSchema,inputResponseSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions,routeAuth}from"#public/channels/auth.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t=e.route??`/eve/v1/mcp`,n=readOAuthResourceOptions(e.auth),r=[GET(t,async(t,r)=>await authenticateMcpRequest(t,r,e.auth,n)),POST(t,async(t,r)=>await authenticateMcpRequest(t,r,e.auth,n)),DELETE(t,async(t,r)=>await authenticateMcpRequest(t,r,e.auth,n))];return n!==void 0&&r.unshift(...protectedResourceMetadataRoutes(n,t)),defineChannel({routes:r})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r){let i=validateMcpHttpRequest(e);if(i!==void 0)return i;let a=await routeAuth(e,n);return a instanceof Response?r===void 0?a:addResourceChallenge(a,e,r):await handleMcpRequest(e,t,a)}async function handleMcpRequest(e,t,n){let i=readRouteSessionCreator(t),a=readRouteChannelName(t),o=readAgentInfoRouteResponse(t);if(a===void 0||i===void 0||o===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let s=await o();if(!s.ok)return s;let c=await s.json();if(typeof c.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let l=typeof c.agent.description==`string`?c.agent.description:void 0,u=new WorkflowAgentInvocationExecution({createSession:i,from:t.from});return await createMcpStreamableHttpServer({authenticate:async()=>n,name:c.agent.name,tools:createInvocationTools(u,l,n.authenticator===`none`&&n.principalType===`anonymous`),version:resolveInstalledPackageInfo().version})(e)}function createInvocationTools(t,r,i){let a=i?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,o=`Starts durable work and returns an invocation handle immediately.${a}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:r===void 0?o:`${r} ${o}`,inputSchema:z.strictObject({message:z.string().min(1),outputSchema:z.looseObject({}).optional()}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(await t.create({auth:n.auth,message:e.message,outputSchema:asJsonObject(e.outputSchema)}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state.${a}`,inputSchema:z.strictObject({invocationId:z.string().min(1)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(requiredInvocation(await t.read({auth:n.auth,invocationId:e.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers a pending input request on a durable invocation.`,inputSchema:z.strictObject({invocationId:z.string().min(1),responses:z.array(inputResponseSchema).min(1)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(requiredMutation(await t.update({auth:n.auth,invocationId:e.invocationId,responses:e.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cancellation of a durable invocation. Read it again to observe acknowledgement.`,inputSchema:z.strictObject({invocationId:z.string().min(1)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(requiredInvocation(await t.cancel({auth:n.auth,invocationId:e.invocationId})))}})]}function requiredInvocation(e){if(e===void 0)throw Error(`Invocation not found.`);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw Error(e.message);case`not_found`:throw Error(`Invocation not found.`)}}function invocationResult(e){let t=parseJsonObject(e);return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}function asJsonObject(e){if(e===void 0)return;let t=parseJsonObject(e);return validateOutputSchemaComplexity(t),t}const AUTHORIZATION_CHALLENGE_SCHEMA=z.strictObject({displayName:z.string().optional(),expiresAt:z.iso.datetime().optional(),instructions:z.string().optional(),url:z.url().optional(),userCode:z.string().optional()}),AUTHORIZATION_REQUEST_SCHEMA=z.strictObject({authorization:AUTHORIZATION_CHALLENGE_SCHEMA.optional(),description:z.string(),name:z.string(),webhookUrl:z.url().optional()}),MCP_INPUT_REQUEST_SCHEMA=inputRequestSchema.safeExtend({action:z.strictObject({callId:z.string(),input:z.record(z.string(),z.json()),kind:z.literal(`tool-call`),toolName:z.string()})}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({inputRequests:z.record(z.string(),MCP_INPUT_REQUEST_SCHEMA),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({authorizations:z.array(AUTHORIZATION_REQUEST_SCHEMA).min(1),pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`authorization_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);function validateOutputSchemaComplexity(e){if(new TextEncoder().encode(JSON.stringify(e)).byteLength>65536)throw Error(`outputSchema must be at most 65536 bytes.`);let t=0,visit=(e,n)=>{if(t++,t>2048)throw Error(`outputSchema must contain at most 2048 nodes.`);if(n>32)throw Error(`outputSchema must be at most 32 levels deep.`);if(Array.isArray(e)){for(let t of e)visit(t,n+1);return}if(!(typeof e!=`object`||!e))for(let[t,r]of Object.entries(e)){if(t===`$ref`&&typeof r==`string`&&!r.startsWith(`#`))throw Error(`outputSchema external $ref values are not supported.`);visit(r,n+1)}};visit(e,0)}export{mcpChannel};
1
+ import{z}from"#compiled/zod/index.js";import{inputRequestSchema,inputResponseSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions,routeAuth}from"#public/channels/auth.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t=e.route??`/eve/v1/mcp`,n=readOAuthResourceOptions(e.auth),r=[GET(t,async(t,r)=>await authenticateMcpRequest(t,r,e.auth,n)),POST(t,async(t,r)=>await authenticateMcpRequest(t,r,e.auth,n)),DELETE(t,async(t,r)=>await authenticateMcpRequest(t,r,e.auth,n))];return n!==void 0&&r.unshift(...protectedResourceMetadataRoutes(n,t)),defineChannel({routes:r})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r){let i=validateMcpHttpRequest(e);if(i!==void 0)return i;let a=await routeAuth(e,n);return a instanceof Response?r===void 0?a:addResourceChallenge(a,e,r):await handleMcpRequest(e,t,a)}async function handleMcpRequest(e,t,n){let i=readRouteSessionCreator(t),a=readRouteChannelName(t),o=readAgentInfoRouteResponse(t);if(a===void 0||i===void 0||o===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let s=await o();if(!s.ok)return s;let c=await s.json();if(typeof c.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let l=typeof c.agent.description==`string`?c.agent.description:void 0,u=new WorkflowAgentInvocationExecution({createSession:i,from:t.from});return await createMcpStreamableHttpServer({authenticate:async()=>n,instructions:MCP_SERVER_INSTRUCTIONS,name:c.agent.name,tools:createInvocationTools(u,l,n.authenticator===`none`&&n.principalType===`anonymous`),version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer every entry in inputRequests in one agent_update call; repeating accepted answers is safe.`,`If status is authorization_required, show the user the authorization url or instructions and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(t,n,r){let i=r?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,a=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${i}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:n===void 0?a:`${n} ${a}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1),outputSchema:z.looseObject({}).optional()}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(await t.create({auth:n.auth,message:e.message,outputSchema:asJsonObject(e.outputSchema)}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. Terminal statuses are completed, failed, and cancelled. input_required needs agent_update; authorization_required needs the user to follow the returned authorization.${i}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(requiredInvocation(await t.read({auth:n.auth,invocationId:e.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in inputRequests, each keyed by its requestId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(requiredMutation(await t.update({auth:n.auth,invocationId:e.invocationId,responses:e.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(e,n){return invocationResult(requiredInvocation(await t.cancel({auth:n.auth,invocationId:e.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject(e);return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}function asJsonObject(e){if(e!==void 0)try{let t=parseJsonObject(e);return validateOutputSchemaComplexity(t),t}catch(e){throw new McpToolOperationError(`invalid_input`,e instanceof Error?e.message:`outputSchema must be a JSON object.`)}}const AUTHORIZATION_CHALLENGE_SCHEMA=z.strictObject({displayName:z.string().optional(),expiresAt:z.iso.datetime().optional(),instructions:z.string().optional(),url:z.url().optional(),userCode:z.string().optional()}),AUTHORIZATION_REQUEST_SCHEMA=z.strictObject({authorization:AUTHORIZATION_CHALLENGE_SCHEMA.optional(),description:z.string(),name:z.string(),webhookUrl:z.url().optional()}),MAX_MESSAGE_BYTES=64*1024,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(t){let n=new TextEncoder;return z.string().refine(e=>n.encode(e).byteLength<=t,{message:`must be at most ${String(t)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=inputResponseSchema.safeExtend({optionId:z.string().max(256).optional(),requestId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),MCP_INPUT_REQUEST_SCHEMA=inputRequestSchema.safeExtend({action:z.strictObject({callId:z.string(),input:z.record(z.string(),z.json()),kind:z.literal(`tool-call`),toolName:z.string()})}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({inputRequests:z.record(z.string(),MCP_INPUT_REQUEST_SCHEMA),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({authorizations:z.array(AUTHORIZATION_REQUEST_SCHEMA).min(1),pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`authorization_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);function validateOutputSchemaComplexity(e){if(new TextEncoder().encode(JSON.stringify(e)).byteLength>65536)throw Error(`outputSchema must be at most 65536 bytes.`);let t=0,visit=(e,n)=>{if(t++,t>2048)throw Error(`outputSchema must contain at most 2048 nodes.`);if(n>32)throw Error(`outputSchema must be at most 32 levels deep.`);if(Array.isArray(e)){for(let t of e)visit(t,n+1);return}if(!(typeof e!=`object`||!e))for(let[t,r]of Object.entries(e)){if(t===`$ref`&&typeof r==`string`&&!r.startsWith(`#`))throw Error(`outputSchema external $ref values are not supported.`);visit(r,n+1)}};visit(e,0)}export{mcpChannel};
@@ -1,3 +1,3 @@
1
- import{createCodexFetch}from"./transport.js";import{isObject}from"#shared/guards.js";import{createOpenAI}from"#compiled/@ai-sdk/openai/index.js";function createCodexSubscriptionModel(t,r={}){let i=t.model.trim();if(i.length===0)throw Error(`Expected "model" to name a Codex model.`);let a=createOpenAI({apiKey:`codex-local-auth`,fetch:createCodexFetch(r),name:`codex`}).responses(i);return{specificationVersion:a.specificationVersion,provider:a.provider,modelId:a.modelId,get supportedUrls(){return a.supportedUrls},doGenerate:e=>a.doGenerate(normalizeCodexCallOptions(e)),doStream:e=>a.doStream(normalizeCodexCallOptions(e))}}function normalizeCodexCallOptions(e){let t=e.providerOptions,n=t?.openai??{},{instructions:r,prompt:i}=hoistSystemInstructions(e.prompt),{maxOutputTokens:a,...o}=e;return{...o,prompt:stripOpenAIItemIdsFromPrompt(i),providerOptions:{...t,openai:{...n,...r!==void 0&&{instructions:r},store:!1}}}}function hoistSystemInstructions(e){let t=e.filter(e=>e.role===`system`).map(e=>e.content);return t.length===0?{instructions:void 0,prompt:e}:{instructions:t.join(`
1
+ import{createCodexFetch}from"./transport.js";import{createOpenAI}from"#compiled/@ai-sdk/openai/index.js";function createCodexSubscriptionModel(n,r={}){let i=n.model.trim();if(i.length===0)throw Error(`Expected "model" to name a Codex model.`);let a=createOpenAI({apiKey:`codex-local-auth`,fetch:createCodexFetch(r),name:`codex`}).responses(i);return{specificationVersion:a.specificationVersion,provider:a.provider,modelId:a.modelId,get supportedUrls(){return a.supportedUrls},doGenerate:e=>a.doGenerate(normalizeCodexCallOptions(e)),doStream:e=>a.doStream(normalizeCodexCallOptions(e))}}function normalizeCodexCallOptions(e){let t=e.providerOptions,n=t?.openai??{},{instructions:r,prompt:i}=hoistSystemInstructions(e.prompt),{maxOutputTokens:a,...o}=e;return{...o,prompt:i,providerOptions:{...t,openai:{...n,...r!==void 0&&{instructions:r},store:!1}}}}function hoistSystemInstructions(e){let t=e.filter(e=>e.role===`system`).map(e=>e.content);return t.length===0?{instructions:void 0,prompt:e}:{instructions:t.join(`
2
2
 
3
- `),prompt:e.filter(e=>e.role!==`system`)}}function stripOpenAIItemIdsFromPrompt(e){return stripOpenAIItemIds(e,new WeakMap)}function stripOpenAIItemIds(e,n){if(typeof e!=`object`||!e)return e;let r=n.get(e);if(r!==void 0)return r;if(n.set(e,e),Array.isArray(e)){let t=!1,r=e.map(e=>{let r=stripOpenAIItemIds(e,n);return r!==e&&(t=!0),r}),i=t?r:e;return n.set(e,i),i}if(!isObject(e))return e;let i=!1,a={};for(let[t,r]of Object.entries(e)){let e=stripOpenAIItemIds(r,n);(t===`providerOptions`||t===`providerMetadata`)&&(e=withoutOpenAIItemId(e)),e!==r&&(i=!0),a[t]=e}let o=i?a:e;return n.set(e,o),o}function withoutOpenAIItemId(e){if(!isObject(e)||!isObject(e.openai)||!(`itemId`in e.openai))return e;let{itemId:n,...r}=e.openai;return{...e,openai:r}}export{createCodexSubscriptionModel};
3
+ `),prompt:e.filter(e=>e.role!==`system`)}}export{createCodexSubscriptionModel};
@@ -1 +1 @@
1
- import{getDefaultCodexTokenBroker}from"./token-broker.js";const CODEX_API_ENDPOINT=`https://chatgpt.com/backend-api/codex/responses`;function createCodexFetch(n={}){let r=n.fetch??fetch,i=n.broker??getDefaultCodexTokenBroker(),a=n.codexApiEndpoint??CODEX_API_ENDPOINT;return async(e,t)=>{let n=rewriteCodexEndpoint(requestUrl(e),a),o=await i.getToken({reason:`request`}),s=await r(n,authenticatedInit(e,t,o));if(s.status!==401||!isReplayable(e,t))return s;await s.body?.cancel();let c=await i.getToken({reason:`rejected`});return r(n,authenticatedInit(e,t,c))}}function rewriteCodexEndpoint(e,n=CODEX_API_ENDPOINT){let r=new URL(e);return r.pathname.includes(`/v1/responses`)||r.pathname.includes(`/chat/completions`)?n:e}function authenticatedInit(e,t,n){let r=cloneHeaders(t?.headers??(e instanceof Request?e.headers:void 0));return r.delete(`authorization`),r.delete(`Authorization`),r.set(`authorization`,`Bearer ${n.token}`),r.set(`originator`,`eve`),n.accountId===void 0?r.delete(`ChatGPT-Account-Id`):r.set(`ChatGPT-Account-Id`,n.accountId),fetchInit(e,t,r)}function isReplayable(e,t){return e instanceof Request?!1:!(t?.body instanceof ReadableStream)}function cloneHeaders(e){return new Headers(e)}function requestUrl(e){return e instanceof Request?e.url:e.toString()}function fetchInit(e,t,n){return t===void 0?e instanceof Request?{body:e.body,cache:e.cache,credentials:e.credentials,headers:n,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}:{headers:n}:{...t,headers:n}}export{createCodexFetch,rewriteCodexEndpoint};
1
+ import{getDefaultCodexTokenBroker}from"./token-broker.js";import{isObject}from"#shared/guards.js";const CODEX_API_ENDPOINT=`https://chatgpt.com/backend-api/codex/responses`;function createCodexFetch(t={}){let r=t.fetch??fetch,i=t.broker??getDefaultCodexTokenBroker(),a=t.codexApiEndpoint??CODEX_API_ENDPOINT;return async(e,t)=>{let n=rewriteCodexEndpoint(requestUrl(e),a),o=stripInputItemIds(t),s=await i.getToken({reason:`request`}),c=await r(n,authenticatedInit(e,o,s));if(c.status!==401||!isReplayable(e,t))return c;await c.body?.cancel();let l=await i.getToken({reason:`rejected`});return r(n,authenticatedInit(e,o,l))}}function stripInputItemIds(e){if(typeof e?.body!=`string`)return e;let n;try{n=JSON.parse(e.body)}catch{return e}if(!isObject(n)||!Array.isArray(n.input))return e;let r=!1;for(let e of n.input)isObject(e)&&`id`in e&&(delete e.id,r=!0);return r?{...e,body:JSON.stringify(n)}:e}function rewriteCodexEndpoint(e,t=CODEX_API_ENDPOINT){let r=new URL(e);return r.pathname.includes(`/v1/responses`)||r.pathname.includes(`/chat/completions`)?t:e}function authenticatedInit(e,t,n){let r=cloneHeaders(t?.headers??(e instanceof Request?e.headers:void 0));return r.delete(`authorization`),r.delete(`Authorization`),r.set(`authorization`,`Bearer ${n.token}`),r.set(`originator`,`eve`),n.accountId===void 0?r.delete(`ChatGPT-Account-Id`):r.set(`ChatGPT-Account-Id`,n.accountId),fetchInit(e,t,r)}function isReplayable(e,t){return e instanceof Request?!1:!(t?.body instanceof ReadableStream)}function cloneHeaders(e){return new Headers(e)}function requestUrl(e){return e instanceof Request?e.url:e.toString()}function fetchInit(e,t,n){return t===void 0?e instanceof Request?{body:e.body,cache:e.cache,credentials:e.credentials,headers:n,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}:{headers:n}:{...t,headers:n}}export{createCodexFetch,rewriteCodexEndpoint};
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * Tool authoring helpers for `agent/tools/*.ts` files.
3
3
  */
4
- export { type BackgroundToolDefinition, type DisabledToolSentinel, defineTool, disableTool, isDisabledToolSentinel, type TaskBinding, type TaskDelegated, type TaskExec, type TaskExecutorBinding, type TaskReceipt, type ToolAuthOptions, type ToolAuthProvider, type ToolDefinition, type ToolContext, type ToolModelOutput, type ToolModelOutputPart, } from "#tools/definition.js";
4
+ export { type BackgroundToolDefinition, type DisabledToolSentinel, defineTool, disableTool, isDisabledToolSentinel, type TaskExec, type TaskReceipt, type ToolAuthOptions, type ToolAuthProvider, type ToolDefinition, type ToolContext, type ToolModelOutput, type ToolModelOutputPart, } from "#tools/definition.js";
5
5
  export { defineDynamic } from "#dynamic/definition.js";
6
6
  export { toolOutput, toolOutputPart } from "#tools/model-output.js";
7
7
  export type { DynamicEvents, DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";
8
8
  export type { DynamicToolEntry, DynamicToolEvents, DynamicToolSet, DynamicToolResult, } from "#tools/dynamic.js";
9
9
  export { type SessionContext } from "#public/definitions/callback-context.js";
10
10
  export { toolResultFrom, type MatchedConnectionResult, type MatchedToolResult, type ToolResultFromFn, } from "#public/tools/result.js";
11
+ export { defineWorkflowTool, type WorkflowToolContext, type WorkflowToolDefinition, type AgentInput, } from "#tools/workflow-definition.js";
12
+ export type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
@@ -1 +1 @@
1
- import{defineTool,disableTool,isDisabledToolSentinel}from"#tools/definition.js";import{defineDynamic}from"#dynamic/definition.js";import{toolOutput,toolOutputPart}from"#tools/model-output.js";import{toolResultFrom}from"#public/tools/result.js";export{defineDynamic,defineTool,disableTool,isDisabledToolSentinel,toolOutput,toolOutputPart,toolResultFrom};
1
+ import{defineTool,disableTool,isDisabledToolSentinel}from"#tools/definition.js";import{defineDynamic}from"#dynamic/definition.js";import{defineWorkflowTool}from"#tools/workflow-definition.js";import{toolOutput,toolOutputPart}from"#tools/model-output.js";import{toolResultFrom}from"#public/tools/result.js";export{defineDynamic,defineTool,defineWorkflowTool,disableTool,isDisabledToolSentinel,toolOutput,toolOutputPart,toolResultFrom};