eve 0.47.7 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/src/channel/delivery-metadata.d.ts +1 -0
  3. package/dist/src/channel/delivery-metadata.js +1 -1
  4. package/dist/src/channel/types.d.ts +10 -8
  5. package/dist/src/chunks/{use-eve-agent-Dg5S44kG.js → use-eve-agent-BZnOzAVd.js} +25 -5
  6. package/dist/src/chunks/{use-eve-agent-B5zw1dwj.js → use-eve-agent-Bgp6INfi.js} +25 -5
  7. package/dist/src/cli/commands/init.js +1 -1
  8. package/dist/src/cli/commands/integration-connect.d.ts +2 -1
  9. package/dist/src/cli/commands/integration-connect.js +1 -1
  10. package/dist/src/cli/commands/register-integration-commands.d.ts +3 -1
  11. package/dist/src/cli/commands/register-integration-commands.js +1 -1
  12. package/dist/src/cli/dev/command-options.d.ts +2 -0
  13. package/dist/src/cli/dev/run-interactive-ui.js +1 -1
  14. package/dist/src/cli/dev/tui/blocks.js +1 -1
  15. package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
  16. package/dist/src/cli/dev/tui/registry-result-message.d.ts +17 -0
  17. package/dist/src/cli/dev/tui/registry-result-message.js +3 -0
  18. package/dist/src/cli/dev/tui/runner.d.ts +11 -4
  19. package/dist/src/cli/dev/tui/runner.js +1 -1
  20. package/dist/src/cli/dev/tui/setup-commands.d.ts +9 -3
  21. package/dist/src/cli/dev/tui/setup-commands.js +2 -3
  22. package/dist/src/cli/dev/tui/setup-flow.d.ts +15 -5
  23. package/dist/src/cli/dev/tui/setup-panel.d.ts +6 -1
  24. package/dist/src/cli/dev/tui/setup-panel.js +4 -4
  25. package/dist/src/cli/dev/tui/setup-selection-input.d.ts +1 -0
  26. package/dist/src/cli/dev/tui/setup-selection-input.js +1 -1
  27. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  28. package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
  29. package/dist/src/cli/dev/tui/tui.d.ts +3 -4
  30. package/dist/src/cli/dev/tui/tui.js +1 -1
  31. package/dist/src/cli/run.js +2 -2
  32. package/dist/src/client/agent-info-schema.d.ts +1 -0
  33. package/dist/src/client/agent-info-schema.js +1 -1
  34. package/dist/src/client/open-stream.d.ts +1 -0
  35. package/dist/src/client/open-stream.js +1 -1
  36. package/dist/src/client/session.js +1 -1
  37. package/dist/src/compiled/.vendor-stamp.json +2 -1
  38. package/dist/src/compiled/@opentelemetry/api/index.d.ts +6 -0
  39. package/dist/src/compiled/@workflow/builders/LICENSE.md +201 -0
  40. package/dist/src/compiled/@workflow/builders/index.d.ts +62 -0
  41. package/dist/src/compiled/@workflow/builders/index.js +1 -0
  42. package/dist/src/compiler/extension-compatibility.d.ts +2 -2
  43. package/dist/src/compiler/extension-compatibility.js +1 -1
  44. package/dist/src/compiler/manifest.d.ts +2 -2
  45. package/dist/src/compiler/manifest.js +1 -1
  46. package/dist/src/compiler/normalize-tool.js +1 -1
  47. package/dist/src/context/keys.d.ts +3 -8
  48. package/dist/src/eve-channel/index.js +1 -1
  49. package/dist/src/eve-channel/types.d.ts +7 -7
  50. package/dist/src/execution/accepted-delivery-deployment.d.ts +7 -0
  51. package/dist/src/execution/accepted-delivery-deployment.js +1 -0
  52. package/dist/src/execution/cancel-descendant-turns-step.d.ts +4 -1
  53. package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
  54. package/dist/src/execution/delegation-tool.js +1 -1
  55. package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +7 -2
  56. package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
  57. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  58. package/dist/src/execution/dispatch-turn-step.js +1 -1
  59. package/dist/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.d.ts +2 -0
  60. package/dist/src/execution/durable-session-migrations/turn-workflow-v1-to-v2.js +1 -0
  61. package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +25 -3
  62. package/dist/src/execution/durable-session-migrations/turn-workflow.js +1 -1
  63. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  64. package/dist/src/execution/finalize-terminal-session.d.ts +17 -0
  65. package/dist/src/execution/finalize-terminal-session.js +1 -0
  66. package/dist/src/execution/inline-turn.d.ts +29 -0
  67. package/dist/src/execution/inline-turn.js +1 -0
  68. package/dist/src/execution/next-driver-action.d.ts +4 -0
  69. package/dist/src/execution/node-step.js +1 -1
  70. package/dist/src/execution/parked-delivery-wait.js +1 -1
  71. package/dist/src/execution/pending-turn-state.d.ts +1 -0
  72. package/dist/src/execution/pending-turn-state.js +1 -1
  73. package/dist/src/execution/proxied-deliver-step.js +1 -1
  74. package/dist/src/execution/remote-agent-dispatch.d.ts +2 -0
  75. package/dist/src/execution/remote-agent-dispatch.js +1 -1
  76. package/dist/src/execution/session-command-token.d.ts +2 -0
  77. package/dist/src/execution/session-command-token.js +1 -1
  78. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  79. package/dist/src/execution/stable-workflow-names.d.ts +12 -0
  80. package/dist/src/execution/stable-workflow-names.js +1 -0
  81. package/dist/src/execution/subagent-event-proxy-step.d.ts +3 -0
  82. package/dist/src/execution/subagent-event-proxy-step.js +1 -1
  83. package/dist/src/execution/subagent-hitl-proxy.d.ts +2 -1
  84. package/dist/src/execution/subagent-hitl-proxy.js +1 -1
  85. package/dist/src/execution/subagent-start-remote.d.ts +2 -0
  86. package/dist/src/execution/subagent-start-remote.js +1 -1
  87. package/dist/src/execution/tasks/child/steps.d.ts +2 -0
  88. package/dist/src/execution/tasks/child/steps.js +1 -1
  89. package/dist/src/execution/tasks/child/workflow.js +1 -1
  90. package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -1
  91. package/dist/src/execution/tasks/parent/dispatch.js +1 -1
  92. package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
  93. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  94. package/dist/src/execution/terminal-session-completion-step.js +1 -1
  95. package/dist/src/execution/terminal-session-event.d.ts +13 -0
  96. package/dist/src/execution/terminal-session-event.js +1 -0
  97. package/dist/src/execution/terminal-session-failure-step.d.ts +1 -0
  98. package/dist/src/execution/terminal-session-failure-step.js +1 -1
  99. package/dist/src/execution/tool-run/answer.d.ts +3 -0
  100. package/dist/src/execution/tool-run/answer.js +1 -0
  101. package/dist/src/execution/tool-run/background.d.ts +14 -0
  102. package/dist/src/execution/tool-run/background.js +1 -0
  103. package/dist/src/execution/tool-run/cancel.d.ts +7 -0
  104. package/dist/src/execution/tool-run/cancel.js +1 -0
  105. package/dist/src/execution/tool-run/dispatch.d.ts +24 -0
  106. package/dist/src/execution/tool-run/dispatch.js +1 -0
  107. package/dist/src/execution/tool-run/emit-run-report-step.d.ts +7 -0
  108. package/dist/src/execution/tool-run/emit-run-report-step.js +1 -0
  109. package/dist/src/execution/tool-run/messages.d.ts +70 -0
  110. package/dist/src/execution/tool-run/messages.js +1 -0
  111. package/dist/src/execution/tool-run/owner-channels.d.ts +29 -0
  112. package/dist/src/execution/tool-run/owner-channels.js +1 -0
  113. package/dist/src/execution/tool-run/owner-inbox.d.ts +11 -0
  114. package/dist/src/execution/tool-run/owner-inbox.js +1 -0
  115. package/dist/src/execution/tool-run/owner.d.ts +13 -0
  116. package/dist/src/execution/tool-run/owner.js +1 -0
  117. package/dist/src/execution/tool-run/resume-hook-step.d.ts +4 -0
  118. package/dist/src/execution/tool-run/resume-hook-step.js +1 -0
  119. package/dist/src/execution/tool-run/run-control.d.ts +18 -0
  120. package/dist/src/execution/tool-run/run-control.js +1 -0
  121. package/dist/src/execution/tool-run/start.d.ts +11 -0
  122. package/dist/src/execution/tool-run/start.js +1 -0
  123. package/dist/src/execution/tool-run/types.d.ts +21 -0
  124. package/dist/src/execution/tool-run/types.js +1 -0
  125. package/dist/src/execution/tool-run/workflow.d.ts +9 -0
  126. package/dist/src/execution/tool-run/workflow.js +1 -0
  127. package/dist/src/execution/tools/subagent/local.js +1 -1
  128. package/dist/src/execution/turn-cancellation-control.d.ts +2 -0
  129. package/dist/src/execution/turn-cancellation-control.js +1 -1
  130. package/dist/src/execution/turn-control-receiver.js +1 -1
  131. package/dist/src/execution/turn-dispatch.d.ts +4 -2
  132. package/dist/src/execution/turn-dispatch.js +1 -1
  133. package/dist/src/execution/turn-execution-cursor.js +1 -1
  134. package/dist/src/execution/turn-workflow.js +1 -1
  135. package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
  136. package/dist/src/execution/wire/session-inbox-contract.js +1 -1
  137. package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
  138. package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
  139. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  140. package/dist/src/execution/wire/session-inbox-wire.js +1 -1
  141. package/dist/src/execution/wire/session-inbox-wire.v1.js +1 -1
  142. package/dist/src/execution/wire/session-inbox-wire.v2-migration.d.ts +0 -2
  143. package/dist/src/execution/wire/session-inbox-wire.v2-migration.js +1 -1
  144. package/dist/src/execution/wire/session-inbox-wire.v2.migration.d.ts +3 -0
  145. package/dist/src/execution/wire/session-inbox-wire.v2.migration.js +1 -0
  146. package/dist/src/execution/wire/session-inbox-wire.v3.d.ts +480 -0
  147. package/dist/src/execution/wire/session-inbox-wire.v3.js +1 -0
  148. package/dist/src/execution/wire/session-inbox-wire.v3.migration.d.ts +3 -0
  149. package/dist/src/execution/wire/session-inbox-wire.v3.migration.js +1 -0
  150. package/dist/src/execution/workflow-entry-finalization.js +1 -1
  151. package/dist/src/execution/workflow-entry.js +1 -1
  152. package/dist/src/execution/workflow-registry.d.ts +5 -0
  153. package/dist/src/execution/workflow-registry.js +1 -0
  154. package/dist/src/execution/workflow-runtime.d.ts +9 -11
  155. package/dist/src/execution/workflow-runtime.js +1 -1
  156. package/dist/src/execution/workflow-steps.js +1 -1
  157. package/dist/src/execution/workflow-webhook-route.d.ts +4 -0
  158. package/dist/src/execution/workflow-webhook-route.js +1 -0
  159. package/dist/src/harness/attachment-staging.js +1 -1
  160. package/dist/src/harness/emission.js +1 -1
  161. package/dist/src/harness/proxy-input-requests.d.ts +10 -0
  162. package/dist/src/harness/proxy-input-requests.js +1 -1
  163. package/dist/src/harness/runtime-actions.d.ts +2 -0
  164. package/dist/src/harness/runtime-actions.js +1 -1
  165. package/dist/src/harness/session-limit-enforcement.js +1 -1
  166. package/dist/src/harness/tool-loop.js +2 -2
  167. package/dist/src/harness/tool-runs.d.ts +21 -0
  168. package/dist/src/harness/tool-runs.js +1 -0
  169. package/dist/src/harness/tools.js +1 -1
  170. package/dist/src/instrumentation/content-policy.d.ts +3 -1
  171. package/dist/src/instrumentation/content-policy.js +1 -1
  172. package/dist/src/instrumentation/runtime.d.ts +2 -2
  173. package/dist/src/instrumentation/runtime.js +1 -1
  174. package/dist/src/internal/application/package.js +1 -1
  175. package/dist/src/internal/attachments/errors.d.ts +3 -0
  176. package/dist/src/internal/authored-module-loader.d.ts +7 -1
  177. package/dist/src/internal/authored-module-loader.js +3 -3
  178. package/dist/src/internal/authored-package-boundary.js +1 -1
  179. package/dist/src/internal/authored-runtime-modules.d.ts +2 -0
  180. package/dist/src/internal/authored-runtime-modules.js +1 -1
  181. package/dist/src/internal/nitro/development-generation.d.ts +2 -0
  182. package/dist/src/internal/nitro/development-generation.js +1 -1
  183. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  184. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
  185. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  186. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  187. package/dist/src/internal/workflow-bundle/authored-workflow-directives.d.ts +17 -0
  188. package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -0
  189. package/dist/src/internal/workflow-bundle/authored-workflow-modules.d.ts +19 -0
  190. package/dist/src/internal/workflow-bundle/authored-workflow-modules.js +1 -0
  191. package/dist/src/internal/workflow-bundle/builder-support.d.ts +17 -2
  192. package/dist/src/internal/workflow-bundle/builder-support.js +4 -3
  193. package/dist/src/internal/workflow-bundle/builder.d.ts +2 -2
  194. package/dist/src/internal/workflow-bundle/builder.js +2 -2
  195. package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.d.ts +2 -0
  196. package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.js +1 -1
  197. package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +3 -0
  198. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +1 -1
  199. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
  200. package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +6 -2
  201. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  202. package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +3 -0
  203. package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
  204. package/dist/src/internal/workflow-bundle/workflow-directive-ast.d.ts +7 -0
  205. package/dist/src/internal/workflow-bundle/workflow-directive-ast.js +1 -0
  206. package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +15 -1
  207. package/dist/src/internal/workflow-bundle/workflow-transformer.js +4 -4
  208. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  209. package/dist/src/protocol/baggage.d.ts +6 -0
  210. package/dist/src/protocol/baggage.js +1 -0
  211. package/dist/src/public/channels/slack/attachments.js +1 -1
  212. package/dist/src/public/channels/teams/attachments.d.ts +2 -2
  213. package/dist/src/public/channels/teams/attachments.js +1 -1
  214. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  215. package/dist/src/public/channels/telegram/attachments.js +1 -1
  216. package/dist/src/public/definitions/remote-agent.d.ts +6 -3
  217. package/dist/src/public/workflow/index.d.ts +3 -0
  218. package/dist/src/public/workflow/index.js +1 -0
  219. package/dist/src/public/workflow-modules.d.js +1 -0
  220. package/dist/src/public/workflow-modules.d.ts +11 -0
  221. package/dist/src/runtime/actions/keys.js +1 -1
  222. package/dist/src/runtime/tools/registry.js +1 -1
  223. package/dist/src/setup/connection-connector.d.ts +4 -2
  224. package/dist/src/setup/connection-connector.js +2 -2
  225. package/dist/src/setup/flows/login.js +1 -1
  226. package/dist/src/setup/flows/model.js +1 -1
  227. package/dist/src/setup/flows/provider.d.ts +5 -0
  228. package/dist/src/setup/flows/provider.js +4 -4
  229. package/dist/src/setup/flows/registry-session.d.ts +24 -7
  230. package/dist/src/setup/flows/registry-session.js +1 -1
  231. package/dist/src/setup/flows/registry.d.ts +35 -29
  232. package/dist/src/setup/flows/registry.js +2 -1
  233. package/dist/src/setup/integrations/web/setup.d.ts +0 -2
  234. package/dist/src/setup/integrations/web/setup.js +1 -1
  235. package/dist/src/setup/prompter.d.ts +24 -4
  236. package/dist/src/setup/prompter.js +1 -1
  237. package/dist/src/setup/scaffold/create/project.js +2 -2
  238. package/dist/src/setup/vercel-project.js +0 -0
  239. package/dist/src/shared/dispatch-action.d.ts +6 -0
  240. package/dist/src/shared/forwarded-trace-policy.d.ts +28 -0
  241. package/dist/src/shared/forwarded-trace-policy.js +1 -0
  242. package/dist/src/shared/instrumentation-decision.d.ts +3 -0
  243. package/dist/src/shared/instrumentation-decision.js +1 -1
  244. package/dist/src/svelte/index.js +1 -1
  245. package/dist/src/svelte/use-eve-agent.js +1 -1
  246. package/dist/src/tools/behavior.d.ts +6 -0
  247. package/dist/src/tools/definition.d.ts +39 -3
  248. package/dist/src/tracing/agent-otel-provider.js +2 -2
  249. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  250. package/dist/src/tracing/agent-trace-context-store.d.ts +1 -1
  251. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  252. package/dist/src/tracing/otel-declaration.d.ts +5 -3
  253. package/dist/src/tracing/otel-registration.d.ts +1 -1
  254. package/dist/src/tracing/otel-registration.js +1 -1
  255. package/dist/src/vue/index.js +1 -1
  256. package/dist/src/vue/use-eve-agent.js +1 -1
  257. package/docs/channels/custom.mdx +2 -0
  258. package/docs/channels/eve.mdx +5 -1
  259. package/docs/channels/teams.mdx +6 -1
  260. package/docs/concepts/sessions-runs-and-streaming.md +4 -2
  261. package/docs/guides/auth-and-route-protection.md +5 -1
  262. package/docs/guides/client/messages.mdx +6 -0
  263. package/docs/guides/dev-tui.md +30 -18
  264. package/docs/guides/remote-agents.md +25 -0
  265. package/docs/reference/cli.md +2 -2
  266. package/docs/tools/meta.json +1 -1
  267. package/docs/tools/overview.mdx +7 -0
  268. package/docs/tools/workflows.mdx +288 -0
  269. package/package.json +12 -1
  270. package/dist/src/internal/authored-directive-prologue.d.ts +0 -4
  271. package/dist/src/internal/authored-directive-prologue.js +0 -1
@@ -1 +1 @@
1
- import{loadContext}from"#context/container.js";import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{tool}from"ai";import{authorizationPendingModelText,isAuthorizationPendingModelOutput,isAuthorizationSignal,modelFacingAuthorizationOutput}from"#harness/authorization.js";import{createBackgroundToolCallBatch,executeBackgroundToolCall}from"#harness/background-tools.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{stashToolInterrupt}from"#harness/tool-interrupts.js";import{resolveWebSearchBackend,resolveWebSearchProviderTool}from"#harness/provider-tools.js";import{normalizeToolJsonOutput,normalizeToolModelOutput}from"#harness/tool-model-output.js";const toolApprovals=new WeakMap;function buildToolSet(e){let t={},n=e.backgroundBatch??createBackgroundToolCallBatch(),r=e.capabilities?.requestInput===!0,s=e.disabledProviderTools;for(let c of e.tools.values()){if(c.behavior?.availability.includes(`requires-request-input`)===!0&&!r||s?.has(c.name))continue;n.setTool(c.name,c.execution===`background`&&c.execute!==void 0?c:void 0);let l=c.toModelOutput,u=buildApprovalFn(c,e),d=tool({description:c.description,execute:wrapToolExecute(c,n),inputSchema:c.inputSchema,...c.execution===`background`?{onInputAvailable:({input:e,toolCallId:t})=>{if(c.execute===void 0)throw Error(`Background tool "${c.name}" has no execute function.`);n.register({callId:t,input:e,toolName:c.name})}}:{},outputSchema:c.outputSchema,...c.execute===void 0?l===void 0?{}:{toModelOutput:async({output:e,toolCallId:t})=>normalizeToolModelOutput({output:await l(e),toolCallId:t,toolName:c.name})}:{toModelOutput:async({output:e,toolCallId:t})=>isAuthorizationPendingModelOutput(e)?{type:`text`,value:authorizationPendingModelText(e.connections)}:l===void 0?typeof e==`string`?{type:`text`,value:e}:normalizeToolModelOutput({output:{type:`json`,value:e??null},toolCallId:t,toolName:c.name}):normalizeToolModelOutput({output:await l(e),toolCallId:t,toolName:c.name})}});t[c.name]=d,c.approval!==void 0&&toolApprovals.set(d,u)}return t}function buildToolSetFromDefinitions(e){let t=new Map;for(let n of e.tools)t.has(n.name)||t.set(n.name,n);return buildToolSet({approvedTools:e.approvedTools,backgroundBatch:e.backgroundBatch,capabilities:e.capabilities,disabledProviderTools:e.disabledProviderTools,tools:t})}function wrapToolExecute(e,t=createBackgroundToolCallBatch()){let n=e.execute;if(n!==void 0)return(r,i)=>{let a;try{a=e.execution===`background`?executeBackgroundToolCall({batch:t,definition:e,options:i,toolInput:r}):n(r,i)}catch(e){return Promise.reject(e)}return isAsyncIterable(a)?normalizeToolExecuteIterable(a,e.name,i):Promise.resolve(a).then(t=>normalizeToolExecuteOutput(t,e.name,i))}}async function*normalizeToolExecuteIterable(e,t,n){for await(let r of e)yield normalizeToolExecuteOutput(r,t,n)}function normalizeToolExecuteOutput(t,n,r){return isAuthorizationSignal(t)?(stashToolInterrupt(loadContext(),r.toolCallId,t),modelFacingAuthorizationOutput(t)):normalizeToolJsonOutput({boundary:`execute`,output:t,toolCallId:r.toolCallId,toolName:n})}async function buildToolSetWithProviderTools(e){let t=e.disabledProviderTools,n={...buildToolSet({approvedTools:e.approvedTools,backgroundBatch:e.backgroundBatch,capabilities:e.capabilities,disabledProviderTools:t,tools:e.tools})};for(let r of e.tools.values()){let i=r.behavior?.handling;if(i?.kind===`provider-tool`&&r.execute===void 0&&!t?.has(r.name)){let t=resolveWebSearchBackend(e.modelReference,i.provider);t===null?delete n[r.name]:n[r.name]=await resolveWebSearchProviderTool(t)}}return n}function buildApprovalFn(e,i){return async(a,o)=>{if(e.approval===void 0)return;let s=isObject(a)?a:void 0,c=await resolveApprovalPolicy(e.approval)({...buildCallbackContext(),approvedTools:i.approvedTools??new Set,callId:o,toolInput:s,toolName:e.name});return typeof c==`boolean`?c?`user-approval`:`not-applicable`:c}}function buildToolApproval(e){return async({toolCall:t})=>{let n=e[t.toolName];return n===void 0?void 0:await toolApprovals.get(n)?.(t.input,t.toolCallId)}}export{buildToolApproval,buildToolSet,buildToolSetFromDefinitions,buildToolSetWithProviderTools,wrapToolExecute};
1
+ import{loadContext}from"#context/container.js";import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{tool}from"ai";import{authorizationPendingModelText,isAuthorizationPendingModelOutput,isAuthorizationSignal,modelFacingAuthorizationOutput}from"#harness/authorization.js";import{createBackgroundToolCallBatch,executeBackgroundToolCall}from"#harness/background-tools.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{stashToolInterrupt}from"#harness/tool-interrupts.js";import{normalizeToolJsonOutput,normalizeToolModelOutput}from"#harness/tool-model-output.js";import{resolveWebSearchBackend,resolveWebSearchProviderTool}from"#harness/provider-tools.js";const toolApprovals=new WeakMap;function buildToolSet(e){let t={},n=e.backgroundBatch??createBackgroundToolCallBatch(),r=e.capabilities?.requestInput===!0,s=e.disabledProviderTools;for(let c of e.tools.values()){if(c.behavior?.availability.includes(`requires-request-input`)===!0&&!r||s?.has(c.name))continue;n.setTool(c.name,c.execution===`background`&&c.execute!==void 0?c:void 0);let l=c.toModelOutput,u=buildApprovalFn(c,e),d=tool({description:c.description,execute:wrapToolExecute(c,n),inputSchema:c.inputSchema,...c.execution===`background`?{onInputAvailable:({input:e,toolCallId:t})=>{if(c.execute===void 0)throw Error(`Background tool "${c.name}" has no execute function.`);n.register({callId:t,input:e,toolName:c.name})}}:{},outputSchema:c.outputSchema,...c.execute===void 0?l===void 0?{}:{toModelOutput:async({output:e,toolCallId:t})=>normalizeToolModelOutput({output:await l(e),toolCallId:t,toolName:c.name})}:{toModelOutput:async({output:e,toolCallId:t})=>isAuthorizationPendingModelOutput(e)?{type:`text`,value:authorizationPendingModelText(e.connections)}:l===void 0?typeof e==`string`?{type:`text`,value:e}:normalizeToolModelOutput({output:{type:`json`,value:e??null},toolCallId:t,toolName:c.name}):normalizeToolModelOutput({output:await l(e),toolCallId:t,toolName:c.name})}});t[c.name]=d,c.approval!==void 0&&toolApprovals.set(d,u)}return t}function buildToolSetFromDefinitions(e){let t=new Map;for(let n of e.tools)t.has(n.name)||t.set(n.name,n);return buildToolSet({approvedTools:e.approvedTools,backgroundBatch:e.backgroundBatch,capabilities:e.capabilities,disabledProviderTools:e.disabledProviderTools,tools:t})}function wrapToolExecute(e,t=createBackgroundToolCallBatch()){let n=e.execute;if(n!==void 0)return(r,i)=>{let a;try{a=e.execution===`background`?executeBackgroundToolCall({batch:t,definition:e,options:i,toolInput:r}):n(r,i)}catch(e){return Promise.reject(e)}return isAsyncIterable(a)?normalizeToolExecuteIterable(a,e.name,i):Promise.resolve(a).then(t=>normalizeToolExecuteOutput(t,e.name,i))}}async function*normalizeToolExecuteIterable(e,t,n){for await(let r of e)yield normalizeToolExecuteOutput(r,t,n)}function normalizeToolExecuteOutput(t,n,r){return isAuthorizationSignal(t)?(stashToolInterrupt(loadContext(),r.toolCallId,t),modelFacingAuthorizationOutput(t)):normalizeToolJsonOutput({boundary:`execute`,output:t,toolCallId:r.toolCallId,toolName:n})}async function buildToolSetWithProviderTools(e){let t=e.disabledProviderTools,n={...buildToolSet({approvedTools:e.approvedTools,backgroundBatch:e.backgroundBatch,capabilities:e.capabilities,disabledProviderTools:t,tools:e.tools})};for(let r of e.tools.values()){let i=r.behavior?.handling;if(i?.kind===`provider-tool`&&r.execute===void 0&&!t?.has(r.name)){let t=resolveWebSearchBackend(e.modelReference,i.provider);t===null?delete n[r.name]:n[r.name]=await resolveWebSearchProviderTool(t)}}return n}function buildApprovalFn(e,i){return async(a,o)=>{if(e.approval===void 0)return;let s=isObject(a)?a:void 0,c=await resolveApprovalPolicy(e.approval)({...buildCallbackContext(),approvedTools:i.approvedTools??new Set,callId:o,toolInput:s,toolName:e.name});return typeof c==`boolean`?c?`user-approval`:`not-applicable`:c}}function buildToolApproval(e){return async({toolCall:t})=>{let n=e[t.toolName];return n===void 0?void 0:await toolApprovals.get(n)?.(t.input,t.toolCallId)}}export{buildToolApproval,buildToolSet,buildToolSetFromDefinitions,buildToolSetWithProviderTools,wrapToolExecute};
@@ -2,4 +2,6 @@ import type { InstrumentationEvent } from "#instrumentation/lifecycle.js";
2
2
  import type { ChannelAudience } from "#shared/channel-audience.js";
3
3
  import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
4
4
  /** Applies OpenTelemetry's trace content ceiling to one OTel provider event. */
5
- export declare function instrumentationEventForTraceDecision(event: InstrumentationEvent, decision: InstrumentationDecision, audience: ChannelAudience): InstrumentationEvent;
5
+ export declare function instrumentationEventForTraceDecision(event: InstrumentationEvent, decision: InstrumentationDecision, audience: ChannelAudience, options?: {
6
+ readonly applyAudienceCeiling?: boolean;
7
+ }): InstrumentationEvent;
@@ -1 +1 @@
1
- import{applyAudienceCeiling}from"#shared/instrumentation-content.js";import{withInstrumentationDecision,withoutInstrumentationContent}from"#instrumentation/content.js";function instrumentationEventForTraceDecision(e,t,n){let r=applyAudienceCeiling(t,n);return r.action===`drop`?withoutInstrumentationContent(e):withInstrumentationDecision(e,r)}export{instrumentationEventForTraceDecision};
1
+ import{applyAudienceCeiling}from"#shared/instrumentation-content.js";import{withInstrumentationDecision,withoutInstrumentationContent}from"#instrumentation/content.js";function instrumentationEventForTraceDecision(e,t,n,r={}){let i=r.applyAudienceCeiling===!1?t:applyAudienceCeiling(t,n);return i.action===`drop`?withoutInstrumentationContent(e):withInstrumentationDecision(e,i)}export{instrumentationEventForTraceDecision};
@@ -75,9 +75,9 @@ export interface SessionInstrumentation {
75
75
  }, execute: (scope: InstrumentationStepScope<TSession>) => Promise<TResult>) => Promise<TResult>;
76
76
  }
77
77
  export interface ExecutionInstrumentation {
78
- readonly createCancellationHandleEvent: (input: {
78
+ readonly createHandleEvent: (input: {
79
79
  readonly handleEvent?: HandleEventFn;
80
- readonly turnId: string;
80
+ readonly turnId?: string;
81
81
  }) => HandleEventFn | undefined;
82
82
  readonly flush: () => Promise<void>;
83
83
  readonly instrumentChannelDelivery: (input: Omit<ChannelDeliveryStartInstrumentation, "hooks" | "policyAgentName"> | Omit<ChannelDeliveryTerminalInstrumentation, "hooks">) => Promise<void>;
@@ -1 +1 @@
1
- import{recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{ChannelInstrumentationKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readSessionTraceDecision}from"#tracing/agent-trace-context-store.js";import{applyAudienceCeiling,shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import{resolveParentLineage}from"#instrumentation/parent-lineage.js";const INSTRUMENTATION_RUNTIME_KEY=Symbol.for(`eve.instrumentation-runtime`),TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function bindInstrumentationRuntime(i,l,u){if(i===void 0)return;let d=i.hooks,readSessionContext=()=>{let e=contextStorage.getStore()??l;return{channel:e.get(ChannelKey),context:e,instrumentation:e.get(ChannelInstrumentationKey),parent:e.get(ParentSessionKey),parentTraceContext:e.get(ParentTraceContextKey),traceSeed:e.get(SessionTraceSeedKey)}},bindHooks=e=>{let n=e.instrumentation;return d.forTrace?.({agentName:u.agentName,audience:normalizeChannelAudience(n?.metadata.audience),channelType:n?.channelType})??d},captureExecutionRuntime=()=>{let e=i.otelSettings,t=i.ownsAgentSpans===!0;return e!==void 0&&!t&&ensureOtelIntegration(),{ownsAgentSpans:t,otelSettings:e,runtimeContextResolvers:i.runtimeContextResolvers,stepStartedRuntimeContextResolver:i.stepStartedRuntimeContextResolver,tracer:e===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(e,n)=>{let r=n.instrumentation,a=normalizeChannelAudience(r?.metadata.audience);return prepareTurnTraceContext({...e,agentName:u.agentName,channelAudience:a,channelType:r?.channelType,instrumentation:i,parentLineage:resolveParentLineage(n.parent,n.channel),parentTraceContext:n.parentTraceContext,rootSessionId:n.parent?.rootSessionId??u.rootSessionId,sessionId:u.sessionId,traceSeed:n.traceSeed})};return{createCancellationHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:u.agentName,channelKind:t.instrumentation?.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),sessionId:u.sessionId,turnId:e.turnId})},flush:i.forceFlush,instrumentChannelDelivery:e=>instrumentChannelDelivery({...e,hooks:d,policyAgentName:u.agentName}),prepareExecution:()=>{let n=captureExecutionRuntime();return{runStep:async(r,a)=>{let o=readSessionContext(),s=bindHooks(o),c=n.otelSettings,l=resolveStepInstrumentationDecision(c,u.agentName,o.instrumentation,o.traceSeed,readSessionTraceDecision(o.context,u.sessionId)),d=n.tracer,f={"eve.environment":r.environment,"eve.session.id":r.session.sessionId,"eve.version":r.eveVersion},p=c?.functionId??u.agentName;p&&(f[`ai.telemetry.functionId`]=p);let m=d!==void 0&&!n.ownsAgentSpans&&l?.action!==`drop`&&r.hasInput?d.startSpan(`ai.eve.turn`,{attributes:f}):void 0,h=m?.spanContext(),g=h===void 0?r.session:{...r.session,state:{...r.session.state,[TURN_TRACE_STATE_KEY]:{spanId:h.spanId,traceFlags:h.traceFlags,traceId:h.traceId}}},_=m===void 0?void 0:trace.setSpan(context.active(),m);if(_===void 0&&d!==void 0){let e=r.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(_=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let v=readSessionContext(),y=snapshotInstrumentationRuntimeContext(v.context),b=v.instrumentation,x=normalizeChannelAudience(b?.metadata.audience),S=shouldCaptureInstrumentationContent(x),C=l===void 0?void 0:applyAudienceCeiling(l,x),w=l?.action===`drop`,T={recordInputs:!w&&(C?.action===`record`?C.recordInputs:S)&&(c?.recordInputs??!1),recordOutputs:!w&&(C?.action===`record`?C.recordOutputs:S)&&(c?.recordOutputs??!1)},telemetry=e=>{if(c===void 0&&e.bridgeIntegration===void 0)return;let t={};for(let n of Object.keys(e.runtimeContext??{}))t[n]=!0;let r=c!==void 0&&!(T.recordInputs&&T.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...n.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:r});return{functionId:c?.functionId??u.agentName,includeRuntimeContext:t,integrations:e.bridgeIntegration===void 0?r?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:T.recordInputs,recordOutputs:T.recordOutputs}},run=()=>a({createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:u.agentName,channelAudience:x,channelKind:b?.kind,hooks:s,parentLineage:resolveParentLineage(v.parent,v.channel),parentTraceContext:v.parentTraceContext,rootSessionId:v.parent?.rootSessionId,sessionId:u.sessionId}),prepareAttempt:e=>{let t={attemptId:`${u.sessionId}:${e.turnId}:${e.stepIndex}:${e.attemptIndex}`,attemptIndex:e.attemptIndex,channelAudience:x,functionId:c?.functionId??u.agentName,rootSessionId:v.parent?.rootSessionId??u.sessionId,sessionId:u.sessionId,stepIndex:e.stepIndex,turnId:e.turnId},n=createAiSdkHookBridge(t,s,i.runInContext,e.runtimeContext);return{complete:()=>s.publish({idempotencyKey:attemptIdempotencyKey(t),scope:t,type:`step.attempt.completed`}),fail:e=>s.publish({error:e,idempotencyKey:attemptIdempotencyKey(t),scope:t,type:`step.attempt.failed`}),scope:t,telemetry:telemetry({bridgeIntegration:n,runtimeContext:e.runtimeContext})}},preparePreamble:e=>preparePreamble(e,v),publishInputResolutions:e=>publishInputResolutions({...e,hooks:s}),recordError:t=>{m!==void 0&&recordErrorOnSpan(m,t)},resolveRuntimeContext:e=>{let r=normalizeChannelAudience(y.channel?.metadata.audience);return buildTelemetryRuntimeContext({...e,capturesContent:shouldCaptureInstrumentationContent(r),context:y,providerResolvers:n.runtimeContextResolvers,stepStartedResolver:n.stepStartedRuntimeContextResolver})},session:g,setTurnId:e=>m?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:h===void 0||!isValidSpanContext(h)?void 0:{spanId:h.spanId,traceFlags:h.traceFlags,traceId:h.traceId}});try{return _===void 0?await run():await context.with(_,run)}finally{m?.end(),m=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,{agentName:e.agentName,rootSessionId:e.rootSessionId,sessionId:e.sessionId})}function initializeSessionInstrumentation(e){let n=getInstrumentationRuntime(),a=e.ctx.get(ChannelInstrumentationKey),o=normalizeChannelAudience(a?.metadata.audience),c=allocateSessionTraceSeed({agentName:e.agentName,audience:o,channelType:a?.channelType,parentTraceContext:e.parentTraceContext,runtime:n});c!==void 0&&e.ctx.set(SessionTraceSeedKey,c),e.ctx.set(OtelTraceEnabledKey,n?.prepareSessionTrace!==void 0)}function allocateSessionTraceSeed(e){if(e.parentTraceContext!==void 0)return{decision:e.parentTraceContext.decision??resolveTracePolicyDecision(isSampledTrace(e.parentTraceContext),e.audience),spanId:e.parentTraceContext.spanId,traceFlags:e.parentTraceContext.traceFlags,traceId:e.parentTraceContext.traceId};if(e.runtime?.prepareSessionTrace===void 0||e.runtime.idGenerator===void 0)return;let t=resolveTracePolicy(e.runtime.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType}),n=e.runtime.idGenerator.generateTraceId(),r=t.action===`record`&&(e.runtime.samplesTrace?.(n)??!0);return{decision:t,spanId:e.runtime.idGenerator.allocateSpanId(),traceFlags:+!!r,traceId:n}}function resolveStepInstrumentationDecision(e,n,r,i,a){if(e===void 0)return;if(i?.decision!==void 0)return i.decision;if(a!==void 0)return a;let o=normalizeChannelAudience(r?.metadata.audience);return i===void 0?resolveTracePolicy(e.tracePolicy,{agentName:n,audience:o,channelType:r?.channelType}):resolveTracePolicyDecision(isSampledTrace(i),o)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}const globalRuntime=globalThis;function registerInstrumentationRuntime(e){let t=globalRuntime[INSTRUMENTATION_RUNTIME_KEY];return t===void 0?(globalRuntime[INSTRUMENTATION_RUNTIME_KEY]=e,e):(t.otelSettings=e.otelSettings,t)}function getInstrumentationRuntime(){return globalRuntime[INSTRUMENTATION_RUNTIME_KEY]}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
1
+ import{createLogger,recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{ChannelInstrumentationKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{applyLiveDeliveryAudienceCeiling,formatTraceContentCeiling,readForwardedTraceAssertion,resolveForwardedTraceSeed,traceContentCeilingToDecision}from"#shared/forwarded-trace-policy.js";import{readSessionTraceDecision}from"#tracing/agent-trace-context-store.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import{resolveParentLineage}from"#instrumentation/parent-lineage.js";import{intersectInstrumentationDecisions,readInstrumentationDecision}from"#shared/instrumentation-decision.js";const INSTRUMENTATION_RUNTIME_KEY=Symbol.for(`eve.instrumentation-runtime`),TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`,log=createLogger(`instrumentation.runtime`);function bindInstrumentationRuntime(e,a,d){if(e===void 0)return;let m=e.hooks,readSessionContext=()=>{let e=contextStorage.getStore()??a,t=e.get(SessionTraceSeedKey),n=resolveForwardedTraceSeed(t),u=t===void 0||n===void 0?void 0:{...t,...n},d=e.get(ParentTraceContextKey);return{channel:e.get(ChannelKey),context:e,instrumentation:e.get(ChannelInstrumentationKey),forwardedTracePolicy:readForwardedTraceAssertion(u?.forwardedTracePolicy),parent:e.get(ParentSessionKey),parentTraceContext:d,traceSeed:u}},bindHooks=e=>{let t=e.instrumentation;return m.forTrace?.({agentName:d.agentName,audience:normalizeChannelAudience(t?.metadata.audience),channelType:t?.channelType})??m},captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,stepStartedRuntimeContextResolver:e.stepStartedRuntimeContextResolver,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,r)=>{let i=r.instrumentation,a=normalizeChannelAudience(i?.metadata.audience);return prepareTurnTraceContext({...t,agentName:d.agentName,channelAudience:a,channelType:i?.channelType,instrumentation:e,parentLineage:resolveParentLineage(r.parent,r.channel),parentTraceContext:r.parentTraceContext,rootSessionId:r.parent?.rootSessionId??d.rootSessionId,sessionId:d.sessionId,traceSeed:r.traceSeed})};return{createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:d.agentName,channelKind:t.instrumentation?.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),sessionId:d.sessionId,turnId:e.turnId})},flush:e.forceFlush,instrumentChannelDelivery:e=>instrumentChannelDelivery({...e,hooks:m,policyAgentName:d.agentName}),prepareExecution:()=>{let r=captureExecutionRuntime();return{runStep:async(i,a)=>{let o=readSessionContext(),s=bindHooks(o),c=r.otelSettings,l=resolveStepInstrumentationDecision(c,d.agentName,o.instrumentation,o.traceSeed,readSessionTraceDecision(o.context,d.sessionId)),f=r.tracer,p={"eve.environment":i.environment,"eve.session.id":i.session.sessionId,"eve.version":i.eveVersion},m=c?.functionId??d.agentName;m&&(p[`ai.telemetry.functionId`]=m);let h=f!==void 0&&!r.ownsAgentSpans&&l?.action!==`drop`&&i.hasInput?f.startSpan(`ai.eve.turn`,{attributes:p}):void 0,g=h?.spanContext(),_=g===void 0?i.session:{...i.session,state:{...i.session.state,[TURN_TRACE_STATE_KEY]:{spanId:g.spanId,traceFlags:g.traceFlags,traceId:g.traceId}}},v=h===void 0?void 0:trace.setSpan(context.active(),h);if(v===void 0&&f!==void 0){let e=i.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(v=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let y=readSessionContext(),b=snapshotInstrumentationRuntimeContext(y.context),x=y.instrumentation,S=normalizeChannelAudience(x?.metadata.audience),C=shouldCaptureInstrumentationContent(S),w=l===void 0?l:applyLiveDeliveryAudienceCeiling(l,S,y.forwardedTracePolicy),T=w===void 0?C:w.action===`record`&&w.recordInputs,E=l?.action===`drop`,D={recordInputs:!E&&(w?.action===`record`?w.recordInputs:C)&&(c?.recordInputs??!1),recordOutputs:!E&&(w?.action===`record`?w.recordOutputs:C)&&(c?.recordOutputs??!1)},telemetry=e=>{if(c===void 0&&e.bridgeIntegration===void 0)return;let t={};for(let n of Object.keys(e.runtimeContext??{}))t[n]=!0;let n=c!==void 0&&!(D.recordInputs&&D.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...r.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:n});return{functionId:c?.functionId??d.agentName,includeRuntimeContext:t,integrations:e.bridgeIntegration===void 0?n?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:D.recordInputs,recordOutputs:D.recordOutputs}},run=()=>a({createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:d.agentName,channelAudience:S,channelKind:x?.kind,hooks:s,parentLineage:resolveParentLineage(y.parent,y.channel),parentTraceContext:y.parentTraceContext,rootSessionId:y.parent?.rootSessionId,sessionId:d.sessionId}),prepareAttempt:t=>{let n={attemptId:`${d.sessionId}:${t.turnId}:${t.stepIndex}:${t.attemptIndex}`,attemptIndex:t.attemptIndex,channelAudience:S,functionId:c?.functionId??d.agentName,rootSessionId:y.parent?.rootSessionId??d.sessionId,sessionId:d.sessionId,stepIndex:t.stepIndex,turnId:t.turnId},r=createAiSdkHookBridge(n,s,e.runInContext,t.runtimeContext);return{complete:()=>s.publish({idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`step.attempt.completed`}),fail:e=>s.publish({error:e,idempotencyKey:attemptIdempotencyKey(n),scope:n,type:`step.attempt.failed`}),scope:n,telemetry:telemetry({bridgeIntegration:r,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,y),publishInputResolutions:e=>publishInputResolutions({...e,hooks:s}),recordError:e=>{h!==void 0&&recordErrorOnSpan(h,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:T,context:b,providerResolvers:r.runtimeContextResolvers,stepStartedResolver:r.stepStartedRuntimeContextResolver}),session:_,setTurnId:e=>h?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:g===void 0||!isValidSpanContext(g)?void 0:{spanId:g.spanId,traceFlags:g.traceFlags,traceId:g.traceId}});try{return v===void 0?await run():await context.with(v,run)}finally{h?.end(),h=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,{agentName:e.agentName,rootSessionId:e.rootSessionId,sessionId:e.sessionId})}function initializeSessionInstrumentation(e){let t=getInstrumentationRuntime(),r=e.ctx.get(ChannelInstrumentationKey),o=readForwardedTraceAssertion(e.parentTraceContext?.forwardedTracePolicy),l=o?.originAudience??normalizeChannelAudience(r?.metadata.audience),u=allocateSessionTraceSeed({agentName:e.agentName,audience:l,channelType:r?.channelType,forwardedTracePolicy:o,parentTraceContext:e.parentTraceContext,runtime:t});if(u!==void 0&&(e.ctx.set(SessionTraceSeedKey,u),o!==void 0&&log.info(`resolved forwarded trace policy`,{ceilingEffective:u.decision?.action===`record`?formatTraceContentCeiling(u.decision):`drop`,ceilingIn:formatTraceContentCeiling(o.ceiling),originAudience:o.originAudience}),o!==void 0&&e.parentTraceContext!==void 0)){let t={...e.parentTraceContext,...u};delete t.forwardedTracePolicy,e.ctx.set(ParentTraceContextKey,t)}e.ctx.set(OtelTraceEnabledKey,t?.prepareSessionTrace!==void 0)}function allocateSessionTraceSeed(e){if(e.parentTraceContext!==void 0){let t=e.forwardedTracePolicy?traceContentCeilingToDecision(e.forwardedTracePolicy.ceiling):void 0,n=readInstrumentationDecision(e.parentTraceContext.decision),r=t?n===void 0?t:intersectInstrumentationDecisions(t,n):n??resolveTracePolicyDecision(isSampledTrace(e.parentTraceContext),e.audience),i=e.forwardedTracePolicy?intersectInstrumentationDecisions(r,resolveTracePolicy(e.runtime?.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType})):r;return{decision:i,forwardedTracePolicy:e.forwardedTracePolicy,spanId:e.parentTraceContext.spanId,traceFlags:e.forwardedTracePolicy!==void 0&&i.action===`drop`?e.parentTraceContext.traceFlags&-2:e.parentTraceContext.traceFlags,traceId:e.parentTraceContext.traceId}}if(e.runtime?.prepareSessionTrace===void 0||e.runtime.idGenerator===void 0)return;let t=resolveTracePolicy(e.runtime.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType}),n=e.runtime.idGenerator.generateTraceId(),r=t.action===`record`&&(e.runtime.samplesTrace?.(n)??!0);return{decision:t,spanId:e.runtime.idGenerator.allocateSpanId(),traceFlags:+!!r,traceId:n}}function resolveStepInstrumentationDecision(e,t,r,i,a){if(e===void 0)return;if(i?.decision!==void 0)return readInstrumentationDecision(i.decision);if(a!==void 0)return a;let o=normalizeChannelAudience(r?.metadata.audience);return i===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,audience:o,channelType:r?.channelType}):resolveTracePolicyDecision(isSampledTrace(i),o)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}const globalRuntime=globalThis;function registerInstrumentationRuntime(e){let t=globalRuntime[INSTRUMENTATION_RUNTIME_KEY];return t===void 0?(globalRuntime[INSTRUMENTATION_RUNTIME_KEY]=e,e):(t.otelSettings=e.otelSettings,t)}function getInstrumentationRuntime(){return globalRuntime[INSTRUMENTATION_RUNTIME_KEY]}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.47.7`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.48.0`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -26,6 +26,9 @@ interface EveAttachmentErrorInput {
26
26
  * Channels can inspect the `.kind` discriminator to decide whether to
27
27
  * drop the attachment and continue the turn (the default posture for
28
28
  * every kind today) or fail the whole delivery (future strict mode).
29
+ * `.message` crosses into model-visible input when the attachment is
30
+ * dropped, so it must not contain URLs, credentials, or verbatim upstream
31
+ * error text. Preserve private diagnostics on `.cause` instead.
29
32
  * The original failure, when there is one, is preserved on `.cause` so
30
33
  * observability can surface the upstream error without losing context.
31
34
  */
@@ -48,7 +48,13 @@ export declare function bundleExtensionDistributionGraph(input: {
48
48
  * Shared dependencies are parsed and emitted once instead of once per authored
49
49
  * entry.
50
50
  */
51
+ export interface AuthoredModuleMapBundle {
52
+ readonly code: string;
53
+ /** Fingerprint of the sources that also feed the driver and step registry; a change rebuilds the host. */
54
+ readonly workflowSourceFingerprint: string | undefined;
55
+ }
51
56
  export declare function bundleAuthoredModuleMapForGeneration(input: {
52
57
  readonly manifest: CompiledAgentManifest;
53
58
  readonly moduleMapPath: string;
54
- }): Promise<string>;
59
+ }): Promise<AuthoredModuleMapBundle>;
60
+ export declare function resolveAuthoredPackageRoot(modulePath: string): string;
@@ -1,4 +1,4 @@
1
- import{createHash}from"node:crypto";import{expectObjectRecord}from"#internal/authored-module.js";import{dirname,join,resolve}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}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{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createExtensionScopePlugin,createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.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 a=(async()=>{try{return await doLoadAuthoredModuleNamespace(e,t)}finally{inFlightModuleLoads.delete(n)}})();return inFlightModuleLoads.set(n,a),a}async function doLoadAuthoredModuleNamespace(e,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,n):await import(createFileImportSpecifier(e)),`Expected "${e}" 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 bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`_chunks/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map;for(let e of n.output)e.type===`chunk`&&r.set(e.fileName,removeRolldownModuleRegionComments(e.code));return r}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),o=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})))),s=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createDynamicCapabilityTransformPlugin(),createAuthoredDirectiveGuardPlugin(),o,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t})].filter(e=>e!==null);try{return removeRolldownModuleRegionComments((await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:s,resolve:{conditionNames:[`eve-source`],extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}})).code)}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}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,a=resolveAuthoredPackageRoot(e),o=resolveAuthoredTsConfigPath(a),s=[r&&r.size>0?{name:`eve-channel-identity`,async resolveId(e,t,n){if(!/channels[/\\]/.test(e)||n.kind!==`import-statement`)return;let a=await this.resolve(e,t,{kind:n.kind,skipSelf:!0});if(a===null||typeof a.id!=`string`)return;let o=resolve(a.id);if(r.has(o))return{id:`${CACHED_CHANNEL_PREFIX}${o}`}},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({packageRoot:a}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:a,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),n.packageBoundaryPlugin].filter(e=>e!==null);try{return(await buildSingleRolldownChunk(`authored module for "${e}"`,{cwd:a,input:e,platform:`node`,plugins:s,resolve:{conditionNames:[`eve-source`],extensions:[...RESOLVE_EXTENSIONS]},tsconfig:o,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(`
1
+ import{createHash}from"node:crypto";import{expectObjectRecord}from"#internal/authored-module.js";import{dirname,join,relative,resolve,sep}from"node:path";import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{existsSync,mkdirSync,realpathSync,writeFileSync}from"node:fs";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{createAuthoredAssetImportPlugin}from"#internal/authored-asset-import-plugin.js";import{createAuthoredModuleBundleError}from"#internal/authored-module-bundle.js";import{createAuthoredModuleEvaluationError}from"#internal/authored-module-evaluation-error.js";import{createAuthoredPackageTsConfigPathsPlugin}from"#internal/authored-package-tsconfig-paths.js";import{createAuthoredRelativeExtensionResolverPlugin}from"#internal/authored-relative-extension-resolver.js";import{createExtensionScopePlugin,createFixedNamespaceScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,normalizeExternalDependencies}from"#internal/authored-package-boundary.js";import{buildSingleRolldownChunk,buildWithNitroRolldown}from"#internal/bundler/nitro-rolldown.js";import{createNodeEsmCompatBannerPlugin}from"#internal/node-esm-compat-banner.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{createDynamicCapabilityTransformPlugin}from"#internal/workflow-bundle/dynamic-capability-transform-plugin.js";import{applyWorkflowTransform,isAuthoredApplicationModule}from"#internal/workflow-bundle/workflow-builders.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(e,n){return expectObjectRecord(AUTHORED_BUNDLED_MODULE_EXTENSION.test(e)?await loadBundledAuthoredModule(e,n):await import(createFileImportSpecifier(e)),`Expected "${e}" 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={}){let n=resolveAuthoredPackageRoot(e);return await buildAuthoredModuleBundle(e,t,{channelIdentity:!0,packageBoundaryPlugin:createRuntimeLoaderPackageBoundaryPlugin({externalDependencies:normalizeExternalDependencies(t.externalDependencies),packageRoot:n}),plugins:[createAuthoredWorkflowDirectivePlugin({appRoot:n})],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 bundleExtensionDistributionGraph(e){let t=[createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:e.packageRoot}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:e.packageRoot,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createDistributionPackageBoundaryPlugin({packageRoot:e.packageRoot,runtimeDependencies:e.runtimeDependencies})];try{let n=await buildWithNitroRolldown({cwd:e.packageRoot,input:Object.fromEntries(e.entries.map(e=>[e.name,e.path])),platform:`node`,plugins:t,resolve:{extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(e.packageRoot),write:!1,output:{chunkFileNames:`_chunks/[name]-[hash].mjs`,codeSplitting:!0,comments:!1,entryFileNames:`[name].mjs`,format:`esm`,sourcemap:!1}}),r=new Map;for(let e of n.output)e.type===`chunk`&&r.set(e.fileName,removeRolldownModuleRegionComments(e.code));return r}catch(t){throw createAuthoredModuleBundleError(e.packageRoot,t)}}async function bundleAuthoredModuleMapForGeneration(e){let t=resolveAuthoredPackageRoot(e.manifest.agentRoot),n=resolvePackageSourceFilePath(`src/internal/programmatic-source-loader.ts`),r=normalizeExternalDependencies([...e.manifest.config.build?.externalDependencies??[],...e.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])]),i=createCompiledModuleMapSource({manifest:e.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:n}),a=createExtensionScopePlugin([e.manifest,...e.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})))),o=new AuthoredWorkflowSourceRecorder(t),c=[createVirtualGenerationModuleMapPlugin({id:e.moduleMapPath,source:i}),createExternalRuntimeImportPlugin(n),createAuthoredWorkflowDirectivePlugin({appRoot:t,recorder:o}),createDynamicCapabilityTransformPlugin({workflowFunctions:e=>o.workflowFunctions(e)}),o.graphPlugin(),a,createAuthoredRelativeExtensionResolverPlugin({extensions:RESOLVE_EXTENSIONS}),createAuthoredAssetImportPlugin({packageRoot:t}),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot:t,extensions:RESOLVE_EXTENSIONS}),createNodeEsmCompatBannerPlugin({includeRequire:!0}),createGenerationPackageBoundaryPlugin({externalDependencies:r,packageRoot:t})].filter(e=>e!==null);try{return{code:removeRolldownModuleRegionComments((await buildSingleRolldownChunk(`authored module map`,{cwd:t,input:e.moduleMapPath,platform:`node`,plugins:c,resolve:{conditionNames:[`eve-source`],extensions:[...RESOLVE_EXTENSIONS]},tsconfig:resolveAuthoredTsConfigPath(t),output:{comments:!1,format:`esm`,sourcemap:!1}})).code),workflowSourceFingerprint:o.fingerprint()}}catch(t){throw createAuthoredModuleBundleError(e.moduleMapPath,t)}}function createExternalRuntimeImportPlugin(e){let t=normalizeEsmImportSpecifier(e);return{name:`eve-external-runtime-import`,resolveId(e){return e===t?{external:!0,id:t}:void 0}}}var AuthoredWorkflowSourceRecorder=class{#e;#t=new Set;#n=new Map;#r=new Map;#i=new Map;constructor(e){this.#e=e}record(e,t,n){this.#r.set(e,t),(n.steps!==void 0||n.workflows!==void 0)&&this.#t.add(e);let r=Object.values(n.workflows??{})[0];r!==void 0&&this.#i.set(e,new Set(Object.keys(r)))}workflowFunctions(e){return this.#i.get(e)}graphPlugin(){let e=this.#n;return{name:`eve-authored-module-graph`,buildEnd(){for(let t of this.getModuleIds()){let n=this.getModuleInfo(t);n!==null&&e.set(t,[...n.importedIds,...n.dynamicallyImportedIds])}}}}fingerprint(){if(this.#t.size===0)return;let t=new Set,n=[...this.#t];for(let e=n.shift();e!==void 0;e=n.shift())t.has(e)||!this.#r.has(e)||(t.add(e),n.push(...this.#n.get(e)??[]));let r=createHash(`sha256`);for(let e of[...t].sort())r.update(relative(this.#e,e).split(sep).join(`/`)).update(`\0`).update(this.#r.get(e)??``).update(`\0`);return r.digest(`hex`)}};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),o=resolveAuthoredTsConfigPath(i),s=[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 o=resolve(i.id);if(r.has(o))return{id:`${CACHED_CHANNEL_PREFIX}${o}`}},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({packageRoot:i}),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:s,resolve:{conditionNames:[`eve-source`],extensions:[...RESOLVE_EXTENSIONS]},tsconfig:o,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){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(t)||isNodeModulesPath(t))return;let{hasDirectives:n}=await prepareAuthoredWorkflowDirectives({filePath:t,source:e});if(n)throw Error(`Module "${t}" uses Workflow directives ("use step" or "use workflow"). Workflow directives are supported in application modules only, not in extensions or instrumentation.`)}}}function createAuthoredWorkflowDirectivePlugin(e){return{name:`eve-authored-workflow-directives`,async transform(t,n){if(!AUTHORED_BUNDLED_MODULE_EXTENSION.test(n)||isNodeModulesPath(n)||!isAuthoredApplicationModule(n,e.appRoot))return;let r=await applyWorkflowTransform(n,t,`client`,n,e.appRoot);return e.recorder?.record(n,t,r.workflowManifest),r.code===t?void 0:{code:r.code,map:null}}}}function removeRolldownModuleRegionComments(e){return e.split(`
3
3
  `).filter(e=>!e.startsWith(`//#region `)&&e!==`//#endregion`).join(`
4
- `)}async function loadBundledAuthoredModule(t,n){let i=await bundleAuthoredModuleCode(t,n),a=normalizeExternalDependencies(n.externalDependencies),c=createHash(`sha1`).update(t).update(`\0`).update(a.join(`\0`)).update(`\0`).update(n.extensionScopeNamespace??``).update(`\0`).update(i).digest(`hex`),l=join(resolveAuthoredPackageRoot(t),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),u=join(l,`${c}.mjs`);existsSync(u)||(mkdirSync(l,{recursive:!0}),writeFileSync(u,i));try{return await import(`${createFileImportSpecifier(u)}?v=${c}`)}catch(e){throw createAuthoredModuleEvaluationError(t,e)}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);if(existsSync(n))return n}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let i=dirname(t);if(i===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=i}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,loadAuthoredModuleNamespace};
4
+ `)}async function loadBundledAuthoredModule(t,n){let i=await bundleAuthoredModuleCode(t,n),a=normalizeExternalDependencies(n.externalDependencies),o=createHash(`sha1`).update(t).update(`\0`).update(a.join(`\0`)).update(`\0`).update(n.extensionScopeNamespace??``).update(`\0`).update(i).digest(`hex`),s=join(resolveAuthoredPackageRoot(t),AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH),l=join(s,`${o}.mjs`);existsSync(l)||(mkdirSync(s,{recursive:!0}),writeFileSync(l,i));try{return await import(`${createFileImportSpecifier(l)}?v=${o}`)}catch(e){throw createAuthoredModuleEvaluationError(t,e)}}function createInFlightModuleLoadKey(e,t){return`${e}\0${normalizeExternalDependencies(t.externalDependencies).join(`\0`)}\0${t.extensionScopeNamespace??``}`}function resolveAuthoredTsConfigPath(e){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=join(e,t);if(existsSync(n))return n}return!1}function resolveAuthoredPackageRoot(e){let t=dirname(e);for(;;){if(existsSync(join(t,`package.json`)))return realpathSync(t);let i=dirname(t);if(i===t)throw Error(`Failed to resolve the authored package root for "${e}".`);t=i}}export{bundleAuthoredModuleCode,bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration,bundleExtensionDistributionGraph,loadAuthoredModuleNamespace,resolveAuthoredPackageRoot};
@@ -1 +1 @@
1
- import{isBuiltin}from"node:module";import{dirname,join,resolve,sep}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const CACHED_CHANNEL_PREFIX=`eve-cached-channel:`,RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(isPackageImport(t)&&(isFrameworkRuntimeImport(t,n)||await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t})!==void 0))return{external:!0,id:t}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,i,a){if(!isPackageImport(n))return;if(isFrameworkRuntimeImport(n,i))return{external:!0,id:n};let o=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:i,kind:a.kind,packageRoot:e.packageRoot,source:n});if(o!==void 0)return{external:!0,id:normalizeEsmImportSpecifier(resolveExistingExternalFilePath(o.resolvedId)??o.resolvedId)};let s=i===void 0||i.startsWith(`\0`)||i.startsWith(`eve-cached-channel:`)?void 0:resolve(i);if(s!==void 0&&isPathInsideOrEqual(toCanonicalPath(s),t)){let e=await this.resolve(n,i,{kind:a.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${s}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(t){let r=new Set(t.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(i,a,o){if(!isPackageImport(i))return;if(i.startsWith(`#`)){let e=await this.resolve(i,a,{kind:o.kind,skipSelf:!0});if(e!==null&&typeof e.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(e.id),toCanonicalPath(t.packageRoot))){let t=nearestPackageName(e.id);if(t!==void 0&&!r.has(t))throw Error(`Package import "${i}" resolves to undeclared package "${t}". Add "${t}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(i))return{external:!0,id:i};let s=packageImportName(i);if(!r.has(s))throw Error(`Package "${i}" is not declared by the extension. Add "${s}" to dependencies, optionalDependencies, or peerDependencies.`);let c=await this.resolve(i,a,{kind:o.kind,skipSelf:!0});if(c===null&&(c=await this.resolve(i,join(t.packageRoot,`package.json`),{kind:o.kind,skipSelf:!0})),c===null||typeof c.id!=`string`)throw Error(`Cannot resolve declared package "${i}". Install the extension's dependencies before building.`);return{external:!0,id:i}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let r=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(r===null&&(r=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),r===null||typeof r.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:r.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let r=dirname(toCanonicalPath(e));for(;;){let e=join(r,`package.json`);if(existsSync(e))try{let t=JSON.parse(readFileSync(e,`utf8`));return typeof t.name==`string`&&t.name.length>0?t.name:void 0}catch{return}let i=dirname(r);if(i===r)return;r=i}}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function isFrameworkRuntimeImport(e,t){return e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),a=resolve(t);return n===a||n.startsWith(`${a}${sep}`)}export{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies};
1
+ import{isBuiltin}from"node:module";import{dirname,join,resolve,sep}from"node:path";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync,readFileSync,realpathSync}from"node:fs";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const CACHED_CHANNEL_PREFIX=`eve-cached-channel:`,RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(isPackageImport(t)){if(isFrameworkRuntimeImport(t,n))return{external:!0,id:resolveFrameworkRuntimeImport(t)};if(await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t})!==void 0)return{external:!0,id:t}}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,i,a){if(!isPackageImport(n))return;if(isFrameworkRuntimeImport(n,i))return{external:!0,id:resolveFrameworkRuntimeImport(n)};let o=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:i,kind:a.kind,packageRoot:e.packageRoot,source:n});if(o!==void 0)return{external:!0,id:normalizeEsmImportSpecifier(resolveExistingExternalFilePath(o.resolvedId)??o.resolvedId)};let s=i===void 0||i.startsWith(`\0`)||i.startsWith(`eve-cached-channel:`)?void 0:resolve(i);if(s!==void 0&&isPathInsideOrEqual(toCanonicalPath(s),t)){let e=await this.resolve(n,i,{kind:a.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${s}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(t){let r=new Set(t.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(i,a,o){if(!isPackageImport(i))return;if(i.startsWith(`#`)){let e=await this.resolve(i,a,{kind:o.kind,skipSelf:!0});if(e!==null&&typeof e.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(e.id),toCanonicalPath(t.packageRoot))){let t=nearestPackageName(e.id);if(t!==void 0&&!r.has(t))throw Error(`Package import "${i}" resolves to undeclared package "${t}". Add "${t}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(i))return{external:!0,id:i};let s=packageImportName(i);if(!r.has(s))throw Error(`Package "${i}" is not declared by the extension. Add "${s}" to dependencies, optionalDependencies, or peerDependencies.`);let c=await this.resolve(i,a,{kind:o.kind,skipSelf:!0});if(c===null&&(c=await this.resolve(i,join(t.packageRoot,`package.json`),{kind:o.kind,skipSelf:!0})),c===null||typeof c.id!=`string`)throw Error(`Cannot resolve declared package "${i}". Install the extension's dependencies before building.`);return{external:!0,id:i}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let r=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(r===null&&(r=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),r===null||typeof r.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:r.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let r=dirname(toCanonicalPath(e));for(;;){let e=join(r,`package.json`);if(existsSync(e))try{let t=JSON.parse(readFileSync(e,`utf8`));return typeof t.name==`string`&&t.name.length>0?t.name:void 0}catch{return}let i=dirname(r);if(i===r)return;r=i}}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function isFrameworkRuntimeImport(e,t){return e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),a=resolve(t);return n===a||n.startsWith(`${a}${sep}`)}export{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies};
@@ -6,6 +6,8 @@ interface PreparedAuthoredRuntimeInstrumentation {
6
6
  export interface PreparedAuthoredRuntimeModules {
7
7
  readonly instrumentation?: PreparedAuthoredRuntimeInstrumentation;
8
8
  readonly moduleMapCode: string;
9
+ /** Identity of authored sources shared by the workflow driver and step registrations. */
10
+ readonly workflowSourceFingerprint: string | undefined;
9
11
  }
10
12
  /** Builds the authored runtime graph before a development or production host packages it. */
11
13
  export declare function prepareAuthoredRuntimeModules(input: {
@@ -1 +1 @@
1
- import{bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration}from"#internal/authored-module-loader.js";import{resolveInstrumentationLayout}from"#internal/instrumentation-layout.js";async function prepareAuthoredRuntimeModules(r){let i=await bundleAuthoredModuleMapForGeneration(r),a=r.manifest.config.experimental?.instrumentationProviders??!1?resolveInstrumentationLayout({agentRoot:r.manifest.agentRoot,providersEnabled:!0}):void 0,o=r.manifest.config.build?.externalDependencies??[],bundleInstrumentationModule=async t=>await bundleAuthoredModuleForGeneration(t,{externalDependencies:o}),s;if(a?.kind===`directory`){let e={};for(let[t,n]of Object.entries(a.modulePathsBySlot))e[t]=await bundleInstrumentationModule(n);s={kind:`directory`,moduleCodeBySlot:e}}return s===void 0?{moduleMapCode:i}:{instrumentation:s,moduleMapCode:i}}export{prepareAuthoredRuntimeModules};
1
+ import{bundleAuthoredModuleForGeneration,bundleAuthoredModuleMapForGeneration}from"#internal/authored-module-loader.js";import{resolveInstrumentationLayout}from"#internal/instrumentation-layout.js";async function prepareAuthoredRuntimeModules(r){let{code:i,workflowSourceFingerprint:a}=await bundleAuthoredModuleMapForGeneration(r),o=r.manifest.config.experimental?.instrumentationProviders??!1?resolveInstrumentationLayout({agentRoot:r.manifest.agentRoot,providersEnabled:!0}):void 0,s=r.manifest.config.build?.externalDependencies??[],bundleInstrumentationModule=async t=>await bundleAuthoredModuleForGeneration(t,{externalDependencies:s}),c;if(o?.kind===`directory`){let e={};for(let[t,n]of Object.entries(o.modulePathsBySlot))e[t]=await bundleInstrumentationModule(n);c={kind:`directory`,moduleCodeBySlot:e}}return c===void 0?{moduleMapCode:i,workflowSourceFingerprint:a}:{instrumentation:c,moduleMapCode:i,workflowSourceFingerprint:a}}export{prepareAuthoredRuntimeModules};
@@ -2,6 +2,8 @@ import type { CompileAgentResult } from "#compiler/compile-agent.js";
2
2
  import { type DevelopmentRuntimeArtifactsActivation, type DevelopmentRuntimeArtifactsSnapshot } from "#internal/nitro/dev-runtime-artifacts.js";
3
3
  export interface DevelopmentGeneration extends DevelopmentRuntimeArtifactsSnapshot {
4
4
  readonly fingerprint: string;
5
+ /** Identity of the authored sources the workflow driver and step registrations are built from. */
6
+ readonly workflowSourceFingerprint?: string;
5
7
  }
6
8
  export declare function stageDevelopmentGeneration(compileResult: CompileAgentResult): Promise<DevelopmentGeneration>;
7
9
  export declare function publishDevelopmentGeneration(compileResult: CompileAgentResult): Promise<DevelopmentGeneration>;
@@ -1 +1 @@
1
- import{rm}from"node:fs/promises";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{writeMaterializedAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(r){let i=await prepareAuthoredRuntimeModules({manifest:r.manifest,moduleMapPath:r.paths.moduleMapPath}),a=await stageDevelopmentRuntimeArtifactsSnapshot(r);try{let e=await writeMaterializedAuthoredModules({prepared:i,runtimeAppRoot:a.runtimeAppRoot});return{...a,fingerprint:e.fingerprint}}catch(t){try{await rm(a.snapshotRoot,{force:!0,recursive:!0})}catch(e){throw AggregateError([t,e],`Failed to materialize and discard development generation "${a.snapshotRoot}".`)}throw t}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){(await activateDevelopmentGenerationTransaction(e)).commit()}async function activateDevelopmentGenerationTransaction(e){let t=await activateDevelopmentRuntimeArtifactsSnapshotTransaction({appRoot:e.appRoot,snapshot:e.generation}),n=!1;return{commit(){n||(n=!0,t.commit(),requestDevelopmentGenerationPrune(e.appRoot))},async rollback(){n||(n=!0,await t.rollback())}}}async function discardDevelopmentGeneration(t){await rm(t.snapshotRoot,{force:!0,recursive:!0})}function requestDevelopmentGenerationPrune(e){let t=developmentGenerationPruneStates.get(e)??{requested:!1,running:void 0};developmentGenerationPruneStates.set(e,t),t.requested=!0,t.running===void 0&&startDevelopmentGenerationPruning(e,t)}function startDevelopmentGenerationPruning(e,t){t.running=(async()=>{for(;t.requested;)t.requested=!1,await pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e})})().catch(e=>{console.warn(`[eve:dev] failed to prune runtime generations: ${String(e)}`)}).finally(()=>{t.running=void 0,t.requested?startDevelopmentGenerationPruning(e,t):developmentGenerationPruneStates.delete(e)})}export{activateDevelopmentGeneration,activateDevelopmentGenerationTransaction,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
1
+ import{rm}from"node:fs/promises";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{writeMaterializedAuthoredModules}from"#internal/materialized-authored-modules.js";import{activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,stageDevelopmentRuntimeArtifactsSnapshot}from"#internal/nitro/dev-runtime-artifacts.js";const developmentGenerationPruneStates=new Map;async function stageDevelopmentGeneration(r){let i=await prepareAuthoredRuntimeModules({manifest:r.manifest,moduleMapPath:r.paths.moduleMapPath}),a=await stageDevelopmentRuntimeArtifactsSnapshot(r);try{let e=await writeMaterializedAuthoredModules({prepared:i,runtimeAppRoot:a.runtimeAppRoot});return i.workflowSourceFingerprint===void 0?{...a,fingerprint:e.fingerprint}:{...a,fingerprint:e.fingerprint,workflowSourceFingerprint:i.workflowSourceFingerprint}}catch(t){try{await rm(a.snapshotRoot,{force:!0,recursive:!0})}catch(e){throw AggregateError([t,e],`Failed to materialize and discard development generation "${a.snapshotRoot}".`)}throw t}}async function publishDevelopmentGeneration(e){let t=await stageDevelopmentGeneration(e);return await activateDevelopmentGeneration({appRoot:e.project.appRoot,generation:t}),t}async function activateDevelopmentGeneration(e){(await activateDevelopmentGenerationTransaction(e)).commit()}async function activateDevelopmentGenerationTransaction(e){let t=await activateDevelopmentRuntimeArtifactsSnapshotTransaction({appRoot:e.appRoot,snapshot:e.generation}),n=!1;return{commit(){n||(n=!0,t.commit(),requestDevelopmentGenerationPrune(e.appRoot))},async rollback(){n||(n=!0,await t.rollback())}}}async function discardDevelopmentGeneration(t){await rm(t.snapshotRoot,{force:!0,recursive:!0})}function requestDevelopmentGenerationPrune(e){let t=developmentGenerationPruneStates.get(e)??{requested:!1,running:void 0};developmentGenerationPruneStates.set(e,t),t.requested=!0,t.running===void 0&&startDevelopmentGenerationPruning(e,t)}function startDevelopmentGenerationPruning(e,t){t.running=(async()=>{for(;t.requested;)t.requested=!1,await pruneDevelopmentRuntimeArtifactsSnapshots({appRoot:e})})().catch(e=>{console.warn(`[eve:dev] failed to prune runtime generations: ${String(e)}`)}).finally(()=>{t.running=void 0,t.requested?startDevelopmentGenerationPruning(e,t):developmentGenerationPruneStates.delete(e)})}export{activateDevelopmentGeneration,activateDevelopmentGenerationTransaction,discardDevelopmentGeneration,publishDevelopmentGeneration,stageDevelopmentGeneration};
@@ -1 +1 @@
1
- import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`],LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestEnablesWorkflow(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.workflowTool!==void 0)}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,n,r){return n.startsWith(`workflow`)?resolveWorkflowModulePath(n):n.startsWith(`.`)||n.startsWith(`/`)||n.startsWith(`file://`)?resolveNitroModuleComparisonPath(r===void 0?e:dirname(resolveNitroModuleComparisonPath(e,r)),n):null}async function collectNitroStepTransformTargets(t,n){let r=await readFile(t,`utf8`),i=new Set;for(let e of parseImportedModuleSpecifiers(r)){let r=resolveNitroImportPath(n,e,t);r!==null&&i.add(normalizeStepTransformComparisonPath(r))}return i}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),a=normalizePath(t),o=r.toLowerCase(),s=a.toLowerCase();if(s.startsWith(`${o}/`))return a.slice(r.length+1);if(s===o)return`.`;let c=relative(r,a).replaceAll(`\\`,`/`);if(c.startsWith(`../`)&&(c=c.split(`/`).filter(e=>e!==`..`).join(`/`)),c.includes(`:`)||c.startsWith(`/`)){let e=a.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return c}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,s=`${r}/src/`,c=`${t}/dist/src/`,l=`${r}/dist/src/`;if(i.startsWith(s))return`src/${n.slice(a.length)}`;if(i.startsWith(l))return`src/${n.slice(c.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})}),clearCachedStepTransformTargets}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})}),clearCachedStepTransformTargets}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace})))),s=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),c=[r,createOptionalEngineDependencyPlugin(a),createExtensionExternalDependencyPlugin(s),o].filter(e=>e!==null);return{nitroRolldownConfig:createNitroBundlerConfig(c),nitroRollupConfig:createNitroBundlerConfig(c),tracedAppDependencies:collectHostedTraceDependencies(e,i),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(s)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestEnablesWorkflow(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){return[addNitroStepModuleSideEffectsPlugin(e,{stepEntrypointPath:t}),addNitroStepTransformPlugin(e,{stepEntrypointPath:t})]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,void 0),i=createApplicationNitroPlugins(e);e.compiledArtifacts.instrumentationPluginPath===void 0&&i.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let a=await createNitro({_cli:{command:`dev`},buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let o=join(a.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(a,e);let l=configureNitroStepPlugins(a,o);return a.hooks.hook(`dev:reload`,()=>{for(let e of l)e()}),externalizeDevelopmentWorkflowBundle(a,e),await configureDevelopmentNitroRoutes(a,e),await addNitroStepNoExternals(a,o),a}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),i=createApplicationNitroBundlerConfiguration(e,n),a=createApplicationNitroPlugins(e);a.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let o=await createNitro({_cli:{command:`build`},buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:t.outputDir},preset:n,plugins:a,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:i.nitroRolldownConfig,rollupConfig:i.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:i.tracedAppDependencies,traceOpts:{nft:{paths:i.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,publicRoutePrefix:t.publicRoutePrefix})});return await writeEveVersionedCacheMetadata(t.buildDir),configureSharedApplicationNitro(o,e),configureNitroStepPlugins(o,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0&&(applyEveCronHandlerRoute(o),registerScheduleTaskHandlers(o,{artifactsConfig:createProductionNitroArtifactsConfig(),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureProductionNitroRoutes(o,e),await addNitroStepNoExternals(o,join(e.workflowBuildDir,`steps.mjs`)),o}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
1
+ import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{createExtensionScopePlugin}from"#internal/bundler/extension-scope-plugin.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{createExtensionExternalDependencyPlugin,resolveExtensionExternalDependencyPaths}from"#internal/nitro/host/extension-external-dependency-plugin.js";import{createNitro}from"nitro/builder";import{prepareEveVersionedCacheDirectory,writeEveVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createProductionNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureDevelopmentNitroRoutes,configureProductionNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyEveCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME,createOptionalEngineDependencyPlugin}from"#internal/nitro/host/optional-engine-dependency-plugin.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{createEveVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`eve.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`],LOCAL_SANDBOX_BACKEND_NAMES=new Set([`docker`,...Object.keys(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME)]);function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveProductionNitroPreset(){return process.env.VERCEL?`vercel`:void 0}function manifestEnablesWorkflow(e){return[e,...e.subagents.map(e=>e.agent)].some(e=>e.workflowTool!==void 0)}function manifestHasWebSocketChannel(e){return e.channelRoutes.effective.some(e=>e.method===`WEBSOCKET`)}function collectHostedTraceDependencies(e,t){let n=new Set(collectExtensionExternalDependencies(e.compileResult.manifest)),r=[...e.compileResult.manifest.config.build?.externalDependencies??[],...e.compileResult.manifest.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])];return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...t,...r,...[...n].map(e=>`${e}*`)])].filter(e=>e!==EVE_PACKAGE_NAME&&e!==`${EVE_PACKAGE_NAME}*`)}function collectExtensionExternalDependencies(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.flatMap(e=>e.externalDependencies))}function collectConfiguredSandboxBackendNames(e){let t=[e,...e.subagents.map(e=>e.agent)];return new Set(t.map(e=>e.sandbox?.backendName).filter(e=>typeof e==`string`))}function shouldPruneLocalSandboxBackends(e){return e.preset===`vercel`&&![...e.configuredBackendNames].some(e=>LOCAL_SANDBOX_BACKEND_NAMES.has(e))}function createDevelopmentWatchOptions(e){return{ignored:[e,join(e,`**`)]}}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,t){return t.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(t)))):isAbsolute(t)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(t))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,t))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.eve/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(e,n,r){return n.startsWith(`workflow`)?resolveWorkflowModulePath(n):n.startsWith(`.`)||n.startsWith(`/`)||n.startsWith(`file://`)?resolveNitroModuleComparisonPath(r===void 0?e:dirname(resolveNitroModuleComparisonPath(e,r)),n):null}async function collectNitroStepTransformTargets(t,n){let r=await readFile(t,`utf8`),i=new Set;for(let e of parseImportedModuleSpecifiers(r)){let r=resolveNitroImportPath(n,e,t);r!==null&&i.add(normalizeStepTransformComparisonPath(r))}return i}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=createPackageRelativeTransformFilename(t);if(n!==void 0)return n;let r=normalizePath(e).replace(/\/$/,``),a=normalizePath(t),o=r.toLowerCase(),s=a.toLowerCase();if(s.startsWith(`${o}/`))return a.slice(r.length+1);if(s===o)return`.`;let c=relative(r,a).replaceAll(`\\`,`/`);if(c.startsWith(`../`)&&(c=c.split(`/`).filter(e=>e!==`..`).join(`/`)),c.includes(`:`)||c.startsWith(`/`)){let e=a.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return c}function createPackageRelativeTransformFilename(e){let t=normalizePath(resolvePackageRoot()).replace(/\/$/,``),n=normalizePath(e),r=t.toLowerCase(),i=n.toLowerCase(),a=`${t}/src/`,s=`${r}/src/`,c=`${t}/dist/src/`,l=`${r}/dist/src/`;if(i.startsWith(s))return`src/${n.slice(a.length)}`;if(i.startsWith(l))return`src/${n.slice(c.length)}`}function addWorkflowModuleSideEffectsPlugin(e,t){let n=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`eve:workflow-module-side-effects`,resolveId(t,r){let i=resolveNitroImportPath(e.options.rootDir,t,r)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return n.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`eve:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})}),clearCachedStepTransformTargets}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n),clearCachedStepTransformTargets=()=>{n=null};return e.hooks.hook(`build:before`,clearCachedStepTransformTargets),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`eve:workflow-step-transform`})}),clearCachedStepTransformTargets}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=new Set(t.map(normalizePath));e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`eve:instrumentation-module-side-effects`,resolveId(e){return n.has(normalizePath(e))?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}function createApplicationNitroBundlerConfiguration(e,t){let n=collectConfiguredSandboxBackendNames(e.compileResult.manifest),r=shouldPruneLocalSandboxBackends({configuredBackendNames:n,preset:t})?createCompiledSandboxBackendPrunePlugin():null,i=[],a=[];for(let[e,t]of Object.entries(OPTIONAL_ENGINE_PACKAGES_BY_BACKEND_NAME))(n.has(e)?i:a).push(t);let o=createExtensionScopePlugin([e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts.map(e=>({sourceRoot:e.sourceRoot,packageNamespace:e.packageNamespace})))),s=[e.compileResult.manifest,...e.compileResult.manifest.subagents.map(e=>e.agent)].flatMap(e=>e.extensionMounts),c=[r,createOptionalEngineDependencyPlugin(a),createExtensionExternalDependencyPlugin(s),o].filter(e=>e!==null);return{nitroRolldownConfig:createNitroBundlerConfig(c),nitroRollupConfig:createNitroBundlerConfig(c),tracedAppDependencies:collectHostedTraceDependencies(e,i),tracedAppDependencyPaths:resolveExtensionExternalDependencyPaths(s)}}function createApplicationNitroPlugins(e){let t=[e.compiledArtifacts.bootstrapPath,e.compiledArtifacts.workflowWorldPluginPath];return manifestEnablesWorkflow(e.compileResult.manifest)&&t.push(resolvePackageSourceFilePath(`src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&t.push(e.compiledArtifacts.instrumentationPluginPath),t}function configureSharedApplicationNitro(e,t){addNitroRoutingImportSpecifierPlugin(e);let n=resolveWorkflowAliases();for(let[t,r]of Object.entries(n))e.options.alias[t]=r;addWorkflowModuleSideEffectsPlugin(e,t.workflowBuildDir),patchWorkflowTransformExcludePath(e,t.workflowBuildDir),t.compiledArtifacts.instrumentationSourcePaths!==void 0&&addInstrumentationModuleSideEffectsPlugin(e,t.compiledArtifacts.instrumentationSourcePaths)}function configureNitroStepPlugins(e,t){return[addNitroStepModuleSideEffectsPlugin(e,{stepEntrypointPath:t}),addNitroStepTransformPlugin(e,{stepEntrypointPath:t})]}function externalizeDevelopmentWorkflowBundle(e,t){let n=new Set([normalizePath(join(t.workflowBuildDir,`workflows.mjs`))]);e.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(normalizePath(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}async function createDevelopmentApplicationNitro(e){let t=e.workspace.nitroBuildDir,n=createApplicationNitroBundlerConfiguration(e,void 0),i=createApplicationNitroPlugins(e);e.compiledArtifacts.instrumentationPluginPath===void 0&&i.unshift(resolvePackageSourceFilePath(`src/internal/nitro/host/local-tracing-runtime-plugin.ts`)),await prepareEveVersionedCacheDirectory(t);let a=await createNitro({_cli:{command:`dev`},buildDir:t,dev:!0,features:{websocket:!0},logLevel:1,output:{dir:e.workspace.nitroOutputDir},plugins:i,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:n.nitroRolldownConfig,rollupConfig:n.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:n.tracedAppDependencies,traceOpts:{nft:{paths:n.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:!1}),watchOptions:createDevelopmentWatchOptions(e.appRoot)},{watch:!0});await writeEveVersionedCacheMetadata(t);let o=join(a.options.buildDir,`workflow`,`steps.mjs`);configureSharedApplicationNitro(a,e);let l=configureNitroStepPlugins(a,o);return a.hooks.hook(`dev:reload`,()=>{for(let e of l)e()}),externalizeDevelopmentWorkflowBundle(a,e),await configureDevelopmentNitroRoutes(a,e),await addNitroStepNoExternals(a,o),a}async function createProductionApplicationNitro(e,t){let n=resolveProductionNitroPreset(),i=createApplicationNitroBundlerConfiguration(e,n),a=createApplicationNitroPlugins(e);a.push(resolvePackageSourceFilePath(`src/internal/nitro/host/sandbox-shutdown-plugin.ts`)),await prepareEveVersionedCacheDirectory(t.buildDir);let o=await createNitro({_cli:{command:`build`},buildDir:t.buildDir,dev:!1,features:{websocket:manifestHasWebSocketChannel(e.compileResult.manifest)},output:{dir:t.outputDir},preset:n,plugins:a,publicAssets:[],scanDirs:[resolvePackageSourceDirectoryPath(`src/execution`)],rolldownConfig:i.nitroRolldownConfig,rollupConfig:i.nitroRollupConfig,rootDir:e.appRoot,serverDir:!1,traceDeps:i.tracedAppDependencies,traceOpts:{nft:{paths:i.tracedAppDependencyPaths}},vercel:createEveVercelOptions({agentName:e.compileResult.manifest.config.name,enabled:n===`vercel`,publicRoutePrefix:t.publicRoutePrefix})});return await writeEveVersionedCacheMetadata(t.buildDir),configureSharedApplicationNitro(o,e),configureNitroStepPlugins(o,join(e.workflowBuildDir,`steps.mjs`)),e.scheduleRegistrations.length>0&&(applyEveCronHandlerRoute(o),registerScheduleTaskHandlers(o,{artifactsConfig:createProductionNitroArtifactsConfig(),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureProductionNitroRoutes(o,e),await addNitroStepNoExternals(o,join(e.workflowBuildDir,`steps.mjs`)),o}export{createDevelopmentApplicationNitro,createProductionApplicationNitro,shouldPruneLocalSandboxBackends};
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{readFile}from"node:fs/promises";import{readDevelopmentEnvironmentHostValues}from"#cli/dev/environment.js";import{resolveCompiledModuleExtensionScopeNamespace}from"#compiler/module-map.js";import{bundleAuthoredModuleForGeneration}from"#internal/authored-module-loader.js";import{computeChannelRouteRegistrations}from"#internal/nitro/host/channel-routes.js";async function computeDevelopmentHostFingerprint(t){let r=t.compileResult.manifest,i=[r,...r.subagents.map(e=>e.agent)],o={agentName:r.config.name,bundler:{externalDependencies:[...new Set([...r.config.build?.externalDependencies??[],...r.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])])].sort((e,t)=>e.localeCompare(t)),extensionScopes:i.flatMap(e=>e.extensionMounts).map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})).sort((e,t)=>e.sourceRoot.localeCompare(t.sourceRoot)),sandboxBackends:[...new Set(i.map(e=>e.sandbox?.backendName).filter(e=>e!==void 0))].sort((e,t)=>e.localeCompare(t))},channels:computeChannelRouteRegistrations(t),environment:readDevelopmentEnvironmentHostValues(t.appRoot),instrumentation:await readInstrumentationSource(t),workflow:{enabled:i.some(e=>e.workflowTool!==void 0),world:r.config.experimental?.workflow?.world??`local`}};return createHash(`sha256`).update(JSON.stringify(o)).digest(`hex`)}async function readInstrumentationSource(e){let n=e.compileResult.manifest.instrumentation;if(n!==void 0){let t=e.compileResult.manifest.bindings[n.sourceId];if(t===void 0)throw Error(`Compiled instrumentation source "${n.sourceId}" has no binding.`);return{kind:`file`,modules:[{slot:null,source:t.backing.kind===`filesystem`?await bundleAuthoredModuleForGeneration(t.backing.sourcePath,{externalDependencies:t.backing.externalDependencies,extensionScopeNamespace:resolveCompiledModuleExtensionScopeNamespace(t)}):JSON.stringify(t.backing)}]}}let a=e.compiledArtifacts.instrumentationSourcePaths,o=e.compiledArtifacts.instrumentationLayout;if(a===void 0||o===void 0)return null;let s=await Promise.all(a.map(async e=>await readFile(e,`utf8`)));return{kind:o.kind,modules:s.map((e,t)=>({slot:o.kind===`directory`?o.slots[t]??null:null,source:e}))}}export{computeDevelopmentHostFingerprint};
1
+ import{createHash}from"node:crypto";import{readFile}from"node:fs/promises";import{readDevelopmentEnvironmentHostValues}from"#cli/dev/environment.js";import{resolveCompiledModuleExtensionScopeNamespace}from"#compiler/module-map.js";import{bundleAuthoredModuleForGeneration}from"#internal/authored-module-loader.js";import{computeChannelRouteRegistrations}from"#internal/nitro/host/channel-routes.js";async function computeDevelopmentHostFingerprint(t){let r=t.compileResult.manifest,i=[r,...r.subagents.map(e=>e.agent)],o={agentName:r.config.name,bundler:{externalDependencies:[...new Set([...r.config.build?.externalDependencies??[],...r.subagents.flatMap(e=>e.configResolver===void 0?e.agent.config.build?.externalDependencies??[]:e.configResolver.build?.externalDependencies??[])])].sort((e,t)=>e.localeCompare(t)),extensionScopes:i.flatMap(e=>e.extensionMounts).map(e=>({packageNamespace:e.packageNamespace,sourceRoot:e.sourceRoot})).sort((e,t)=>e.sourceRoot.localeCompare(t.sourceRoot)),sandboxBackends:[...new Set(i.map(e=>e.sandbox?.backendName).filter(e=>e!==void 0))].sort((e,t)=>e.localeCompare(t))},channels:computeChannelRouteRegistrations(t),environment:readDevelopmentEnvironmentHostValues(t.appRoot),instrumentation:await readInstrumentationSource(t),workflow:{authoredSources:t.generation.workflowSourceFingerprint??null,enabled:i.some(e=>e.workflowTool!==void 0),world:r.config.experimental?.workflow?.world??`local`}};return createHash(`sha256`).update(JSON.stringify(o)).digest(`hex`)}async function readInstrumentationSource(e){let n=e.compileResult.manifest.instrumentation;if(n!==void 0){let t=e.compileResult.manifest.bindings[n.sourceId];if(t===void 0)throw Error(`Compiled instrumentation source "${n.sourceId}" has no binding.`);return{kind:`file`,modules:[{slot:null,source:t.backing.kind===`filesystem`?await bundleAuthoredModuleForGeneration(t.backing.sourcePath,{externalDependencies:t.backing.externalDependencies,extensionScopeNamespace:resolveCompiledModuleExtensionScopeNamespace(t)}):JSON.stringify(t.backing)}]}}let a=e.compiledArtifacts.instrumentationSourcePaths,o=e.compiledArtifacts.instrumentationLayout;if(a===void 0||o===void 0)return null;let s=await Promise.all(a.map(async e=>await readFile(e,`utf8`)));return{kind:o.kind,modules:s.map((e,t)=>({slot:o.kind===`directory`?o.slots[t]??null:null,source:e}))}}export{computeDevelopmentHostFingerprint};
@@ -1 +1 @@
1
- import{resolveModelEndpointStatus}from"#internal/resolve-model-endpoint-status.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";function toChatGptEndpoint(e){if(e===void 0)return;let t={state:e.kind};return e.kind===`ready`&&e.accountLabel!==void 0?{...t,accountLabel:e.accountLabel}:t}function buildAgentInfoResponse(r,i){let{manifest:a}=r,o=toModuleSource(a,a.config.source);if(o.binding===void 0)throw Error(`Compiled config source "${a.config.source.sourceId}" has no binding.`);let s=collectCompositionDiagnostics(a),c=collectRemoteAgents(a);return{agent:{agentRoot:a.agentRoot,appRoot:a.appRoot,config:{...o,binding:o.binding},description:a.config.description,model:a.config.dynamicModel===void 0?{contextWindowTokens:a.config.model.contextWindowTokens,endpoint:resolveModelEndpointStatus(a.config.model.routing,i.gatewayCredentials,toChatGptEndpoint(i.chatgptAuth)),id:a.config.model.id,providerOptions:a.config.model.providerOptions,reasoning:a.config.reasoning,routing:a.config.model.routing,source:a.config.model.source===void 0?void 0:toModuleSource(a,a.config.model.source)}:{reasoning:a.config.reasoning,routing:{kind:`dynamic`,resolver:renderDynamicResolver(a,{...a.config.dynamicModel,slug:`model`})}},name:a.config.name,nodeId:ROOT_COMPILED_AGENT_NODE_ID,outputSchema:a.config.outputSchema},capabilities:{devRoutes:i.mode===`development`},channels:{routes:a.channelRoutes.effective.map(e=>({...toModuleSource(a,e),adapterKind:e.adapterKind,method:e.method,name:e.name,urlPath:e.urlPath})),shadowed:[...a.channelRoutes.shadowed]},composition:s,connections:a.connections.map(e=>({...toModuleSource(a,e),connectionName:e.connectionName,description:e.description,hasApproval:!1,hasAuthorization:e.vercelConnect!==void 0,hasHeaders:!1,protocol:e.protocol,url:e.url})),diagnostics:{discoveryErrors:a.diagnosticsSummary.errors,discoveryWarnings:a.diagnosticsSummary.warnings},hooks:a.hooks.map(e=>({...toModuleSource(a,e),eventNames:[...e.eventNames],slug:e.slug})),instructions:{dynamic:a.dynamicInstructions.map(e=>renderDynamicResolver(a,e)),static:a.instructions.map(e=>({...toOwnedSource(a,e),content:e.content,name:e.name,role:e.role}))},instrumentation:a.instrumentation===void 0?void 0:toModuleSource(a,a.instrumentation),kernelEffects:projectPreparedKernelEffects(a),kind:`eve-agent-info`,memories:a.memories.map(e=>({...toModuleSource(a,e),description:e.description,slot:e.slot,visibility:e.visibility})),mode:i.mode,remoteAgents:{entries:c,total:c.length},sandbox:{...toModuleSource(a,a.sandbox),backendKind:a.sandbox.backendName,description:a.sandbox.description,hasBootstrap:!1,hasOnSession:!1,revalidationKey:a.sandbox.revalidationKey,sourceHash:a.sandbox.sourceHash},schedules:a.schedules.map(e=>({...toOwnedSource(a,e),cron:e.cron,hasRun:e.hasRun,markdown:e.markdown,name:e.name})),skills:{dynamic:a.dynamicSkills.map(e=>renderDynamicResolver(a,e)),static:a.skills.map(e=>({...toOwnedSource(a,e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name}))},subagents:{local:a.subagents.map(e=>{let t={...toOwnedSource(a,e),description:e.description,entryPath:e.entryPath,name:e.name,nodeId:e.nodeId,parentNodeId:e.parentNodeId,rootPath:e.rootPath,summary:summarizeNode(e.agent)};return e.configResolver===void 0?t:{...t,configResolver:renderDynamicResolver(e.agent,{...e.configResolver,slug:`config`})}}),total:a.subagents.length},tools:{dynamic:a.dynamicTools.map(e=>renderDynamicResolver(a,e)),static:a.tools.map(e=>({...toModuleSource(a,e),description:e.description,hasAuth:!1,hasExecute:e.hasExecute,hasModelOutputProjection:e.hasModelOutputProjection,hasOutputSchema:e.outputSchema!==void 0,inputSchema:e.inputSchema,name:e.name,outputSchema:e.outputSchema,requiresApproval:e.requiresApproval}))},version:4,workflow:a.workflowTool===void 0?{enabled:!1,toolName:WORKFLOW_TOOL_NAME}:{enabled:!0,source:toModuleSource(a,a.workflowTool),toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:a.workspaceResourceRoot,rootEntries:[...a.workspaceResourceRoot.rootEntries]}}}function toModuleSource(e,t){let n=e.bindings[t.sourceId];if(n===void 0)throw Error(`Compiled source "${t.sourceId}" has no binding.`);return sourceProjection(t,n.owner,n)}function toOwnedSource(e,t){let n=e.bindings[t.sourceId],r=n?.owner??t.owner;if(r===void 0)throw Error(`Compiled source "${t.sourceId}" has no owner.`);return sourceProjection(t,r,n)}function sourceProjection(e,t,n){let r={logicalPath:e.logicalPath,owner:t,sourceId:e.sourceId,sourceKind:toAgentInfoSourceKind(e.sourceKind)},i=n===void 0?void 0:{backing:n.backing,logicalPath:n.logicalPath,owner:n.owner};return n!==void 0&&e.exportName!==void 0?{...r,binding:i,exportName:e.exportName}:n===void 0?e.exportName===void 0?r:{...r,exportName:e.exportName}:{...r,binding:i}}function toAgentInfoSourceKind(e){switch(e){case`markdown`:case`module`:case`skill-package`:return e;default:throw Error(`Unsupported compiled source kind "${e}".`)}}function renderDynamicResolver(e,t){return{...toModuleSource(e,t),eventNames:[...t.eventNames],slug:t.slug}}function summarizeNode(e){return{channels:e.channelRoutes.effective.length,connections:e.connections.length,hooks:e.hooks.length,instructions:e.instructions.length,memories:e.memories.length,schedules:e.schedules.length,skills:e.skills.length,tools:e.tools.length}}function collectRemoteAgents(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.remoteAgents.map(e=>({...sourceProjection(e,e.owner,e.binding),description:e.description,name:e.name,nodeId:e.nodeId,parentNodeId:e.parentNodeId,url:e.url})))}function collectCompositionDiagnostics(e){let t=[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.sourceComposition.entries).map(e=>{let t={kind:e.kind,logicalPath:e.source.logicalPath,owner:e.source.owner,sourceId:e.source.sourceId};return e.kind===`shadowed`?{...t,winnerSourceId:e.winnerSourceId}:t});return{disabled:t.filter(e=>e.kind===`disabled`),shadowed:t.filter(e=>e.kind===`shadowed`)}}function projectPreparedKernelEffects(e){let t=[];for(let n of e.tools){let e=n.behavior,r=e?.handling;if(!(e===void 0||r===void 0))switch(r.kind){case`dispatch`:t.push({action:r.action===`self-agent`?`subagent-call`:r.action,audience:[...e.availability],kind:`dispatch`,sourceId:n.sourceId});break;case`provider-tool`:t.push({audience:[...e.availability],kind:`provider-tool`,sourceId:n.sourceId});break;case`request-input`:t.push({audience:[...e.availability],kind:`request-input`,sourceId:n.sourceId});break;default:throw Error(`Unsupported compiled tool handling: ${String(r)}`)}}return t}export{buildAgentInfoResponse};
1
+ import{resolveModelEndpointStatus}from"#internal/resolve-model-endpoint-status.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";function toChatGptEndpoint(e){if(e===void 0)return;let t={state:e.kind};return e.kind===`ready`&&e.accountLabel!==void 0?{...t,accountLabel:e.accountLabel}:t}function buildAgentInfoResponse(r,i){let{manifest:a}=r,o=toModuleSource(a,a.config.source);if(o.binding===void 0)throw Error(`Compiled config source "${a.config.source.sourceId}" has no binding.`);let s=collectCompositionDiagnostics(a),c=collectRemoteAgents(a);return{agent:{agentRoot:a.agentRoot,appRoot:a.appRoot,config:{...o,binding:o.binding},description:a.config.description,model:a.config.dynamicModel===void 0?{contextWindowTokens:a.config.model.contextWindowTokens,endpoint:resolveModelEndpointStatus(a.config.model.routing,i.gatewayCredentials,toChatGptEndpoint(i.chatgptAuth)),id:a.config.model.id,providerOptions:a.config.model.providerOptions,reasoning:a.config.reasoning,routing:a.config.model.routing,source:a.config.model.source===void 0?void 0:toModuleSource(a,a.config.model.source)}:{reasoning:a.config.reasoning,routing:{kind:`dynamic`,resolver:renderDynamicResolver(a,{...a.config.dynamicModel,slug:`model`})}},name:a.config.name,nodeId:ROOT_COMPILED_AGENT_NODE_ID,outputSchema:a.config.outputSchema},capabilities:{devRoutes:i.mode===`development`},channels:{routes:a.channelRoutes.effective.map(e=>({...toModuleSource(a,e),adapterKind:e.adapterKind,method:e.method,name:e.name,urlPath:e.urlPath})),shadowed:[...a.channelRoutes.shadowed]},composition:s,connections:a.connections.map(e=>({...toModuleSource(a,e),connectionName:e.connectionName,description:e.description,hasApproval:!1,hasAuthorization:e.vercelConnect!==void 0,hasHeaders:!1,protocol:e.protocol,url:e.url})),diagnostics:{discoveryErrors:a.diagnosticsSummary.errors,discoveryWarnings:a.diagnosticsSummary.warnings},hooks:a.hooks.map(e=>({...toModuleSource(a,e),eventNames:[...e.eventNames],slug:e.slug})),instructions:{dynamic:a.dynamicInstructions.map(e=>renderDynamicResolver(a,e)),static:a.instructions.map(e=>({...toOwnedSource(a,e),content:e.content,name:e.name,role:e.role}))},instrumentation:a.instrumentation===void 0?void 0:toModuleSource(a,a.instrumentation),kernelEffects:projectPreparedKernelEffects(a),kind:`eve-agent-info`,memories:a.memories.map(e=>({...toModuleSource(a,e),description:e.description,slot:e.slot,visibility:e.visibility})),mode:i.mode,remoteAgents:{entries:c,total:c.length},sandbox:{...toModuleSource(a,a.sandbox),backendKind:a.sandbox.backendName,description:a.sandbox.description,hasBootstrap:!1,hasOnSession:!1,revalidationKey:a.sandbox.revalidationKey,sourceHash:a.sandbox.sourceHash},schedules:a.schedules.map(e=>({...toOwnedSource(a,e),cron:e.cron,hasRun:e.hasRun,markdown:e.markdown,name:e.name})),skills:{dynamic:a.dynamicSkills.map(e=>renderDynamicResolver(a,e)),static:a.skills.map(e=>({...toOwnedSource(a,e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name}))},subagents:{local:a.subagents.map(e=>{let t={...toOwnedSource(a,e),description:e.description,entryPath:e.entryPath,name:e.name,nodeId:e.nodeId,parentNodeId:e.parentNodeId,rootPath:e.rootPath,summary:summarizeNode(e.agent)};return e.configResolver===void 0?t:{...t,configResolver:renderDynamicResolver(e.agent,{...e.configResolver,slug:`config`})}}),total:a.subagents.length},tools:{dynamic:a.dynamicTools.map(e=>renderDynamicResolver(a,e)),static:a.tools.map(e=>({...toModuleSource(a,e),description:e.description,hasAuth:!1,hasExecute:e.hasExecute,hasModelOutputProjection:e.hasModelOutputProjection,hasOutputSchema:e.outputSchema!==void 0,inputSchema:e.inputSchema,name:e.name,outputSchema:e.outputSchema,requiresApproval:e.requiresApproval}))},version:4,workflow:a.workflowTool===void 0?{enabled:!1,toolName:WORKFLOW_TOOL_NAME}:{enabled:!0,source:toModuleSource(a,a.workflowTool),toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:a.workspaceResourceRoot,rootEntries:[...a.workspaceResourceRoot.rootEntries]}}}function toModuleSource(e,t){let n=e.bindings[t.sourceId];if(n===void 0)throw Error(`Compiled source "${t.sourceId}" has no binding.`);return sourceProjection(t,n.owner,n)}function toOwnedSource(e,t){let n=e.bindings[t.sourceId],r=n?.owner??t.owner;if(r===void 0)throw Error(`Compiled source "${t.sourceId}" has no owner.`);return sourceProjection(t,r,n)}function sourceProjection(e,t,n){let r={logicalPath:e.logicalPath,owner:t,sourceId:e.sourceId,sourceKind:toAgentInfoSourceKind(e.sourceKind)},i=n===void 0?void 0:{backing:n.backing,logicalPath:n.logicalPath,owner:n.owner};return n!==void 0&&e.exportName!==void 0?{...r,binding:i,exportName:e.exportName}:n===void 0?e.exportName===void 0?r:{...r,exportName:e.exportName}:{...r,binding:i}}function toAgentInfoSourceKind(e){switch(e){case`markdown`:case`module`:case`skill-package`:return e;default:throw Error(`Unsupported compiled source kind "${e}".`)}}function renderDynamicResolver(e,t){return{...toModuleSource(e,t),eventNames:[...t.eventNames],slug:t.slug}}function summarizeNode(e){return{channels:e.channelRoutes.effective.length,connections:e.connections.length,hooks:e.hooks.length,instructions:e.instructions.length,memories:e.memories.length,schedules:e.schedules.length,skills:e.skills.length,tools:e.tools.length}}function collectRemoteAgents(e){return[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.remoteAgents.map(e=>({...sourceProjection(e,e.owner,e.binding),description:e.description,name:e.name,nodeId:e.nodeId,parentNodeId:e.parentNodeId,url:e.url})))}function collectCompositionDiagnostics(e){let t=[e,...e.subagents.map(e=>e.agent)].flatMap(e=>e.sourceComposition.entries).map(e=>{let t={kind:e.kind,logicalPath:e.source.logicalPath,owner:e.source.owner,sourceId:e.source.sourceId};return e.kind===`shadowed`?{...t,winnerSourceId:e.winnerSourceId}:t});return{disabled:t.filter(e=>e.kind===`disabled`),shadowed:t.filter(e=>e.kind===`shadowed`)}}function projectPreparedKernelEffects(e){let t=[];for(let n of e.tools){let e=n.behavior,r=e?.handling;if(!(e===void 0||r===void 0))switch(r.kind){case`dispatch`:t.push({action:r.action===`self-agent`?`subagent-call`:r.action,audience:[...e.availability],kind:`dispatch`,sourceId:n.sourceId});break;case`provider-tool`:t.push({audience:[...e.availability],kind:`provider-tool`,sourceId:n.sourceId});break;case`request-input`:t.push({audience:[...e.availability],kind:`request-input`,sourceId:n.sourceId});break;case`workflow-tool`:t.push({action:`workflow-tool-call`,audience:[...e.availability],kind:`dispatch`,sourceId:n.sourceId});break;default:throw Error(`Unsupported compiled tool handling: ${String(r)}`)}}return t}export{buildAgentInfoResponse};
@@ -1 +1 @@
1
- import{createAttachSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{createChannelOperations}from"#channel/channel-operations.js";import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse,attachHomeRouteMetadata,attachRemoteAgentStreamHeadersResolver,attachRouteChannelName,attachRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{withLocalDevRequestScope}from"#runtime/local-dev-capability.js";import{traceChannelRequest}from"#internal/nitro/routes/channel-request-instrumentation.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#channel/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){return await traceChannelRequest({request:e.req,routeKey:t},async i=>{let o=await resolveNitroChannelRuntimeBundle(r),s=o.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(s===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});i?.setAttribute(`eve.channel.name`,s.name);let c=getChannelInstrumentationKind(s.definition)??s.adapter?.kind;c!==void 0&&i?.setAttribute(`eve.channel.kind`,c);let l=buildRouteArgs(e,o,s.name,c??`channel`,r,i),u;try{u=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(s.handler)return await s.handler(e.req,l.args);let t={waitUntil:l.args.waitUntil,params:l.args.params,requestIp:l.args.requestIp};return await s.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:s.name});return flushBackgroundTasks(e,l.backgroundTasks,t,s.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,l.backgroundTasks,t,s.name),u})}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),o=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(o===void 0||o.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let s=o.websocket,c=getChannelInstrumentationKind(o.definition)??o.adapter?.kind??`channel`,l=buildRouteArgs(e,i,o.name,c,r,void 0);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await s(e.req,l.args));return flushBackgroundTasks(e,l.backgroundTasks,t,o.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:o.name});return flushBackgroundTasks(e,l.backgroundTasks,t,o.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withLocalDevRequestScope(t,async()=>await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n)):await n()}function buildRouteArgs(t,n,a,d,f,p){let m=readVercelRequestId(t.req.headers),h=extractRequestIp(t,f),g=[],_=t.context.params??{},v={};for(let[e,t]of Object.entries(_))v[e]=decodeURIComponent(t);let waitUntil=e=>{g.push(e)},y=n.channels.find(e=>e.name===a),b=y?.adapter??{kind:`channel`},x=p?.spanContext(),S={channelKind:d,channelName:a,requestId:m,requestTraceContext:x===void 0?void 0:{spanId:x.spanId,traceFlags:x.traceFlags,traceId:x.traceId}},C=createChannelOperations({adapter:b,channelName:a,metadata:S,runtime:n.runtime,turnPolicy:y?.turnPolicy}),w=createAttachSessionFn(n.runtime,{...S,turnPolicy:y?.turnPolicy}),T=createCrossChannelToFn(n.runtime,toCrossChannelTargets(n.channels)),E=attachRouteSessionCreator(attachHomeRouteMetadata(attachRouteChannelName(attachAgentInfoRouteResponse({attachSession:w,...C,params:v,requestIp:h,to:T,waitUntil},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(f)}),a),{agentName:n.agentName}),async e=>await n.runtime.createSession({...e,adapter:b,channelName:a,continuationToken:e.continuationToken===void 0?void 0:`${a}:${e.continuationToken}`,delivery:createChannelDeliveryMetadata(S),requestId:m}));return n.resolveRemoteAgentStreamHeaders!==void 0&&attachRemoteAgentStreamHeadersResolver(E,n.resolveRemoteAgentStreamHeaders),{args:E,backgroundTasks:g}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
1
+ import{createAttachSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{createChannelOperations}from"#channel/channel-operations.js";import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse,attachHomeRouteMetadata,attachRemoteAgentStreamHeadersResolver,attachRouteChannelName,attachRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{withLocalDevRequestScope}from"#runtime/local-dev-capability.js";import{traceChannelRequest}from"#internal/nitro/routes/channel-request-instrumentation.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#channel/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){return await traceChannelRequest({request:e.req,routeKey:t},async i=>{let o=await resolveNitroChannelRuntimeBundle(r),s=o.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(s===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});i?.setAttribute(`eve.channel.name`,s.name);let c=getChannelInstrumentationKind(s.definition)??s.adapter?.kind;c!==void 0&&i?.setAttribute(`eve.channel.kind`,c);let l=buildRouteArgs(e,o,s.name,c??`channel`,r,i),u;try{u=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(s.handler)return await s.handler(e.req,l.args);let t={waitUntil:l.args.waitUntil,params:l.args.params,requestIp:l.args.requestIp};return await s.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:s.name});return flushBackgroundTasks(e,l.backgroundTasks,t,s.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,l.backgroundTasks,t,s.name),u})}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),o=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(o===void 0||o.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let s=o.websocket,c=getChannelInstrumentationKind(o.definition)??o.adapter?.kind??`channel`,l=buildRouteArgs(e,i,o.name,c,r,void 0);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await s(e.req,l.args));return flushBackgroundTasks(e,l.backgroundTasks,t,o.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:o.name});return flushBackgroundTasks(e,l.backgroundTasks,t,o.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withLocalDevRequestScope(t,async()=>await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n)):await n()}function buildRouteArgs(t,n,a,d,f,p){let m=readVercelRequestId(t.req.headers),h=extractRequestIp(t,f),g=[],_=t.context.params??{},v={};for(let[e,t]of Object.entries(_))v[e]=decodeURIComponent(t);let waitUntil=e=>{g.push(e)},y=n.channels.find(e=>e.name===a),b=y?.adapter??{kind:`channel`},x=p?.spanContext(),S={acceptedDeploymentId:process.env.VERCEL_DEPLOYMENT_ID?.trim()||void 0,channelKind:d,channelName:a,requestId:m,requestTraceContext:x===void 0?void 0:{spanId:x.spanId,traceFlags:x.traceFlags,traceId:x.traceId}},C=createChannelOperations({adapter:b,channelName:a,metadata:S,runtime:n.runtime,turnPolicy:y?.turnPolicy}),w=createAttachSessionFn(n.runtime,{...S,turnPolicy:y?.turnPolicy}),T=createCrossChannelToFn(n.runtime,toCrossChannelTargets(n.channels)),E=attachRouteSessionCreator(attachHomeRouteMetadata(attachRouteChannelName(attachAgentInfoRouteResponse({attachSession:w,...C,params:v,requestIp:h,to:T,waitUntil},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(f)}),a),{agentName:n.agentName}),async e=>await n.runtime.createSession({...e,adapter:b,channelName:a,continuationToken:e.continuationToken===void 0?void 0:`${a}:${e.continuationToken}`,delivery:createChannelDeliveryMetadata(S),requestId:m}));return n.resolveRemoteAgentStreamHeaders!==void 0&&attachRemoteAgentStreamHeadersResolver(E,n.resolveRemoteAgentStreamHeaders),{args:E,backgroundTasks:g}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
@@ -0,0 +1,17 @@
1
+ export interface AuthoredWorkflowDirectiveSource {
2
+ /** Name of the top-level `"use workflow"` function the default export's `execute` is or references. */
3
+ readonly executeWorkflow?: string;
4
+ readonly hasDirectives: boolean;
5
+ readonly hasWorkflowDirective: boolean;
6
+ readonly source: string;
7
+ }
8
+ /**
9
+ * The directive transform understands one shape: a top-level `async function`
10
+ * whose first statement is the directive. A tool's `execute` method is hoisted
11
+ * into that shape here; every other placement is a build error, because an
12
+ * ignored directive would run side effects inline in a replayed body.
13
+ */
14
+ export declare function prepareAuthoredWorkflowDirectives(input: {
15
+ readonly filePath: string;
16
+ readonly source: string;
17
+ }): Promise<AuthoredWorkflowDirectiveSource>;
@@ -0,0 +1 @@
1
+ import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{detectWorkflowPatterns}from"#compiled/@workflow/builders/index.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const HOISTED_EXECUTE_NAME=`execute`;async function prepareAuthoredWorkflowDirectives(i){let a=await parseWithNitroRolldownAst(i.filePath,i.source),o=a.body??[];for(let e of o){if(typeof e.directive!=`string`)break;let t=readWorkflowDirective(e);if(t!==void 0)throw Error(`${JSON.stringify(t)} in "${i.filePath}" is a module-level directive. Put it as the first statement of the function it marks: a top-level "async function" declaration or, for "use workflow", the "execute" method of the module's default export.`)}let s=new Set;for(let e of o){let t=e.type===`FunctionDeclaration`?e:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`?e.declaration:void 0;t!==void 0&&s.add(t)}let c=findDefaultExportExecuteProperty(o),l=c!==void 0&&isAstNode(c.value)&&isFunctionLike(c.value)?c.value:void 0;l!==void 0&&s.add(l);let u=collectDirectiveFunctions(a);if(u.length===0)return{hasDirectives:!1,hasWorkflowDirective:!1,source:i.source};let d=u.some(e=>e.directive===`use workflow`),f=detectWorkflowPatterns(i.source).hasDirective;for(let e of u){if(!f)throw Error(`${JSON.stringify(e.directive)} in "${i.filePath}" is not on its own line. Write it as the first statement of the function body, on a line by itself.`);if(!s.has(e.fn))throw Error(`${JSON.stringify(e.directive)} in "${i.filePath}" marks ${describeFunction(e.fn)}. Workflow directives must mark a top-level "async function" declaration or, for "use workflow", the "execute" method of the module's default export.`);if(e.fn.async!==!0)throw Error(`${JSON.stringify(e.directive)} in "${i.filePath}" marks ${describeFunction(e.fn)}, which is not async. Declare it with "async function".`);if(e.fn===l&&e.directive!==`use workflow`)throw Error(`"use step" in "${i.filePath}" marks the default export's "execute" method. A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`)}let p=u.find(e=>e.fn===l);if(p===void 0||c===void 0){let e={hasDirectives:!0,hasWorkflowDirective:d,source:i.source},t=readExecuteReference(c,u);return t===void 0?e:{...e,executeWorkflow:t}}if(declaresTopLevelBinding(o,HOISTED_EXECUTE_NAME))throw Error(`"use workflow" in "${i.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`);return{executeWorkflow:HOISTED_EXECUTE_NAME,hasDirectives:!0,hasWorkflowDirective:d,source:hoistExecuteMethod(i.source,c,p.fn)}}function readExecuteReference(e,t){let n=e?.value;if(!isAstNode(n)||n.type!==`Identifier`||typeof n.name!=`string`)return;let r=n.name;return t.find(e=>e.directive===`use workflow`&&e.fn.id?.name===r)===void 0?void 0:r}function findDefaultExportExecuteProperty(e){let t=e.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration,n=t?.type===`CallExpression`?t.arguments?.[0]:t;if(n?.type===`ObjectExpression`)return n.properties?.find(e=>e.type===`Property`&&e.kind===`init`&&e.computed!==!0&&readPropertyName(e.key)===HOISTED_EXECUTE_NAME)}function hoistExecuteMethod(e,t,n){if(t.start===void 0||t.end===void 0||!isAstNode(n.body)||n.body.start===void 0||n.body.end===void 0)throw Error(`Cannot hoist an execute method without source ranges.`);let i=n.params??[],a=i[0],o=i[i.length-1],s=a?.start===void 0||o?.end===void 0?``:e.slice(a.start,o.end),c=sliceNode(e,n.typeParameters),l=sliceNode(e,n.returnType),u=e.slice(n.body.start,n.body.end),d=`async function${n.generator===!0?`*`:``} ${HOISTED_EXECUTE_NAME}${c}(${s})${l} ${u}`;return`${e.slice(0,t.start)}${HOISTED_EXECUTE_NAME}${e.slice(t.end)}\n${d}\n`}function sliceNode(e,t){return t==null||t.start===void 0||t.end===void 0?``:e.slice(t.start,t.end)}function declaresTopLevelBinding(e,t){for(let n of e){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e!=null){if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.name===t)return!0;if(e.type===`VariableDeclaration`){for(let n of e.declarations??[])if(n.id?.name===t)return!0}if(e.type===`ImportDeclaration`){for(let n of e.specifiers??[])if(n.local?.name===t)return!0}}}return!1}function collectDirectiveFunctions(e){let t=[];return visit(e,e=>{if(!isFunctionLike(e))return;let n=readLeadingDirective(e);n!==void 0&&t.push({directive:n,fn:e})}),t}function readLeadingDirective(e){if(!(!isAstNode(e.body)||e.body.type!==`BlockStatement`||!Array.isArray(e.body.body)))return readWorkflowDirective(e.body.body[0])}function describeFunction(e){return e.type===`FunctionDeclaration`?e.id?.name===void 0?`a nested function declaration`:`the nested function "${e.id.name}"`:e.type===`ArrowFunctionExpression`?`an arrow function`:e.id?.name===void 0?`a function expression`:`the function "${e.id.name}"`}function readPropertyName(e){if(e!=null){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`&&typeof e.value==`string`)return e.value}}function isFunctionLike(e){return e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`}function visit(e,t){if(!e.type?.startsWith(`TS`)){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visit(e,t);else isAstNode(n)&&visit(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}export{prepareAuthoredWorkflowDirectives};
@@ -0,0 +1,19 @@
1
+ export interface AuthoredWorkflowModules {
2
+ readonly directiveModules: readonly string[];
3
+ readonly workflowModules: readonly string[];
4
+ }
5
+ /**
6
+ * Scans the whole application root, as the SDK's bundler integrations do, so a
7
+ * step helper can live wherever the tool imports it from. The SDK's pre-scan
8
+ * picks the files worth parsing.
9
+ */
10
+ export declare function discoverAuthoredWorkflowModules(appRoot: string): Promise<AuthoredWorkflowModules>;
11
+ /**
12
+ * The workflow id a tool's `execute` will run as, or `undefined` for an
13
+ * ordinary tool. Derived from the source the way the transform derives it, so
14
+ * the compiled manifest and the driver registry name the same run.
15
+ */
16
+ export declare function readAuthoredExecuteWorkflowId(input: {
17
+ readonly appRoot: string;
18
+ readonly filePath: string;
19
+ }): Promise<string | undefined>;
@@ -0,0 +1 @@
1
+ import{prepareAuthoredWorkflowDirectives}from"./authored-workflow-directives.js";import{isWorkflowSourceFile}from"./builder-support.js";import{authoredWorkflowId,isAuthoredApplicationModule,isAuthoredApplicationRoot}from"./workflow-builders.js";import{readFile,readdir}from"node:fs/promises";import{join}from"node:path";import{detectWorkflowPatterns,isGeneratedWorkflowFile}from"#compiled/@workflow/builders/index.js";const IGNORED_DIRECTORIES=new Set([`.cache`,`.eve`,`.git`,`.next`,`.nitro`,`.nuxt`,`.output`,`.pnpm-store`,`.svelte-kit`,`.swc`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.yarn`,`coverage`,`dist`,`node_modules`]);function isIgnoredDirectory(e){return IGNORED_DIRECTORIES.has(e)||e.startsWith(`.output.`)}async function discoverAuthoredWorkflowModules(t){let n=[],a=[];if(!isAuthoredApplicationRoot(t))return{directiveModules:n,workflowModules:a};let o=await collectSourceFiles(t);for(let i of o.sort()){if(!isAuthoredApplicationModule(i,t)||isGeneratedWorkflowFile(i))continue;let o=await readFile(i,`utf8`);if(!detectWorkflowPatterns(o).hasDirective)continue;let s=await prepareAuthoredWorkflowDirectives({filePath:i,source:o});s.hasDirectives&&(n.push(i),s.hasWorkflowDirective&&a.push(i))}return{directiveModules:n,workflowModules:a}}async function collectSourceFiles(e){let n=[];async function visit(e){let r;try{r=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let i of r){let r=join(e,i.name);if(i.isDirectory()){isIgnoredDirectory(i.name)||await visit(r);continue}i.isFile()&&isWorkflowSourceFile(i.name)&&n.push(r)}}return await visit(e),n}async function readAuthoredExecuteWorkflowId(t){if(!isAuthoredApplicationModule(t.filePath,t.appRoot))return;let i=await readFile(t.filePath,`utf8`);if(!detectWorkflowPatterns(i).hasDirective)return;let{executeWorkflow:a}=await prepareAuthoredWorkflowDirectives({filePath:t.filePath,source:i});return a===void 0?void 0:authoredWorkflowId(t.filePath,t.appRoot,a)}export{discoverAuthoredWorkflowModules,readAuthoredExecuteWorkflowId};
@@ -10,6 +10,8 @@ export interface WorkflowBundleBuilderOptions {
10
10
  /** Test-harness-only: also scans `src/internal/testing/`. */
11
11
  includeTestFixtures?: boolean;
12
12
  }
13
+ export declare const WORKFLOW_SOURCE_EXTENSIONS: readonly string[];
14
+ export declare function isWorkflowSourceFile(fileName: string): boolean;
13
15
  export interface WorkflowBundleBuilderConfig {
14
16
  readonly buildTarget: "standalone";
15
17
  readonly dirs: readonly string[];
@@ -25,8 +27,9 @@ export interface WorkflowBundleDiscoveredEntries {
25
27
  }
26
28
  export interface WorkflowBundleCreateWorkflowsBundleOptions {
27
29
  readonly additionalOutputs?: readonly WorkflowBundleOutput[];
28
- readonly discoveredEntries?: WorkflowBundleDiscoveredEntries;
29
- readonly inputFiles: readonly string[];
30
+ readonly appWorkflowFiles: readonly string[];
31
+ readonly frameworkSerdeFiles: readonly string[];
32
+ readonly frameworkWorkflowFiles: readonly string[];
30
33
  readonly outfile: string;
31
34
  readonly stepRegistrationsPath: string;
32
35
  readonly tsconfigPath?: string;
@@ -49,6 +52,12 @@ export declare function createWorkflowImport(filePath: string, workingDir: strin
49
52
  export declare function createWorkflowVirtualEntryPlugin(source: string): WorkflowRolldownPlugin;
50
53
  export declare function createWorkflowPseudoPackagePlugin(): WorkflowRolldownPlugin;
51
54
  export declare function createWorkflowRuntimeAliasPlugin(): WorkflowRolldownPlugin;
55
+ /**
56
+ * `workflow` resolves to the body-side shim. A `workflow/api` import still live
57
+ * after step bodies were stubbed means a body calls the runtime API; fail the
58
+ * build here rather than the driver later.
59
+ */
60
+ export declare function createWorkflowDriverAliasPlugin(workingDir: string): WorkflowRolldownPlugin;
52
61
  export declare function createEvePackageImportsPlugin(workingDir: string, options?: {
53
62
  workflowCondition?: boolean;
54
63
  }): WorkflowRolldownPlugin;
@@ -74,6 +83,12 @@ export declare function bundleFinalWorkflowOutput(input: {
74
83
  queueNamespace: string;
75
84
  stepRegistrationsPath?: string;
76
85
  }): Promise<void>;
86
+ /**
87
+ * Chunks share state only through globals (the workflow registry, the serde
88
+ * class registry, `Symbol.for` keys), so each runs in its own IIFE and their
89
+ * top-level declarations never collide.
90
+ */
91
+ export declare function composeWorkflowDriverCode(chunks: readonly string[]): string;
77
92
  export declare function createWorkflowEntrypointSource(input: {
78
93
  readonly code: string;
79
94
  readonly queueNamespace: string;