eve 0.24.3 → 0.24.5

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 (214) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/src/channel/adapter.d.ts +4 -2
  3. package/dist/src/channel/adapter.js +1 -1
  4. package/dist/src/channel/session.d.ts +5 -1
  5. package/dist/src/channel/types.d.ts +20 -6
  6. package/dist/src/chunks/{use-eve-agent-dEGV09g_.js → use-eve-agent-8rerxDHY.js} +74 -10
  7. package/dist/src/chunks/{use-eve-agent-CFBTHlPx.js → use-eve-agent-DhgdHzDG.js} +74 -10
  8. package/dist/src/cli/commands/build.d.ts +14 -0
  9. package/dist/src/cli/commands/build.js +1 -0
  10. package/dist/src/cli/commands/channels.js +1 -1
  11. package/dist/src/cli/commands/link.d.ts +6 -5
  12. package/dist/src/cli/commands/link.js +1 -1
  13. package/dist/src/cli/dev/tui/runner.d.ts +2 -2
  14. package/dist/src/cli/dev/tui/runner.js +1 -1
  15. package/dist/src/cli/run.d.ts +3 -2
  16. package/dist/src/cli/run.js +1 -1
  17. package/dist/src/client/index.d.ts +2 -2
  18. package/dist/src/client/message-reducer.js +1 -1
  19. package/dist/src/client/ndjson.js +1 -1
  20. package/dist/src/client/open-stream.d.ts +3 -2
  21. package/dist/src/client/open-stream.js +1 -1
  22. package/dist/src/client/session-utils.js +1 -1
  23. package/dist/src/client/session.d.ts +19 -5
  24. package/dist/src/client/session.js +1 -1
  25. package/dist/src/client/types.d.ts +11 -2
  26. package/dist/src/compiled/.vendor-stamp.json +5 -5
  27. package/dist/src/compiled/@workflow/core/index.js +2 -2
  28. package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +55 -0
  29. package/dist/src/compiled/@workflow/core/runtime/run-id-time.d.ts +9 -0
  30. package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +2 -0
  31. package/dist/src/compiled/@workflow/core/runtime/step-latency.d.ts +70 -4
  32. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +10 -1
  33. package/dist/src/compiled/@workflow/core/runtime.js +3 -3
  34. package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +6 -0
  35. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +25 -0
  36. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  37. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  38. package/dist/src/compiled/@workflow/errors/index.d.ts +16 -0
  39. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  40. package/dist/src/compiled/@workflow/world/attributes.d.ts +7 -0
  41. package/dist/src/compiled/@workflow/world/events.d.ts +16 -0
  42. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  43. package/dist/src/compiled/@workflow/world-local/index.js +3 -3
  44. package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
  45. package/dist/src/compiled/_chunks/workflow/attribute-changes-DXbmITuI.js +20 -0
  46. package/dist/src/compiled/_chunks/workflow/{dist-DpDDcpTl.js → dist-BYo8Gno2.js} +1 -1
  47. package/dist/src/compiled/_chunks/workflow/{dist-Blxnyb7-.js → dist-CSfKNxQW.js} +1 -1
  48. package/dist/src/compiled/_chunks/workflow/resume-hook-DvvgYsRt.js +1 -0
  49. package/dist/src/compiled/_chunks/workflow/run-BdvQmV5a.js +1 -0
  50. package/dist/src/compiled/_chunks/workflow/run-id-BdE0MZz9.js +1 -0
  51. package/dist/src/compiled/_chunks/workflow/sleep-DzxrwWTs.js +1 -0
  52. package/dist/src/discover/filesystem.js +1 -1
  53. package/dist/src/evals/assertions/run.d.ts +3 -3
  54. package/dist/src/evals/context.js +1 -1
  55. package/dist/src/evals/index.d.ts +2 -1
  56. package/dist/src/evals/match.d.ts +4 -0
  57. package/dist/src/evals/match.js +1 -1
  58. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  59. package/dist/src/evals/session.d.ts +10 -2
  60. package/dist/src/evals/session.js +1 -1
  61. package/dist/src/evals/target.js +1 -1
  62. package/dist/src/evals/types.d.ts +52 -2
  63. package/dist/src/execution/cancel-descendant-turns-step.d.ts +6 -0
  64. package/dist/src/execution/cancel-descendant-turns-step.js +1 -0
  65. package/dist/src/execution/create-session-step.js +1 -1
  66. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  67. package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
  68. package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +1 -0
  69. package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
  70. package/dist/src/execution/next-driver-action.d.ts +7 -0
  71. package/dist/src/execution/node-step.js +1 -1
  72. package/dist/src/execution/remote-agent-dispatch.d.ts +6 -0
  73. package/dist/src/execution/remote-agent-dispatch.js +1 -1
  74. package/dist/src/execution/settle-cancelled-turn-step.d.ts +16 -0
  75. package/dist/src/execution/settle-cancelled-turn-step.js +1 -0
  76. package/dist/src/execution/subagent-event-proxy-step.js +1 -1
  77. package/dist/src/execution/subagent-hitl-proxy.js +1 -1
  78. package/dist/src/execution/terminal-session-failure-step.d.ts +6 -0
  79. package/dist/src/execution/terminal-session-failure-step.js +1 -0
  80. package/dist/src/execution/turn-cancellation-control.d.ts +27 -0
  81. package/dist/src/execution/turn-cancellation-control.js +1 -0
  82. package/dist/src/execution/turn-cancellation-token.d.ts +9 -0
  83. package/dist/src/execution/turn-cancellation-token.js +1 -0
  84. package/dist/src/execution/turn-dispatch.d.ts +14 -1
  85. package/dist/src/execution/turn-dispatch.js +1 -1
  86. package/dist/src/execution/turn-execution-cursor.d.ts +2 -1
  87. package/dist/src/execution/turn-execution-cursor.js +1 -1
  88. package/dist/src/execution/turn-workflow.d.ts +9 -1
  89. package/dist/src/execution/turn-workflow.js +1 -1
  90. package/dist/src/execution/workflow-entry.js +1 -1
  91. package/dist/src/execution/workflow-runtime.d.ts +3 -1
  92. package/dist/src/execution/workflow-runtime.js +1 -1
  93. package/dist/src/execution/workflow-steps.d.ts +8 -6
  94. package/dist/src/execution/workflow-steps.js +1 -1
  95. package/dist/src/harness/active-turn-id.d.ts +11 -0
  96. package/dist/src/harness/active-turn-id.js +1 -0
  97. package/dist/src/harness/advertised-tools.js +1 -1
  98. package/dist/src/harness/cancelled-turn-emission.d.ts +11 -0
  99. package/dist/src/harness/cancelled-turn-emission.js +1 -0
  100. package/dist/src/harness/emission.d.ts +4 -2
  101. package/dist/src/harness/emission.js +1 -1
  102. package/dist/src/harness/execute-tool.d.ts +0 -1
  103. package/dist/src/harness/proxy-input-requests.d.ts +5 -0
  104. package/dist/src/harness/proxy-input-requests.js +1 -1
  105. package/dist/src/harness/runtime-actions.d.ts +16 -12
  106. package/dist/src/harness/runtime-actions.js +1 -1
  107. package/dist/src/harness/session-limit-enforcement.js +1 -1
  108. package/dist/src/harness/tool-loop.js +2 -2
  109. package/dist/src/internal/application/build-profile.d.ts +64 -0
  110. package/dist/src/internal/application/build-profile.js +1 -0
  111. package/dist/src/internal/application/compiled-artifacts.js +3 -2
  112. package/dist/src/internal/application/package.js +1 -1
  113. package/dist/src/internal/authored-module-loader.d.ts +10 -0
  114. package/dist/src/internal/authored-module-loader.js +3 -3
  115. package/dist/src/internal/authored-module-map-loader.js +1 -1
  116. package/dist/src/internal/bundler/nitro-rolldown.d.ts +18 -2
  117. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  118. package/dist/src/internal/materialized-authored-modules.d.ts +2 -4
  119. package/dist/src/internal/materialized-authored-modules.js +1 -1
  120. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  121. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  122. package/dist/src/internal/nitro/host/build-application.js +1 -1
  123. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  124. package/dist/src/internal/nitro/host/types.d.ts +2 -0
  125. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -1
  126. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +7 -1
  127. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  128. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  129. package/dist/src/internal/nitro/routes/channel-route-context.d.ts +3 -0
  130. package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
  131. package/dist/src/internal/nitro/routes/runtime-stack.js +1 -1
  132. package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
  133. package/dist/src/internal/workflow/development-world-client.js +1 -1
  134. package/dist/src/internal/workflow/development-world-server.js +1 -1
  135. package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -0
  136. package/dist/src/internal/workflow/local-world-data-directory.js +1 -0
  137. package/dist/src/internal/workflow-bundle/builder-support.js +3 -3
  138. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  139. package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
  140. package/dist/src/protocol/cancel-turn.d.ts +11 -0
  141. package/dist/src/protocol/cancel-turn.js +1 -0
  142. package/dist/src/protocol/message.d.ts +23 -3
  143. package/dist/src/protocol/message.js +2 -2
  144. package/dist/src/protocol/routes.d.ts +10 -0
  145. package/dist/src/protocol/routes.js +1 -1
  146. package/dist/src/public/channels/discord/discordChannel.d.ts +1 -0
  147. package/dist/src/public/channels/eve.d.ts +2 -1
  148. package/dist/src/public/channels/eve.js +2 -2
  149. package/dist/src/public/channels/github/githubChannel.d.ts +1 -0
  150. package/dist/src/public/channels/linear/api.d.ts +0 -1
  151. package/dist/src/public/channels/linear/api.js +17 -22
  152. package/dist/src/public/channels/linear/linearChannel.d.ts +1 -0
  153. package/dist/src/public/channels/linear/linearChannel.js +1 -1
  154. package/dist/src/public/channels/slack/slackChannel.d.ts +1 -0
  155. package/dist/src/public/channels/teams/teamsChannel.d.ts +1 -0
  156. package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
  157. package/dist/src/public/channels/twilio/twilioChannel.d.ts +1 -0
  158. package/dist/src/public/definitions/channel.d.ts +25 -14
  159. package/dist/src/public/definitions/channel.js +1 -1
  160. package/dist/src/public/next/index.js +1 -1
  161. package/dist/src/public/next/resolve-eve-binary.d.ts +12 -0
  162. package/dist/src/public/next/resolve-eve-binary.js +1 -0
  163. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  164. package/dist/src/runtime/framework-tools/agent.d.ts +13 -0
  165. package/dist/src/runtime/framework-tools/agent.js +1 -0
  166. package/dist/src/runtime/framework-tools/index.d.ts +7 -2
  167. package/dist/src/runtime/framework-tools/index.js +1 -1
  168. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  169. package/dist/src/runtime/types.d.ts +2 -1
  170. package/dist/src/services/dev-client/runtime-artifacts.d.ts +2 -2
  171. package/dist/src/services/dev-client.d.ts +10 -18
  172. package/dist/src/services/dev-client.js +1 -1
  173. package/dist/src/setup/boxes/reconcile-host-framework-preset.d.ts +26 -0
  174. package/dist/src/setup/boxes/reconcile-host-framework-preset.js +1 -0
  175. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  176. package/dist/src/setup/index.js +1 -1
  177. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  178. package/dist/src/setup/scaffold/create/extension.js +0 -1
  179. package/dist/src/setup/scaffold/create/project.js +2 -4
  180. package/dist/src/setup/scaffold/index.d.ts +1 -1
  181. package/dist/src/setup/scaffold/index.js +1 -1
  182. package/dist/src/setup/scaffold/update/channels.d.ts +7 -1
  183. package/dist/src/setup/scaffold/update/channels.js +2 -2
  184. package/dist/src/setup/scaffold/update/connections.js +3 -3
  185. package/dist/src/setup/vercel-project-framework.d.ts +12 -0
  186. package/dist/src/setup/vercel-project-framework.js +1 -1
  187. package/dist/src/shared/continuation-token.d.ts +2 -0
  188. package/dist/src/shared/continuation-token.js +1 -0
  189. package/dist/src/svelte/index.js +1 -1
  190. package/dist/src/svelte/use-eve-agent.js +1 -1
  191. package/dist/src/vue/index.js +1 -1
  192. package/dist/src/vue/use-eve-agent.js +1 -1
  193. package/docs/channels/eve.mdx +11 -1
  194. package/docs/concepts/default-harness.md +2 -0
  195. package/docs/concepts/execution-model-and-durability.md +1 -1
  196. package/docs/concepts/sessions-runs-and-streaming.md +24 -4
  197. package/docs/evals/assertions.mdx +2 -2
  198. package/docs/evals/cases.mdx +31 -0
  199. package/docs/evals/overview.mdx +1 -1
  200. package/docs/evals/targets.mdx +2 -1
  201. package/docs/guides/client/continuations.mdx +16 -1
  202. package/docs/guides/client/streaming.mdx +31 -2
  203. package/docs/guides/deployment.md +1 -1
  204. package/docs/guides/frontend/overview.mdx +4 -2
  205. package/docs/guides/frontend/use-eve-agent-svelte.mdx +2 -2
  206. package/docs/guides/frontend/use-eve-agent-vue.mdx +2 -2
  207. package/docs/guides/remote-agents.md +2 -0
  208. package/docs/reference/cli.md +16 -3
  209. package/docs/subagents.mdx +10 -0
  210. package/package.json +6 -6
  211. package/dist/src/compiled/_chunks/workflow/attribute-changes-MGTOG_uX.js +0 -20
  212. package/dist/src/compiled/_chunks/workflow/resume-hook-DHP5ql3-.js +0 -1
  213. package/dist/src/compiled/_chunks/workflow/run-D8hv1ptT.js +0 -1
  214. package/dist/src/compiled/_chunks/workflow/sleep-uA9pS-PT.js +0 -1
@@ -1,3 +1,3 @@
1
- import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ParentSessionKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,isNoOutputGeneratedError,summarizeKnownModelCallConfigError,summarizeKnownModelCallRequestError}from"#harness/model-call-error.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent,createStepStartedEvent}from"#protocol/message.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ToolLoopAgent,isStepCount}from"ai";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt,getPendingWorkflowInterrupt,setPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowRuntimeActionInterrupts,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{getActiveDynamicModelSelection}from"#context/dynamic-model-lifecycle.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{resolveAssistantStepText}from"#harness/messages.js";import{buildDynamicInstructionMessages}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{consumeDeferredStepInput,getApprovedTools,hasDeferredStepInput,hasStepInput,resolvePendingInput,setPendingInputBatch}from"#harness/input-requests.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getWorkflowContinuationSecurity,readWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{buildWorkflowHostTools}from"#harness/workflow-sandbox.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{getInvalidToolCallInputError}from"#harness/tool-call-input-errors.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{createWorkflowLifecycle}from"#harness/workflow-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{applySessionLimitContinuation,enforceSessionTokenLimit}from"#harness/session-limit-enforcement.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{buildToolApproval,buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{continueWorkflowSandboxInterrupt,getWorkflowSandboxInterrupt,unwrapWorkflowSandboxResult}from"#shared/workflow-sandbox.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#runtime/framework-tools/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n){if(e===void 0)return;let r={};for(let e of Object.keys(n??{}))r[e]=!0;return{functionId:e.functionId??t,includeRuntimeContext:r,isEnabled:!0,recordInputs:e.recordInputs??!0,recordOutputs:e.recordOutputs??!0}}function mergeSystemInstructions(e){if(e.length===0)return;if(e.length===1)return{...e[0]};let t;for(let n of e)n.providerOptions!==void 0&&(t={...t,...n.providerOptions});let n={role:`system`,content:e.map(e=>e.content).join(`
1
+ import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ParentSessionKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,isNoOutputGeneratedError,summarizeKnownModelCallConfigError,summarizeKnownModelCallRequestError}from"#harness/model-call-error.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent,createStepStartedEvent}from"#protocol/message.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ToolLoopAgent,isStepCount}from"ai";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt,getPendingWorkflowInterrupt,setPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowRuntimeActionInterrupts,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{getActiveDynamicModelSelection}from"#context/dynamic-model-lifecycle.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveAssistantStepText}from"#harness/messages.js";import{buildDynamicInstructionMessages}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{consumeDeferredStepInput,getApprovedTools,hasDeferredStepInput,hasStepInput,resolvePendingInput,setPendingInputBatch}from"#harness/input-requests.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getWorkflowContinuationSecurity,readWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{buildWorkflowHostTools}from"#harness/workflow-sandbox.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{getInvalidToolCallInputError}from"#harness/tool-call-input-errors.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{createWorkflowLifecycle}from"#harness/workflow-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{applySessionLimitContinuation,enforceSessionTokenLimit}from"#harness/session-limit-enforcement.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{buildToolApproval,buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{continueWorkflowSandboxInterrupt,getWorkflowSandboxInterrupt,unwrapWorkflowSandboxResult}from"#shared/workflow-sandbox.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#runtime/framework-tools/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n){if(e===void 0)return;let r={};for(let e of Object.keys(n??{}))r[e]=!0;return{functionId:e.functionId??t,includeRuntimeContext:r,isEnabled:!0,recordInputs:e.recordInputs??!0,recordOutputs:e.recordOutputs??!0}}function mergeSystemInstructions(e){if(e.length===0)return;if(e.length===1)return{...e[0]};let t;for(let n of e)n.providerOptions!==void 0&&(t={...t,...n.providerOptions});let n={role:`system`,content:e.map(e=>e.content).join(`
2
2
 
3
- `)};return t!==void 0&&(n.providerOptions=t),n}function buildGatewayAttributionHeaders(e,t){if(typeof e!=`string`)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0;if(!n&&!i)return;let a={};return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}async function resolveActiveRuntimeModel(e){if(e.ctx===void 0)return{model:await e.config.resolveModel(e.session.agent.modelReference),session:e.session};let t=e.session.agent.dynamicModelDefaultReference??e.session.agent.modelReference,n=getActiveDynamicModelSelection(e.ctx);return n===null?{model:await e.config.resolveModel(t),session:updateSessionModelReference(e.session,t)}:{model:n.model===void 0?await e.config.resolveModel(n.reference):n.model,session:updateSessionModelReference(e.session,n.reference)}}function updateSessionModelReference(e,t){let n=e.agent.modelReference;return{...e,agent:{...e.agent,modelReference:t},compaction:updateCompactionThresholdForModelReference({compaction:e.compaction,modelReference:t,priorReference:n})}}function updateCompactionThresholdForModelReference(e){if(e.modelReference.contextWindowTokens===void 0||e.priorReference.contextWindowTokens===void 0)return e.compaction;let t=e.compaction.threshold/e.priorReference.contextWindowTokens;return{...e.compaction,threshold:Math.max(1,Math.floor(e.modelReference.contextWindowTokens*t))}}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function createToolLoopHarness(t){let n=t.handleEvent,c=getInstrumentationConfig();c!==void 0&&ensureOtelIntegration();let f=c===void 0?void 0:trace.getTracer(`eve`),p=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(f&&hasStepInput(t)){let t=c?.functionId??p,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=f.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(f,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(f,v,y){let b=f;y&&(b=setTurnTraceState(b,y.spanContext()));let x=getHarnessEmissionState(b.state),S=consumeDeferredStepInput({input:v,session:b});b=S.session;let O=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(O.outcome===`unresolved`)return{next:null,session:O.session};b=O.session;let M=resolvePendingInput({history:O.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(M.outcome===`unresolved`)return n&&M.deferredMessage===!0&&hasStepInput(v)?(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),x=await emitTurnEpilogue(n,x,t.mode),{next:null,session:setHarnessEmissionState(M.session,x)}):{next:null,session:M.session};if(n&&M.rejectedActions)for(let e of M.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:M.rejectedActions.event.sequence,stepIndex:M.rejectedActions.event.stepIndex,turnId:M.rejectedActions.event.turnId}));n&&hasStepInput(v)&&(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),b=setHarnessEmissionState(b,x),y&&y.setAttribute(`eve.turn.id`,x.turnId)),b=M.session;let N=M.messages,P=await applySessionLimitContinuation({config:t,emit:n,emissionState:x,limitContinuation:M.limitContinuation,session:b});if(P.result!==null)return P.result;if(b=P.session,S.input?.context!==void 0&&M.deferredContext!==!0)for(let e of S.input.context)N.push({content:e,role:`user`});if(S.input?.message!==void 0&&!M.deferredMessage&&!M.consumedMessage){let e=await stageAttachmentsToSandbox(S.input.message);N.push({content:e,role:`user`})}let F=contextStorage.getStore();F!==void 0&&t.dispatchDynamicModelEvent!==void 0&&await t.dispatchDynamicModelEvent({ctx:F,event:createStepStartedEvent({sequence:x.sequence,stepIndex:x.stepIndex,turnId:x.turnId}),fallback:b.agent.dynamicModelDefaultReference??b.agent.modelReference,messages:N});let I=await resolveActiveRuntimeModel({config:t,ctx:F,session:b});b=I.session;let L=I.model,R=detectPromptCachePath(L),z=R.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,B=buildGatewayAttributionHeaders(L,t.runtimeIdentity);({messages:N,session:b}=await maybeCompact({abortSignal:t.abortSignal,emit:n,emissionState:x,headers:B,messages:N,model:L,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let V=getApprovedTools(b),H=b.outputSchema===void 0&&F!==void 0&&isScheduleAppAuth(F.get(AuthKey))&&F.get(ParentSessionKey)===void 0,U=await hydrateSandboxAttachments(N),W=[],G=[];for(let e of U)e.role===`system`?W.push(e):G.push(e);if(F!==void 0){W.push(...buildDynamicInstructionMessages(F));let e=F.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&W.push({role:`system`,content:e})}H&&W.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let K=G,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=W.length>0||t.length>0?[...t,...n,...W]:void 0,i=r!==void 0&&z?applySystemCacheBreakpoint(r,z):r,a=i===void 0?b.agent.system??void 0:mergeSystemInstructions(i);return{instructions:a,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:a,messages:K},session:b})}},runSingleModelCall=async e=>{let{instructions:i,telemetryRuntimeContext:a={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(a[`eve.retry.reason`]=e.retryReason);let o=e.trailingUserNote?[...K,{role:`user`,content:e.trailingUserNote}]:K,s=getAdvertisedTools({session:b,tools:t.tools}),u=await buildToolSetWithProviderTools({approvedTools:V,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:s});if(F!==void 0){let n=getAdvertisedTools({session:b,tools:buildDynamicTools(F)}),r=buildToolSetFromDefinitions({approvedTools:V,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r))u[e]=t}b.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(b.outputSchema));let d=n===void 0?void 0:({tools:e})=>createWorkflowLifecycle({emit:n,emissionState:x,tools:e}),f=t.workflow===!0?{lifecycle:d,maxSubagents:t.workflowMaxSubagents}:void 0,h=await getAdvertisedTools({modelTools:u,session:b,tools:s,workflow:f});b=h.session;let g=h.modelTools,_=z?applyLastToolCacheBreakpoint(g,z):g,v=buildStepHooks({cachePath:R,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:z,session:b}),y=new ToolLoopAgent({headers:B,instructions:i,model:L,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:v.onStepFinish,prepareStep:v.prepareStep,reasoning:b.agent.reasoning,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),toolApproval:buildToolApproval(g),tools:_});return(async()=>{if(n){let e=[...t.tools].filter(([e,t])=>t.runtimeAction!==void 0&&s.get(e)===void 0).map(([e])=>e),r=new Set([ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...e]),i=await y.stream({abortSignal:t.abortSignal,messages:o}),{emittedActionCallIds:a,handledInlineToolResultCallIds:c,invalidInputToolCallIds:u,inlineAuthorizationResults:d,trailingInlineToolResultParts:f}=await emitStreamContent(n,x,i.fullStream,{excludedActionToolNames:r,tools:t.tools});throwIfTurnAborted(t.abortSignal);let[p,m]=await Promise.all([v.stepResult,i.responseMessages]);if(isEmptyModelResponse(p)&&extractToolResultCallIds(m).size===0&&d.length===0&&f.length===0)throw new EmptyModelResponseError;await emitStepActions(n,x,p,{emittedActionCallIds:a,excludedActionCallIds:u,excludedActionToolNames:r,handledInlineToolResultCallIds:c,tools:s});let h=p.toolResults,g=new Map(h.map(e=>[e.toolCallId,e]));for(let e of d)g.set(e.toolCallId,e);return withAccumulatedResponseMessages({invalidInputToolCallIds:u,responseMessages:appendMissingToolResultMessages({append:f,responseMessages:m}),stepResult:p,toolResults:[...g.values()]})}let e=await y.generate({abortSignal:t.abortSignal,messages:o});throwIfTurnAborted(t.abortSignal);let r=await v.stepResult;if(isEmptyModelResponse(r)&&extractToolResultCallIds(e.responseMessages).size===0)throw new EmptyModelResponseError;return withAccumulatedResponseMessages({responseMessages:e.responseMessages,stepResult:r})})().catch(rethrowNoOutputAsEmptyResponse)},runOneModelCall=async e=>runModelCallWithRetries(t=>runSingleModelCall({...e,preparedInput:t===1?e.preparedInput:void 0,suppressStepStartedEmission:t===1?e.suppressStepStartedEmission:!0}),{sessionId:b.sessionId,turnId:x.turnId},t.abortSignal),q=prepareModelCallInput();n&&await emitStepStarted(n,x,N);let J=await continuePendingWorkflowInterrupt({childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,runStep,session:b});if(J!==null)return J;let Y=await enforceSessionTokenLimit({config:t,emit:n,emissionState:x,messages:N,session:b});if(Y!==null)return Y;let X;try{X=await runOneModelCall({preparedInput:q,suppressStepStartedEmission:!0})}catch(r){throwIfTurnAborted(t.abortSignal);let a=await runModelCallRecoveryPipeline({error:r,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:H,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(throwIfTurnAborted(t.abortSignal),a.outcome===`recovered`)X=a.result;else{let r=a.error;if(y&&recordErrorOnSpan(y,r),!n)throw r;let o=extractWorkflowStreamWriteErrorDetails(r);if(o!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...o,errorId:t,error:r,sessionId:b.sessionId,turnId:x.turnId}),x=await emitRecoverableFailedTurn(n,x,{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...o,errorId:t},message:toErrorMessage(r)}),{next:null,session:setHarnessEmissionState(b,x)}}let s=classifyModelCallError(r),c=createErrorId(),f=s===`terminal`?summarizeKnownModelCallConfigError(r):null,p=f===null?summarizeKnownModelCallRequestError(r):null,_=f?.message??p?.message??toErrorMessage(r),v=extractModelCallErrorDetails(r),S=buildModelCallFailureDetails({configSummary:f,error:r,errorId:c,modelCallDetails:v,requestSummary:p}),C=buildModelCallFailureLogFields({error:r,errorId:c,modelCallDetails:v,requestSummary:p,sessionId:b.sessionId,turnId:x.turnId});if(s===`terminal`)return f===null?log.error(p?.message??`model call failed terminally`,C):log.error(`${f.name}: ${f.message}`,{errorId:c,sessionId:b.sessionId,turnId:x.turnId}),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:S,message:_,sessionId:b.sessionId}),{next:t.mode===`task`?{done:!0,isError:!0,output:_}:{done:!0,output:``},session:b};if(t.mode===`task`){if(s===`recoverable`&&!(r instanceof EmptyModelResponseError))throw log.warn(p?.message??`model call failed recoverably in task mode — rethrowing for durable step retry`,C),r;return log.error(p?.message??`model call failed; failing the task run`,C),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:S,message:_,sessionId:b.sessionId}),{next:{done:!0,isError:!0,output:_},session:b}}return log.error(p?.message??`model call failed — parking session for retry by the user`,C),x=await emitRecoverableFailedTurn(n,x,{code:`MODEL_CALL_FAILED`,details:S,message:_}),{next:null,session:setHarnessEmissionState(b,x)}}}let Z=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:extractTokenUsageDelta({costUsd:extractGatewayCostUsd(X.providerMetadata),usage:X.usage})});b=setTurnUsageState(b,Z);let Q;try{Q=formatLanguageModelGatewayId(L)}catch{Q=void 0}return await setEveAttributes({"$eve.model":Q,"$eve.input_tokens":Z.inputTokens,"$eve.output_tokens":Z.outputTokens,"$eve.cache_read_tokens":Z.cacheReadTokens,"$eve.cache_write_tokens":Z.cacheWriteTokens,"$eve.cost_usd":Z.sawCost?Z.costUsd:void 0,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:N,result:X,runStep,session:b})}return runStep}function extractTokenUsageDelta(e){let t=e.usage;if(!(t===void 0&&e.costUsd===void 0))return{cacheReadTokens:t?.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:t?.inputTokenDetails?.cacheWriteTokens,costUsd:e.costUsd,inputTokens:t?.inputTokens,outputTokens:t?.outputTokens}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function buildModelCallFailureDetails(e){let{configSummary:t,error:r,errorId:i,modelCallDetails:a,requestSummary:o}=e;return t===null?o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}:{errorId:i,message:t.message,name:t.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.requestSummary===null?{...t,error:e.error}:{...t,details:e.modelCallDetails}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}function withAccumulatedResponseMessages(e){let{stepResult:t}=e;return{content:t.content,finishReason:t.finishReason,...e.invalidInputToolCallIds===void 0?{}:{invalidInputToolCallIds:e.invalidInputToolCallIds},providerMetadata:t.providerMetadata,response:{...t.response,messages:[...e.responseMessages]},text:t.text,toolCalls:t.toolCalls,toolResults:e.toolResults===void 0?t.toolResults:[...e.toolResults],usage:t.usage}}function appendMissingToolResultMessages(e){let t=extractToolResultCallIds(e.responseMessages),n=e.append.filter(e=>!t.has(e.toolCallId));return[...e.responseMessages,...n.length>0?[{role:`tool`,content:[...n]}]:[]]}function getInvalidToolCallInputErrors(e){let t=[];for(let n of e.toolCalls){if(n.toolName===FINAL_OUTPUT_TOOL_NAME)continue;let e=getInvalidToolCallInputError({toolCall:n});e!==void 0&&t.push(e)}return t}function extractToolResultCallIds(e){let t=new Set;for(let n of e)if(!(n.role!==`tool`||!Array.isArray(n.content)))for(let e of n.content)e.type===`tool-result`&&t.add(e.toolCallId);return t}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=getInvalidToolCallInputErrors({toolCalls:i.toolCalls}),d=new Set([...i.invalidInputToolCallIds??[],...u.map(e=>e.toolCallId)]),f=l?[]:appendMissingToolResultMessages({append:u.map(e=>createToolResultMessagePartFromToolError(e)),responseMessages:i.response.messages}),p=l?null:c,m=new Set;for(let e of[...i.content??[],...i.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&m.add(e.toolCallId);let h=normalizeProviderToolHistory({messages:f,providerExecutedOutcomeIds:m}),g=h.messages,_={...s,compaction:createNextCompactionConfig(s.compaction,r,i)},y=t.workflow===!0?readWorkflowContinuationSecurity(_):void 0;if(y!==void 0){let e=await getWorkflowSandboxInterrupt(i,y);if(e!==void 0){if(!isWorkflowRuntimeActionInterrupt(e))throw Error(`Unsupported Workflow interrupt kind "${e.payload.kind}".`);return parkOnWorkflowInterrupt({baseSession:_,emissionState:o,interrupt:e,promptMessages:r,responseMessages:g})}}let b=extractToolApprovalInputRequests({content:i.content??[],excludedCallIds:d}),S=new Set(b.map(e=>e.action.callId)),C=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:new Set([...d,...S])}),w=[...b,...C],T=getAdvertisedTools({session:_,tools:t.tools}),E=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>!d.has(e.toolCallId)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).filter(e=>T.get(e.toolName)?.runtimeAction===void 0?(log.warn(`runtime action tool call blocked because tool is not advertised`,{callId:e.toolCallId,sessionId:_.sessionId,toolName:e.toolName}),!1):!0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:T}));if(E.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:E,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:g,session:{..._,history:[...r]}}),o)};if(w.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:w,responseMessages:g,session:{..._,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:w,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),e=setHarnessEmissionState(e,o))),{next:null,session:e}}let D=findAuthorizationSignalFromToolResults(i.toolResults);if(D){let{challenges:e}=D;if(n)for(let t of e)await n(createAuthorizationRequiredEvent({authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));return{next:null,session:setHarnessEmissionState({..._,history:[...r],state:setPendingAuthorization(_.state,{challenges:e})},o)}}let k=g,A=[...r,...k],j={..._,history:A};return!(j.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(k.at(-1)?.role===`tool`||h.outcomeEndsResponse||hasDeferredStepInput(j))?(n&&(o=advanceStep(o),j=setHarnessEmissionState(j,o)),{next:a,session:j}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:j.outputSchema,session:j,stepOutput:p}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:j.outputSchema,session:j})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME)?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i}=e,{emissionState:a,session:o}=e;if(i===void 0)return t&&(a=await emitTurnEpilogue(t,a,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o};let s=extractFinalOutput(r);return s===void 0?(t&&(a=await emitRecoverableFailedTurn(t,a,OUTPUT_SCHEMA_NOT_FULFILLED),o=setHarnessEmissionState(o,a)),{next:null,session:o}):(o=persistStructuredAssistantTurn(o,n,s),t&&(a=await emitStructuredResult(t,a,s,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o})}async function continuePendingWorkflowInterrupt(e){let t=getPendingWorkflowInterrupt(e.session.state);if(t===void 0)return null;let n=t.interrupt;if(!isWorkflowRuntimeActionInterrupt(n))throw Error(`Unsupported Workflow interrupt kind "${n.payload.kind}".`);let i=e.emit===void 0?void 0:createWorkflowLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools}),a=getWorkflowContinuationSecurity(e.session),o;try{let t=buildWorkflowHostTools({tools:e.config.tools}),r=e.childResults??[],s=n,c=0;for(;;){o=await continueWorkflowSandboxInterrupt({continuationSecurity:a,interrupt:s,lifecycle:i,resolution:r[c]?.output,tools:t});let e=await unwrapWorkflowSandboxResult(o,a);if(e.status!==`interrupted`||!isWorkflowRuntimeActionInterrupt(e.interrupt)||c+1>=r.length)break;let n=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(n===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);c++,s=n}}catch(e){logError(log,`Workflow interrupt continuation failed`,e),o={error:`workflow_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let s=await unwrapWorkflowSandboxResult(o,a),c=s.status===`interrupted`?s.interrupt:s.output,l=replaceWorkflowToolResult([...e.session.history,...t.responseMessages],n.outerToolCallId,c),u=clearPendingWorkflowInterrupt({...e.session,history:l});if(s.status===`interrupted`){if(!isWorkflowRuntimeActionInterrupt(s.interrupt))throw Error(`Unsupported Workflow interrupt kind "${s.interrupt.payload.kind}".`);let t=e.session.history.length,n=l.slice(0,t),r=l.slice(t);return u={...u,history:n},parkOnWorkflowInterrupt({baseSession:u,emissionState:e.emissionState,interrupt:s.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:u}}function replaceWorkflowToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}function parkOnWorkflowInterrupt(e){let t=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(t===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);let n={...e.baseSession,history:[...e.promptMessages]};return{next:null,session:setHarnessEmissionState(setPendingWorkflowInterrupt({interrupt:t,responseMessages:e.responseMessages,session:n}),e.emissionState)}}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t.length),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session;if(!shouldCompact(r,i.compaction))return{messages:r,session:i};let a=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:i.agent.modelReference,resolveModel:e.resolveModel});if(t&&await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(r,i.compaction)})),r=await compactMessages(r,a.model,i.compaction,a.providerOptions,e.telemetry,e.headers,e.abortSignal),e.onCompaction)for(let t of e.onCompaction())r.push(t);return t&&await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId})),{messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t,n){for(let r=1;;r++){throwIfTurnAborted(n);try{return await e(r)}catch(e){if(throwIfTurnAborted(n),r===3||classifyModelCallError(e)!==`retry`)throw e;let i=500*2**(r-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:r,delayMs:i,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,i))}}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{createToolLoopHarness};
3
+ `)};return t!==void 0&&(n.providerOptions=t),n}function buildGatewayAttributionHeaders(e,t){if(typeof e!=`string`)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0;if(!n&&!i)return;let a={};return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}async function resolveActiveRuntimeModel(e){if(e.ctx===void 0)return{model:await e.config.resolveModel(e.session.agent.modelReference),session:e.session};let t=e.session.agent.dynamicModelDefaultReference??e.session.agent.modelReference,n=getActiveDynamicModelSelection(e.ctx);return n===null?{model:await e.config.resolveModel(t),session:updateSessionModelReference(e.session,t)}:{model:n.model===void 0?await e.config.resolveModel(n.reference):n.model,session:updateSessionModelReference(e.session,n.reference)}}function updateSessionModelReference(e,t){let n=e.agent.modelReference;return{...e,agent:{...e.agent,modelReference:t},compaction:updateCompactionThresholdForModelReference({compaction:e.compaction,modelReference:t,priorReference:n})}}function updateCompactionThresholdForModelReference(e){if(e.modelReference.contextWindowTokens===void 0||e.priorReference.contextWindowTokens===void 0)return e.compaction;let t=e.compaction.threshold/e.priorReference.contextWindowTokens;return{...e.compaction,threshold:Math.max(1,Math.floor(e.modelReference.contextWindowTokens*t))}}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function createToolLoopHarness(t){let n=t.handleEvent,c=getInstrumentationConfig();c!==void 0&&ensureOtelIntegration();let f=c===void 0?void 0:trace.getTracer(`eve`),p=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(f&&hasStepInput(t)){let t=c?.functionId??p,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=f.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(f,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(f,v,y){let b=f;y&&(b=setTurnTraceState(b,y.spanContext()));let x=getHarnessEmissionState(b.state),S=consumeDeferredStepInput({input:v,session:b});b=S.session;let O=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(O.outcome===`unresolved`)return{next:null,session:O.session};b=O.session;let M=resolvePendingInput({history:O.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(M.outcome===`unresolved`)return n&&M.deferredMessage===!0&&hasStepInput(v)?(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),x=await emitTurnEpilogue(n,x,t.mode,M.session.continuationToken),{next:null,session:setHarnessEmissionState(M.session,x)}):{next:null,session:M.session};if(n&&M.rejectedActions)for(let e of M.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:M.rejectedActions.event.sequence,stepIndex:M.rejectedActions.event.stepIndex,turnId:M.rejectedActions.event.turnId}));n&&hasStepInput(v)&&(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),b=setHarnessEmissionState(b,x),y&&y.setAttribute(`eve.turn.id`,x.turnId)),b=M.session;let N=M.messages,P=await applySessionLimitContinuation({config:t,emit:n,emissionState:x,limitContinuation:M.limitContinuation,session:b});if(P.result!==null)return P.result;if(b=P.session,S.input?.context!==void 0&&M.deferredContext!==!0)for(let e of S.input.context)N.push({content:e,role:`user`});if(S.input?.message!==void 0&&!M.deferredMessage&&!M.consumedMessage){let e=await stageAttachmentsToSandbox(S.input.message);N.push({content:e,role:`user`})}let F=contextStorage.getStore();F!==void 0&&t.dispatchDynamicModelEvent!==void 0&&await t.dispatchDynamicModelEvent({ctx:F,event:createStepStartedEvent({sequence:x.sequence,stepIndex:x.stepIndex,turnId:x.turnId}),fallback:b.agent.dynamicModelDefaultReference??b.agent.modelReference,messages:N});let I=await resolveActiveRuntimeModel({config:t,ctx:F,session:b});b=I.session;let L=I.model,R=detectPromptCachePath(L),z=R.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,B=buildGatewayAttributionHeaders(L,t.runtimeIdentity);({messages:N,session:b}=await maybeCompact({abortSignal:t.abortSignal,emit:n,emissionState:x,headers:B,messages:N,model:L,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let V=getApprovedTools(b),H=b.outputSchema===void 0&&F!==void 0&&isScheduleAppAuth(F.get(AuthKey))&&F.get(ParentSessionKey)===void 0,U=await hydrateSandboxAttachments(N),W=[],G=[];for(let e of U)e.role===`system`?W.push(e):G.push(e);if(F!==void 0){W.push(...buildDynamicInstructionMessages(F));let e=F.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&W.push({role:`system`,content:e})}H&&W.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let K=G,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=W.length>0||t.length>0?[...t,...n,...W]:void 0,i=r!==void 0&&z?applySystemCacheBreakpoint(r,z):r,a=i===void 0?b.agent.system??void 0:mergeSystemInstructions(i);return{instructions:a,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:a,messages:K},session:b})}},runSingleModelCall=async e=>{let{instructions:i,telemetryRuntimeContext:a={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(a[`eve.retry.reason`]=e.retryReason);let o=e.trailingUserNote?[...K,{role:`user`,content:e.trailingUserNote}]:K,s=getAdvertisedTools({session:b,tools:t.tools}),u=await buildToolSetWithProviderTools({approvedTools:V,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:s});if(F!==void 0){let n=getAdvertisedTools({session:b,tools:buildDynamicTools(F)}),r=buildToolSetFromDefinitions({approvedTools:V,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r))u[e]=t}b.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(b.outputSchema));let d=n===void 0?void 0:({tools:e})=>createWorkflowLifecycle({emit:n,emissionState:x,tools:e}),f=t.workflow===!0?{lifecycle:d,maxSubagents:t.workflowMaxSubagents}:void 0,h=await getAdvertisedTools({modelTools:u,session:b,tools:s,workflow:f});b=h.session;let g=h.modelTools,_=z?applyLastToolCacheBreakpoint(g,z):g,v=buildStepHooks({cachePath:R,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:z,session:b}),y=new ToolLoopAgent({headers:B,instructions:i,model:L,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:v.onStepFinish,prepareStep:v.prepareStep,reasoning:b.agent.reasoning,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),toolApproval:buildToolApproval(g),tools:_});return(async()=>{if(n){let e=[...t.tools].filter(([e,t])=>t.runtimeAction!==void 0&&s.get(e)===void 0).map(([e])=>e),r=new Set([ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...e]),i=await y.stream({abortSignal:t.abortSignal,messages:o}),{emittedActionCallIds:a,handledInlineToolResultCallIds:c,invalidInputToolCallIds:u,inlineAuthorizationResults:d,trailingInlineToolResultParts:f}=await emitStreamContent(n,x,i.fullStream,{excludedActionToolNames:r,tools:t.tools});throwIfTurnAborted(t.abortSignal);let[p,m]=await Promise.all([v.stepResult,i.responseMessages]);if(isEmptyModelResponse(p)&&extractToolResultCallIds(m).size===0&&d.length===0&&f.length===0)throw new EmptyModelResponseError;await emitStepActions(n,x,p,{emittedActionCallIds:a,excludedActionCallIds:u,excludedActionToolNames:r,handledInlineToolResultCallIds:c,tools:s});let h=p.toolResults,g=new Map(h.map(e=>[e.toolCallId,e]));for(let e of d)g.set(e.toolCallId,e);return withAccumulatedResponseMessages({invalidInputToolCallIds:u,responseMessages:appendMissingToolResultMessages({append:f,responseMessages:m}),stepResult:p,toolResults:[...g.values()]})}let e=await y.generate({abortSignal:t.abortSignal,messages:o});throwIfTurnAborted(t.abortSignal);let r=await v.stepResult;if(isEmptyModelResponse(r)&&extractToolResultCallIds(e.responseMessages).size===0)throw new EmptyModelResponseError;return withAccumulatedResponseMessages({responseMessages:e.responseMessages,stepResult:r})})().catch(rethrowNoOutputAsEmptyResponse)},runOneModelCall=async e=>runModelCallWithRetries(t=>runSingleModelCall({...e,preparedInput:t===1?e.preparedInput:void 0,suppressStepStartedEmission:t===1?e.suppressStepStartedEmission:!0}),{sessionId:b.sessionId,turnId:x.turnId},t.abortSignal),q=prepareModelCallInput();n&&await emitStepStarted(n,x,N);let J=await continuePendingWorkflowInterrupt({childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,runStep,session:b});if(J!==null)return J;let Y=await enforceSessionTokenLimit({config:t,emit:n,emissionState:x,messages:N,session:b});if(Y!==null)return Y;let X;try{X=await runOneModelCall({preparedInput:q,suppressStepStartedEmission:!0})}catch(r){throwIfTurnAborted(t.abortSignal);let a=await runModelCallRecoveryPipeline({error:r,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:H,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(throwIfTurnAborted(t.abortSignal),a.outcome===`recovered`)X=a.result;else{let r=a.error;if(y&&recordErrorOnSpan(y,r),!n)throw r;let o=extractWorkflowStreamWriteErrorDetails(r);if(o!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...o,errorId:t,error:r,sessionId:b.sessionId,turnId:x.turnId}),x=await emitRecoverableFailedTurn(n,x,{code:`WORKFLOW_STREAM_WRITE_FAILED`,continuationToken:b.continuationToken,details:{...o,errorId:t},message:toErrorMessage(r)}),{next:null,session:setHarnessEmissionState(b,x)}}let s=classifyModelCallError(r),c=createErrorId(),f=s===`terminal`?summarizeKnownModelCallConfigError(r):null,p=f===null?summarizeKnownModelCallRequestError(r):null,_=f?.message??p?.message??toErrorMessage(r),v=extractModelCallErrorDetails(r),S=buildModelCallFailureDetails({configSummary:f,error:r,errorId:c,modelCallDetails:v,requestSummary:p}),C=buildModelCallFailureLogFields({error:r,errorId:c,modelCallDetails:v,requestSummary:p,sessionId:b.sessionId,turnId:x.turnId});if(s===`terminal`)return f===null?log.error(p?.message??`model call failed terminally`,C):log.error(`${f.name}: ${f.message}`,{errorId:c,sessionId:b.sessionId,turnId:x.turnId}),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:S,message:_,sessionId:b.sessionId}),{next:t.mode===`task`?{done:!0,isError:!0,output:_}:{done:!0,output:``},session:b};if(t.mode===`task`){if(s===`recoverable`&&!(r instanceof EmptyModelResponseError))throw log.warn(p?.message??`model call failed recoverably in task mode — rethrowing for durable step retry`,C),r;return log.error(p?.message??`model call failed; failing the task run`,C),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:S,message:_,sessionId:b.sessionId}),{next:{done:!0,isError:!0,output:_},session:b}}return log.error(p?.message??`model call failed — parking session for retry by the user`,C),x=await emitRecoverableFailedTurn(n,x,{code:`MODEL_CALL_FAILED`,continuationToken:b.continuationToken,details:S,message:_}),{next:null,session:setHarnessEmissionState(b,x)}}}let Z=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:extractTokenUsageDelta({costUsd:extractGatewayCostUsd(X.providerMetadata),usage:X.usage})});b=setTurnUsageState(b,Z);let Q;try{Q=formatLanguageModelGatewayId(L)}catch{Q=void 0}return await setEveAttributes({"$eve.model":Q,"$eve.input_tokens":Z.inputTokens,"$eve.output_tokens":Z.outputTokens,"$eve.cache_read_tokens":Z.cacheReadTokens,"$eve.cache_write_tokens":Z.cacheWriteTokens,"$eve.cost_usd":Z.sawCost?Z.costUsd:void 0,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:N,result:X,runStep,session:b})}return runStep}function extractTokenUsageDelta(e){let t=e.usage;if(!(t===void 0&&e.costUsd===void 0))return{cacheReadTokens:t?.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:t?.inputTokenDetails?.cacheWriteTokens,costUsd:e.costUsd,inputTokens:t?.inputTokens,outputTokens:t?.outputTokens}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function buildModelCallFailureDetails(e){let{configSummary:t,error:r,errorId:i,modelCallDetails:a,requestSummary:o}=e;return t===null?o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}:{errorId:i,message:t.message,name:t.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.requestSummary===null?{...t,error:e.error}:{...t,details:e.modelCallDetails}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}function withAccumulatedResponseMessages(e){let{stepResult:t}=e;return{content:t.content,finishReason:t.finishReason,...e.invalidInputToolCallIds===void 0?{}:{invalidInputToolCallIds:e.invalidInputToolCallIds},providerMetadata:t.providerMetadata,response:{...t.response,messages:[...e.responseMessages]},text:t.text,toolCalls:t.toolCalls,toolResults:e.toolResults===void 0?t.toolResults:[...e.toolResults],usage:t.usage}}function appendMissingToolResultMessages(e){let t=extractToolResultCallIds(e.responseMessages),n=e.append.filter(e=>!t.has(e.toolCallId));return[...e.responseMessages,...n.length>0?[{role:`tool`,content:[...n]}]:[]]}function getInvalidToolCallInputErrors(e){let t=[];for(let n of e.toolCalls){if(n.toolName===FINAL_OUTPUT_TOOL_NAME)continue;let e=getInvalidToolCallInputError({toolCall:n});e!==void 0&&t.push(e)}return t}function extractToolResultCallIds(e){let t=new Set;for(let n of e)if(!(n.role!==`tool`||!Array.isArray(n.content)))for(let e of n.content)e.type===`tool-result`&&t.add(e.toolCallId);return t}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=getInvalidToolCallInputErrors({toolCalls:i.toolCalls}),d=new Set([...i.invalidInputToolCallIds??[],...u.map(e=>e.toolCallId)]),f=l?[]:appendMissingToolResultMessages({append:u.map(e=>createToolResultMessagePartFromToolError(e)),responseMessages:i.response.messages}),p=l?null:c,m=new Set;for(let e of[...i.content??[],...i.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&m.add(e.toolCallId);let h=normalizeProviderToolHistory({messages:f,providerExecutedOutcomeIds:m}),g=h.messages,_={...s,compaction:createNextCompactionConfig(s.compaction,r,i)},y=t.workflow===!0?readWorkflowContinuationSecurity(_):void 0;if(y!==void 0){let e=await getWorkflowSandboxInterrupt(i,y);if(e!==void 0){if(!isWorkflowRuntimeActionInterrupt(e))throw Error(`Unsupported Workflow interrupt kind "${e.payload.kind}".`);return parkOnWorkflowInterrupt({baseSession:_,emissionState:o,interrupt:e,promptMessages:r,responseMessages:g})}}let b=extractToolApprovalInputRequests({content:i.content??[],excludedCallIds:d}),S=new Set(b.map(e=>e.action.callId)),C=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:new Set([...d,...S])}),w=[...b,...C],T=getAdvertisedTools({session:_,tools:t.tools}),E=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>!d.has(e.toolCallId)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).filter(e=>T.get(e.toolName)?.runtimeAction===void 0?(log.warn(`runtime action tool call blocked because tool is not advertised`,{callId:e.toolCallId,sessionId:_.sessionId,toolName:e.toolName}),!1):!0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:T}));if(E.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:E,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:g,session:{..._,history:[...r]}}),o)};if(w.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:w,responseMessages:g,session:{..._,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:w,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode,e.continuationToken),e=setHarnessEmissionState(e,o))),{next:null,session:e}}let D=findAuthorizationSignalFromToolResults(i.toolResults);if(D){let{challenges:e}=D;if(n)for(let t of e)await n(createAuthorizationRequiredEvent({authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));return{next:null,session:setHarnessEmissionState({..._,history:[...r],state:setPendingAuthorization(_.state,{challenges:e})},o)}}let k=g,A=[...r,...k],j={..._,history:A};return!(j.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(k.at(-1)?.role===`tool`||h.outcomeEndsResponse||hasDeferredStepInput(j))?(n&&(o=advanceStep(o),j=setHarnessEmissionState(j,o)),{next:a,session:j}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:j.outputSchema,session:j,stepOutput:p}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:j.outputSchema,session:j})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME)?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r,i){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r,i)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`,s.continuationToken),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`,s.continuationToken),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i}=e,{emissionState:a,session:o}=e;if(i===void 0)return t&&(a=await emitTurnEpilogue(t,a,`conversation`,o.continuationToken),o=setHarnessEmissionState(o,a)),{next:null,session:o};let s=extractFinalOutput(r);return s===void 0?(t&&(a=await emitRecoverableFailedTurn(t,a,{...OUTPUT_SCHEMA_NOT_FULFILLED,continuationToken:o.continuationToken}),o=setHarnessEmissionState(o,a)),{next:null,session:o}):(o=persistStructuredAssistantTurn(o,n,s),t&&(a=await emitStructuredResult(t,a,s,`conversation`,o.continuationToken),o=setHarnessEmissionState(o,a)),{next:null,session:o})}async function continuePendingWorkflowInterrupt(e){let t=getPendingWorkflowInterrupt(e.session.state);if(t===void 0)return null;let n=t.interrupt;if(!isWorkflowRuntimeActionInterrupt(n))throw Error(`Unsupported Workflow interrupt kind "${n.payload.kind}".`);let i=e.emit===void 0?void 0:createWorkflowLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools}),a=getWorkflowContinuationSecurity(e.session),o;try{let t=buildWorkflowHostTools({tools:e.config.tools}),r=e.childResults??[],s=n,c=0;for(;;){o=await continueWorkflowSandboxInterrupt({continuationSecurity:a,interrupt:s,lifecycle:i,resolution:r[c]?.output,tools:t});let e=await unwrapWorkflowSandboxResult(o,a);if(e.status!==`interrupted`||!isWorkflowRuntimeActionInterrupt(e.interrupt)||c+1>=r.length)break;let n=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(n===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);c++,s=n}}catch(e){logError(log,`Workflow interrupt continuation failed`,e),o={error:`workflow_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let s=await unwrapWorkflowSandboxResult(o,a),c=s.status===`interrupted`?s.interrupt:s.output,l=replaceWorkflowToolResult([...e.session.history,...t.responseMessages],n.outerToolCallId,c),u=clearPendingWorkflowInterrupt({...e.session,history:l});if(s.status===`interrupted`){if(!isWorkflowRuntimeActionInterrupt(s.interrupt))throw Error(`Unsupported Workflow interrupt kind "${s.interrupt.payload.kind}".`);let t=e.session.history.length,n=l.slice(0,t),r=l.slice(t);return u={...u,history:n},parkOnWorkflowInterrupt({baseSession:u,emissionState:e.emissionState,interrupt:s.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:u}}function replaceWorkflowToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}function parkOnWorkflowInterrupt(e){let t=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(t===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);let n={...e.baseSession,history:[...e.promptMessages]};return{next:null,session:setHarnessEmissionState(setPendingWorkflowInterrupt({interrupt:t,responseMessages:e.responseMessages,session:n}),e.emissionState)}}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t.length),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session;if(!shouldCompact(r,i.compaction))return{messages:r,session:i};let a=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:i.agent.modelReference,resolveModel:e.resolveModel});if(t&&await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(r,i.compaction)})),r=await compactMessages(r,a.model,i.compaction,a.providerOptions,e.telemetry,e.headers,e.abortSignal),e.onCompaction)for(let t of e.onCompaction())r.push(t);return t&&await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId})),{messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t,n){for(let r=1;;r++){throwIfTurnAborted(n);try{return await e(r)}catch(e){if(throwIfTurnAborted(n),r===3||classifyModelCallError(e)!==`retry`)throw e;let i=500*2**(r-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:r,delayMs:i,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,i))}}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{createToolLoopHarness};
@@ -0,0 +1,64 @@
1
+ /** Version of the machine-readable `eve build --profile` report schema. */
2
+ export declare const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION: 1;
3
+ /** Deployment target represented by one build profile. */
4
+ export type ApplicationBuildProfileTarget = "local" | "vercel";
5
+ /** One completed phase in an application build profile. */
6
+ export interface ApplicationBuildProfilePhase {
7
+ readonly durationMs: number;
8
+ readonly name: string;
9
+ }
10
+ /** Size totals for one Vercel function directory in the published output. */
11
+ export interface ApplicationBuildProfileFunctionBundle {
12
+ readonly files: number;
13
+ readonly gzipBytes: number;
14
+ readonly path: string;
15
+ readonly rawBytes: number;
16
+ }
17
+ /** Final output-size measurements collected after a successful publication. */
18
+ export interface ApplicationBuildProfileOutput {
19
+ readonly files: number;
20
+ readonly functionBundles: readonly ApplicationBuildProfileFunctionBundle[];
21
+ readonly gzipBytes: number;
22
+ readonly rawBytes: number;
23
+ }
24
+ /** Timing data gathered while an application build runs. */
25
+ export interface ApplicationBuildProfileTiming {
26
+ readonly durationMs: number;
27
+ readonly phases: readonly ApplicationBuildProfilePhase[];
28
+ }
29
+ /** Stable JSON document written by `eve build --profile <path>`. */
30
+ export interface ApplicationBuildProfile {
31
+ readonly durationMs: number;
32
+ readonly kind: "eve-build-profile";
33
+ readonly output: ApplicationBuildProfileOutput;
34
+ readonly phases: readonly ApplicationBuildProfilePhase[];
35
+ readonly schemaVersion: typeof APPLICATION_BUILD_PROFILE_SCHEMA_VERSION;
36
+ readonly target: ApplicationBuildProfileTarget;
37
+ }
38
+ interface ApplicationBuildProfilerOptions {
39
+ readonly now?: () => number;
40
+ }
41
+ /**
42
+ * Records elapsed build phases only when profile output was requested. The
43
+ * injected clock keeps its serialization behavior independently testable.
44
+ */
45
+ export declare class ApplicationBuildProfiler {
46
+ #private;
47
+ constructor(options?: ApplicationBuildProfilerOptions);
48
+ measure<T>(name: string, operation: () => T | Promise<T>): Promise<T>;
49
+ finish(): ApplicationBuildProfileTiming;
50
+ }
51
+ /** Creates the versioned report shape from completed timings and output measurements. */
52
+ export declare function createApplicationBuildProfile(input: {
53
+ readonly output: ApplicationBuildProfileOutput;
54
+ readonly target: ApplicationBuildProfileTarget;
55
+ readonly timing: ApplicationBuildProfileTiming;
56
+ }): ApplicationBuildProfile;
57
+ /**
58
+ * Measures regular files in the published output without following symlinks.
59
+ * Each `.func` directory receives its own subtotal for Vercel output.
60
+ */
61
+ export declare function measureApplicationBuildOutput(outputDirectory: string): Promise<ApplicationBuildProfileOutput>;
62
+ /** Writes one formatted profile JSON document outside the build output. */
63
+ export declare function writeApplicationBuildProfile(outputPath: string, profile: ApplicationBuildProfile): Promise<void>;
64
+ export {};
@@ -0,0 +1 @@
1
+ import{dirname,join,relative,sep}from"node:path";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{performance}from"node:perf_hooks";import{gzipSync}from"node:zlib";const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION=1;function roundDuration(e){return Math.round(Math.max(0,e)*10)/10}function createMutableOutputSize(){return{files:0,gzipBytes:0,rawBytes:0}}function toOutputSize(e){return{files:e.files,gzipBytes:e.gzipBytes,rawBytes:e.rawBytes}}function toProfilePath(e,t){return relative(e,t).split(sep).join(`/`)}function measureFileSize(e){return{gzipBytes:gzipSync(e).byteLength,rawBytes:e.byteLength}}function addFileSize(e,t){e.files+=1,e.rawBytes+=t.rawBytes,e.gzipBytes+=t.gzipBytes}var ApplicationBuildProfiler=class{#e;#t=[];#n;#r=!1;constructor(e={}){this.#e=e.now??performance.now.bind(performance),this.#n=this.#e()}async measure(e,t){if(this.#r)throw Error(`Cannot record a phase after the build profile has finished.`);let n=this.#e();try{return await t()}finally{this.#t.push({durationMs:roundDuration(this.#e()-n),name:e})}}finish(){if(this.#r)throw Error(`The build profile has already finished.`);return this.#r=!0,{durationMs:roundDuration(this.#e()-this.#n),phases:[...this.#t]}}};function createApplicationBuildProfile(e){return{durationMs:e.timing.durationMs,kind:`eve-build-profile`,output:e.output,phases:e.timing.phases,schemaVersion:1,target:e.target}}async function measureApplicationBuildOutput(e){let n=createMutableOutputSize(),r=new Map,visit=async(i,o)=>{let s=await readdir(i,{withFileTypes:!0});for(let a of s){let s=join(i,a.name);if(a.isDirectory()){await visit(s,a.name.endsWith(`.func`)?toProfilePath(e,s):o);continue}if(!a.isFile())continue;let c=measureFileSize(await readFile(s));if(addFileSize(n,c),o!==void 0){let e=r.get(o)??createMutableOutputSize();addFileSize(e,c),r.set(o,e)}}};return await visit(e,void 0),{...toOutputSize(n),functionBundles:[...r.entries()].map(([e,t])=>({path:e,...toOutputSize(t)})).sort((e,t)=>e.path.localeCompare(t.path))}}async function writeApplicationBuildProfile(t,n){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(n,null,2)}\n`,`utf8`)}export{APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile};
@@ -1,7 +1,8 @@
1
- import{getWorldImport}from"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/world-target.js";import"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/index.js";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{join}from"node:path";import{copyFile,mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),a=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),c=resolveInstrumentationModule(e.compileResult.manifest.agentRoot);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,await createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),await writeFile(a,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld})),c!==void 0&&await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let l={bootstrapPath:t,workflowWorldPluginPath:a};return c!==void 0&&(l.instrumentationPluginPath=r,l.instrumentationSourcePath=c),l}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),c=join(e.outDir,`compiled-artifacts-instrumentation-source.mjs`),l=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),u=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(u===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(l,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let d={bootstrapPath:t,workflowWorldPluginPath:l};return u.instrumentation!==void 0&&(await copyFile(join(e.runtimeAppRoot,`.eve`,`compile`,u.instrumentation),c),await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)})),d.instrumentationPluginPath=r,d.instrumentationSourcePath=c),d}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
1
+ import{getWorldImport}from"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/world-target.js";import"../../node_modules/.pnpm/@workflow_utils@5.0.0-beta.6/node_modules/@workflow/utils/dist/index.js";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{join}from"node:path";import{copyFile,mkdir,writeFile}from"node:fs/promises";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),a=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),c=resolveInstrumentationModule(e.compileResult.manifest.agentRoot);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,await createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),await writeFile(a,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld})),c!==void 0&&await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)}));let l={bootstrapPath:t,workflowWorldPluginPath:a};return c!==void 0&&(l.instrumentationPluginPath=r,l.instrumentationSourcePath=c),l}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),c=join(e.outDir,`compiled-artifacts-instrumentation-source.mjs`),l=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),d=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(d===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(l,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let f={bootstrapPath:t,workflowWorldPluginPath:l};return d.instrumentation!==void 0&&(await copyFile(join(e.runtimeAppRoot,`.eve`,`compile`,d.instrumentation),c),await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,instrumentationPath:c,registerConfigPath:resolvePackageSourceFilePath(`src/harness/instrumentation-config.ts`)})),f.instrumentationPluginPath=r,f.instrumentationSourcePath=c),f}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
2
2
  `)}const INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];function resolveInstrumentationModule(e){for(let t of INSTRUMENTATION_EXTENSIONS){let n=join(e,`instrumentation${t}`);if(existsSync(n))return n}}function stripCompiledModuleMapExports(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
3
3
  `)}async function createCompiledArtifactsBootstrapSource(e){let t=e.compileResult.manifest.config.name,r=stripCompiledModuleMapExports(createCompiledModuleMapSource({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by eve. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(t)});`,``,r,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``].join(`
4
- `)}function createWorkflowWorldPluginSource(r){let i=getWorldImport({WORKFLOW_TARGET_WORLD:r.configuredWorld??r.defaultWorld}),a=i===`@workflow/world-local`||i===`@workflow/world-vercel`?resolvePackageCompiledFilePath(`src/compiled/${i}/index.js`):i,o=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),s=resolvePackageSourceFilePath(`src/internal/workflow/validate-world.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(r.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(a)};`,`import { createWorldFromModule, getWorld, setWorld } from ${stringifyEsmImportSpecifier(o)};`,`import { validateWorkflowWorld } from ${stringifyEsmImportSpecifier(s)};`,``,`const workflowWorld = await createWorldFromModule(workflowWorldModule);`,`validateWorkflowWorld({ packageName: ${JSON.stringify(r.configuredWorld)}, world: workflowWorld });`,`setWorld(workflowWorld);`,`await getWorld();`,`await workflowWorld.start?.();`,``,`export default function installWorkflowWorldPlugin() {}`,``].join(`
4
+ `)}function createWorkflowWorldPluginSource(r){let i=getWorldImport({WORKFLOW_TARGET_WORLD:r.configuredWorld??r.defaultWorld}),a=i===`@workflow/world-local`||i===`@workflow/world-vercel`?resolvePackageCompiledFilePath(`src/compiled/${i}/index.js`):i,o=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),s=resolvePackageSourceFilePath(`src/internal/workflow/validate-world.ts`),c=i===`@workflow/world-local`?resolvePackageSourceFilePath(`src/internal/workflow/local-world-data-directory.ts`):void 0,u=c===void 0?`const workflowWorld = await createWorldFromModule(workflowWorldModule);`:[`const workflowWorld = await workflowWorldModule.createWorld({`,` dataDir: resolveLocalWorkflowWorldDataDirectory(process.cwd()),`,`});`].join(`
5
+ `),d=c===void 0?`createWorldFromModule, getWorld, setWorld`:`getWorld, setWorld`;return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(r.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(a)};`,...c===void 0?[]:[`import { resolveLocalWorkflowWorldDataDirectory } from ${stringifyEsmImportSpecifier(c)};`],`import { ${d} } from ${stringifyEsmImportSpecifier(o)};`,`import { validateWorkflowWorld } from ${stringifyEsmImportSpecifier(s)};`,``,u,`validateWorkflowWorld({ packageName: ${JSON.stringify(r.configuredWorld)}, world: workflowWorld });`,`setWorld(workflowWorld);`,`await getWorld();`,`await workflowWorld.start?.();`,``,`export default function installWorkflowWorldPlugin() {}`,``].join(`
5
6
  `)}function createDevelopmentWorkflowWorldPluginSource(e){if(!usesParentDevelopmentWorkflowWorld(e.configuredWorld))return createWorkflowWorldPluginSource({...e,defaultWorld:`local`});let r=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),i=resolvePackageSourceFilePath(`src/internal/workflow/development-world-client.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import { getWorld, setWorld } from ${stringifyEsmImportSpecifier(r)};`,`import { createDevelopmentWorkflowWorld } from ${stringifyEsmImportSpecifier(i)};`,``,`setWorld(createDevelopmentWorkflowWorld());`,`await getWorld();`,``,`export default function installDevelopmentWorkflowWorldPlugin() {}`,``].join(`
6
7
  `)}function createInstrumentationPluginSource(e){return[`// Generated by eve. Do not edit by hand.`,`import * as instrumentationModule from ${stringifyEsmImportSpecifier(e.instrumentationPath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(e.registerConfigPath)};`,``,`if (instrumentationModule.default != null) {`,` registerInstrumentationConfig(instrumentationModule.default, { agentName: ${JSON.stringify(e.agentName)} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
7
8
  `)}export{createCompiledArtifactsBootstrapSource,createDevelopmentWorkflowWorldPluginSource,createWorkflowWorldPluginSource,writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.24.3`,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 isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.24.5`,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 isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1,3 +1,4 @@
1
+ import type { CompiledAgentManifest } from "#compiler/manifest.js";
1
2
  export interface AuthoredModuleLoadOptions {
2
3
  readonly externalDependencies?: readonly string[];
3
4
  /**
@@ -25,3 +26,12 @@ export declare function bundleAuthoredModuleCode(modulePath: string, options?: A
25
26
  * configured external dependencies keep their normal runtime resolution.
26
27
  */
27
28
  export declare function bundleAuthoredModuleForGeneration(modulePath: string, options?: AuthoredModuleLoadOptions): Promise<string>;
29
+ /**
30
+ * Bundles every runtime-authored module in one immutable generation graph.
31
+ * Shared dependencies are parsed and emitted once instead of once per authored
32
+ * entry.
33
+ */
34
+ export declare function bundleAuthoredModuleMapForGeneration(input: {
35
+ readonly manifest: CompiledAgentManifest;
36
+ readonly moduleMapPath: string;
37
+ }): Promise<string>;
@@ -1,4 +1,4 @@
1
- import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{createHash}from"node:crypto";import{buildWithNitroRolldown,getSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{assertNoWorkflowDirectivePrologue}from"#internal/authored-directive-prologue.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(t,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t,n):await import(createFileImportSpecifier(t)),`Expected "${t}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{channelIdentity:!1,packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function buildAuthoredModuleBundle(e,t,n){let r=n.channelIdentity?getChannelModuleCache():void 0,i=resolveAuthoredPackageRoot(e),a=resolveAuthoredTsConfigPath(i),o=[r&&r.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let i=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(i===null||typeof i.id!=`string`)return;let a=resolve(i.id);if(r.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(CACHED_CHANNEL_PREFIX.length);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
2
- `),moduleType:`js`}}}:null,...n.plugins,t.extensionScopeNamespace===void 0?null:createFixedNamespaceScopePlugin(t.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:i,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return getSingleRolldownChunk(await buildWithNitroRolldown({cwd:i,input:e,platform:`node`,plugins:o,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:a,write:!1,output:{codeSplitting:!1,comments:!1,format:`esm`,sourcemap:n.sourcemap}}),`authored module for "${e}"`).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t)||await assertNoWorkflowDirectivePrologue({filePath:t,source:e})}}}function removeRolldownModuleRegionComments(e){return e.split(`
1
+ import{expectObjectRecord}from"#internal/authored-module.js";import{existsSync,mkdirSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import{createHash}from"node:crypto";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{assertNoWorkflowDirectivePrologue}from"#internal/authored-directive-prologue.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createExtensionScopePlugin,createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";const AUTHORED_BUNDLED_MODULE_EXTENSION=/\.[cm]?[jt]sx?$/,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH=join(`node_modules`,`.cache`,`eve`,`authored-modules`),CHANNEL_MODULE_CACHE_KEY=`__eveChannelModuleCache__`;function getChannelModuleCache(){return globalThis[CHANNEL_MODULE_CACHE_KEY]}const inFlightModuleLoads=new Map;function loadAuthoredModuleNamespace(e,t={}){let n=createInFlightModuleLoadKey(resolve(e),t),r=inFlightModuleLoads.get(n);if(r!==void 0)return r;let i=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,i),i}async function doLoadAuthoredModuleNamespace(t,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)?await loadBundledAuthoredModule(t,n):await import(createFileImportSpecifier(t)),`Expected "${t}" to export a module namespace object.`)}function createFileImportSpecifier(e){let t=e.replaceAll(`\\`,`/`);return/^[A-Za-z]:\//.test(t)?`file:///${encodeURI(t)}`:t.startsWith(`/`)?`file://${encodeURI(t)}`:t}async function bundleAuthoredModuleCode(e,t={}){return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[],sourcemap:`inline`})}async function bundleAuthoredModuleForGeneration(e,t={}){return removeRolldownModuleRegionComments(await buildAuthoredModuleBundle(e,t,{channelIdentity:!1,packageBoundaryPlugin:createGenerationPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:resolveAuthoredPackageRoot(e)}),plugins:[createAuthoredDirectiveGuardPlugin()],sourcemap:!1}))}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=normalizeExternalDependencies([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.config.build?.externalDependencies??[])),r=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath}),i=createExtensionScopePlugin(e.manifest.extensionMounts.map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot}))),a=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:r}),createAuthoredDirectiveGuardPlugin(),i,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:n,packageRoot:t})].filter(e=>e!==null);try{return removeRolldownModuleRegionComments((await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:a,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}})).code)}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function createVirtualGenerationModuleMapPlugin(e){return{name:`eve-generation-module-map`,resolveId(t){return t===e.id?t:void 0},load(t){return t===e.id?{code:e.source,moduleType:`js`}:void 0}}}async function buildAuthoredModuleBundle(e,t,n){let r=n.channelIdentity?getChannelModuleCache():void 0,i=resolveAuthoredPackageRoot(e),a=resolveAuthoredTsConfigPath(i),o=[r&&r.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let i=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(i===null||typeof i.id!=`string`)return;let a=resolve(i.id);if(r.has(a))return{id:`${CACHED_CHANNEL_PREFIX}${a}`}},load(e){if(!e.startsWith(CACHED_CHANNEL_PREFIX))return;let t=e.slice(CACHED_CHANNEL_PREFIX.length);return{code:[`const cache = globalThis["${CHANNEL_MODULE_CACHE_KEY}"];`,`export default cache.get(${JSON.stringify(t)});`].join(`
2
+ `),moduleType:`js`}}}:null,...n.plugins,t.extensionScopeNamespace===void 0?null:createFixedNamespaceScopePlugin(t.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin(),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:i,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{cwd:i,input:e,platform:`node`,plugins:o,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:a,output:{comments:!1,format:`esm`,sourcemap:n.sourcemap}})).code}catch(t){throw createAuthoredModuleBundleError(e,t)}}function createAuthoredDirectiveGuardPlugin(){return{name:`eve-authored-directive-guard`,async transform(e,t){!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t)||await assertNoWorkflowDirectivePrologue({filePath:t,source:e})}}}function removeRolldownModuleRegionComments(e){return e.split(`
3
3
  `).filter(e=>!e.startsWith(`//#region `)&&e!==`//#endregion`).join(`
4
- `)}async function loadBundledAuthoredModule(e,r){let a=await bundleAuthoredModuleCode(e,r),o=normalizeExternalDependencies(r.externalDependencies),s=createHash(`sha1`).update(e).update(`\0`).update(o.join(`\0`)).update(`\0`).update(r.extensionScopeNamespace??``).update(`\0`).update(a).digest(`hex`),c=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(c,`${s}.mjs`);return existsSync(l)||(mkdirSync(c,{recursive:!0}),writeFileSync(l,a)),await import(`${createFileImportSpecifier(l)}?v=${s}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function resolveAuthoredTsConfigPath(e){for(let n of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,n);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let n=dirname(e);for(;;){if(existsSync(join(n,`package.json`)))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve the authored package root for "${e}".`);n=r}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,loadAuthoredModuleNamespace};
4
+ `)}async function loadBundledAuthoredModule(e,r){let a=await bundleAuthoredModuleCode(e,r),o=normalizeExternalDependencies(r.externalDependencies),s=createHash(`sha1`).update(e).update(`\0`).update(o.join(`\0`)).update(`\0`).update(r.extensionScopeNamespace??``).update(`\0`).update(a).digest(`hex`),c=join(resolveAuthoredPackageRoot(e),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(c,`${s}.mjs`);return existsSync(l)||(mkdirSync(c,{recursive:!0}),writeFileSync(l,a)),await import(`${createFileImportSpecifier(l)}?v=${s}`)}function createAuthoredRelativeExtensionResolverPlugin(e){return{name:`eve-authored-relative-extension-resolver`,resolveId(t,n){if(n===void 0||n.startsWith(`\0`)||n.startsWith(CACHED_CHANNEL_PREFIX)||!isPathImport(t))return;let r=resolveExistingImportPath(isAbsolute(t)?t:resolve(dirname(n),t),e.extensions);if(r!==void 0)return{id:r}}}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveExistingImportPath(e,t){if(isFile(e))return e;for(let n of t){let t=`${e}${n}`;if(isFile(t))return t}for(let n of t){let t=join(e,`index${n}`);if(isFile(t))return t}}function isFile(e){try{return statSync(e).isFile()}catch{return!1}}function resolveAuthoredTsConfigPath(e){for(let n of[`tsconfig.json`,`jsconfig.json`]){let r=join(e,n);if(existsSync(r))return r}return!1}function resolveAuthoredPackageRoot(e){let n=dirname(e);for(;;){if(existsSync(join(n,`package.json`)))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve the authored package root for "${e}".`);n=r}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,loadAuthoredModuleNamespace};
@@ -1 +1 @@
1
- import{expectObjectRecord}from"#internal/authored-module.js";import{join}from"node:path";import{collectModuleRefsForManifest}from"#compiler/module-map.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{pathToFileURL}from"node:url";const EXT_CONFIG_SCOPE=Symbol.for(`eve.ext-config-scope`);async function loadCompiledModuleMapFromAuthoredSource(e){return await hydrateCompiledModuleMapFromManifest(await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}),e.compiledArtifactsSource.appRoot)}async function hydrateCompiledModuleMapFromManifest(e,t){let n={},i=[{agentRoot:e.agentRoot,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))],a={byMountNamespace:new Map(e.extensionMounts.map(e=>[e.namespace,e.packageNamespace])),byMountSourceId:new Map(e.extensionMounts.map(e=>[e.mountSourceId,e.packageNamespace]))},s=await readMaterializedAuthoredModuleIndex(t);for(let e of i){let r=s?.nodes[e.nodeId]?.modules;if(s!==void 0&&r===void 0)throw Error(`Materialized authored module index is missing node "${e.nodeId}".`);n[e.nodeId]={modules:await hydrateCompiledNodeScope({agentRoot:e.agentRoot,manifest:e.manifest,materializedModules:r,runtimeAppRoot:t,scopeIndex:a})}}return{nodes:n}}function extensionNamespaceForSourceId(e,t){let n=e.match(/^ext:([^:]+):/);return n===null?void 0:t.byMountNamespace.get(n[1])}async function hydrateCompiledNodeScope(r){let a=collectModuleRefsForManifest(r.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),o=r.manifest.config.build?.externalDependencies??[],l=globalThis,u={};for(let n of a){let a=join(r.agentRoot,n.logicalPath),d=extensionNamespaceForSourceId(n.sourceId,r.scopeIndex),f=r.scopeIndex.byMountSourceId.get(n.sourceId);f!==void 0&&(l[EXT_CONFIG_SCOPE]=f);try{let c=r.materializedModules?.[n.sourceId];if(r.materializedModules!==void 0&&c===void 0)throw Error(`Materialized authored module index is missing source "${n.sourceId}".`);if(c!==void 0){u[n.sourceId]=expectObjectRecord(await import(`${pathToFileURL(join(r.runtimeAppRoot,`.eve`,`compile`,c)).href}?generation=${encodeURIComponent(c)}`),`Expected materialized authored module "${n.sourceId}" to export a namespace object.`);continue}u[n.sourceId]=await loadAuthoredModuleNamespace(a,{externalDependencies:o,extensionScopeNamespace:d})}finally{f!==void 0&&(l[EXT_CONFIG_SCOPE]=void 0)}}return u}export{loadCompiledModuleMapFromAuthoredSource};
1
+ import{join}from"node:path";import{collectModuleRefsForManifest,compiledModuleMapSchema}from"#compiler/module-map.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{pathToFileURL}from"node:url";import{formatValidationError}from"#runtime/validation.js";const EXT_CONFIG_SCOPE=Symbol.for(`eve.ext-config-scope`);async function loadCompiledModuleMapFromAuthoredSource(e){return await hydrateCompiledModuleMapFromManifest(await loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}),e.compiledArtifactsSource.appRoot)}async function hydrateCompiledModuleMapFromManifest(e,t){let n=await readMaterializedAuthoredModuleIndex(t);if(n!==void 0)return await loadMaterializedCompiledModuleMap({moduleMapPath:n.moduleMap,runtimeAppRoot:t});let i={},a=[{agentRoot:e.agentRoot,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))],s={byMountNamespace:new Map(e.extensionMounts.map(e=>[e.namespace,e.packageNamespace])),byMountSourceId:new Map(e.extensionMounts.map(e=>[e.mountSourceId,e.packageNamespace]))};for(let e of a)i[e.nodeId]={modules:await hydrateCompiledNodeScope({agentRoot:e.agentRoot,manifest:e.manifest,scopeIndex:s})};return{nodes:i}}async function loadMaterializedCompiledModuleMap(t){let r=join(t.runtimeAppRoot,`.eve`,`compile`,t.moduleMapPath),i=await import(`${pathToFileURL(r).href}?generation=${encodeURIComponent(t.moduleMapPath)}`),a=compiledModuleMapSchema.safeParse(i.moduleMap??i.default);if(!a.success)throw Error(`Expected materialized authored module map "${r}" to export a valid compiled eve module map. ${formatValidationError(a.error)}`);return a.data}function extensionNamespaceForSourceId(e,t){let n=e.match(/^ext:([^:]+):/);return n===null?void 0:t.byMountNamespace.get(n[1])}async function hydrateCompiledNodeScope(n){let r=collectModuleRefsForManifest(n.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),a=n.manifest.config.build?.externalDependencies??[],o=globalThis,s={};for(let t of r){let r=join(n.agentRoot,t.logicalPath),c=extensionNamespaceForSourceId(t.sourceId,n.scopeIndex),l=n.scopeIndex.byMountSourceId.get(t.sourceId);l!==void 0&&(o[EXT_CONFIG_SCOPE]=l);try{s[t.sourceId]=await loadAuthoredModuleNamespace(r,{externalDependencies:a,extensionScopeNamespace:c})}finally{l!==void 0&&(o[EXT_CONFIG_SCOPE]=void 0)}}return s}export{loadCompiledModuleMapFromAuthoredSource};
@@ -11,7 +11,6 @@ type RolldownOutputAsset = {
11
11
  type RolldownOutput = {
12
12
  readonly output: readonly [RolldownOutputChunk, ...(RolldownOutputChunk | RolldownOutputAsset)[]];
13
13
  };
14
- export type RolldownBuild = (options: Record<string, unknown>) => Promise<RolldownOutput>;
15
14
  type RolldownParseAst = (sourceText: string, options?: Record<string, unknown> | null, filename?: string) => unknown;
16
15
  export type RolldownParserLanguage = "js" | "jsx" | "ts" | "tsx";
17
16
  type RolldownParseAstModule = {
@@ -24,6 +23,23 @@ type RolldownParseAstModule = {
24
23
  export declare function loadNitroRolldownParseAst(): Promise<RolldownParseAstModule>;
25
24
  export declare function inferRolldownParserLanguage(filename: string): RolldownParserLanguage;
26
25
  export declare function parseWithNitroRolldownAst(filename: string, sourceText: string): Promise<unknown>;
26
+ /**
27
+ * Runs a raw Rolldown build. Prefer {@link buildSingleRolldownChunk} for any
28
+ * bundle whose consumer expects one in-memory file; use this directly only
29
+ * for multi-file, written-to-disk output.
30
+ */
27
31
  export declare function buildWithNitroRolldown(options: Record<string, unknown>): Promise<RolldownOutput>;
28
- export declare function getSingleRolldownChunk(output: RolldownOutput, description: string): RolldownOutputChunk;
32
+ /**
33
+ * Runs a Rolldown build whose contract is exactly one in-memory chunk:
34
+ * code splitting is disabled and the result is asserted to contain a
35
+ * single JavaScript chunk, so dynamic imports are inlined rather than
36
+ * split into lazy chunks. Every eve single-file bundle (the authored-module
37
+ * evaluator, immutable development generations, and workflow step/function
38
+ * bundles) goes through this helper so the single-file policy and its
39
+ * assertion cannot drift apart. The final Nitro production server build
40
+ * does not use it and keeps code splitting enabled.
41
+ */
42
+ export declare function buildSingleRolldownChunk(description: string, options: Record<string, unknown> & {
43
+ readonly output?: Record<string, unknown>;
44
+ }): Promise<RolldownOutputChunk>;
29
45
  export {};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{pathToFileURL}from"node:url";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown`)).href))(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`)).href))(),rolldownParseAstPromise}function inferRolldownParserLanguage(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}async function parseWithNitroRolldownAst(e,t){let{parseAst:n}=await loadNitroRolldownParseAst();return n(t,{astType:`ts`,lang:inferRolldownParserLanguage(e),range:!0,sourceType:`module`},e)}async function buildWithNitroRolldown(e){let{build:t}=await loadNitroRolldown();return await t(e)}function getSingleRolldownChunk(e,t){let n=e.output.filter(e=>e.type===`chunk`),r=n[0];if(r===void 0||n.length!==1)throw Error(`Expected one bundled ${t}.`);return r}export{buildWithNitroRolldown,getSingleRolldownChunk,inferRolldownParserLanguage,loadNitroRolldownParseAst,parseWithNitroRolldownAst};
1
+ import{createRequire}from"node:module";import{pathToFileURL}from"node:url";let rolldownPromise,rolldownParseAstPromise;function loadNitroRolldown(){return rolldownPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown`)).href))(),rolldownPromise}function loadNitroRolldownParseAst(){return rolldownParseAstPromise??=(async()=>await import(pathToFileURL(createRequire(createRequire(import.meta.url).resolve(`nitro/package.json`)).resolve(`rolldown/parseAst`)).href))(),rolldownParseAstPromise}function inferRolldownParserLanguage(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}async function parseWithNitroRolldownAst(e,t){let{parseAst:n}=await loadNitroRolldownParseAst();return n(t,{astType:`ts`,lang:inferRolldownParserLanguage(e),range:!0,sourceType:`module`},e)}async function buildWithNitroRolldown(e){let{build:t}=await loadNitroRolldown();return await t(e)}async function buildSingleRolldownChunk(e,t){return getSingleRolldownChunk(await buildWithNitroRolldown({...t,write:!1,output:{...t.output,codeSplitting:!1}}),e)}function getSingleRolldownChunk(e,t){let n=e.output.filter(e=>e.type===`chunk`),r=n[0];if(r===void 0||n.length!==1)throw Error(`Expected one bundled ${t}.`);return r}export{buildSingleRolldownChunk,buildWithNitroRolldown,inferRolldownParserLanguage,loadNitroRolldownParseAst,parseWithNitroRolldownAst};
@@ -1,10 +1,8 @@
1
1
  export interface MaterializedAuthoredModuleIndex {
2
2
  readonly fingerprint: string;
3
3
  readonly instrumentation?: string;
4
- readonly nodes: Readonly<Record<string, {
5
- readonly modules: Readonly<Record<string, string>>;
6
- }>>;
7
- readonly version: 1;
4
+ readonly moduleMap: string;
5
+ readonly version: 2;
8
6
  }
9
7
  export declare function materializeAuthoredModules(input: {
10
8
  readonly runtimeAppRoot: string;
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{join,relative,sep}from"node:path";import{lstat,mkdir,readFile,readdir,readlink,writeFile}from"node:fs/promises";import{createHash}from"node:crypto";import{collectModuleRefsForManifest}from"#compiler/module-map.js";import{COMPILED_AGENT_MANIFEST_KIND,ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{bundleAuthoredModuleForGeneration}from"#internal/authored-module-loader.js";import{serializeCompiledManifestForFingerprint}from"#internal/compiled-manifest-fingerprint.js";const MATERIALIZED_MODULES_DIRECTORY=`authored-modules`,MATERIALIZED_MODULES_INDEX=`authored-modules.json`,INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];async function materializeAuthoredModules(e){let n=join(e.runtimeAppRoot,`.eve`,`compile`),r=await readCompiledManifest(join(n,`compiled-agent-manifest.json`)),i=join(n,MATERIALIZED_MODULES_DIRECTORY),o=createExtensionScopeIndex(r),s={},c=createHash(`sha256`);await mkdir(i,{recursive:!0}),c.update(`manifest\0`).update(serializeCompiledManifestForFingerprint({manifest:r,runtimeAppRoot:e.runtimeAppRoot})).update(`\0`);for(let e of collectNodeManifests(r)){let n={};for(let r of collectModuleRefsForManifest(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId))){let a=await bundleAuthoredModuleForGeneration(join(e.agentRoot,r.logicalPath),{externalDependencies:e.manifest.config.build?.externalDependencies??[],extensionScopeNamespace:extensionNamespaceForSourceId(r.sourceId,o)}),s=createMaterializedModuleFileName(e.nodeId,r.sourceId,a);await writeFile(join(i,s),a),c.update(`module\0`).update(e.nodeId).update(`\0`).update(r.sourceId).update(`\0`).update(a).update(`\0`),n[r.sourceId]=join(MATERIALIZED_MODULES_DIRECTORY,s)}s[e.nodeId]={modules:n}}let u=resolveInstrumentationModule(r.agentRoot),d;if(u!==void 0){let e=await bundleAuthoredModuleForGeneration(u,{externalDependencies:r.config.build?.externalDependencies??[]}),n=createMaterializedModuleFileName(ROOT_COMPILED_AGENT_NODE_ID,`instrumentation`,e);await writeFile(join(i,n),e),d=join(MATERIALIZED_MODULES_DIRECTORY,n),c.update(`instrumentation\0`).update(e).update(`\0`)}await hashDirectoryIfPresent({fingerprint:c,path:join(n,`workspace-resources`),root:join(n,`workspace-resources`)});let f={fingerprint:c.digest(`hex`),nodes:s,version:1};return d!==void 0&&(f.instrumentation=d),await writeFile(join(n,MATERIALIZED_MODULES_INDEX),`${JSON.stringify(f)}\n`),f}async function readMaterializedAuthoredModuleIndex(n){let r=join(n,`.eve`,`compile`,MATERIALIZED_MODULES_INDEX);if(!existsSync(r))return;let i=JSON.parse(await readFile(r,`utf8`));if(i.version!==1||typeof i.fingerprint!=`string`||i.fingerprint.length===0||typeof i.nodes!=`object`||i.nodes===null||i.instrumentation!==void 0&&typeof i.instrumentation!=`string`)throw Error(`Invalid materialized authored module index at "${r}".`);return i}function collectNodeManifests(e){return[{agentRoot:e.agentRoot,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))]}function createExtensionScopeIndex(e){return{byMountNamespace:new Map(e.extensionMounts.map(e=>[e.namespace,e.packageNamespace]))}}function extensionNamespaceForSourceId(e,t){let n=e.match(/^ext:([^:]+):/u);return n===null?void 0:t.byMountNamespace.get(n[1])}async function readCompiledManifest(e){let t=JSON.parse(await readFile(e,`utf8`));if(t.kind!==COMPILED_AGENT_MANIFEST_KIND)throw Error(`Invalid compiled agent manifest at "${e}".`);return t}function resolveInstrumentationModule(n){for(let r of INSTRUMENTATION_EXTENSIONS){let i=join(n,`instrumentation${r}`);if(existsSync(i))return i}}function createMaterializedModuleFileName(e,t,n){return`${createHash(`sha256`).update(e).update(`\0`).update(t).update(`\0`).update(n).digest(`hex`)}.mjs`}async function hashDirectoryIfPresent(r){if(!existsSync(r.path))return;let a=await lstat(r.path),l=toPortablePath(relative(r.root,r.path));if(a.isSymbolicLink()){r.fingerprint.update(l).update(`\0link\0`).update(await readlink(r.path)).update(`\0`);return}if(a.isDirectory()){for(let e of(await readdir(r.path)).sort())await hashDirectoryIfPresent({...r,path:join(r.path,e)});return}a.isFile()&&r.fingerprint.update(l).update(`\0file\0`).update(await readFile(r.path)).update(`\0`)}function toPortablePath(e){return e.split(sep).join(`/`)}export{materializeAuthoredModules,readMaterializedAuthoredModuleIndex};
1
+ import{existsSync}from"node:fs";import{join,relative,sep}from"node:path";import{lstat,mkdir,readFile,readdir,readlink,writeFile}from"node:fs/promises";import{createHash}from"node:crypto";import{COMPILED_AGENT_MANIFEST_KIND,ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration}from"#internal/authored-module-loader.js";import{serializeCompiledManifestForFingerprint}from"#internal/compiled-manifest-fingerprint.js";const MATERIALIZED_MODULES_DIRECTORY=`authored-modules`,MATERIALIZED_MODULES_INDEX=`authored-modules.json`,INSTRUMENTATION_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`];async function materializeAuthoredModules(e){let n=join(e.runtimeAppRoot,`.eve`,`compile`),r=await readCompiledManifest(join(n,`compiled-agent-manifest.json`)),i=join(n,MATERIALIZED_MODULES_DIRECTORY),o=createHash(`sha256`);await mkdir(i,{recursive:!0}),o.update(`manifest\0`).update(serializeCompiledManifestForFingerprint({manifest:r,runtimeAppRoot:e.runtimeAppRoot})).update(`\0`);let s=await bundleAuthoredModuleMapForGeneration({manifest:r,moduleMapPath:join(n,`module-map.mjs`)}),c=createMaterializedModuleFileName(ROOT_COMPILED_AGENT_NODE_ID,`module-map`,s),u=join(MATERIALIZED_MODULES_DIRECTORY,c);await writeFile(join(i,c),s),o.update(`module-map\0`).update(s).update(`\0`);let d=resolveInstrumentationModule(r.agentRoot),f;if(d!==void 0){let e=await bundleAuthoredModuleForGeneration(d,{externalDependencies:r.config.build?.externalDependencies??[]}),n=createMaterializedModuleFileName(ROOT_COMPILED_AGENT_NODE_ID,`instrumentation`,e);await writeFile(join(i,n),e),f=join(MATERIALIZED_MODULES_DIRECTORY,n),o.update(`instrumentation\0`).update(e).update(`\0`)}await hashDirectoryIfPresent({fingerprint:o,path:join(n,`workspace-resources`),root:join(n,`workspace-resources`)});let p={fingerprint:o.digest(`hex`),moduleMap:u,version:2};return f!==void 0&&(p.instrumentation=f),await writeFile(join(n,MATERIALIZED_MODULES_INDEX),`${JSON.stringify(p)}\n`),p}async function readMaterializedAuthoredModuleIndex(n){let r=join(n,`.eve`,`compile`,MATERIALIZED_MODULES_INDEX);if(!existsSync(r))return;let i=JSON.parse(await readFile(r,`utf8`));if(i.version!==2||typeof i.fingerprint!=`string`||i.fingerprint.length===0||typeof i.moduleMap!=`string`||i.moduleMap.length===0||i.instrumentation!==void 0&&typeof i.instrumentation!=`string`)throw Error(`Invalid materialized authored module index at "${r}".`);return i}async function readCompiledManifest(e){let t=JSON.parse(await readFile(e,`utf8`));if(t.kind!==COMPILED_AGENT_MANIFEST_KIND)throw Error(`Invalid compiled agent manifest at "${e}".`);return t}function resolveInstrumentationModule(n){for(let r of INSTRUMENTATION_EXTENSIONS){let i=join(n,`instrumentation${r}`);if(existsSync(i))return i}}function createMaterializedModuleFileName(e,t,n){return`${createHash(`sha256`).update(e).update(`\0`).update(t).update(`\0`).update(n).digest(`hex`)}.mjs`}async function hashDirectoryIfPresent(r){if(!existsSync(r.path))return;let a=await lstat(r.path),l=toPortablePath(relative(r.root,r.path));if(a.isSymbolicLink()){r.fingerprint.update(l).update(`\0link\0`).update(await readlink(r.path)).update(`\0`);return}if(a.isDirectory()){for(let e of(await readdir(r.path)).sort())await hashDirectoryIfPresent({...r,path:join(r.path,e)});return}a.isFile()&&r.fingerprint.update(l).update(`\0file\0`).update(await readFile(r.path)).update(`\0`)}function toPortablePath(e){return e.split(sep).join(`/`)}export{materializeAuthoredModules,readMaterializedAuthoredModuleIndex};
@@ -1 +1 @@
1
- import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{createDevelopmentSourceSnapshotPlan}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY=`dev-runtime`;function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`current.json`)}function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`snapshots`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),n=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(n),a=await readOptionalFile(n);try{await writeFile(t,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:t,pointerPath:n,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:t,pointerPath:n,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(!(t===void 0||t.version===1))return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function readDevelopmentRuntimeArtifactsPointer(n){if(!(n===void 0||!existsSync(n)))try{let e=JSON.parse(readFileSync(n,`utf8`));return e.kind!==`eve-dev-runtime-artifacts-pointer`||typeof e.version!=`number`?void 0:e.version===1&&typeof e.appRoot==`string`&&e.appRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:e.version===2&&typeof e.appRoot==`string`&&typeof e.runtimeAppRoot==`string`&&e.runtimeAppRoot.length>0&&typeof e.snapshotRoot==`string`&&e.snapshotRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.runtimeAppRoot,snapshotRoot:e.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:t});await writeFile(e.manifestPath,`${JSON.stringify(n,null,2)}\n`)}function rewriteManifestRoots(e){if(Array.isArray(e.value))return e.value.map(t=>rewriteManifestRoots({...e,value:t}));if(e.value===null||typeof e.value!=`object`)return e.value;let t={};for(let[n,r]of Object.entries(e.value)){if(typeof r==`string`&&(n===`appRoot`||n===`agentRoot`)){t[n]=rewritePathWithinAppRoot({appRoot:e.appRoot,path:r,runtimeAppRoot:e.runtimeAppRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,value:r})}return t}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot))return e.path;let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let r=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(r,t);try{await renameWithTransientBusyRetry(r,e)}catch(e){throw await rm(r,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.runtimeAppRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime app root "${e.runtimeAppRoot}".`)}function collectManifestRootPaths(e){if(Array.isArray(e))return e.flatMap(e=>collectManifestRootPaths(e));if(typeof e!=`object`||!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if((n===`appRoot`||n===`agentRoot`)&&typeof r==`string`){t.push(r);continue}t.push(...collectManifestRootPaths(r))}return t}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{activateDevelopmentRuntimeArtifactsSnapshot,activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
1
+ import{existsSync,readFileSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,mkdir,readFile,rm,writeFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{renameWithTransientBusyRetry}from"#shared/rename-with-retry.js";import{copyDevelopmentSourceSnapshot}from"#internal/nitro/dev-runtime-source-snapshot-copy.js";import{createDevelopmentSourceSnapshotPlan,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER,pruneDevelopmentRuntimeArtifactsSnapshotDirectory,recordRetiredDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts-retention.js";const DEV_RUNTIME_ARTIFACTS_DIRECTORY=`dev-runtime`;function resolveDevelopmentRuntimeArtifactsPointerPath(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`current.json`)}function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e){return join(e,`.eve`,DEV_RUNTIME_ARTIFACTS_DIRECTORY,`snapshots`)}function isDevelopmentRuntimeArtifactsSnapshotRoot(e,t){return dirname(resolve(t))===resolve(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e))}async function stageDevelopmentRuntimeArtifactsSnapshot(e){let t=join(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.project.appRoot),`${Date.now().toString(36)}-${randomUUID()}`),n=await createDevelopmentSourceSnapshotPlan({appRoot:e.project.appRoot,snapshotRoot:t});try{await copyDevelopmentSourceSnapshot(n),await cp(e.paths.compileDirectoryPath,join(n.runtimeAppRoot,`.eve`,`compile`),{recursive:!0}),await rewriteSnapshotCompiledManifest({appRoot:e.project.appRoot,manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}),await validateSnapshotCompiledManifestRoots({manifestPath:join(n.runtimeAppRoot,`.eve`,`compile`,`compiled-agent-manifest.json`),runtimeAppRoot:n.runtimeAppRoot}),await writeFile(join(t,`generation.json`),`${JSON.stringify({runtimeAppRoot:n.runtimeAppRoot})}\n`)}catch(e){throw await rm(t,{force:!0,recursive:!0}).catch(()=>{}),e}return{runtimeAppRoot:n.runtimeAppRoot,snapshotRoot:t,snapshotSourceRoot:n.snapshotSourceRoot,sourceRoot:n.sourceRoot}}async function activateDevelopmentRuntimeArtifactsSnapshot(e){(await activateDevelopmentRuntimeArtifactsSnapshotTransaction(e)).commit()}async function activateDevelopmentRuntimeArtifactsSnapshotTransaction(e){let t=join(e.snapshot.snapshotRoot,DEVELOPMENT_RUNTIME_ARTIFACTS_ACTIVATED_MARKER),n=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),i=readDevelopmentRuntimeArtifactsPointer(n),a=await readOptionalFile(n);try{await writeFile(t,``),await writeDevelopmentRuntimeArtifactsPointer(e),i?.version===2&&i.snapshotRoot!==e.snapshot.snapshotRoot&&isDevelopmentRuntimeArtifactsSnapshotRoot(e.appRoot,i.snapshotRoot)&&await recordRetiredDevelopmentRuntimeArtifactsSnapshot(i.snapshotRoot).catch(e=>{console.warn(`[eve:dev] failed to record retired runtime generation "${i.snapshotRoot}": ${String(e)}`)})}catch(e){throw await rollbackFailedActivation({cause:e,markerPath:t,pointerPath:n,previousPointerSource:a})}let o=!1;return{commit(){o=!0},async rollback(){if(o)return;o=!0;let e=await restoreDevelopmentRuntimeArtifactsActivation({markerPath:t,pointerPath:n,previousPointerSource:a});if(e!==void 0)throw e}}}function readDevelopmentRuntimeArtifactsSnapshotRoot(e){let t=readDevelopmentRuntimeArtifactsPointer(e);if(t!==void 0)return t.version===1?t.appRoot:t.runtimeAppRoot}function readActiveDevelopmentRuntimeArtifactsSnapshot(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e));if(!(t===void 0||t.version===1))return{runtimeAppRoot:t.runtimeAppRoot,snapshotRoot:t.snapshotRoot}}function readDevelopmentRuntimeArtifactsRevision(e){return{revision:readDevelopmentRuntimeArtifactsSnapshotRoot(resolveDevelopmentRuntimeArtifactsPointerPath(e))??e}}async function pruneDevelopmentRuntimeArtifactsSnapshots(e){let t=readDevelopmentRuntimeArtifactsPointer(resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot));await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({activeSnapshotRoot:t?.version===2?t.snapshotRoot:void 0,gracePeriodMs:e.gracePeriodMs,now:e.now,protectAll:t?.version===1,retainCount:e.retainCount,snapshotsDirectory:resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(e.appRoot)})}function readDevelopmentRuntimeArtifactsPointer(n){if(!(n===void 0||!existsSync(n)))try{let e=JSON.parse(readFileSync(n,`utf8`));return e.kind!==`eve-dev-runtime-artifacts-pointer`||typeof e.version!=`number`?void 0:e.version===1&&typeof e.appRoot==`string`&&e.appRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,version:1}:e.version===2&&typeof e.appRoot==`string`&&typeof e.runtimeAppRoot==`string`&&e.runtimeAppRoot.length>0&&typeof e.snapshotRoot==`string`&&e.snapshotRoot.length>0?{appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.runtimeAppRoot,snapshotRoot:e.snapshotRoot,version:2}:void 0}catch{return}}async function rewriteSnapshotCompiledManifest(e){let t=JSON.parse(await readFile(e.manifestPath,`utf8`)),n=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t});await writeFile(e.manifestPath,`${JSON.stringify(n,null,2)}\n`)}function rewriteManifestRoots(e){if(Array.isArray(e.value))return e.value.map(t=>rewriteManifestRoots({...e,value:t}));if(e.value===null||typeof e.value!=`object`)return e.value;let t={};for(let[n,r]of Object.entries(e.value)){if(typeof r==`string`&&(n===`appRoot`||n===`agentRoot`)){t[n]=rewritePathWithinAppRoot({appRoot:e.appRoot,path:r,runtimeAppRoot:e.runtimeAppRoot});continue}if(typeof r==`string`&&n===`sourceRoot`){t[n]=rewritePathWithinSourceRoot({path:r,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot});continue}t[n]=rewriteManifestRoots({appRoot:e.appRoot,runtimeAppRoot:e.runtimeAppRoot,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:r})}return t}function rewritePathWithinSourceRoot(e){return isPathInsideOrEqual(e.path,e.sourceRoot)?toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:e.path,sourceRoot:e.sourceRoot}):e.path}function rewritePathWithinAppRoot(e){if(!isPathInsideOrEqual(e.path,e.appRoot))return e.path;let t=relative(e.appRoot,e.path);return t.length===0?e.runtimeAppRoot:join(e.runtimeAppRoot,t)}async function writeDevelopmentRuntimeArtifactsPointer(e){let t=resolveDevelopmentRuntimeArtifactsPointerPath(e.appRoot),n={appRoot:e.appRoot,kind:`eve-dev-runtime-artifacts-pointer`,runtimeAppRoot:e.snapshot.runtimeAppRoot,snapshotRoot:e.snapshot.snapshotRoot,version:2};await writeDevelopmentRuntimeArtifactsPointerSource(t,`${JSON.stringify(n,null,2)}\n`)}async function writeDevelopmentRuntimeArtifactsPointerSource(e,t){let r=`${e}.${randomUUID()}.tmp`;await mkdir(dirname(e),{recursive:!0}),await writeFile(r,t);try{await renameWithTransientBusyRetry(r,e)}catch(e){throw await rm(r,{force:!0}).catch(()=>{}),e}}async function readOptionalFile(e){try{return await readFile(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}async function rollbackFailedActivation(e){let t=await restoreDevelopmentRuntimeArtifactsActivation(e);return t===void 0?e.cause:AggregateError([e.cause,t],`Development runtime activation and rollback failed.`,{cause:e.cause})}async function restoreDevelopmentRuntimeArtifactsActivation(e){let t=(await Promise.allSettled([e.previousPointerSource===void 0?rm(e.pointerPath,{force:!0}):writeDevelopmentRuntimeArtifactsPointerSource(e.pointerPath,e.previousPointerSource),rm(e.markerPath,{force:!0})])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length!==0)return AggregateError(t,`Failed to restore development runtime activation.`)}async function validateSnapshotCompiledManifestRoots(e){let t=collectManifestRootPaths(JSON.parse(await readFile(e.manifestPath,`utf8`)));for(let n of t)if(!isPathInsideOrEqual(n,e.runtimeAppRoot))throw Error(`Development runtime snapshot manifest root "${n}" is outside runtime app root "${e.runtimeAppRoot}".`)}function collectManifestRootPaths(e){if(Array.isArray(e))return e.flatMap(e=>collectManifestRootPaths(e));if(typeof e!=`object`||!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if((n===`appRoot`||n===`agentRoot`)&&typeof r==`string`){t.push(r);continue}t.push(...collectManifestRootPaths(r))}return t}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{activateDevelopmentRuntimeArtifactsSnapshot,activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,readActiveDevelopmentRuntimeArtifactsSnapshot,readDevelopmentRuntimeArtifactsRevision,readDevelopmentRuntimeArtifactsSnapshotRoot,resolveDevelopmentRuntimeArtifactsPointerPath,stageDevelopmentRuntimeArtifactsSnapshot};
@@ -1 +1 @@
1
- import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,n){let i=relative(e.sourceRoot,n);return i.length===0?!1:i.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(n,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:n})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
1
+ import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,n){let i=relative(e.sourceRoot,n);return i.length===0?!1:i.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(n,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:n})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
@@ -1 +1 @@
1
- import{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,join,resolve}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{resolveDiscoveryProject}from"#discover/project.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{RecoverablePublicationError,publishApplicationBuildArtifacts}from"#internal/application/output-publication.js";import{stageProductionCompilerArtifacts}from"#internal/application/production-compiler-artifacts.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{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{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";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let a=Array.from(new Set([resolve(e),resolve(t)])),s=await findClosestVercelOutputDirectory(e);if(s!==void 0)try{let e=JSON.parse(await readFile(join(s,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:await resolveVercelOutputConfigRoot(s),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let c=e;for(;;){for(let e of[join(c,`vercel.json`),join(c,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),r=resolveCoDeployedEveServicePrefix({appRoots:a,configRoot:e.endsWith(`vercel.json`)?c:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(r!==void 0)return r}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(c);if(e===c)return;c=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime:r})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareEveVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeEveVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t,n){let i=await createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n});try{return await buildNitroOutput(i)}finally{await i.close()}}async function buildApplication(e,t){let n=await tryReadExtensionBuildConfig(e);if(n!==null)throw Error(`Package "${n.packageName}" is an eve extension. Run \`eve extension build\` instead of \`eve build\`.`);let r=await createApplicationBuildWorkspace((await resolveDiscoveryProject(e)).appRoot,t.vercelServiceOutput?.serviceOutputDirectory),i=!1;try{return await buildApplicationInWorkspace(r,t)}catch(e){throw i=e instanceof RecoverablePublicationError,e}finally{i||await removeApplicationBuildWorkspace(r)}}async function buildApplicationInWorkspace(e,n){let i=await prepareProductionApplicationHost(e);if(!process.env.VERCEL){let t=await createProductionApplicationNitro(i,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`});try{await buildNitroOutput(t),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath}),await stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir})}finally{await t.close()}return await publishCompletedApplicationBuild(e),e.publication.output.finalDir}let a=await resolveCoDeployedEveServicePrefixForVercelFunctionOutput(i.appRoot,i.compileResult.project.agentRoot),o=await createProductionApplicationNitro(i,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`});try{await buildNitroOutput(o),n.skipVercelSandboxPrewarm||await 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)}});let r=await buildVercelNitroSurface(i,e,`flow`);await emitVercelWorkflowFunctions({agentName:i.compileResult.manifest.config.name,appRoot:i.appRoot,compiledArtifactsBootstrapPath:i.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e.publication.output.stagedDir,workflowBuildDir:e.workflow.buildDir}),a!==void 0&&await normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:a}),n.vercelServiceOutput!==void 0&&await copyHostMiddlewareFunctions({hostOutputDirectory:n.vercelServiceOutput.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir}),await emitVercelAgentSummary({manifest:i.compileResult.manifest,outputPath:e.publication.summary.stagedPath})}finally{await o.close()}return await 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{resolvePackageRoot,resolvePackageSourceFilePath}from"#internal/application/package.js";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";import{readFile}from"node:fs/promises";import{toErrorMessage}from"#shared/errors.js";import{resolveDiscoveryProject}from"#discover/project.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{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{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{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";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)}`)}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServiceRoot(e,t){return typeof t.root==`string`&&t.root.trim().length>0?resolve(e,t.root):normalizeEntrypoint(e,t.entrypoint)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function normalizeServiceCollection(e){if(isRecord(e))return Object.values(e).filter(isRecord);if(Array.isArray(e))return e.filter(isRecord)}function resolveCoDeployedEveServicePrefix(e){if(!isRecord(e.config))return;let t=normalizeServiceCollection(e.config.experimentalServices)??normalizeServiceCollection(e.config.experimentalServicesV2)??normalizeServiceCollection(e.config.services);if(t===void 0)return;let n=!1,r;for(let i of t){if(i.framework!==`eve`){n=!0;continue}let t=normalizeServiceRoot(e.configRoot,i),a=normalizeServicePrefix(i);t!==null&&e.appRoots.includes(t)&&a.length>0&&a!==`/`&&(r=a)}return n?r:void 0}async function resolveCoDeployedEveServicePrefixForVercelFunctionOutput(e,t){let r=Array.from(new Set([resolve(e),resolve(t)])),a=await findClosestVercelOutputDirectory(e);if(a!==void 0)try{let e=JSON.parse(await readFile(join(a,`config.json`),`utf8`)),t=resolveCoDeployedEveServicePrefix({appRoots:r,configRoot:await resolveVercelOutputConfigRoot(a),config:e});if(t!==void 0)return t}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let s=e;for(;;){for(let e of[join(s,`vercel.json`),join(s,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),i=resolveCoDeployedEveServicePrefix({appRoots:r,configRoot:e.endsWith(`vercel.json`)?s:await resolveVercelOutputConfigRoot(dirname(e)),config:t});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let e=dirname(s);if(e===s)return;s=e}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function resolveVercelOutputConfigRoot(e){let t=dirname(dirname(e));try{let e=JSON.parse(await readFile(join(t,`.vercel`,`project.json`),`utf8`));if(isRecord(e)&&isRecord(e.settings)&&typeof e.settings.rootDirectory==`string`&&e.settings.rootDirectory.trim().length>0)return resolve(t,e.settings.rootDirectory)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}return t}async function emitVercelWorkflowFunctions(t){let n=new WorkflowBundleBuilder({agentName:t.agentName,appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifactsBootstrapPath,outDir:t.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),r=await readVercelServerRuntime(t.outputDir);await n.buildVercelOutput({flowNitroOutputDir:t.flowNitroOutputDir,outputDir:t.outputDir,runtime: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 buildVercelNitroSurface(e,t,n,r){let a=`nitro.${n}`,o=await measureBuildPhase(r,`${a}.create`,()=>createProductionApplicationNitro(e,{buildDir:join(t.nitro.buildDir,n),outputDir:join(t.nitro.surfaceOutputDir,n),surface:n}));try{return await buildNitroOutput(o,r,a)}finally{await measureBuildPhase(r,`${a}.close`,()=>o.close())}}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 a=await measureBuildPhase(r,`host.prepare`,()=>prepareProductionApplicationHost(e));if(!process.env.VERCEL){let t=await measureBuildPhase(r,`nitro.all.create`,()=>createProductionApplicationNitro(a,{buildDir:e.nitro.buildDir,outputDir:e.publication.output.stagedDir,surface:`all`}));try{await buildNitroOutput(t,r,`nitro.all`),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:a.compileResult.manifest,outputPath:e.publication.summary.stagedPath})),await measureBuildPhase(r,`compiler-artifacts.stage`,()=>stageProductionCompilerArtifacts({compilerArtifactsRoot:e.compiler.artifactsDir,outputDir:e.publication.output.stagedDir}))}finally{await measureBuildPhase(r,`nitro.all.close`,()=>t.close())}return await measureBuildPhase(r,`output.publish`,()=>publishCompletedApplicationBuild(e)),e.publication.output.finalDir}let o=await measureBuildPhase(r,`vercel.service-prefix.resolve`,()=>resolveCoDeployedEveServicePrefixForVercelFunctionOutput(a.appRoot,a.compileResult.project.agentRoot)),s=await measureBuildPhase(r,`nitro.app.create`,()=>createProductionApplicationNitro(a,{buildDir:join(e.nitro.buildDir,`app`),outputDir:e.publication.output.stagedDir,surface:`app`}));try{await buildNitroOutput(s,r,`nitro.app`),n.skipVercelSandboxPrewarm||await measureBuildPhase(r,`sandbox.prewarm`,()=>runVercelBuildPrewarm({appRoot:a.appRoot,compiledArtifactsSource:createDiskRuntimeCompiledArtifactsSource(e.compiler.rootDir,{moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`),sandboxAppRoot:a.appRoot}),log(e){console.log(e)}}));let i=await buildVercelNitroSurface(a,e,`flow`,r);await measureBuildPhase(r,`workflow.emit`,()=>emitVercelWorkflowFunctions({agentName:a.compileResult.manifest.config.name,appRoot:a.appRoot,compiledArtifactsBootstrapPath:a.compiledArtifacts.bootstrapPath,flowNitroOutputDir:i,outputDir:e.publication.output.stagedDir,workflowBuildDir:e.workflow.buildDir})),o!==void 0&&await measureBuildPhase(r,`vercel.functions.normalize`,()=>normalizeEveVercelFunctionOutput(e.publication.output.stagedDir,{servicePrefix:o}));let c=n.vercelServiceOutput;c!==void 0&&await measureBuildPhase(r,`vercel.host-middleware.copy`,()=>copyHostMiddlewareFunctions({hostOutputDirectory:c.hostOutputDirectory,serviceOutputDirectory:e.publication.output.stagedDir})),await measureBuildPhase(r,`agent-summary.emit`,()=>emitVercelAgentSummary({manifest:a.compileResult.manifest,outputPath:e.publication.summary.stagedPath}))}finally{await measureBuildPhase(r,`nitro.app.close`,()=>s.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};