eve 0.81.0 → 0.82.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 (327) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/src/channel/channel-address.d.ts +21 -2
  3. package/dist/src/channel/channel-address.js +1 -1
  4. package/dist/src/channel/channel-operations.d.ts +32 -1
  5. package/dist/src/channel/channel-operations.js +1 -1
  6. package/dist/src/channel/delivery-idempotency.d.ts +4 -0
  7. package/dist/src/channel/delivery-idempotency.js +1 -0
  8. package/dist/src/channel/routes.d.ts +6 -0
  9. package/dist/src/channel/session.d.ts +5 -0
  10. package/dist/src/channel/session.js +1 -1
  11. package/dist/src/channel/types.d.ts +14 -11
  12. package/dist/src/chunks/{use-eve-agent-Bp6nbhfV.js → use-eve-agent-DTu78IAF.js} +36 -0
  13. package/dist/src/chunks/{use-eve-agent-DLkjJIm3.js → use-eve-agent-DlznYwQk.js} +36 -0
  14. package/dist/src/cli/dev/command-options.d.ts +1 -0
  15. package/dist/src/cli/dev/diagnostic-dump.js +1 -1
  16. package/dist/src/cli/run.d.ts +1 -0
  17. package/dist/src/cli/run.js +1 -1
  18. package/dist/src/client/index.d.ts +1 -1
  19. package/dist/src/client/message-reducer-types.d.ts +7 -3
  20. package/dist/src/client/message-reducer.js +1 -1
  21. package/dist/src/client/transcript-reducer.d.ts +6 -3
  22. package/dist/src/client/transcript-reducer.js +1 -1
  23. package/dist/src/compiled/.vendor-stamp.json +2 -2
  24. package/dist/src/compiled/@eve/catalog/index.js +1 -1
  25. package/dist/src/compiler/extension-compatibility.d.ts +19 -18
  26. package/dist/src/compiler/extension-compatibility.js +1 -1
  27. package/dist/src/compiler/load-binding-namespace.d.ts +2 -0
  28. package/dist/src/compiler/load-binding-namespace.js +1 -1
  29. package/dist/src/compiler/manifest.js +1 -1
  30. package/dist/src/compiler/module-lifecycle.d.ts +1 -1
  31. package/dist/src/compiler/module-lifecycle.js +1 -1
  32. package/dist/src/compiler/module-map.js +1 -1
  33. package/dist/src/compiler/normalize-agent-config.js +1 -1
  34. package/dist/src/compiler/normalize-manifest.js +1 -1
  35. package/dist/src/compiler/project-sources.d.ts +6 -0
  36. package/dist/src/compiler/project-sources.js +1 -1
  37. package/dist/src/context/keys.d.ts +2 -0
  38. package/dist/src/context/keys.js +1 -1
  39. package/dist/src/evals/cli/eval-state-directory.d.ts +7 -0
  40. package/dist/src/evals/cli/eval-state-directory.js +1 -0
  41. package/dist/src/evals/cli/eval.js +2 -2
  42. package/dist/src/eve-channel/create-request.d.ts +2 -1
  43. package/dist/src/eve-channel/index.js +1 -1
  44. package/dist/src/eve-channel/request.d.ts +2 -1
  45. package/dist/src/eve-channel/request.js +1 -2
  46. package/dist/src/eve-channel/support.d.ts +11 -1
  47. package/dist/src/eve-channel/support.js +2 -1
  48. package/dist/src/eve-channel/types.d.ts +25 -0
  49. package/dist/src/execution/agent-sessions/context.d.ts +2 -13
  50. package/dist/src/execution/agent-sessions/context.js +1 -1
  51. package/dist/src/execution/agent-sessions/runtime-overrides.d.ts +5 -0
  52. package/dist/src/execution/agent-sessions/runtime-overrides.js +1 -0
  53. package/dist/src/execution/agent-sessions/session.d.ts +2 -2
  54. package/dist/src/execution/agent-sessions/session.js +1 -1
  55. package/dist/src/execution/agent-sessions/steps.d.ts +2 -0
  56. package/dist/src/execution/agent-sessions/steps.js +1 -1
  57. package/dist/src/execution/coordination-dispatch-shared.d.ts +5 -5
  58. package/dist/src/execution/coordination-dispatch-step.d.ts +17 -2
  59. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  60. package/dist/src/execution/create-session-step.d.ts +5 -2
  61. package/dist/src/execution/create-session-step.js +1 -1
  62. package/dist/src/execution/deliver-payloads.js +1 -1
  63. package/dist/src/execution/durable-session-store.d.ts +0 -1
  64. package/dist/src/execution/dynamic-connection-recovery.js +1 -1
  65. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  66. package/dist/src/execution/effective-agent-config.d.ts +8 -2
  67. package/dist/src/execution/effective-agent-config.js +1 -1
  68. package/dist/src/execution/hook-ownership.d.ts +8 -0
  69. package/dist/src/execution/hook-ownership.js +1 -1
  70. package/dist/src/execution/install-workflow-deployment-id.d.ts +3 -0
  71. package/dist/src/execution/install-workflow-deployment-id.js +1 -0
  72. package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
  73. package/dist/src/execution/node-step.d.ts +1 -0
  74. package/dist/src/execution/node-step.js +1 -1
  75. package/dist/src/execution/runtime-context.d.ts +2 -0
  76. package/dist/src/execution/runtime-context.js +1 -1
  77. package/dist/src/execution/session/active-turn.js +1 -1
  78. package/dist/src/execution/session/admission.js +1 -1
  79. package/dist/src/execution/session/checkpoint-migrations.js +1 -1
  80. package/dist/src/execution/session/entry-input.d.ts +20 -8
  81. package/dist/src/execution/session/entry-input.js +1 -1
  82. package/dist/src/execution/session/entry.js +1 -1
  83. package/dist/src/execution/session/finalization.js +1 -1
  84. package/dist/src/execution/session/handoff-steps.d.ts +75 -13
  85. package/dist/src/execution/session/handoff-steps.js +1 -1
  86. package/dist/src/execution/session/handoff.d.ts +73 -34
  87. package/dist/src/execution/session/handoff.js +1 -1
  88. package/dist/src/execution/session/input-queue.d.ts +5 -1
  89. package/dist/src/execution/session/input-queue.js +1 -1
  90. package/dist/src/execution/session/pending-history.d.ts +5 -0
  91. package/dist/src/execution/session/pending-history.js +1 -0
  92. package/dist/src/execution/session/pending-turn-state.js +1 -1
  93. package/dist/src/execution/session/program.d.ts +1 -1
  94. package/dist/src/execution/session/program.js +1 -1
  95. package/dist/src/execution/session/run-watch.d.ts +22 -0
  96. package/dist/src/execution/session/run-watch.js +1 -0
  97. package/dist/src/execution/session/timeout-control.d.ts +18 -4
  98. package/dist/src/execution/session/timeout-control.js +1 -1
  99. package/dist/src/execution/session/timeout.d.ts +1 -2
  100. package/dist/src/execution/session/timeout.js +1 -1
  101. package/dist/src/execution/session/turn-event-handler.js +1 -1
  102. package/dist/src/execution/session/turn-step-result.js +1 -1
  103. package/dist/src/execution/session/turn-step.js +1 -1
  104. package/dist/src/execution/session/turn-waiting-step.js +1 -1
  105. package/dist/src/execution/session/turn.js +1 -1
  106. package/dist/src/execution/session-inbox/address.d.ts +4 -1
  107. package/dist/src/execution/session-inbox/end-stranded-session.js +1 -1
  108. package/dist/src/execution/session-inbox/hook-release.d.ts +9 -2
  109. package/dist/src/execution/session-inbox/hook-release.js +1 -1
  110. package/dist/src/execution/session-inbox/inbox.d.ts +66 -6
  111. package/dist/src/execution/session-inbox/inbox.js +1 -1
  112. package/dist/src/execution/session-inbox/protocol.js +1 -1
  113. package/dist/src/execution/session-inbox/resume.d.ts +4 -3
  114. package/dist/src/execution/session.d.ts +0 -12
  115. package/dist/src/execution/session.js +2 -2
  116. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  117. package/dist/src/execution/tasks/model-step.js +1 -1
  118. package/dist/src/execution/tasks/start.d.ts +4 -4
  119. package/dist/src/execution/tasks/start.js +1 -1
  120. package/dist/src/execution/tasks/steps.js +1 -1
  121. package/dist/src/execution/terminate-child-sessions-step.js +1 -1
  122. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  123. package/dist/src/execution/tools/workflow/body.d.ts +2 -2
  124. package/dist/src/execution/workflow-runtime.d.ts +11 -12
  125. package/dist/src/execution/workflow-runtime.js +1 -1
  126. package/dist/src/harness/hitl/approvals.js +1 -1
  127. package/dist/src/harness/hitl/budget-request.d.ts +12 -6
  128. package/dist/src/harness/hitl/budget-request.js +1 -1
  129. package/dist/src/harness/hitl/budget.d.ts +7 -1
  130. package/dist/src/harness/hitl/budget.js +1 -1
  131. package/dist/src/harness/hitl/coordinator.js +1 -1
  132. package/dist/src/harness/hitl/delivery.d.ts +1 -1
  133. package/dist/src/harness/hitl/delivery.js +1 -1
  134. package/dist/src/harness/hitl/index.js +1 -1
  135. package/dist/src/harness/hitl/intake.d.ts +2 -2
  136. package/dist/src/harness/hitl/intake.js +1 -1
  137. package/dist/src/harness/messages.d.ts +5 -0
  138. package/dist/src/harness/messages.js +1 -1
  139. package/dist/src/harness/model-call/call.d.ts +2 -2
  140. package/dist/src/harness/model-call/call.js +1 -1
  141. package/dist/src/harness/model-call/request.d.ts +2 -2
  142. package/dist/src/harness/session-machine/transitions.d.ts +3 -1
  143. package/dist/src/harness/session-machine/transitions.js +1 -1
  144. package/dist/src/harness/step/context.d.ts +3 -0
  145. package/dist/src/harness/step/context.js +1 -1
  146. package/dist/src/harness/step/intake.d.ts +5 -2
  147. package/dist/src/harness/step/intake.js +1 -1
  148. package/dist/src/harness/tool-loop.js +1 -1
  149. package/dist/src/harness/turn-tag-state.d.ts +7 -26
  150. package/dist/src/harness/turn-tag-state.js +1 -1
  151. package/dist/src/harness/types.d.ts +10 -25
  152. package/dist/src/instrumentation/content.d.ts +1 -1
  153. package/dist/src/instrumentation/content.js +1 -1
  154. package/dist/src/instrumentation/lifecycle.d.ts +4 -2
  155. package/dist/src/internal/application/build-profile.d.ts +3 -0
  156. package/dist/src/internal/application/build-profile.js +1 -1
  157. package/dist/src/internal/application/compiled-artifacts.js +2 -2
  158. package/dist/src/internal/application/dev-environment.d.ts +13 -0
  159. package/dist/src/internal/application/dev-environment.js +1 -1
  160. package/dist/src/internal/application/stamped-package-version.js +1 -1
  161. package/dist/src/internal/authored-definition/connection.js +1 -1
  162. package/dist/src/internal/authored-definition/core.js +1 -1
  163. package/dist/src/internal/authored-module-build-options.d.ts +7 -0
  164. package/dist/src/internal/authored-module-build-options.js +1 -0
  165. package/dist/src/internal/authored-module-graph.d.ts +13 -0
  166. package/dist/src/internal/authored-module-graph.js +1 -0
  167. package/dist/src/internal/authored-module-loader.d.ts +22 -1
  168. package/dist/src/internal/authored-module-loader.js +1 -3
  169. package/dist/src/internal/authored-module.d.ts +7 -0
  170. package/dist/src/internal/authored-module.js +1 -1
  171. package/dist/src/internal/authored-package-boundary.js +1 -1
  172. package/dist/src/internal/bundler/nitro-rolldown.d.ts +5 -1
  173. package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
  174. package/dist/src/internal/development-programmatic-source-loader.d.ts +1 -0
  175. package/dist/src/internal/development-programmatic-source-loader.js +1 -1
  176. package/dist/src/internal/mcp/skills.js +1 -1
  177. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  178. package/dist/src/internal/nitro/dev-runtime-generation-metadata.js +1 -1
  179. package/dist/src/internal/nitro/host/build-application.js +1 -1
  180. package/dist/src/internal/nitro/host/build-deployment-id.d.ts +8 -0
  181. package/dist/src/internal/nitro/host/build-deployment-id.js +1 -0
  182. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  183. package/dist/src/internal/nitro/host/dev-server-state.js +1 -1
  184. package/dist/src/internal/nitro/host/skill-server-assets.js +1 -1
  185. package/dist/src/internal/nitro/host/stage-build-deployment-id.d.ts +2 -0
  186. package/dist/src/internal/nitro/host/stage-build-deployment-id.js +1 -0
  187. package/dist/src/internal/nitro/host/start-production-server.d.ts +1 -0
  188. package/dist/src/internal/nitro/host/start-production-server.js +3 -3
  189. package/dist/src/internal/nitro/routes/schedule-task.d.ts +3 -0
  190. package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
  191. package/dist/src/internal/programmatic-source-loader.d.ts +1 -0
  192. package/dist/src/internal/programmatic-source-loader.js +1 -1
  193. package/dist/src/internal/schedules/disabled.d.ts +2 -0
  194. package/dist/src/internal/schedules/disabled.js +1 -0
  195. package/dist/src/internal/workflow/development-world-client.js +1 -1
  196. package/dist/src/internal/workflow/development-world-server.js +1 -1
  197. package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -1
  198. package/dist/src/internal/workflow/local-world-data-directory.js +1 -1
  199. package/dist/src/internal/workflow-bundle/builder.js +1 -1
  200. package/dist/src/protocol/message.d.ts +27 -1
  201. package/dist/src/protocol/message.js +2 -2
  202. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +13 -0
  203. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
  204. package/dist/src/public/channels/chat-sdk/fetch-message.d.ts +10 -0
  205. package/dist/src/public/channels/chat-sdk/fetch-message.js +1 -0
  206. package/dist/src/public/channels/chat-sdk/index.d.ts +1 -1
  207. package/dist/src/public/channels/chat-sdk/messageToUserContent.d.ts +2 -1
  208. package/dist/src/public/channels/chat-sdk/messageToUserContent.js +1 -1
  209. package/dist/src/public/channels/chat-sdk/reply-context.d.ts +15 -0
  210. package/dist/src/public/channels/chat-sdk/reply-context.js +2 -0
  211. package/dist/src/public/channels/discord/discordChannel.d.ts +3 -0
  212. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  213. package/dist/src/public/channels/github/dispatch.js +1 -1
  214. package/dist/src/public/channels/github/githubChannel.d.ts +3 -0
  215. package/dist/src/public/channels/imessage-tapbacks.d.ts +74 -0
  216. package/dist/src/public/channels/imessage-tapbacks.js +1 -0
  217. package/dist/src/public/channels/index.d.ts +2 -1
  218. package/dist/src/public/channels/index.js +1 -1
  219. package/dist/src/public/channels/linear/linearChannel.d.ts +3 -0
  220. package/dist/src/public/channels/linear/linearChannel.js +1 -1
  221. package/dist/src/public/channels/linq/inboundContent.d.ts +7 -0
  222. package/dist/src/public/channels/linq/inboundContent.js +1 -1
  223. package/dist/src/public/channels/linq/index.d.ts +1 -0
  224. package/dist/src/public/channels/linq/index.js +1 -1
  225. package/dist/src/public/channels/linq/linqChannel.d.ts +17 -1
  226. package/dist/src/public/channels/linq/linqChannel.js +1 -1
  227. package/dist/src/public/channels/photon/attachments.d.ts +5 -2
  228. package/dist/src/public/channels/photon/attachments.js +1 -1
  229. package/dist/src/public/channels/photon/inboundContent.d.ts +7 -0
  230. package/dist/src/public/channels/photon/inboundContent.js +2 -1
  231. package/dist/src/public/channels/photon/index.d.ts +1 -0
  232. package/dist/src/public/channels/photon/index.js +1 -1
  233. package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +17 -1
  234. package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
  235. package/dist/src/public/channels/slack/api.d.ts +14 -1
  236. package/dist/src/public/channels/slack/api.js +1 -1
  237. package/dist/src/public/channels/slack/model-context.d.ts +7 -0
  238. package/dist/src/public/channels/slack/model-context.js +1 -1
  239. package/dist/src/public/channels/slack/reply-delivery.d.ts +5 -0
  240. package/dist/src/public/channels/slack/reply-delivery.js +1 -1
  241. package/dist/src/public/channels/slack/slackChannel.d.ts +17 -3
  242. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  243. package/dist/src/public/channels/teams/teamsChannel.d.ts +3 -0
  244. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  245. package/dist/src/public/channels/telegram/telegramChannel.d.ts +3 -0
  246. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  247. package/dist/src/public/definitions/agent.d.ts +1 -1
  248. package/dist/src/public/definitions/channel.d.ts +2 -2
  249. package/dist/src/public/definitions/channel.js +1 -1
  250. package/dist/src/public/definitions/hook.d.ts +1 -0
  251. package/dist/src/public/index.d.ts +1 -1
  252. package/dist/src/public/tools/index.d.ts +1 -1
  253. package/dist/src/runtime/agent/resolve-model.d.ts +4 -0
  254. package/dist/src/runtime/agent/resolve-model.js +1 -1
  255. package/dist/src/runtime/resolve-agent.js +1 -1
  256. package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
  257. package/dist/src/runtime/subagents/dynamic-agent-config.d.ts +2 -1
  258. package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -1
  259. package/dist/src/runtime/types.d.ts +3 -2
  260. package/dist/src/setup/scaffold/create/project.js +1 -1
  261. package/dist/src/shared/agent-definition.d.ts +31 -42
  262. package/dist/src/shared/gateway-routing.d.ts +20 -0
  263. package/dist/src/shared/gateway-routing.js +1 -0
  264. package/dist/src/shared/session-history.d.ts +22 -0
  265. package/dist/src/shared/session-history.js +1 -0
  266. package/dist/src/shared/skill-package.js +1 -1
  267. package/dist/src/subagents/tool.d.ts +1 -3
  268. package/dist/src/subagents/tool.js +1 -1
  269. package/dist/src/svelte/index.js +1 -1
  270. package/dist/src/svelte/use-eve-agent.js +1 -1
  271. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  272. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  273. package/dist/src/tools/workflow-definition.d.ts +14 -1
  274. package/dist/src/tracing/eve/agent-otel-provider.js +1 -1
  275. package/dist/src/tracing/eve/conversation-context.d.ts +4 -1
  276. package/dist/src/tracing/eve/conversation-context.js +1 -1
  277. package/dist/src/tracing/eve/gateway.d.ts +5 -0
  278. package/dist/src/tracing/eve/gateway.js +1 -1
  279. package/dist/src/tracing/eve/invoke-tool-span.js +1 -1
  280. package/dist/src/tracing/eve/operation-input.d.ts +0 -12
  281. package/dist/src/tracing/eve/operation-input.js +1 -1
  282. package/dist/src/tracing/eve/otel-registration.js +1 -1
  283. package/dist/src/tracing/eve/policy.d.ts +1 -1
  284. package/dist/src/tracing/eve/policy.js +1 -1
  285. package/dist/src/tracing/eve/session.d.ts +5 -2
  286. package/dist/src/tracing/eve/session.js +1 -1
  287. package/dist/src/vue/index.js +1 -1
  288. package/dist/src/vue/use-eve-agent.js +1 -1
  289. package/docs/README.md +1 -0
  290. package/docs/agent-config.md +108 -65
  291. package/docs/channels/chat-sdk.mdx +10 -3
  292. package/docs/channels/custom.mdx +38 -6
  293. package/docs/channels/eve.mdx +73 -0
  294. package/docs/channels/linq.mdx +51 -0
  295. package/docs/channels/photon.mdx +68 -2
  296. package/docs/channels/slack.mdx +6 -2
  297. package/docs/concepts/built-in-tools.md +1 -1
  298. package/docs/concepts/execution-model-and-durability.mdx +27 -11
  299. package/docs/concepts/sessions-runs-and-streaming.md +9 -8
  300. package/docs/connections/overview.mdx +1 -1
  301. package/docs/experimental/dynamic-schedules.mdx +186 -0
  302. package/docs/experimental/meta.json +4 -0
  303. package/docs/guides/client/streaming.mdx +1 -0
  304. package/docs/guides/deployment/self-hosting.md +3 -0
  305. package/docs/guides/hooks.md +21 -1
  306. package/docs/guides/instrumentation/otel.mdx +20 -0
  307. package/docs/memory/overview.mdx +2 -1
  308. package/docs/patterns/dynamic-scheduling.md +3 -1
  309. package/docs/patterns/meta.json +1 -0
  310. package/docs/patterns/voice-notes.md +67 -0
  311. package/docs/reference/cli.md +14 -7
  312. package/docs/sandbox/index.mdx +2 -0
  313. package/docs/schedules.mdx +2 -0
  314. package/docs/subagents/index.mdx +2 -0
  315. package/docs/tools/overview.mdx +2 -1
  316. package/docs/tools/tasks-upgrade.md +12 -7
  317. package/docs/tools/tasks.md +10 -6
  318. package/docs/tools/workflows.mdx +36 -5
  319. package/docs/tutorial/connect-a-warehouse.mdx +1 -1
  320. package/docs/tutorial/run-analysis.mdx +1 -1
  321. package/package.json +1 -1
  322. package/dist/src/execution/run-session-limits.d.ts +0 -12
  323. package/dist/src/execution/run-session-limits.js +0 -1
  324. package/dist/src/harness/session-usage-limits.d.ts +0 -49
  325. package/dist/src/harness/session-usage-limits.js +0 -1
  326. package/dist/src/subagents/token-budget.d.ts +0 -15
  327. package/dist/src/subagents/token-budget.js +0 -1
@@ -1 +1 @@
1
- import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";var NodeModuleEvaluationContext=class{#e={};#t=new NodeModuleLifecycle;loadNamespace;constructor(e,t,n,r,i){this.loadNamespace=createCompiledBindingNamespaceLoader({appRoot:i,mountSourceId:t,mounts:n,evaluationId:r,onLoad:e=>this.#t.recordCompileLoad(e),registries:e,resolveBinding:e=>this.#e[e]})}setBindings(e){this.#e=e}requireRuntimeEntry(e){this.#t.requireRuntimeEntry(e)}finalizeBindings(){return this.#t.finalize(this.#e)}};function markConfigRuntimeEntries(e,t){let n=[e.dynamicModel,e.model?.source,e.compaction?.model?.source];for(let e of n)e!==void 0&&t.requireRuntimeEntry(e.sourceId)}var NodeModuleLifecycle=class{#e=new Set;#t=new Set;recordCompileLoad(e){this.#e.add(e)}requireRuntimeEntry(e){this.#t.add(e)}finalize(e){let t=collectRuntimeEntryClosure(e,this.#t),n={};for(let[r,i]of Object.entries(e)){let e={compile:this.#e.has(r),runtimeEntry:t.has(r)};if(!e.compile&&!e.runtimeEntry)throw Error(`Selected module binding "${r}" has no compile or runtime usage.`);n[r]=Object.freeze({...i,usage:Object.freeze(e)})}return n}};function collectRuntimeEntryClosure(e,t){let n=new Set,r=new Set,visit=t=>{if(n.has(t))return;if(r.has(t))throw Error(`Compiled module dependency cycle includes "${t}".`);let i=e[t];if(i===void 0)throw Error(`Runtime module entry "${t}" has no selected binding.`);if(r.add(t),i.backing.kind===`programmatic`)for(let e of Object.values(i.backing.dependencies??{}))visit(e);r.delete(t),n.add(t)};for(let e of t)visit(e);return n}export{NodeModuleEvaluationContext,markConfigRuntimeEntries};
1
+ import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";var NodeModuleEvaluationContext=class{#e={};#t=new NodeModuleLifecycle;loadNamespace;constructor(e,t,n,r,i,a){this.loadNamespace=createCompiledBindingNamespaceLoader({appRoot:i,graph:a,mountSourceId:t,mounts:n,evaluationId:r,onLoad:e=>this.#t.recordCompileLoad(e),registries:e,resolveBinding:e=>this.#e[e]})}setBindings(e){this.#e=e}requireRuntimeEntry(e){this.#t.requireRuntimeEntry(e)}finalizeBindings(){return this.#t.finalize(this.#e)}};function markConfigRuntimeEntries(e,t){let n=[e.dynamicModel,e.model?.source,e.compaction?.model?.source,e.limits?.sessionUsage===!0?e.source:void 0];for(let e of n)e!==void 0&&t.requireRuntimeEntry(e.sourceId)}var NodeModuleLifecycle=class{#e=new Set;#t=new Set;recordCompileLoad(e){this.#e.add(e)}requireRuntimeEntry(e){this.#t.add(e)}finalize(e){let t=collectRuntimeEntryClosure(e,this.#t),n={};for(let[r,i]of Object.entries(e)){let e={compile:this.#e.has(r),runtimeEntry:t.has(r)};if(!e.compile&&!e.runtimeEntry)throw Error(`Selected module binding "${r}" has no compile or runtime usage.`);n[r]=Object.freeze({...i,usage:Object.freeze(e)})}return n}};function collectRuntimeEntryClosure(e,t){let n=new Set,r=new Set,visit=t=>{if(n.has(t))return;if(r.has(t))throw Error(`Compiled module dependency cycle includes "${t}".`);let i=e[t];if(i===void 0)throw Error(`Runtime module entry "${t}" has no selected binding.`);if(r.add(t),i.backing.kind===`programmatic`)for(let e of Object.values(i.backing.dependencies??{}))visit(e);r.delete(t),n.add(t)};for(let e of t)visit(e);return n}export{NodeModuleEvaluationContext,markConfigRuntimeEntries};
@@ -1,4 +1,4 @@
1
- import{z}from"#compiled/zod/index.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import"#compiler/source-graph.js";import{createCompiledBindingNamespaceLoader,resolveExtensionBindingMountId}from"#compiler/load-binding-namespace.js";import{bindingMountId}from"#compiler/extension-mount-bindings.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const compiledModuleNodeScopeSchema=z.object({modules:z.record(z.string(),z.object({}).passthrough())}).strict(),compiledModuleMapSchema=z.object({nodes:z.record(z.string(),compiledModuleNodeScopeSchema)}).strict();function createCompiledModuleMapSource(e){let t=dirnameFilesystemPath(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=!1,a=collectBoundNodeScopes(e.manifest).map(e=>{let a=new Map(e.mounts.map(e=>[e.mountSourceId,e])),o=new Map(e.mounts.map(e=>[e.mountId,e.mountSourceId])),s=new Map(e.modules.map(e=>[e.sourceId,`module_${r++}`]));return{modules:orderBoundModules(e.modules,e=>o.get(bindingMountId(e)??``)).map(({binding:e,sourceId:r})=>{let o=s.get(r);if(e.backing.kind===`filesystem`){let i=createImportSpecifier({fromDirectory:t,importSpecifierStyle:n,targetPath:e.backing.sourcePath})+(bindingMountId(e)===void 0?``:`?eve-mount=${encodeURIComponent(bindingMountId(e))}`),s=bindingMountId(e)!==void 0&&!a.has(r);return{bindingName:o,importSpecifier:s?void 0:i,initializer:`memoizeModuleNamespaceFactories(${s?`await import(${JSON.stringify(i)})`:`imported_${o}`})`,sourceId:r}}let c=a.get(r);if(c?.programmaticImport!==void 0){let e=`${c.programmaticImport.specifier}?eve-mount=${encodeURIComponent(c.mountId)}`;return{bindingName:o,initializer:`memoizeModuleNamespaceFactories({ default: (await import(${JSON.stringify(e)})).default(${JSON.stringify(c.programmaticImport.config)}) })`,sourceId:r}}return i=!0,{bindingName:o,initializer:`await loadProgrammaticModule(${JSON.stringify(e.backing)}, ${renderProgrammaticDependencies(e.backing.dependencies,s)})`,sourceId:r}}),nodeId:e.nodeId}}),o=a.flatMap(e=>e.modules),s=o.flatMap(e=>e.importSpecifier===void 0?[]:[`import * as imported_${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`]),c=o.flatMap(e=>e.initializer===void 0?[]:[`const ${e.bindingName} = ${e.initializer};`]);return[`// Generated by eve. Do not edit by hand.`,...i||o.length>0?[`import { loadFrameworkProgrammaticModule as loadProgrammaticModule, memoizeModuleNamespaceFactories } from ${JSON.stringify(normalizeEsmImportSpecifier(e.programmaticLoaderImportSpecifier??`eve/internal/programmatic-source-loader`))};`]:[],...s,...i||o.length>0?[``]:[],...c,...c.length>0?[``]:[],`export const moduleMap = ${renderModuleMap(a)};`,``,`export default moduleMap;`,``].join(`
1
+ import{z}from"#compiled/zod/index.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import"#compiler/source-graph.js";import{createCompiledBindingNamespaceLoader,resolveExtensionBindingMountId}from"#compiler/load-binding-namespace.js";import{bindingMountId}from"#compiler/extension-mount-bindings.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const compiledModuleNodeScopeSchema=z.object({modules:z.record(z.string(),z.object({}).passthrough())}).strict(),compiledModuleMapSchema=z.object({nodes:z.record(z.string(),compiledModuleNodeScopeSchema)}).strict();function createCompiledModuleMapSource(e){let t=dirnameFilesystemPath(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=!1,a=collectBoundNodeScopes(e.manifest).map(e=>{let a=new Map(e.mounts.map(e=>[e.mountSourceId,e])),o=new Map(e.mounts.map(e=>[e.mountId,e.mountSourceId])),s=new Map(e.modules.map(e=>[e.sourceId,`module_${r++}`]));return{modules:orderBoundModules(e.modules,e=>o.get(bindingMountId(e)??``)).map(({binding:e,sourceId:r})=>{let o=s.get(r);if(e.backing.kind===`filesystem`){let i=createImportSpecifier({fromDirectory:t,importSpecifierStyle:n,targetPath:e.backing.sourcePath})+(bindingMountId(e)===void 0?``:`?eve-mount=${encodeURIComponent(bindingMountId(e))}`),s=bindingMountId(e)!==void 0&&!a.has(r);return{bindingName:o,importSpecifier:s?void 0:i,initializer:`memoizeModuleNamespaceFactories(interopAuthoredModuleNamespace(${s?`await import(${JSON.stringify(i)})`:`imported_${o}`}))`,sourceId:r}}let c=a.get(r);if(c?.programmaticImport!==void 0){let e=`${c.programmaticImport.specifier}?eve-mount=${encodeURIComponent(c.mountId)}`;return{bindingName:o,initializer:`memoizeModuleNamespaceFactories({ default: (await import(${JSON.stringify(e)})).default(${JSON.stringify(c.programmaticImport.config)}) })`,sourceId:r}}return i=!0,{bindingName:o,initializer:`await loadProgrammaticModule(${JSON.stringify(e.backing)}, ${renderProgrammaticDependencies(e.backing.dependencies,s)})`,sourceId:r}}),nodeId:e.nodeId}}),o=a.flatMap(e=>e.modules),s=o.flatMap(e=>e.importSpecifier===void 0?[]:[`import * as imported_${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`]),c=o.flatMap(e=>e.initializer===void 0?[]:[`const ${e.bindingName} = ${e.initializer};`]);return[`// Generated by eve. Do not edit by hand.`,...i||o.length>0?[`import { interopAuthoredModuleNamespace, loadFrameworkProgrammaticModule as loadProgrammaticModule, memoizeModuleNamespaceFactories } from ${JSON.stringify(normalizeEsmImportSpecifier(e.programmaticLoaderImportSpecifier??`eve/internal/programmatic-source-loader`))};`]:[],...s,...i||o.length>0?[``]:[],...c,...c.length>0?[``]:[],`export const moduleMap = ${renderModuleMap(a)};`,``,`export default moduleMap;`,``].join(`
2
2
  `)}async function createProgrammaticCompiledModuleMap(e,t){let n={};for(let r of collectBoundNodeScopes(e)){let i={},a=Object.fromEntries(r.modules.map(({binding:e,sourceId:t})=>[t,e])),o=new Map(r.mounts.map(e=>[e.mountId,e.mountSourceId])),s=createCompiledBindingNamespaceLoader({appRoot:e.appRoot,bindings:a,registries:t,mountSourceId:e=>o.get(bindingMountId(e)??``)});for(let{sourceId:e}of r.modules)i[e]=await s(e);n[r.nodeId]={modules:i}}return{nodes:n}}function collectRuntimeModuleBindingsForManifest(e){let t=new Map(Object.entries(e.bindings).filter(([,e])=>e.usage.runtimeEntry));for(let n of e.remoteAgents)if(n.binding.usage.runtimeEntry){if(t.has(n.sourceId))throw Error(`Remote agent binding "${n.sourceId}" collides with a node binding.`);t.set(n.sourceId,n.binding)}return orderBoundModules([...t].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({binding:t,sourceId:e})))}function orderBoundModules(e,t){let n=new Map(e.map(e=>[e.sourceId,e])),r=[],i=new Set,a=new Set,visit=e=>{if(a.has(e.sourceId))return;if(i.has(e.sourceId))throw Error(`Compiled module dependency cycle includes "${e.sourceId}".`);i.add(e.sourceId);let o=t?.(e.binding);if(o!==void 0&&o!==e.sourceId){let e=n.get(o);e!==void 0&&visit(e)}if(e.binding.backing.kind===`programmatic`)for(let t of Object.values(e.binding.backing.dependencies??{})){let r=n.get(t);if(r===void 0)throw Error(`Programmatic binding "${e.sourceId}" depends on missing binding "${t}".`);visit(r)}i.delete(e.sourceId),a.add(e.sourceId),r.push(e)};for(let t of e)visit(t);return r}function renderProgrammaticDependencies(e,t){let n=Object.entries(e??{});return n.length===0?`Object.freeze({})`:`Object.freeze({ ${n.map(([e,n])=>`${JSON.stringify(e)}: ${t.get(n)}`).join(`, `)} })`}function collectBoundNodeScopes(e){return[{modules:collectRuntimeModuleBindingsForManifest(e),mounts:e.extensionMounts,nodeId:ROOT_COMPILED_AGENT_NODE_ID},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({modules:collectRuntimeModuleBindingsForManifest(e.agent),mounts:e.agent.extensionMounts,nodeId:e.nodeId}))]}function renderModuleMap(e){return renderFrozenObject([{key:`nodes`,value:renderFrozenObject(e.map(e=>({key:e.nodeId,value:renderFrozenObject([{key:`modules`,value:renderFrozenObject(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function renderFrozenObject(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
3
3
  `,`\n${r}`)}`).join(`,
4
4
  `),`${n}})`].join(`
@@ -1 +1 @@
1
- import{isAbsolute,relative,resolve}from"node:path";import{normalizeLogicalPath}from"#discover/filesystem.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonObject}from"#shared/json.js";import{isDynamicModelDefinition}from"#shared/agent-definition.js";import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{classifyModelRouting}from"#internal/classify-model-routing.js";import{isMockModel}from"#internal/mock-model-identity.js";import{isChatGptModelRouting}from"#shared/chatgpt-model.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileAgentConfig(e,t,n){let r=n.source,i=formatAgentConfigModulePath(e,r,n.binding),a=normalizeAgentDefinition(Object.hasOwn(n,`definition`)?n.definition:await loadModuleBackedDefinition({binding:n.binding,displayPath:i,kind:`agent config`,loadNamespace:createCompiledBindingNamespaceLoader({appRoot:e.appRoot,bindings:{[r.sourceId]:n.binding},registries:t.registries}),source:r}),`Expected the agent config export "${r.exportName??`default`}" from "${i}" to match the public eve shape.`),o=isDynamicModelDefinition(a.model)?a.model:void 0,s=o===void 0?await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:a.modelContextWindowTokens,promptCache:a.modelOptions?.promptCache,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.model}):void 0,c={},l={compaction:c,name:e.agentId,source:{...r}};a.defaultTools!==void 0&&(l.defaultTools=a.defaultTools),a.description!==void 0&&(l.description=a.description);let u;o!==void 0&&(u={eventNames:Object.keys(o.events),exportName:r.exportName,sourceKind:`module`,logicalPath:r.logicalPath,sourceId:r.sourceId});let d=normalizeExperimentalDefinition(a.experimental);if(d!==void 0&&(l.experimental=d),a.build!==void 0&&(l.build={externalDependencies:a.build.externalDependencies===void 0?void 0:[...a.build.externalDependencies]}),a.reasoning!==void 0&&(l.reasoning=a.reasoning),a.tool!==void 0&&(l.tool=a.tool),a.limits!==void 0&&(l.limits={maxInputTokensPerSession:a.limits.maxInputTokensPerSession,maxOutputTokensPerSession:a.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:a.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:a.limits.sessionTimeoutMs}),a.compaction?.model!==void 0&&(c.model=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:a.compaction.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.compaction.model})),a.compaction?.thresholdPercent!==void 0&&(c.thresholdPercent=a.compaction.thresholdPercent),u!==void 0)return{...l,dynamicModel:u};if(s===void 0)throw Error(`Expected a static agent model to compile to a concrete model reference.`);return{...l,model:s}}function normalizeExperimentalDefinition(e){if(e===void 0)return;let t={};return e.workflow!==void 0&&(t.workflow={modelCallsPerStep:e.workflow.modelCallsPerStep,retention:e.workflow.retention,world:e.workflow.world}),t}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`){let t=classifyModelRouting(e.value,e.providerOptions);return rejectGatewayPromptCache(e,t),await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:t},e)}let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${e.sourcePath??t.logicalPath}" to provide a valid AI SDK language model.`);let i=classifyModelRouting(n,e.providerOptions);rejectGatewayPromptCache(e,i);let a={id:formatLanguageModelGatewayId(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:i};if(e.promptCache!==void 0&&(a.promptCache=e.promptCache),e.contextWindowTokens===void 0){if(isChatGptModelRouting(a.routing))return{...a,contextWindowTokens:2e5};if(isMockModel(n))return{...a,contextWindowTokens:1e6};try{let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...a,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens,maxOutputTokens:t.limits.maxOutputTokens}}catch{}}return await withCompiledRuntimeModelLimits(a,e)}function rejectGatewayPromptCache(e,t){if(e.promptCache!==void 0&&t.kind===`gateway`)throw Error(`${e.sourcePath??`agent.ts`}: modelOptions.promptCache applies only to models eve calls directly, but "${formatLanguageModelGatewayId(e.value)}" routes through AI Gateway, which manages its own prompt caching. Remove promptCache, or configure Gateway caching with providerOptions.gateway.caching.`)}function formatAgentConfigModulePath(e,t,n){return n.backing.kind===`programmatic`?t.logicalPath:normalizeLogicalPath(relative(resolveTopLevelAgentRoot(e),n.backing.sourcePath))}function resolveTopLevelAgentRoot(e){let t=resolve(e.appRoot),n=resolve(t,`agent`);return isPathInsideOrEqual(n,resolve(e.agentRoot))?n:t}function isPathInsideOrEqual(e,t){let n=relative(e,t);return n===``||!n.startsWith(`..`)&&!isAbsolute(n)}async function withCompiledRuntimeModelLimits(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${toErrorMessage(n)}`)}if(n===null)throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`);return{...e,contextWindowTokens:n.contextWindowTokens,maxOutputTokens:n.maxOutputTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=parseJsonObject(r);return t}export{compileAgentConfig};
1
+ import{isAbsolute,relative,resolve}from"node:path";import{normalizeLogicalPath}from"#discover/filesystem.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonObject}from"#shared/json.js";import{isDynamicModelDefinition}from"#shared/agent-definition.js";import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{classifyModelRouting}from"#internal/classify-model-routing.js";import{isMockModel}from"#internal/mock-model-identity.js";import{isChatGptModelRouting}from"#shared/chatgpt-model.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileAgentConfig(e,t,n){let r=n.source,i=formatAgentConfigModulePath(e,r,n.binding),a=normalizeAgentDefinition(Object.hasOwn(n,`definition`)?n.definition:await loadModuleBackedDefinition({binding:n.binding,displayPath:i,kind:`agent config`,loadNamespace:createCompiledBindingNamespaceLoader({appRoot:e.appRoot,bindings:{[r.sourceId]:n.binding},registries:t.registries}),source:r}),`Expected the agent config export "${r.exportName??`default`}" from "${i}" to match the public eve shape.`),o=isDynamicModelDefinition(a.model)?a.model:void 0,s=o===void 0?await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:a.modelContextWindowTokens,promptCache:a.modelOptions?.promptCache,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.model}):void 0,c={},l={compaction:c,name:e.agentId,source:{...r}};a.defaultTools!==void 0&&(l.defaultTools=a.defaultTools),a.description!==void 0&&(l.description=a.description);let u;o!==void 0&&(u={eventNames:Object.keys(o.events),exportName:r.exportName,sourceKind:`module`,logicalPath:r.logicalPath,sourceId:r.sourceId});let d=normalizeExperimentalDefinition(a.experimental);if(d!==void 0&&(l.experimental=d),a.build!==void 0&&(l.build={externalDependencies:a.build.externalDependencies===void 0?void 0:[...a.build.externalDependencies]}),a.reasoning!==void 0&&(l.reasoning=a.reasoning),a.tool!==void 0&&(l.tool=a.tool),a.limits!==void 0&&(l.limits={sessionTimeoutMs:a.limits.sessionTimeoutMs,sessionUsage:a.limits.sessionUsage!==void 0||void 0}),a.compaction?.model!==void 0&&(c.model=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:a.compaction.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.compaction.model})),a.compaction?.thresholdPercent!==void 0&&(c.thresholdPercent=a.compaction.thresholdPercent),u!==void 0)return{...l,dynamicModel:u};if(s===void 0)throw Error(`Expected a static agent model to compile to a concrete model reference.`);return{...l,model:s}}function normalizeExperimentalDefinition(e){if(e===void 0)return;let t={};return e.workflow!==void 0&&(t.workflow={modelCallsPerStep:e.workflow.modelCallsPerStep,retention:e.workflow.retention,world:e.workflow.world}),t}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`){let t=classifyModelRouting(e.value,e.providerOptions);return rejectGatewayPromptCache(e,t),await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:t},e)}let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${e.sourcePath??t.logicalPath}" to provide a valid AI SDK language model.`);let i=classifyModelRouting(n,e.providerOptions);rejectGatewayPromptCache(e,i);let a={id:formatLanguageModelGatewayId(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:i};if(e.promptCache!==void 0&&(a.promptCache=e.promptCache),e.contextWindowTokens===void 0){if(isChatGptModelRouting(a.routing))return{...a,contextWindowTokens:2e5};if(isMockModel(n))return{...a,contextWindowTokens:1e6};try{let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...a,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens,maxOutputTokens:t.limits.maxOutputTokens}}catch{}}return await withCompiledRuntimeModelLimits(a,e)}function rejectGatewayPromptCache(e,t){if(e.promptCache!==void 0&&t.kind===`gateway`)throw Error(`${e.sourcePath??`agent.ts`}: modelOptions.promptCache applies only to models eve calls directly, but "${formatLanguageModelGatewayId(e.value)}" routes through AI Gateway, which manages its own prompt caching. Remove promptCache, or configure Gateway caching with providerOptions.gateway.caching.`)}function formatAgentConfigModulePath(e,t,n){return n.backing.kind===`programmatic`?t.logicalPath:normalizeLogicalPath(relative(resolveTopLevelAgentRoot(e),n.backing.sourcePath))}function resolveTopLevelAgentRoot(e){let t=resolve(e.appRoot),n=resolve(t,`agent`);return isPathInsideOrEqual(n,resolve(e.agentRoot))?n:t}function isPathInsideOrEqual(e,t){let n=relative(e,t);return n===``||!n.startsWith(`..`)&&!isAbsolute(n)}async function withCompiledRuntimeModelLimits(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${toErrorMessage(n)}`)}if(n===null)throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`);return{...e,contextWindowTokens:n.contextWindowTokens,maxOutputTokens:n.maxOutputTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=parseJsonObject(r);return t}export{compileAgentConfig};
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import{noDevelopmentExtensions,prepareDevelopmentExtensions}from"#compiler/development-extensions.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId}from"#compiler/manifest.js";import{summarizeCompilerDiagnostics}from"#compiler/diagnostics.js";import{composeAgentModuleCandidates,createAgentModuleBinding,createProgrammaticModuleCandidates,disableComposedCandidate,isAgentModuleCandidate}from"#compiler/source-graph.js";import{compileMemoryDefinition}from"#compiler/normalize-memory.js";import{frameworkAgentSourceRegistry}from"#framework/sources/registry.js";import{bindingMountId}from"#compiler/extension-mount-bindings.js";import{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileChannelRoutes,compileExtensionMounts,createCompiledRemoteAgent,createExtensionCompileMounts,expectSubagentDescription,loadSelectedNodeConfig,mergeExternalDependencies,withDiagnosticsSummary,withExtensionNamespace}from"#compiler/normalize-manifest-helpers.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{assertRemoteAgentDefinitionHasNoLocalPackageEntries,normalizeSubagentConfig}from"#compiler/normalize-subagent.js";import{NodeModuleEvaluationContext,markConfigRuntimeEntries}from"#compiler/module-lifecycle.js";import{assertStaticConnectionOwnership}from"#compiler/connection-ownership.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{applyAgentToolPolicy,applyDefaultToolPolicy,canDisableToolWithoutSelectedSource}from"#compiler/default-tool-policy.js";import{resolveWorkspaceSubagentDefinition}from"#compiler/resolve-workspace-subagent.js";import{workspaceSubagentName}from"#public/definitions/workspace-agent.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{createMemoryWrapperCandidates}from"#compiler/memory-wrapper-candidates.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileScheduleCollectionDefinition}from"#compiler/normalize-schedule-collection.js";import{isScheduleCollectionDefinition}from"#shared/schedule-collection-definition.js";import{createScheduleCollectionWrapperCandidates}from"#compiler/schedule-collection-wrapper-candidates.js";import{assertSkillNameAvailable,compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{finalizeNodeSourceState}from"#compiler/node-source-state.js";import{projectAgentSources,projectSelectedSources}from"#compiler/project-sources.js";async function compileAgentManifest(e,t={}){let n=[frameworkAgentSourceRegistry,...t.sourceRegistries??[]];assertUniqueRegistryIds(n);let r={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot),registries:n},i=t.diagnostics??[],a=await prepareDevelopmentExtensions({diagnostics:i,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID,selection:t.developmentExtensions??noDevelopmentExtensions()}),o=await new AgentGraphCompiler(r,n,i).compileStaticNode({developmentExtensionCandidates:a.candidates,inheritedExternalDependencies:[],isRoot:!0,layer:`application`,manifest:a.manifest,nodeId:ROOT_COMPILED_AGENT_NODE_ID,nodePath:``,owner:{kind:`application`}}),s=summarizeCompilerDiagnostics(i),c=withDiagnosticsSummary(o.descendants,s);return createCompiledAgentManifest({...o.manifest,diagnosticsSummary:s,subagents:c})}var AgentGraphCompiler=class{context;registries;diagnostics;mounts=new Map;evaluationId=randomUUID();constructor(e,t,n){this.context=e,this.registries=t,this.diagnostics=n}async compileStaticNode(e){let t=await this.createPhaseOneNodeSourceState(e,e.inheritedExternalDependencies),n=await compileAgentConfig(e.manifest,this.context,{binding:t.selectedConfig.binding,definition:t.selectedConfig.definition,source:t.selectedConfig.source});assertRootOnlyConfig(n,e.isRoot,e.manifest.agentId),applyAgentToolPolicy(t,n),applyDefaultToolPolicy(t,n);let r=mergeExternalDependencies(e.inheritedExternalDependencies,n.build?.externalDependencies,e.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));r.length>0&&(n={...n,build:{...n.build,externalDependencies:r}});let i=finalizeNodeSourceState(t,r);markConfigRuntimeEntries(n,i.evaluation);let a=await this.compileResources(e,i),o=await this.compileChildren(e,i,r),s=createCompiledAgentNodeManifest({...a,config:n,remoteAgents:o.remoteAgents});return{descendants:o.nodes,manifest:s}}async compileChildren(e,t,n){let r=[],i=[],a=collectSelectedSourceIds(t.composed),o=t.projected.subagents.filter(e=>a.has(e.candidate.sourceId));for(let t of o){let a=t.source,o=createCompiledSubagentNodeId(e.nodeId,a.sourceId),s={extensionScope:t.extensionScope??e.extensionScope,mountId:t.mountId,inheritedExternalDependencies:n,isRoot:!1,layer:t.candidate.layer,manifest:a.manifest,nodeId:o,nodePath:t.nodePath,owner:t.owner,parentNodeId:e.nodeId},c=await this.createPhaseOneNodeSourceState(s,n),l=normalizeSubagentConfig(c.selectedConfig.definition,`Expected the subagent config export "${c.selectedConfig.source.exportName??`default`}" from "${a.entryPath}" to match the public eve shape.`);if(l.kind===`remote`){let n=workspaceSubagentName(c.selectedConfig.definition),r=n===void 0?l:await resolveWorkspaceSubagentDefinition({definition:l,name:n,registries:this.registries,source:a});assertRemoteAgentDefinitionHasNoLocalPackageEntries(a);let s=c.selectedConfig.source.sourceId;c.evaluation.setBindings({[s]:c.selectedConfig.binding}),c.evaluation.requireRuntimeEntry(s);let u=c.evaluation.finalizeBindings()[s];if(u===void 0)throw Error(`Remote subagent "${o}" has no finalized config binding.`);i.push(createCompiledRemoteAgent({binding:u,definition:r,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,source:a,sourceRef:c.selectedConfig.source}));continue}let u,d;l.kind===`local`?(u=await compileAgentConfig(a.manifest,this.context,{binding:c.selectedConfig.binding,definition:l.definition,source:c.selectedConfig.source}),assertRootOnlyConfig(u,!1,a.manifest.agentId),applyAgentToolPolicy(c,u),applyDefaultToolPolicy(c,u)):d=l.build?.externalDependencies;let f=mergeExternalDependencies(n,u?.build?.externalDependencies,d,a.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));u!==void 0&&f.length>0&&(u={...u,build:{...u.build,externalDependencies:f}});let p=finalizeNodeSourceState(c,f);u===void 0?p.evaluation.requireRuntimeEntry(c.selectedConfig.source.sourceId):markConfigRuntimeEntries(u,p.evaluation);let m=await this.compileResources(s,p),h=await this.compileChildren(s,p,f),g={backing:t.candidate.backing,entryPath:a.entryPath,logicalPath:a.logicalPath,name:a.subagentId,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,rootPath:a.rootPath,sourceId:a.sourceId,sourceKind:`module`},_;_=u===void 0?{...g,agent:createCompiledAgentResources({...m,remoteAgents:h.remoteAgents}),configResolver:{build:l.kind===`dynamic`?l.build:void 0,eventNames:l.kind===`dynamic`?l.eventNames:[],exportName:c.selectedConfig.source.exportName,logicalPath:c.selectedConfig.source.logicalPath,sourceId:c.selectedConfig.source.sourceId,sourceKind:`module`}}:{...g,agent:createCompiledAgentNodeManifest({...m,config:u,remoteAgents:h.remoteAgents}),description:expectSubagentDescription(u,a)},r.push(_,...h.nodes)}return{nodes:r,remoteAgents:i}}composeNodeSources(e,t){let n=projectAgentSources({externalDependencies:t,extensionScope:e.extensionScope,mountId:e.mountId,layer:e.layer,manifest:e.manifest,nodeId:e.nodeId,nodePath:e.nodePath,owner:e.owner}),r=[],i=[];for(let t of this.registries){let n=t===frameworkAgentSourceRegistry;for(let a of t.registrations){if(a.applyTo===`root`&&!e.isRoot)continue;!n&&a.applyTo===`all-local-nodes`&&assertApplicationOverlayCanApplyToAllNodes(a.source.modules.map(e=>e.logicalPath));let t=createProgrammaticModuleCandidates({layer:n?`framework-default`:`application`,nodeId:e.nodeId,owner:n?{feature:a.source.id,kind:`framework`}:{kind:`application`},registration:a});(n?r:i).push(...t)}}let a=[...r,...e.developmentExtensionCandidates??[],...n.candidates,...createMemoryWrapperCandidates([...n.candidates,...i]),...createScheduleCollectionWrapperCandidates([...n.candidates,...i],e.manifest.agentId),...i],o=composeAgentModuleCandidates(a),s=projectSelectedSources({candidates:o.selected.values(),resources:n.resources});return{composed:o,orderedCandidates:a,projected:n,sourcesBySourceId:new Map(s.map(e=>[e.candidate.sourceId,e])),subagentsBySourceId:new Map(n.subagents.map(e=>[e.candidate.sourceId,e]))}}async createPhaseOneNodeSourceState(e,t){let n=this.composeNodeSources(e,t),{mounts:r,sourceIds:i}=createExtensionCompileMounts(e.manifest,e.nodePath);for(let[e,t]of r)this.mounts.set(e,t);let a=new NodeModuleEvaluationContext(this.registries,e=>i.get(bindingMountId(e)??``),this.mounts,this.evaluationId,e.manifest.appRoot);return a.setBindings(Object.fromEntries([...n.composed.selected.values()].filter(isAgentModuleCandidate).map(e=>[e.sourceId,createAgentModuleBinding(e)]))),{evaluation:a,graph:n,selectedConfig:await loadSelectedNodeConfig(n,a)}}async compileResources(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m=[],h,g=collectSelectedSourceIds(t.composed),_=t.evaluation.loadNamespace;for(let v of t.orderedCandidates){if(!g.has(v.sourceId))continue;let y=t.sourcesBySourceId.get(v.sourceId);if(y===void 0)continue;let b=t.bindings[v.sourceId],x={binding:b,loadNamespace:_,owner:v.owner};switch(y.kind){case`config`:case`extension`:break;case`channel`:{let n=await compileChannelDefinition(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_});n.kind===`disabled`?(t.composed=disableComposedCandidate({candidate:v,composed:t.composed}),delete t.bindings[v.sourceId],g.delete(v.sourceId)):m.push(...n.definitions);break}case`connection`:{let n=await compileConnectionDefinition(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_});if(n.kind===`connection`){if(n.definition.experimental_events===!0&&e.nodeId!==ROOT_COMPILED_AGENT_NODE_ID)throw Error(`experimental_events currently requires a root-agent connection.`);c.push(n.definition)}else l.push(withExtensionNamespace(n.definition,v.owner));t.evaluation.requireRuntimeEntry(v.sourceId);break}case`hook`:d.push(await compileHookEntry(y.source,{binding:b,loadNamespace:_})),t.evaluation.requireRuntimeEntry(v.sourceId);break;case`instructions`:{let n=await compileInstructionsEntry(e.manifest.agentRoot,y.source,x);n.kind===`instructions`?o.push(n.definition):(s.push(n.definition),t.evaluation.requireRuntimeEntry(v.sourceId));break}case`memory`:u.push(await compileMemoryDefinition(y.source,{binding:b,loadNamespace:_})),t.evaluation.requireRuntimeEntry(v.sourceId);break;case`sandbox`:h=await compileSandboxDefinition(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_}),h.inheritsParent||t.evaluation.requireRuntimeEntry(v.sourceId);break;case`schedule`:{let n=y.source.sourceKind===`module`?await loadModuleBackedDefinition({binding:b,loadNamespace:_,kind:`schedule`,source:y.source}):y.source.definition;if(isScheduleCollectionDefinition(n)){p.push(compileScheduleCollectionDefinition(y.source,n)),t.evaluation.requireRuntimeEntry(v.sourceId);break}let r=compileScheduleDefinition(e.manifest.agentRoot,y.source,n,x.owner);f.push(r),r.sourceKind===`module`&&r.hasRun&&t.evaluation.requireRuntimeEntry(v.sourceId);break}case`skill`:{let n=await compileSkillSource(e.manifest.agentRoot,y.source,x);n.kind===`skill`?(assertSkillNameAvailable(n.definition),i.push(n.definition)):(a.push(withExtensionNamespace(n.definition,v.owner)),t.evaluation.requireRuntimeEntry(v.sourceId));break}case`tool`:{let i=await compileToolEntry(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_});i.kind===`disabled`?(t.composed=disableComposedCandidate({allowUnmatched:canDisableToolWithoutSelectedSource(t,i.name),candidate:v,composed:t.composed}),delete t.bindings[v.sourceId],g.delete(v.sourceId)):i.kind===`tool`?(n.push(i.definition),i.definition.hasExecute&&t.evaluation.requireRuntimeEntry(v.sourceId)):i.kind===`dynamic-tool`?(r.push(withExtensionNamespace(i.definition,v.owner)),t.evaluation.requireRuntimeEntry(v.sourceId)):(assertNonExtensionSpecialTool(v,`Web search`),n.push(i.definition));break}}}if(h===void 0)throw Error(`Agent node "${e.nodeId}" has no selected sandbox source.`);assertUniqueBy(n,e=>e.name,`tool name`),assertUniqueBy(r,e=>e.slug,`dynamic tool slug`),assertUniqueBy(c,e=>e.connectionName,`connection name`),assertUniqueBy(l,e=>e.slug,`dynamic connection slug`),assertUniqueBy(i,e=>e.name,`skill name`),assertStaticConnectionOwnership({connectionNames:c.map(e=>e.connectionName),subagentNames:t.projected.subagents.filter(e=>g.has(e.candidate.sourceId)).map(e=>e.source.subagentId),toolNames:n.map(e=>e.name)});let v=compileChannelRoutes(t,m,this.diagnostics,e.nodeId),y=compileExtensionMounts(e.manifest,t.composed,e.nodePath);for(let e of y)t.evaluation.requireRuntimeEntry(e.mountSourceId);let b=t.evaluation.finalizeBindings();return createCompiledAgentResources({agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,bindings:b,channelRoutes:v,connections:c,diagnosticsSummary:summarizeCompilerDiagnostics(this.diagnostics),dynamicConnections:l,dynamicInstructions:s,dynamicSkills:a,dynamicTools:r,extensionMounts:y,hooks:d,memories:u,instructions:o,sandbox:h,sandboxWorkspaces:e.manifest.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:f,scheduleCollections:p,skills:i,sourceComposition:t.composed.composition,tools:n})}};export{compileAgentManifest};
1
+ import{randomUUID}from"node:crypto";import{noDevelopmentExtensions,prepareDevelopmentExtensions}from"#compiler/development-extensions.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId}from"#compiler/manifest.js";import{summarizeCompilerDiagnostics}from"#compiler/diagnostics.js";import{composeAgentModuleCandidates,createAgentModuleBinding,createProgrammaticModuleCandidates,disableComposedCandidate,isAgentModuleCandidate}from"#compiler/source-graph.js";import{compileMemoryDefinition}from"#compiler/normalize-memory.js";import{frameworkAgentSourceRegistry}from"#framework/sources/registry.js";import{bindingMountId}from"#compiler/extension-mount-bindings.js";import{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileChannelRoutes,compileExtensionMounts,createCompiledRemoteAgent,createExtensionCompileMounts,expectSubagentDescription,loadSelectedNodeConfig,mergeExternalDependencies,withDiagnosticsSummary,withExtensionNamespace}from"#compiler/normalize-manifest-helpers.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{assertRemoteAgentDefinitionHasNoLocalPackageEntries,normalizeSubagentConfig}from"#compiler/normalize-subagent.js";import{NodeModuleEvaluationContext,markConfigRuntimeEntries}from"#compiler/module-lifecycle.js";import{assertStaticConnectionOwnership}from"#compiler/connection-ownership.js";import{createAuthoredModuleGraph}from"#internal/authored-module-graph.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{applyAgentToolPolicy,applyDefaultToolPolicy,canDisableToolWithoutSelectedSource}from"#compiler/default-tool-policy.js";import{resolveWorkspaceSubagentDefinition}from"#compiler/resolve-workspace-subagent.js";import{workspaceSubagentName}from"#public/definitions/workspace-agent.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{createMemoryWrapperCandidates}from"#compiler/memory-wrapper-candidates.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileScheduleCollectionDefinition}from"#compiler/normalize-schedule-collection.js";import{isScheduleCollectionDefinition}from"#shared/schedule-collection-definition.js";import{createScheduleCollectionWrapperCandidates}from"#compiler/schedule-collection-wrapper-candidates.js";import{assertSkillNameAvailable,compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{finalizeNodeSourceState}from"#compiler/node-source-state.js";import{listApplicationModulePaths,projectAgentSources,projectSelectedSources}from"#compiler/project-sources.js";async function compileAgentManifest(e,t={}){let n=[frameworkAgentSourceRegistry,...t.sourceRegistries??[]];assertUniqueRegistryIds(n);let r={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot),registries:n},i=t.diagnostics??[],a=await prepareDevelopmentExtensions({diagnostics:i,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID,selection:t.developmentExtensions??noDevelopmentExtensions()}),o=await new AgentGraphCompiler(r,n,i,createAuthoredModuleGraph(listApplicationModulePaths(a.manifest),{appRoot:e.appRoot})).compileStaticNode({developmentExtensionCandidates:a.candidates,inheritedExternalDependencies:[],isRoot:!0,layer:`application`,manifest:a.manifest,nodeId:ROOT_COMPILED_AGENT_NODE_ID,nodePath:``,owner:{kind:`application`}}),s=summarizeCompilerDiagnostics(i),c=withDiagnosticsSummary(o.descendants,s);return createCompiledAgentManifest({...o.manifest,diagnosticsSummary:s,subagents:c})}var AgentGraphCompiler=class{context;registries;diagnostics;mounts=new Map;evaluationId=randomUUID();moduleGraph;constructor(e,t,n,r){this.context=e,this.registries=t,this.diagnostics=n,this.moduleGraph=r}async compileStaticNode(e){let t=await this.createPhaseOneNodeSourceState(e,e.inheritedExternalDependencies),n=await compileAgentConfig(e.manifest,this.context,{binding:t.selectedConfig.binding,definition:t.selectedConfig.definition,source:t.selectedConfig.source});assertRootOnlyConfig(n,e.isRoot,e.manifest.agentId),applyAgentToolPolicy(t,n),applyDefaultToolPolicy(t,n);let r=mergeExternalDependencies(e.inheritedExternalDependencies,n.build?.externalDependencies,e.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));r.length>0&&(n={...n,build:{...n.build,externalDependencies:r}});let i=finalizeNodeSourceState(t,r);markConfigRuntimeEntries(n,i.evaluation);let a=await this.compileResources(e,i),o=await this.compileChildren(e,i,r),s=createCompiledAgentNodeManifest({...a,config:n,remoteAgents:o.remoteAgents});return{descendants:o.nodes,manifest:s}}async compileChildren(e,t,n){let r=[],i=[],a=collectSelectedSourceIds(t.composed),o=t.projected.subagents.filter(e=>a.has(e.candidate.sourceId));for(let t of o){let a=t.source,o=createCompiledSubagentNodeId(e.nodeId,a.sourceId),s={extensionScope:t.extensionScope??e.extensionScope,mountId:t.mountId,inheritedExternalDependencies:n,isRoot:!1,layer:t.candidate.layer,manifest:a.manifest,nodeId:o,nodePath:t.nodePath,owner:t.owner,parentNodeId:e.nodeId},c=await this.createPhaseOneNodeSourceState(s,n),l=normalizeSubagentConfig(c.selectedConfig.definition,`Expected the subagent config export "${c.selectedConfig.source.exportName??`default`}" from "${a.entryPath}" to match the public eve shape.`);if(l.kind===`remote`){let n=workspaceSubagentName(c.selectedConfig.definition),r=n===void 0?l:await resolveWorkspaceSubagentDefinition({definition:l,name:n,registries:this.registries,source:a});assertRemoteAgentDefinitionHasNoLocalPackageEntries(a);let s=c.selectedConfig.source.sourceId;c.evaluation.setBindings({[s]:c.selectedConfig.binding}),c.evaluation.requireRuntimeEntry(s);let u=c.evaluation.finalizeBindings()[s];if(u===void 0)throw Error(`Remote subagent "${o}" has no finalized config binding.`);i.push(createCompiledRemoteAgent({binding:u,definition:r,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,source:a,sourceRef:c.selectedConfig.source}));continue}let u,d;l.kind===`local`?(u=await compileAgentConfig(a.manifest,this.context,{binding:c.selectedConfig.binding,definition:l.definition,source:c.selectedConfig.source}),assertRootOnlyConfig(u,!1,a.manifest.agentId),applyAgentToolPolicy(c,u),applyDefaultToolPolicy(c,u)):d=l.build?.externalDependencies;let f=mergeExternalDependencies(n,u?.build?.externalDependencies,d,a.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));u!==void 0&&f.length>0&&(u={...u,build:{...u.build,externalDependencies:f}});let p=finalizeNodeSourceState(c,f);u===void 0?p.evaluation.requireRuntimeEntry(c.selectedConfig.source.sourceId):markConfigRuntimeEntries(u,p.evaluation);let m=await this.compileResources(s,p),h=await this.compileChildren(s,p,f),g={backing:t.candidate.backing,entryPath:a.entryPath,logicalPath:a.logicalPath,name:a.subagentId,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,rootPath:a.rootPath,sourceId:a.sourceId,sourceKind:`module`},_;_=u===void 0?{...g,agent:createCompiledAgentResources({...m,remoteAgents:h.remoteAgents}),configResolver:{build:l.kind===`dynamic`?l.build:void 0,eventNames:l.kind===`dynamic`?l.eventNames:[],exportName:c.selectedConfig.source.exportName,logicalPath:c.selectedConfig.source.logicalPath,sourceId:c.selectedConfig.source.sourceId,sourceKind:`module`}}:{...g,agent:createCompiledAgentNodeManifest({...m,config:u,remoteAgents:h.remoteAgents}),description:expectSubagentDescription(u,a)},r.push(_,...h.nodes)}return{nodes:r,remoteAgents:i}}composeNodeSources(e,t){let n=projectAgentSources({externalDependencies:t,extensionScope:e.extensionScope,mountId:e.mountId,layer:e.layer,manifest:e.manifest,nodeId:e.nodeId,nodePath:e.nodePath,owner:e.owner}),r=[],i=[];for(let t of this.registries){let n=t===frameworkAgentSourceRegistry;for(let a of t.registrations){if(a.applyTo===`root`&&!e.isRoot)continue;!n&&a.applyTo===`all-local-nodes`&&assertApplicationOverlayCanApplyToAllNodes(a.source.modules.map(e=>e.logicalPath));let t=createProgrammaticModuleCandidates({layer:n?`framework-default`:`application`,nodeId:e.nodeId,owner:n?{feature:a.source.id,kind:`framework`}:{kind:`application`},registration:a});(n?r:i).push(...t)}}let a=[...r,...e.developmentExtensionCandidates??[],...n.candidates,...createMemoryWrapperCandidates([...n.candidates,...i]),...createScheduleCollectionWrapperCandidates([...n.candidates,...i],e.manifest.agentId),...i],o=composeAgentModuleCandidates(a),s=projectSelectedSources({candidates:o.selected.values(),resources:n.resources});return{composed:o,orderedCandidates:a,projected:n,sourcesBySourceId:new Map(s.map(e=>[e.candidate.sourceId,e])),subagentsBySourceId:new Map(n.subagents.map(e=>[e.candidate.sourceId,e]))}}async createPhaseOneNodeSourceState(e,t){let n=this.composeNodeSources(e,t),{mounts:r,sourceIds:i}=createExtensionCompileMounts(e.manifest,e.nodePath);for(let[e,t]of r)this.mounts.set(e,t);let a=new NodeModuleEvaluationContext(this.registries,e=>i.get(bindingMountId(e)??``),this.mounts,this.evaluationId,e.manifest.appRoot,this.moduleGraph);return a.setBindings(Object.fromEntries([...n.composed.selected.values()].filter(isAgentModuleCandidate).map(e=>[e.sourceId,createAgentModuleBinding(e)]))),{evaluation:a,graph:n,selectedConfig:await loadSelectedNodeConfig(n,a)}}async compileResources(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m=[],h,g=collectSelectedSourceIds(t.composed),_=t.evaluation.loadNamespace;for(let v of t.orderedCandidates){if(!g.has(v.sourceId))continue;let y=t.sourcesBySourceId.get(v.sourceId);if(y===void 0)continue;let b=t.bindings[v.sourceId],x={binding:b,loadNamespace:_,owner:v.owner};switch(y.kind){case`config`:case`extension`:break;case`channel`:{let n=await compileChannelDefinition(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_});n.kind===`disabled`?(t.composed=disableComposedCandidate({candidate:v,composed:t.composed}),delete t.bindings[v.sourceId],g.delete(v.sourceId)):m.push(...n.definitions);break}case`connection`:{let n=await compileConnectionDefinition(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_});if(n.kind===`connection`){if(n.definition.experimental_events===!0&&e.nodeId!==ROOT_COMPILED_AGENT_NODE_ID)throw Error(`experimental_events currently requires a root-agent connection.`);c.push(n.definition)}else l.push(withExtensionNamespace(n.definition,v.owner));t.evaluation.requireRuntimeEntry(v.sourceId);break}case`hook`:d.push(await compileHookEntry(y.source,{binding:b,loadNamespace:_})),t.evaluation.requireRuntimeEntry(v.sourceId);break;case`instructions`:{let n=await compileInstructionsEntry(e.manifest.agentRoot,y.source,x);n.kind===`instructions`?o.push(n.definition):(s.push(n.definition),t.evaluation.requireRuntimeEntry(v.sourceId));break}case`memory`:u.push(await compileMemoryDefinition(y.source,{binding:b,loadNamespace:_})),t.evaluation.requireRuntimeEntry(v.sourceId);break;case`sandbox`:h=await compileSandboxDefinition(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_}),h.inheritsParent||t.evaluation.requireRuntimeEntry(v.sourceId);break;case`schedule`:{let n=y.source.sourceKind===`module`?await loadModuleBackedDefinition({binding:b,loadNamespace:_,kind:`schedule`,source:y.source}):y.source.definition;if(isScheduleCollectionDefinition(n)){p.push(compileScheduleCollectionDefinition(y.source,n)),t.evaluation.requireRuntimeEntry(v.sourceId);break}let r=compileScheduleDefinition(e.manifest.agentRoot,y.source,n,x.owner);f.push(r),r.sourceKind===`module`&&r.hasRun&&t.evaluation.requireRuntimeEntry(v.sourceId);break}case`skill`:{let n=await compileSkillSource(e.manifest.agentRoot,y.source,x);n.kind===`skill`?(assertSkillNameAvailable(n.definition),i.push(n.definition)):(a.push(withExtensionNamespace(n.definition,v.owner)),t.evaluation.requireRuntimeEntry(v.sourceId));break}case`tool`:{let i=await compileToolEntry(e.manifest.agentRoot,y.source,{binding:b,loadNamespace:_});i.kind===`disabled`?(t.composed=disableComposedCandidate({allowUnmatched:canDisableToolWithoutSelectedSource(t,i.name),candidate:v,composed:t.composed}),delete t.bindings[v.sourceId],g.delete(v.sourceId)):i.kind===`tool`?(n.push(i.definition),i.definition.hasExecute&&t.evaluation.requireRuntimeEntry(v.sourceId)):i.kind===`dynamic-tool`?(r.push(withExtensionNamespace(i.definition,v.owner)),t.evaluation.requireRuntimeEntry(v.sourceId)):(assertNonExtensionSpecialTool(v,`Web search`),n.push(i.definition));break}}}if(h===void 0)throw Error(`Agent node "${e.nodeId}" has no selected sandbox source.`);assertUniqueBy(n,e=>e.name,`tool name`),assertUniqueBy(r,e=>e.slug,`dynamic tool slug`),assertUniqueBy(c,e=>e.connectionName,`connection name`),assertUniqueBy(l,e=>e.slug,`dynamic connection slug`),assertUniqueBy(i,e=>e.name,`skill name`),assertStaticConnectionOwnership({connectionNames:c.map(e=>e.connectionName),subagentNames:t.projected.subagents.filter(e=>g.has(e.candidate.sourceId)).map(e=>e.source.subagentId),toolNames:n.map(e=>e.name)});let v=compileChannelRoutes(t,m,this.diagnostics,e.nodeId),y=compileExtensionMounts(e.manifest,t.composed,e.nodePath);for(let e of y)t.evaluation.requireRuntimeEntry(e.mountSourceId);let b=t.evaluation.finalizeBindings();return createCompiledAgentResources({agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,bindings:b,channelRoutes:v,connections:c,diagnosticsSummary:summarizeCompilerDiagnostics(this.diagnostics),dynamicConnections:l,dynamicInstructions:s,dynamicSkills:a,dynamicTools:r,extensionMounts:y,hooks:d,memories:u,instructions:o,sandbox:h,sandboxWorkspaces:e.manifest.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:f,scheduleCollections:p,skills:i,sourceComposition:t.composed.composition,tools:n})}};export{compileAgentManifest};
@@ -53,6 +53,12 @@ export declare function projectAgentSources(input: {
53
53
  readonly owner?: AgentSourceOwner;
54
54
  readonly mountId?: string;
55
55
  }): ProjectedAgentSources;
56
+ /**
57
+ * Lists the application module files a compile may evaluate, across local
58
+ * subagents, so they can be bundled as one shared graph. Extension mounts load
59
+ * with their own scope and are left out.
60
+ */
61
+ export declare function listApplicationModulePaths(manifest: AgentSourceManifest): string[];
56
62
  export declare function projectSelectedSources(input: {
57
63
  readonly candidates: Iterable<AgentSourceCandidate>;
58
64
  readonly resources: readonly ProjectedResourceSource[];
@@ -1 +1 @@
1
- import{join,posix}from"node:path";import{stripLogicalPathExtension}from"#discover/filesystem.js";import{canonicalSourceSlot,extensionMountId}from"#compiler/source-graph.js";import{mountRefNamespace}from"#discover/extensions.js";const MODULE_KIND_BY_SLOT_ROOT={agent:`config`,channels:`channel`,extensions:`extension`,hooks:`hook`,instructions:`instructions`,memory:`memory`,sandbox:`sandbox`,schedules:`schedule`,skills:`skill`,tools:`tool`};function projectAgentSources(e){let t=e.owner??{kind:`application`},n=[],r=[],i=[];projectManifest({externalDependencies:e.externalDependencies,candidates:n,projection:createApplicationManifestSourceProjection(e.extensionScope),layer:e.layer??`application`,manifest:e.manifest,nodeId:e.nodeId,subagentsPath:posix.join(e.nodePath,`subagents`),owner:t,mountId:e.mountId,declarationMountIds:new Map(e.manifest.extensions.map(t=>[t.sourceId,posix.join(e.nodePath,`extensions`,mountRefNamespace(t.logicalPath))])),resources:r,subagents:i});for(let t of[...e.manifest.resolvedExtensions].sort((e,t)=>e.namespace.localeCompare(t.namespace))){let a=extensionMountId(e.nodePath,t.namespace),o=createExtensionManifestSourceProjection(t),s={kind:`extension`,mountId:a,namespace:t.namespace,packageName:t.packageName};projectManifest({externalDependencies:mergeDependencies(e.externalDependencies,t.externalDependencies),candidates:n,projection:o,layer:`extension-package`,manifest:t.manifest,nodeId:e.nodeId,subagentsPath:posix.join(a,`subagents`),owner:s,mountId:a,resources:r,sourceIdPrefix:`ext:${t.namespace}:`,subagents:i}),t.overrides!==void 0&&projectManifest({externalDependencies:e.externalDependencies,candidates:n,projection:o,layer:`extension-override`,manifest:t.overrides,nodeId:e.nodeId,subagentsPath:posix.join(a,`subagents`),owner:{kind:`application`},mountId:a,resources:r,sourceIdPrefix:`ext-override:${t.namespace}:`,subagents:i})}return{candidates:n,resources:r,subagents:i}}function projectSelectedSources(e){let t=new Map(e.resources.map(e=>[e.candidate.sourceId,e])),n=[];for(let r of e.candidates)if(isModuleCandidate(r))n.push(projectModuleCandidate(r));else{let e=t.get(r.sourceId);e!==void 0&&n.push(e)}return n}function createFilesystemModuleCandidate(e){return{backing:{externalDependencies:[...e.externalDependencies],...e.owner.kind===`extension`&&e.extensionScope!==void 0?{extensionScope:e.extensionScope}:{},kind:`filesystem`,mountId:e.mountId,sourcePath:join(e.sourceRoot,e.source.logicalPath)},exportName:e.source.exportName,form:`direct`,layer:e.layer,logicalPath:e.logicalPath,nodeId:e.nodeId,owner:e.owner,sourceId:e.sourceId??e.source.sourceId}}function createApplicationManifestSourceProjection(e){let t={logicalPath:e=>e,name:e=>e};return e!==void 0&&(t.extensionScope=e),t}function createExtensionManifestSourceProjection(e){let{namespace:t,sourceRoot:n}=e;return{extensionScope:{namespace:t,sourceRoot:n},logicalPath:e=>qualifyExtensionContributionLogicalPath(e,t),name:e=>`${t}__${e}`}}function projectManifest(e){let{projection:t}=e,sourceId=t=>`${e.sourceIdPrefix??``}${t}`,pushModule=(n,r,i=e.mountId)=>{let a=t.logicalPath(r??n.logicalPath),o=createFilesystemModuleCandidate({externalDependencies:e.externalDependencies,...t.extensionScope===void 0?{}:{extensionScope:t.extensionScope},layer:e.layer,logicalPath:a,nodeId:e.nodeId,owner:e.owner,mountId:i,source:n,sourceId:sourceId(n.sourceId),sourceRoot:e.manifest.agentRoot});e.candidates.push(o)},pushResource=(n,r)=>{let i=t.logicalPath(r.logicalPath),a={...r,...r.sourceKind===`skill-package`?{name:t.name(r.name)}:{},logicalPath:i,sourceId:sourceId(r.sourceId)},o={backing:{kind:`resource`,sourcePath:r.sourceKind===`skill-package`?r.skillFilePath:join(e.manifest.agentRoot,r.logicalPath)},form:`direct`,layer:e.layer,logicalPath:i,nodeId:e.nodeId,owner:e.owner,sourceId:a.sourceId};e.candidates.push(o),e.resources.push({candidate:o,kind:n,source:a})};if(e.manifest.configModule!==void 0){let t=e.manifest.configModule.logicalPath;pushModule(e.manifest.configModule,canonicalSourceSlot(t)===`agent`?void 0:`agent.ts`)}let n=new Set(e.manifest.resolvedExtensions.map(e=>e.namespace));for(let t of e.manifest.extensions)n.has(mountRefNamespace(t.logicalPath))&&pushModule(t,void 0,e.declarationMountIds?.get(t.sourceId));for(let t of e.manifest.channels)pushModule(t);for(let t of e.manifest.connections)pushModule(t);for(let t of e.manifest.hooks)pushModule(t);for(let t of e.manifest.memories)pushModule(t);e.manifest.sandbox!==null&&pushModule(e.manifest.sandbox);for(let t of e.manifest.tools)pushModule(t);for(let t of e.manifest.instructions)t.sourceKind===`module`?pushModule(t):pushResource(`instructions`,t);for(let t of e.manifest.schedules)t.sourceKind===`module`?pushModule(t):pushResource(`schedule`,t);for(let t of e.manifest.skills)t.sourceKind===`module`?pushModule(t):pushResource(`skill`,t);for(let n of e.manifest.subagents){let r=t.name(n.subagentId),i=t.logicalPath(n.logicalPath);if(r===`agent`)throw Error(`Subagent "${i}" uses the reserved name "agent". Rename its path; eve reserves "agent" for the built-in root-copy target.`);let a={...n,logicalPath:i,sourceId:sourceId(n.sourceId),subagentId:r},o={backing:{kind:`resource`,sourcePath:n.entryPath},form:`direct`,layer:e.layer,logicalPath:i,nodeId:e.nodeId,owner:e.owner,sourceId:a.sourceId};e.candidates.push(o),e.subagents.push({candidate:o,mountId:e.mountId,nodePath:posix.join(e.subagentsPath,n.subagentId),...t.extensionScope===void 0?{}:{extensionScope:t.extensionScope},owner:e.owner,source:a})}}function projectModuleCandidate(e){let t={exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`},n=canonicalSourceSlot(e.logicalPath);if(n.startsWith(`connections/`))return{candidate:e,kind:`connection`,source:{...t,connectionName:deriveConnectionName(e.logicalPath)}};let r=MODULE_KIND_BY_SLOT_ROOT[n.split(`/`,1)[0]];if(r===void 0)throw Error(`Agent module source slot "${e.logicalPath}" is not compiled yet.`);return{candidate:e,kind:r,source:t}}function isModuleCandidate(e){return e.backing.kind!==`resource`}const EXTENSION_CONTRIBUTION_ROOTS=new Set([`channels`,`connections`,`hooks`,`instructions`,`schedules`,`skills`,`subagents`,`tools`]);function qualifyExtensionContributionLogicalPath(e,t){let n=e.split(`/`);if(n.length===1){let n=stripLogicalPathExtension(e);if(n===`instructions`||n===`system`)return`instructions/${t}${e.slice(e.lastIndexOf(`.`))}`;throw Error(`Extension source slot "${e}" cannot be namespace-scoped.`)}let r=n[0];if(!EXTENSION_CONTRIBUTION_ROOTS.has(r))throw Error(`Extension source slot "${e}" cannot be namespace-scoped.`);return n[1]=`${t}__${n[1]}`,n.join(`/`)}function deriveConnectionName(e){let t=stripLogicalPathExtension(e).replace(/^connections\//,``);return t.endsWith(`/connection`)?t.slice(0,-11):t}function mergeDependencies(...e){return[...new Set(e.flat())]}export{projectAgentSources,projectSelectedSources,qualifyExtensionContributionLogicalPath};
1
+ import{join,posix}from"node:path";import{stripLogicalPathExtension}from"#discover/filesystem.js";import{canonicalSourceSlot,extensionMountId}from"#compiler/source-graph.js";import{mountRefNamespace}from"#discover/extensions.js";const MODULE_KIND_BY_SLOT_ROOT={agent:`config`,channels:`channel`,extensions:`extension`,hooks:`hook`,instructions:`instructions`,memory:`memory`,sandbox:`sandbox`,schedules:`schedule`,skills:`skill`,tools:`tool`};function projectAgentSources(e){let t=e.owner??{kind:`application`},n=[],r=[],i=[];projectManifest({externalDependencies:e.externalDependencies,candidates:n,projection:createApplicationManifestSourceProjection(e.extensionScope),layer:e.layer??`application`,manifest:e.manifest,nodeId:e.nodeId,subagentsPath:posix.join(e.nodePath,`subagents`),owner:t,mountId:e.mountId,declarationMountIds:new Map(e.manifest.extensions.map(t=>[t.sourceId,posix.join(e.nodePath,`extensions`,mountRefNamespace(t.logicalPath))])),resources:r,subagents:i});for(let t of[...e.manifest.resolvedExtensions].sort((e,t)=>e.namespace.localeCompare(t.namespace))){let a=extensionMountId(e.nodePath,t.namespace),o=createExtensionManifestSourceProjection(t),s={kind:`extension`,mountId:a,namespace:t.namespace,packageName:t.packageName};projectManifest({externalDependencies:mergeDependencies(e.externalDependencies,t.externalDependencies),candidates:n,projection:o,layer:`extension-package`,manifest:t.manifest,nodeId:e.nodeId,subagentsPath:posix.join(a,`subagents`),owner:s,mountId:a,resources:r,sourceIdPrefix:`ext:${t.namespace}:`,subagents:i}),t.overrides!==void 0&&projectManifest({externalDependencies:e.externalDependencies,candidates:n,projection:o,layer:`extension-override`,manifest:t.overrides,nodeId:e.nodeId,subagentsPath:posix.join(a,`subagents`),owner:{kind:`application`},mountId:a,resources:r,sourceIdPrefix:`ext-override:${t.namespace}:`,subagents:i})}return{candidates:n,resources:r,subagents:i}}function listApplicationModulePaths(e){return[...[...e.configModule===void 0?[]:[e.configModule],...e.sandbox===null?[]:[e.sandbox],...e.channels,...e.connections,...e.hooks,...e.memories,...e.tools,...e.instructions,...e.schedules,...e.skills].flatMap(t=>t.sourceKind===`module`?[join(e.agentRoot,t.logicalPath)]:[]),...e.subagents.flatMap(e=>listApplicationModulePaths(e.manifest))]}function projectSelectedSources(e){let t=new Map(e.resources.map(e=>[e.candidate.sourceId,e])),n=[];for(let r of e.candidates)if(isModuleCandidate(r))n.push(projectModuleCandidate(r));else{let e=t.get(r.sourceId);e!==void 0&&n.push(e)}return n}function createFilesystemModuleCandidate(e){return{backing:{externalDependencies:[...e.externalDependencies],...e.owner.kind===`extension`&&e.extensionScope!==void 0?{extensionScope:e.extensionScope}:{},kind:`filesystem`,mountId:e.mountId,sourcePath:join(e.sourceRoot,e.source.logicalPath)},exportName:e.source.exportName,form:`direct`,layer:e.layer,logicalPath:e.logicalPath,nodeId:e.nodeId,owner:e.owner,sourceId:e.sourceId??e.source.sourceId}}function createApplicationManifestSourceProjection(e){let t={logicalPath:e=>e,name:e=>e};return e!==void 0&&(t.extensionScope=e),t}function createExtensionManifestSourceProjection(e){let{namespace:t,sourceRoot:n}=e;return{extensionScope:{namespace:t,sourceRoot:n},logicalPath:e=>qualifyExtensionContributionLogicalPath(e,t),name:e=>`${t}__${e}`}}function projectManifest(e){let{projection:t}=e,sourceId=t=>`${e.sourceIdPrefix??``}${t}`,pushModule=(n,r,i=e.mountId)=>{let a=t.logicalPath(r??n.logicalPath),o=createFilesystemModuleCandidate({externalDependencies:e.externalDependencies,...t.extensionScope===void 0?{}:{extensionScope:t.extensionScope},layer:e.layer,logicalPath:a,nodeId:e.nodeId,owner:e.owner,mountId:i,source:n,sourceId:sourceId(n.sourceId),sourceRoot:e.manifest.agentRoot});e.candidates.push(o)},pushResource=(n,r)=>{let i=t.logicalPath(r.logicalPath),a={...r,...r.sourceKind===`skill-package`?{name:t.name(r.name)}:{},logicalPath:i,sourceId:sourceId(r.sourceId)},o={backing:{kind:`resource`,sourcePath:r.sourceKind===`skill-package`?r.skillFilePath:join(e.manifest.agentRoot,r.logicalPath)},form:`direct`,layer:e.layer,logicalPath:i,nodeId:e.nodeId,owner:e.owner,sourceId:a.sourceId};e.candidates.push(o),e.resources.push({candidate:o,kind:n,source:a})};if(e.manifest.configModule!==void 0){let t=e.manifest.configModule.logicalPath;pushModule(e.manifest.configModule,canonicalSourceSlot(t)===`agent`?void 0:`agent.ts`)}let n=new Set(e.manifest.resolvedExtensions.map(e=>e.namespace));for(let t of e.manifest.extensions)n.has(mountRefNamespace(t.logicalPath))&&pushModule(t,void 0,e.declarationMountIds?.get(t.sourceId));for(let t of e.manifest.channels)pushModule(t);for(let t of e.manifest.connections)pushModule(t);for(let t of e.manifest.hooks)pushModule(t);for(let t of e.manifest.memories)pushModule(t);e.manifest.sandbox!==null&&pushModule(e.manifest.sandbox);for(let t of e.manifest.tools)pushModule(t);for(let t of e.manifest.instructions)t.sourceKind===`module`?pushModule(t):pushResource(`instructions`,t);for(let t of e.manifest.schedules)t.sourceKind===`module`?pushModule(t):pushResource(`schedule`,t);for(let t of e.manifest.skills)t.sourceKind===`module`?pushModule(t):pushResource(`skill`,t);for(let n of e.manifest.subagents){let r=t.name(n.subagentId),i=t.logicalPath(n.logicalPath);if(r===`agent`)throw Error(`Subagent "${i}" uses the reserved name "agent". Rename its path; eve reserves "agent" for the built-in root-copy target.`);let a={...n,logicalPath:i,sourceId:sourceId(n.sourceId),subagentId:r},o={backing:{kind:`resource`,sourcePath:n.entryPath},form:`direct`,layer:e.layer,logicalPath:i,nodeId:e.nodeId,owner:e.owner,sourceId:a.sourceId};e.candidates.push(o),e.subagents.push({candidate:o,mountId:e.mountId,nodePath:posix.join(e.subagentsPath,n.subagentId),...t.extensionScope===void 0?{}:{extensionScope:t.extensionScope},owner:e.owner,source:a})}}function projectModuleCandidate(e){let t={exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`},n=canonicalSourceSlot(e.logicalPath);if(n.startsWith(`connections/`))return{candidate:e,kind:`connection`,source:{...t,connectionName:deriveConnectionName(e.logicalPath)}};let r=MODULE_KIND_BY_SLOT_ROOT[n.split(`/`,1)[0]];if(r===void 0)throw Error(`Agent module source slot "${e.logicalPath}" is not compiled yet.`);return{candidate:e,kind:r,source:t}}function isModuleCandidate(e){return e.backing.kind!==`resource`}const EXTENSION_CONTRIBUTION_ROOTS=new Set([`channels`,`connections`,`hooks`,`instructions`,`schedules`,`skills`,`subagents`,`tools`]);function qualifyExtensionContributionLogicalPath(e,t){let n=e.split(`/`);if(n.length===1){let n=stripLogicalPathExtension(e);if(n===`instructions`||n===`system`)return`instructions/${t}${e.slice(e.lastIndexOf(`.`))}`;throw Error(`Extension source slot "${e}" cannot be namespace-scoped.`)}let r=n[0];if(!EXTENSION_CONTRIBUTION_ROOTS.has(r))throw Error(`Extension source slot "${e}" cannot be namespace-scoped.`);return n[1]=`${t}__${n[1]}`,n.join(`/`)}function deriveConnectionName(e){let t=stripLogicalPathExtension(e).replace(/^connections\//,``);return t.endsWith(`/connection`)?t.slice(0,-11):t}function mergeDependencies(...e){return[...new Set(e.flat())]}export{listApplicationModulePaths,projectAgentSources,projectSelectedSources,qualifyExtensionContributionLogicalPath};
@@ -13,6 +13,7 @@ import type { InstrumentationChannelDeliveryRef } from "#instrumentation/lifecyc
13
13
  import type { UserModelMessage } from "#harness/messages.js";
14
14
  import type { HandleEventFn } from "#harness/types.js";
15
15
  import type { PersistedDynamicToolMetadata } from "#context/dynamic-tool-metadata.js";
16
+ import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";
16
17
  import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
17
18
  import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
18
19
  import type { SandboxAccess, SandboxSessionEndReason } from "#sandbox/state.js";
@@ -222,6 +223,7 @@ export declare const SessionDynamicSubagentSelectionsKey: ContextKey<Readonly<Re
222
223
  export declare const TurnDynamicSubagentSelectionsKey: ContextKey<Readonly<Record<string, DurableDynamicSubagentSelection>>>;
223
224
  export declare const SessionDynamicSubagentRuntimeRevisionKey: ContextKey<string>;
224
225
  export declare const DynamicSubagentAgentConfigKey: ContextKey<DynamicSubagentAgentConfig>;
226
+ export declare const AgentSessionRuntimeOverridesKey: ContextKey<AgentSessionRuntimeOverrides>;
225
227
  /**
226
228
  * Durable state for one session-scoped dynamic skill.
227
229
  */
@@ -1 +1 @@
1
- import{SESSION_INBOX_CONTEXT_KEY}from"#execution/session-inbox/address.js";import{ContextKey}from"#context/key.js";import{STUB_CONTEXT_KEY}from"#tool-stubs/types.js";import{SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";const AuthKey=new ContextKey(`eve.auth`),ToolStubsKey=new ContextKey(STUB_CONTEXT_KEY),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ConversationIdKey=new ContextKey(`eve.conversationId`),SessionInboxKey=new ContextKey(SESSION_INBOX_CONTEXT_KEY),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ContinuationHookTokensKey=new ContextKey(`eve.continuationHookTokens`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),LocalDevRequestKey=new ContextKey(`eve.internal.localDevRequest`),OccurrenceIdKey=new ContextKey(`eve.scheduleOccurrenceId`),ScheduleIdKey=new ContextKey(`eve.scheduleId`),ScheduleInstanceKey=new ContextKey(`eve.scheduleInstance`),SessionTitleKey=new ContextKey(`eve.sessionTitle`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnDeliveryIdsKey=new ContextKey(`eve.turnDeliveryIds`),HistoryStateKey=new ContextKey(`eve.historyState`),OfferedCatalogToolsKey=new ContextKey(`eve.offeredCatalogTools`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ParentSessionKey=new ContextKey(`eve.parentSession`),SessionPredecessorKey=new ContextKey(`eve.sessionPredecessor`),TraceRootKey=new ContextKey(`eve.traceRoot`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SessionTraceSeedKey=new ContextKey(`eve.sessionTraceSeed`),OtelTraceEnabledKey=new ContextKey(`eve.otelTraceEnabled`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(SESSION_CALLBACK_CONTEXT_KEY_NAME),LegacyRemoteAgentCallerKey=new ContextKey(`eve.legacyRemoteAgentCaller`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),SandboxTerminalCleanupKey=new ContextKey(`eve.internal.sandboxTerminalCleanup`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),StaticModelReferenceKey=new ContextKey(`eve.staticModelReference`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),TurnMemoryLocksKey=new ContextKey(`eve.memory.turnLocks`),PreparedMemoryPreambleKey=new ContextKey(`eve.memory.preparedPreamble`),PendingMemoryCommitKey=new ContextKey(`eve.memory.pendingCommit`),PreparedMemoryCompactionKey=new ContextKey(`eve.memory.preparedCompaction`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),DynamicSkillSandboxKey=new ContextKey(`eve.dynamicSkillSandbox`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSkillSandboxKey,DynamicSubagentAgentConfigKey,HandleEventKey,HistoryStateKey,InitiatorAuthKey,LegacyRemoteAgentCallerKey,LiveStepDynamicModelSelectionKey,LocalDevRequestKey,OccurrenceIdKey,OfferedCatalogToolsKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,PendingMemoryCommitKey,PreparedMemoryCompactionKey,PreparedMemoryPreambleKey,RuntimeModelMetadataCacheKey,SandboxKey,SandboxTerminalCleanupKey,ScheduleIdKey,ScheduleInstanceKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionInboxKey,SessionKey,SessionPredecessorKey,SessionTitleKey,SessionTraceSeedKey,StaticModelReferenceKey,StepDynamicToolMetadataKey,ToolStubsKey,TraceRootKey,TurnDeliveryIdsKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnMemoryLocksKey};
1
+ import{SESSION_INBOX_CONTEXT_KEY}from"#execution/session-inbox/address.js";import{ContextKey}from"#context/key.js";import{STUB_CONTEXT_KEY}from"#tool-stubs/types.js";import{SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";const AuthKey=new ContextKey(`eve.auth`),ToolStubsKey=new ContextKey(STUB_CONTEXT_KEY),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ConversationIdKey=new ContextKey(`eve.conversationId`),SessionInboxKey=new ContextKey(SESSION_INBOX_CONTEXT_KEY),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ContinuationHookTokensKey=new ContextKey(`eve.continuationHookTokens`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),LocalDevRequestKey=new ContextKey(`eve.internal.localDevRequest`),OccurrenceIdKey=new ContextKey(`eve.scheduleOccurrenceId`),ScheduleIdKey=new ContextKey(`eve.scheduleId`),ScheduleInstanceKey=new ContextKey(`eve.scheduleInstance`),SessionTitleKey=new ContextKey(`eve.sessionTitle`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnDeliveryIdsKey=new ContextKey(`eve.turnDeliveryIds`),HistoryStateKey=new ContextKey(`eve.historyState`),OfferedCatalogToolsKey=new ContextKey(`eve.offeredCatalogTools`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ParentSessionKey=new ContextKey(`eve.parentSession`),SessionPredecessorKey=new ContextKey(`eve.sessionPredecessor`),TraceRootKey=new ContextKey(`eve.traceRoot`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SessionTraceSeedKey=new ContextKey(`eve.sessionTraceSeed`),OtelTraceEnabledKey=new ContextKey(`eve.otelTraceEnabled`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(SESSION_CALLBACK_CONTEXT_KEY_NAME),LegacyRemoteAgentCallerKey=new ContextKey(`eve.legacyRemoteAgentCaller`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),SandboxTerminalCleanupKey=new ContextKey(`eve.internal.sandboxTerminalCleanup`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),StaticModelReferenceKey=new ContextKey(`eve.staticModelReference`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),TurnMemoryLocksKey=new ContextKey(`eve.memory.turnLocks`),PreparedMemoryPreambleKey=new ContextKey(`eve.memory.preparedPreamble`),PendingMemoryCommitKey=new ContextKey(`eve.memory.pendingCommit`),PreparedMemoryCompactionKey=new ContextKey(`eve.memory.preparedCompaction`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),AgentSessionRuntimeOverridesKey=new ContextKey(`eve.agentSessionRuntimeOverrides`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),DynamicSkillSandboxKey=new ContextKey(`eve.dynamicSkillSandbox`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,AgentSessionRuntimeOverridesKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSkillSandboxKey,DynamicSubagentAgentConfigKey,HandleEventKey,HistoryStateKey,InitiatorAuthKey,LegacyRemoteAgentCallerKey,LiveStepDynamicModelSelectionKey,LocalDevRequestKey,OccurrenceIdKey,OfferedCatalogToolsKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,PendingMemoryCommitKey,PreparedMemoryCompactionKey,PreparedMemoryPreambleKey,RuntimeModelMetadataCacheKey,SandboxKey,SandboxTerminalCleanupKey,ScheduleIdKey,ScheduleInstanceKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionInboxKey,SessionKey,SessionPredecessorKey,SessionTitleKey,SessionTraceSeedKey,StaticModelReferenceKey,StepDynamicToolMetadataKey,ToolStubsKey,TraceRootKey,TurnDeliveryIdsKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnMemoryLocksKey};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Creates the per-run state directory for the server `eve eval` starts, after
3
+ * removing directories left by eval runs whose process died before cleanup
4
+ * (Ctrl-C, CI timeouts, crashes). Directories of live concurrent runs stay.
5
+ */
6
+ export declare function createEvalStateDirectory(appRoot: string, runId: string): Promise<string>;
7
+ export declare function removeEvalStateDirectory(directory: string): Promise<void>;
@@ -0,0 +1 @@
1
+ import{mkdir,readFile,readdir,rm,writeFile}from"node:fs/promises";import{join}from"node:path";const OWNER_FILE_NAME=`owner.json`;async function createEvalStateDirectory(e,t){let n=join(e,`.eve`,`eval-servers`);await removeAbandonedEvalStateDirectories(n);let r=join(n,t);return await mkdir(r,{recursive:!0}),await writeFile(join(r,OWNER_FILE_NAME),JSON.stringify({pid:process.pid})),r}async function removeEvalStateDirectory(e){await rm(e,{force:!0,recursive:!0,maxRetries:5,retryDelay:100})}async function removeAbandonedEvalStateDirectories(e){let t;try{t=await readdir(e)}catch{return}await Promise.all(t.map(async t=>{let n=join(e,t),r=await readOwnerPid(n);r===void 0||isProcessAlive(r)||await removeEvalStateDirectory(n).catch(()=>{})}))}async function readOwnerPid(e){try{let t=JSON.parse(await readFile(join(e,OWNER_FILE_NAME),`utf8`));return typeof t.pid==`number`&&Number.isInteger(t.pid)&&t.pid>0?t.pid:void 0}catch{return}}function isProcessAlive(e){try{return process.kill(e,0),!0}catch(e){return e instanceof Error&&`code`in e&&e.code===`EPERM`}}export{createEvalStateDirectory,removeEvalStateDirectory};
@@ -1,4 +1,4 @@
1
- import{randomUUID}from"node:crypto";import{readFile}from"node:fs/promises";import{basename,join}from"node:path";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{noDevelopmentExtensions}from"#compiler/development-extensions.js";import{EVE_EVALUATION_ENV_FLAG,EVE_EVALUATION_RUN_ID_ENV}from"#internal/application/dev-environment.js";import{shutdownActiveSandboxHandles}from"#execution/sandbox/active-handles.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{filterEvalsByTags}from"#evals/cli/filter.js";import{discoverAndImportEvals,discoverEvalConfig,findMisplacedEvalDirs}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{Console}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n,r=process.cwd()){await loadDevelopmentEnvironmentFiles(r);let i=e.length>0?e:void 0,a=await discoverAndImportEvals(r,i);if(a.length===0){let e=await findMisplacedEvalDirs(r);e.length>0?n.error(`No evals found under evals/, but eval files are present inside agent/:
1
+ import{randomUUID}from"node:crypto";import{readFile}from"node:fs/promises";import{basename,join}from"node:path";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{noDevelopmentExtensions}from"#compiler/development-extensions.js";import{EVE_DEV_STATE_DIR_ENV,EVE_EVALUATION_ENV_FLAG,EVE_EVALUATION_RUN_ID_ENV}from"#internal/application/dev-environment.js";import{shutdownActiveSandboxHandles}from"#execution/sandbox/active-handles.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{createEvalStateDirectory,removeEvalStateDirectory}from"#evals/cli/eval-state-directory.js";import{filterEvalsByTags}from"#evals/cli/filter.js";import{discoverAndImportEvals,discoverEvalConfig,findMisplacedEvalDirs}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{Console}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n,r=process.cwd()){await loadDevelopmentEnvironmentFiles(r);let i=e.length>0?e:void 0,a=await discoverAndImportEvals(r,i);if(a.length===0){let e=await findMisplacedEvalDirs(r);e.length>0?n.error(`No evals found under evals/, but eval files are present inside agent/:
2
2
  `+e.map(e=>` - ${e}`).join(`
3
3
  `)+`
4
- eve eval only scans the top-level evals/ directory (a sibling of agent/). Move these files there.`):i?n.error(`No evals found matching: ${i.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let o=t.tag??[],s=t.excludeTag??[],c=filterEvalsByTags({evaluations:a,includeTags:o,excludeTags:[]});if(c.length===0){n.error(`No evals matched the provided tags (${o.join(`, `)}).`),process.exitCode=2;return}let l=filterEvalsByTags({evaluations:c,includeTags:[],excludeTags:s});if(t.list===!0){printEvalList(l,t.json===!0,n);return}if(l.length===0){n.log(`All ${c.length} matching evals are excluded by tags (${s.join(`, `)}); nothing to run.`);return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let f;try{f=await discoverEvalConfig(r)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h,g;try{if(g=await f.setup?.(),t.url)h=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:r}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(r),kind:`remote`,url:t.url});else{process.env[EVE_EVALUATION_ENV_FLAG]=`1`,process.env[EVE_EVALUATION_RUN_ID_ENV]=randomUUID(),p=createDevelopmentServer(r,{developmentExtensions:noDevelopmentExtensions(),host:`127.0.0.1`,port:0});let e=await p.start();h=await createEvalClient({kind:`local`,url:e.url}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(r),kind:`local`,url:e.url})}let e=t.json===!0?[]:[Console()];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let i=await runEvals({evaluations:l,config:f,setupContext:g,target:m,client:h,appRoot:r,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(i,null,2));let a=i.failed>0,o=t.strict===!0&&i.scored>0;(a||o)&&(process.exitCode=1)}finally{for(let e of[()=>p?.close(),()=>p&&shutdownActiveSandboxHandles({log:e=>n.error(e)}),()=>f.teardown?.(g)])try{await e()}catch(e){n.error(`Eval cleanup failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}let _=typeof process.exitCode==`number`?process.exitCode:0;await flushStandardStreams(),process.exit(_)}async function flushStandardStreams(){await Promise.all([flushStream(process.stdout),flushStream(process.stderr)])}async function flushStream(e){await new Promise(t=>{let n=!1,settle=()=>{n||(n=!0,setImmediate(()=>{e.off(`error`,settle),t()}))};e.once(`error`,settle);try{e.write(``,settle)}catch{settle()}})}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(e){try{let t=JSON.parse(await readFile(join(e,`package.json`),`utf8`));return typeof t.name==`string`&&t.name.length>0?t.name:basename(e)}catch{return basename(e)}}export{runEvalCommand};
4
+ eve eval only scans the top-level evals/ directory (a sibling of agent/). Move these files there.`):i?n.error(`No evals found matching: ${i.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let o=t.tag??[],s=t.excludeTag??[],c=filterEvalsByTags({evaluations:a,includeTags:o,excludeTags:[]});if(c.length===0){n.error(`No evals matched the provided tags (${o.join(`, `)}).`),process.exitCode=2;return}let l=filterEvalsByTags({evaluations:c,includeTags:[],excludeTags:s});if(t.list===!0){printEvalList(l,t.json===!0,n);return}if(l.length===0){n.log(`All ${c.length} matching evals are excluded by tags (${s.join(`, `)}); nothing to run.`);return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let f;try{f=await discoverEvalConfig(r)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h,g,_;try{if(_=await f.setup?.(),t.url)g=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:r}),h=await resolveEvalTargetHandle({client:g,expectedAgentName:await readExpectedAgentName(r),kind:`remote`,url:t.url});else{let e=randomUUID();process.env[EVE_EVALUATION_ENV_FLAG]=`1`,process.env[EVE_EVALUATION_RUN_ID_ENV]=e,m=await createEvalStateDirectory(r,e),process.env[EVE_DEV_STATE_DIR_ENV]=m,p=createDevelopmentServer(r,{developmentExtensions:noDevelopmentExtensions(),host:`127.0.0.1`,port:0});let t=await p.start();g=await createEvalClient({kind:`local`,url:t.url}),h=await resolveEvalTargetHandle({client:g,expectedAgentName:await readExpectedAgentName(r),kind:`local`,url:t.url})}let e=t.json===!0?[]:[Console()];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let i=await runEvals({evaluations:l,config:f,setupContext:_,target:h,client:g,appRoot:r,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(i,null,2));let a=i.failed>0,o=t.strict===!0&&i.scored>0;(a||o)&&(process.exitCode=1)}finally{for(let e of[()=>p?.close(),()=>p&&shutdownActiveSandboxHandles({log:e=>n.error(e)}),()=>m&&removeEvalStateDirectory(m),()=>f.teardown?.(_)])try{await e()}catch(e){n.error(`Eval cleanup failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}let v=typeof process.exitCode==`number`?process.exitCode:0;await flushStandardStreams(),process.exit(v)}async function flushStandardStreams(){await Promise.all([flushStream(process.stdout),flushStream(process.stderr)])}async function flushStream(e){await new Promise(t=>{let n=!1,settle=()=>{n||(n=!0,setImmediate(()=>{e.off(`error`,settle),t()}))};e.once(`error`,settle);try{e.write(``,settle)}catch{settle()}})}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(e){try{let t=JSON.parse(await readFile(join(e,`package.json`),`utf8`));return typeof t.name==`string`&&t.name.length>0?t.name:basename(e)}catch{return basename(e)}}export{runEvalCommand};
@@ -1,6 +1,7 @@
1
1
  import type { UserContent } from "ai";
2
2
  import type { SessionCallback, SessionCapabilities } from "#channel/types.js";
3
3
  import type { LegacyRemoteAgentCaller } from "#execution/legacy-remote-agent/protocol.js";
4
+ import type { ClientContextValue } from "#eve-channel/types.js";
4
5
  import type { JsonObject } from "#shared/json.js";
5
6
  import type { ToolStub } from "#tool-stubs/types.js";
6
7
  export interface ParsedCreateBody {
@@ -8,7 +9,7 @@ export interface ParsedCreateBody {
8
9
  callback?: SessionCallback;
9
10
  capabilities?: SessionCapabilities;
10
11
  message?: string | UserContent;
11
- context?: readonly string[];
12
+ context?: ClientContextValue;
12
13
  operationId?: string;
13
14
  outputSchema?: JsonObject;
14
15
  /** Remote agent protocol of a delegating caller; set only with {@link callback}. */
@@ -1 +1 @@
1
- import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{readMatchedStubRules,readStubFailure}from"#execution/tool-stubs/steps.js";import{InvalidToolStubTargetError}from"#tool-stubs/validate-targets.js";import{getRun}from"#internal/workflow/runtime.js";import{proxyStreamHeaders}from"#eve-channel/stream-headers.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{legacyTaskInputRoute}from"#execution/legacy-remote-agent/protocol.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{agentDelegation}from"#tracing/eve/delegation.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage,strandedSessionResponse}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function createdSessionBody(e,t){let n={ok:!0,sessionId:e,status:`accepted`};return t.protocolVersion!==void 0&&(n.protocolVersion=t.protocolVersion),n}function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(legacyTaskInputRoute.path,legacyTaskInputRoute.handler),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=sessionAuthFromResult(i),o=await parseOptionalJsonRequest(n);if(o instanceof Response)return o;if(o.stubs!==void 0&&i.allowToolStubs!==!0)return Response.json({ok:!1,error:`Tool stubbing is not permitted for this caller.`},{status:403});let s=rejectSessionContinuationToken(o);if(s!==null)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:o});if(c instanceof Response)return c;let l=parseCreateBody(o);if(l instanceof Response)return l;l.callback!==void 0&&l.legacyRemoteAgentCaller!==void 0&&log.info(`serving a remote agent protocol 1 caller`,{callerOrigin:new URL(l.callback.url).origin,forwarder:i.principalId});let u=l.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),d;if(typeof u==`object`){if(u.callId!==l.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=c.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(a,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?d=u:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else u===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let f=l.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),p=l.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),f)??f,m=checkUploadPolicy(l,t);if(m!==null)return m;if(l.operationId!==void 0&&c.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let h=l.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:c.auth,operationId:l.operationId});if(h!==void 0){let e=await r.resolveSession(h);if(e!==void 0)return Response.json(createdSessionBody(e.id,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let g=f===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),_=c.accepted&&f!==void 0&&(f.traceFlags&1)==1?typeof g==`object`?g:g===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,v=p;_!==void 0&&p!==void 0&&(v={...p,forwardedTracePolicy:_}),g===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof g==`object`&&(_===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:g.originAudience,ceiling:formatTraceContentCeiling(g.ceiling),forwarder:i.principalId}));let y=l.message===void 0?{auth:c.auth}:await resolveOnMessage({auth:c.auth,config:e,invocation:d===void 0||l.operationId===void 0?void 0:{operationId:l.operationId},message:l.message,request:n});if(y instanceof Response)return y;let b=readRouteSessionCreator(r);if(b===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let x;try{x=await agentDelegation.receive({headers:n.headers,delegated:l.callback!==void 0,trusted:c.accepted,parent:d,callerTrace:p,parentTraceContext:v},({conversationId:e,parentTraceContext:t})=>b({audienceAuth:a,toolStubs:l.stubs===void 0?void 0:{rules:l.stubs,token:crypto.randomUUID()},auth:y.auth,capabilities:l.capabilities??{requestInput:!0},callback:l.callback,legacyRemoteAgentCaller:l.legacyRemoteAgentCaller,continuationToken:h,initiatorAuth:c.accepted?c.initiatorAuth:void 0,input:attachClientContext({message:l.message,context:y.context,outputSchema:l.outputSchema},l.context),conversationId:e,parent:d,parentTraceContext:t,traceRoot:d===void 0?void 0:{kind:`own`},title:y.title}))}catch(e){if(e instanceof InvalidToolStubTargetError)return Response.json({error:e.message,ok:!1},{status:400});let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json(createdSessionBody(x.sessionId,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:x.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:sessionAuthFromResult(a),payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f,p=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.title,p=t.auth}let m;try{let e=r(o),t=attachClientContext({auth:p,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:f},l.context);m=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return m.status===`accepted`?Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`,deliveryId:m.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202}):Response.json({code:m.retryable?`session_not_ready`:`session_not_active`,error:m.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return Response.json({ok:!0,...s},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STUBS_ROUTE_PATTERN,async(t,{params:n})=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;if(r.allowToolStubs!==!0)return Response.json({error:`Tool stubbing is not permitted for this caller.`,ok:!1},{status:403});let i=requireSessionId(n);if(i instanceof Response)return i;try{return await getRun(i).exists?Response.json({error:await readStubFailure(i)??null,matchedRuleIds:await readMatchedStubRules(i)},{headers:{"cache-control":`no-store`}}):Response.json({error:`Session not found.`,ok:!1},{status:404})}catch(e){let t=logError(log,`tool-stub verification request failed`,e,{sessionId:i});return Response.json({error:`Failed to verify tool stubs.`,errorId:t,ok:!1},{status:500})}}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteAgentBinding({callId:a,childSessionId:o,childStreamPath:l,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d(u)}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=proxyStreamHeaders(h.headers);return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events,fetchFile:e.fetchFile,uploadPolicy:e.uploadPolicy})}export{eveChannel};
1
+ import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{validateSessionHistory}from"#shared/session-history.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{readMatchedStubRules,readStubFailure}from"#execution/tool-stubs/steps.js";import{InvalidToolStubTargetError}from"#tool-stubs/validate-targets.js";import{getRun}from"#internal/workflow/runtime.js";import{proxyStreamHeaders}from"#eve-channel/stream-headers.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{legacyTaskInputRoute}from"#execution/legacy-remote-agent/protocol.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{agentDelegation}from"#tracing/eve/delegation.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage,resolveTurnClientContext,strandedSessionResponse}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function createdSessionBody(e,t){let n={ok:!0,sessionId:e,status:`accepted`};return t.protocolVersion!==void 0&&(n.protocolVersion=t.protocolVersion),n}function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(legacyTaskInputRoute.path,legacyTaskInputRoute.handler),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=sessionAuthFromResult(i),o=await parseOptionalJsonRequest(n);if(o instanceof Response)return o;if(o.stubs!==void 0&&i.allowToolStubs!==!0)return Response.json({ok:!1,error:`Tool stubbing is not permitted for this caller.`},{status:403});let s=rejectSessionContinuationToken(o);if(s!==null)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:o});if(c instanceof Response)return c;let l=parseCreateBody(o);if(l instanceof Response)return l;l.callback!==void 0&&l.legacyRemoteAgentCaller!==void 0&&log.info(`serving a remote agent protocol 1 caller`,{callerOrigin:new URL(l.callback.url).origin,forwarder:i.principalId});let u=l.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),d;if(typeof u==`object`){if(u.callId!==l.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=c.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(a,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?d=u:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else u===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let f=l.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),p=l.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),f)??f,m=checkUploadPolicy(l,t);if(m!==null)return m;if(l.operationId!==void 0&&c.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let h=l.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:c.auth,operationId:l.operationId});if(h!==void 0){let e=await r.resolveSession(h);if(e!==void 0)return Response.json(createdSessionBody(e.id,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let g=f===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),_=c.accepted&&f!==void 0&&(f.traceFlags&1)==1?typeof g==`object`?g:g===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,v=p;_!==void 0&&p!==void 0&&(v={...p,forwardedTracePolicy:_}),g===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof g==`object`&&(_===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:g.originAudience,ceiling:formatTraceContentCeiling(g.ceiling),forwarder:i.principalId}));let y=l.message===void 0?{auth:c.auth,clientContext:resolveTurnClientContext(void 0,l.context)}:await resolveOnMessage({auth:c.auth,clientContext:l.context,config:e,invocation:d===void 0||l.operationId===void 0?void 0:{operationId:l.operationId},message:l.message,request:n});if(y instanceof Response)return y;let b=readRouteSessionCreator(r);if(b===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let x;try{x=await agentDelegation.receive({headers:n.headers,delegated:l.callback!==void 0,trusted:c.accepted,parent:d,callerTrace:p,parentTraceContext:v},({conversationId:e,parentTraceContext:t})=>b({audienceAuth:a,toolStubs:l.stubs===void 0?void 0:{rules:l.stubs,token:crypto.randomUUID()},auth:y.auth,capabilities:l.capabilities??{requestInput:!0},callback:l.callback,legacyRemoteAgentCaller:l.legacyRemoteAgentCaller,continuationToken:h,initiatorAuth:c.accepted?c.initiatorAuth:void 0,input:attachClientContext({message:l.message,context:y.context,history:validateSessionHistory(`history`in y?y.history:void 0),outputSchema:l.outputSchema},y.clientContext),conversationId:e,parent:d,parentTraceContext:t,traceRoot:d===void 0?void 0:{kind:`own`},title:y.title}))}catch(e){if(e instanceof InvalidToolStubTargetError)return Response.json({error:e.message,ok:!1},{status:400});let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json(createdSessionBody(x.sessionId,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:x.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:sessionAuthFromResult(a),payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d=resolveTurnClientContext(void 0,l.context),f,p,m,h=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,clientContext:l.context,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.clientContext,f=t.context,p=t.history,m=t.title,h=t.auth}let g;try{let e=r(o),t=attachClientContext({auth:h,callback:l.callback,context:f,history:p,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:m},d);g=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return g.status===`accepted`?Response.json({ok:!0,sessionId:g.sessionId,status:`accepted`,deliveryId:g.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:g.sessionId},status:202}):Response.json({code:g.retryable?`session_not_ready`:`session_not_active`,error:g.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return Response.json({ok:!0,...s},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STUBS_ROUTE_PATTERN,async(t,{params:n})=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;if(r.allowToolStubs!==!0)return Response.json({error:`Tool stubbing is not permitted for this caller.`,ok:!1},{status:403});let i=requireSessionId(n);if(i instanceof Response)return i;try{return await getRun(i).exists?Response.json({error:await readStubFailure(i)??null,matchedRuleIds:await readMatchedStubRules(i)},{headers:{"cache-control":`no-store`}}):Response.json({error:`Session not found.`,ok:!1},{status:404})}catch(e){let t=logError(log,`tool-stub verification request failed`,e,{sessionId:i});return Response.json({error:`Failed to verify tool stubs.`,errorId:t,ok:!1},{status:500})}}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteAgentBinding({callId:a,childSessionId:o,childStreamPath:l,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d(u)}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=proxyStreamHeaders(h.headers);return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events,fetchFile:e.fetchFile,uploadPolicy:e.uploadPolicy})}export{eveChannel};
@@ -1,6 +1,7 @@
1
1
  import type { UserContent } from "ai";
2
2
  import type { SessionAuthContext, SessionCallback, TurnPolicy } from "#channel/types.js";
3
3
  import type { Session } from "#channel/session.js";
4
+ import type { ClientContextValue } from "#eve-channel/types.js";
4
5
  import { type UploadPolicy } from "#public/channels/upload-policy.js";
5
6
  import { type ValidatedInputResponse } from "#shared/input.js";
6
7
  import { type JsonObject } from "#shared/json.js";
@@ -15,7 +16,7 @@ interface ParsedSessionMessageBody {
15
16
  callback?: SessionCallback;
16
17
  message?: string | UserContent;
17
18
  inputResponses?: readonly ValidatedInputResponse[];
18
- context?: readonly string[];
19
+ context?: ClientContextValue;
19
20
  outputSchema?: JsonObject;
20
21
  turnPolicy?: TurnPolicy;
21
22
  }
@@ -1,4 +1,3 @@
1
- import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{strandedSessionResponse}from"#eve-channel/support.js";import{parseToolStubs}from"#tool-stubs/rules.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isExpiredWorkflowRunError,isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};if(n.stubs!==void 0)try{d.stubs=parseToolStubs(n.stubs)}catch(e){return Response.json({ok:!1,error:e instanceof Error?e.message:`Invalid tool stubs.`},{status:400})}return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e);if(Object.hasOwn(t,`stubs`))return Response.json({ok:!1,error:`Tool stubs are fixed at session creation.`},{status:400});let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseFollow(e),i=!r||parseIncludeTailIndex(e);try{let a=t.getEventStream({follow:r,startIndex:n});a.catch(()=>{});let o;try{o=await t.getStreamTailIndex()}catch(e){throw a.then(e=>e.cancel()).catch(()=>{}),e}let s=await a,c=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,l=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i&&l.set(EVE_STREAM_TAIL_INDEX_HEADER,String(o)),new Response(serializeAsNdjson(s,e.signal,i?streamEventLimit(n,o):void 0,c!==void 0),{headers:l})}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;if(isExpiredWorkflowRunError(e))return Response.json({code:`session_expired`,error:`Session history is no longer available.`,ok:!1},{headers:{"cache-control":`no-store`},status:410});let n=isMissingWorkflowRunError(e);return Response.json({error:n?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:n?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
2
- ${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseFollow(e){let t=new URL(e.url).searchParams.get(`follow`);return t!==`0`&&t!==`false`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
1
+ import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{strandedSessionResponse}from"#eve-channel/support.js";import{parseToolStubs}from"#tool-stubs/rules.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isExpiredWorkflowRunError,isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};if(n.stubs!==void 0)try{d.stubs=parseToolStubs(n.stubs)}catch(e){return Response.json({ok:!1,error:e instanceof Error?e.message:`Invalid tool stubs.`},{status:400})}return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e);if(Object.hasOwn(t,`stubs`))return Response.json({ok:!1,error:`Tool stubs are fixed at session creation.`},{status:400});let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseFollow(e),i=!r||parseIncludeTailIndex(e);try{let a=t.getEventStream({follow:r,startIndex:n});a.catch(()=>{});let o;try{o=await t.getStreamTailIndex()}catch(e){throw a.then(e=>e.cancel()).catch(()=>{}),e}let s=await a,c=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,l=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i&&l.set(EVE_STREAM_TAIL_INDEX_HEADER,String(o)),new Response(serializeAsNdjson(s,e.signal,i?streamEventLimit(n,o):void 0,c!==void 0),{headers:l})}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;if(isExpiredWorkflowRunError(e))return Response.json({code:`session_expired`,error:`Session history is no longer available.`,ok:!1},{headers:{"cache-control":`no-store`},status:410});let n=isMissingWorkflowRunError(e);return Response.json({error:n?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:n?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?e:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e:Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseFollow(e){let t=new URL(e.url).searchParams.get(`follow`);return t!==`0`&&t!==`false`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
3
2
  `)),scheduleHeartbeat(e)}catch{clearTimers()}},1e4)},startLease=e=>{scheduleHeartbeat(e),s=setTimeout(()=>{clearTimers();try{e.enqueue(i.encode(`${JSON.stringify(EVE_STREAM_LEASE_ENDED_CONTROL)}\n`)),e.terminate()}catch{}},6e4)},c=new TransformStream({start(e){e.enqueue(i.encode(`
4
3
  `)),n===0?e.terminate():r&&startLease(e)},transform(e,t){t.enqueue(i.encode(`${JSON.stringify(e)}\n`)),a+=1,a===n?(clearTimers(),t.terminate()):r&&scheduleHeartbeat(t)},flush(){clearTimers()}});return e.pipeTo(c.writable,{signal:t}).catch(()=>{}).finally(clearTimers),c.readable}export{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId};
@@ -1,8 +1,9 @@
1
1
  import type { UserContent } from "ai";
2
2
  import type { SessionAuthContext } from "#channel/types.js";
3
+ import type { SessionHistoryMessage } from "#shared/session-history.js";
3
4
  import type { MessageStreamEvent } from "#protocol/message.js";
4
5
  import type { ChannelCors } from "#public/definitions/channel.js";
5
- import { type EveChannelCors, type EveChannelInput, type EveHandle } from "#eve-channel/types.js";
6
+ import { type ClientContextValue, type EveChannelCors, type EveChannelInput, type EveHandle } from "#eve-channel/types.js";
6
7
  export declare function healthResponse(): Response;
7
8
  /** Clients display the error text directly; keep operator details in structured fields. */
8
9
  export declare function strandedSessionResponse(error: unknown): Response | undefined;
@@ -30,15 +31,24 @@ export declare function findRemoteAgentBinding(input: RemoteAgentStreamCoordinat
30
31
  export declare function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors;
31
32
  interface OnMessageOutcome {
32
33
  readonly auth: SessionAuthContext | null;
34
+ /** Model-ready turn context: `onMessage`'s replacement, or the request's labeled entries. */
35
+ readonly clientContext?: readonly string[];
33
36
  readonly context?: readonly string[];
37
+ readonly history?: readonly SessionHistoryMessage[];
34
38
  readonly title?: string;
35
39
  }
36
40
  export declare function resolveOnMessage(input: {
37
41
  readonly auth: SessionAuthContext | null;
42
+ readonly clientContext?: ClientContextValue;
38
43
  readonly config: EveChannelInput;
39
44
  readonly invocation?: EveHandle["invocation"];
40
45
  readonly message: string | UserContent;
41
46
  readonly request: Request;
42
47
  readonly sessionId?: string;
43
48
  }): Promise<OnMessageOutcome | Response>;
49
+ /**
50
+ * The turn's model context messages: `onMessage`'s replacement as written, otherwise
51
+ * the request's entries labeled as client-supplied. Empty means none.
52
+ */
53
+ export declare function resolveTurnClientContext(replacement: ClientContextValue | undefined, requested: ClientContextValue | undefined): readonly string[] | undefined;
44
54
  export {};
@@ -1 +1,2 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{defaultEveAuth}from"#eve-channel/types.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`eve.channel`);function healthResponse(){return Response.json({ok:!0,status:`ready`,workflowId:workflowEntryReference.workflowId})}function strandedSessionResponse(e){if(!SessionStrandedError.is(e))return;let t={code:`session_stranded`,error:`This session is no longer available.`,ok:!1};return e.owner.eveVersion!==void 0&&(t.eveVersion=e.owner.eveVersion),Response.json(t,{headers:{"cache-control":`no-store`},status:409})}async function findRemoteAgentBinding(e){let t=await e.parent.getStreamTailIndex();if(t<0)return;let n=(await e.parent.getEventStream({startIndex:0})).getReader();try{for(let r=0;r<=t;r+=1){let t=await n.read();if(t.done)break;let r=readRemoteAgentBinding(t.value,e);if(r!==void 0)return r}}finally{await n.cancel().catch(()=>{})}}function readRemoteAgentBinding(e,t){if(e.type!==`agent.started`)return;let{data:n}=e;if(n.callId===t.callId&&n.sessionId===t.childSessionId&&n.streamPath===t.childStreamPath&&n.remote!==void 0)return{name:n.name,...n.remote}}function normalizeEveCors(e){if(e===void 0||e===!1)return!1;if(e===!0)return!0;let t={};return e.origin!==void 0&&(t.origin=normalizeEveCorsOrigin(e.origin)),e.methods!==void 0&&(t.methods=e.methods),e.allowedHeaders!==void 0&&(t.allowHeaders=e.allowedHeaders),e.exposedHeaders!==void 0&&(t.exposeHeaders=e.exposedHeaders),e.credentials!==void 0&&(t.credentials=e.credentials),e.maxAge!==void 0&&(t.maxAge=e.maxAge),e.preflightStatus!==void 0&&(t.preflight={statusCode:e.preflightStatus}),t}function normalizeEveCorsOrigin(e){return e===`*`||e===`null`?e:typeof e==`string`?[e]:e}async function resolveOnMessage(e){let t=e.config.onMessage??defaultOnMessage,n;try{let r={caller:e.auth,request:e.request};if(n=await t({eve:e.sessionId===void 0?e.invocation===void 0?r:{...r,invocation:e.invocation}:{...r,sessionId:e.sessionId}},e.message),n==null)throw TypeError(`eveChannel onMessage must return an auth result.`)}catch(t){let n=logError(log,`onMessage handler failed`,t,{sessionId:e.sessionId});return Response.json({error:`onMessage handler failed.`,errorId:n,ok:!1},{status:500})}return{auth:n.auth,context:n.context,title:n.title}}function defaultOnMessage(e){return{auth:defaultEveAuth(e)}}export{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage,strandedSessionResponse};
1
+ import{createLogger,logError}from"#internal/logging.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{defaultEveAuth}from"#eve-channel/types.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`eve.channel`);function healthResponse(){return Response.json({ok:!0,status:`ready`,workflowId:workflowEntryReference.workflowId})}function strandedSessionResponse(e){if(!SessionStrandedError.is(e))return;let t={code:`session_stranded`,error:`This session is no longer available.`,ok:!1};return e.owner.eveVersion!==void 0&&(t.eveVersion=e.owner.eveVersion),Response.json(t,{headers:{"cache-control":`no-store`},status:409})}async function findRemoteAgentBinding(e){let t=await e.parent.getStreamTailIndex();if(t<0)return;let n=(await e.parent.getEventStream({startIndex:0})).getReader();try{for(let r=0;r<=t;r+=1){let t=await n.read();if(t.done)break;let r=readRemoteAgentBinding(t.value,e);if(r!==void 0)return r}}finally{await n.cancel().catch(()=>{})}}function readRemoteAgentBinding(e,t){if(e.type!==`agent.started`)return;let{data:n}=e;if(n.callId===t.callId&&n.sessionId===t.childSessionId&&n.streamPath===t.childStreamPath&&n.remote!==void 0)return{name:n.name,...n.remote}}function normalizeEveCors(e){if(e===void 0||e===!1)return!1;if(e===!0)return!0;let t={};return e.origin!==void 0&&(t.origin=normalizeEveCorsOrigin(e.origin)),e.methods!==void 0&&(t.methods=e.methods),e.allowedHeaders!==void 0&&(t.allowHeaders=e.allowedHeaders),e.exposedHeaders!==void 0&&(t.exposeHeaders=e.exposedHeaders),e.credentials!==void 0&&(t.credentials=e.credentials),e.maxAge!==void 0&&(t.maxAge=e.maxAge),e.preflightStatus!==void 0&&(t.preflight={statusCode:e.preflightStatus}),t}function normalizeEveCorsOrigin(e){return e===`*`||e===`null`?e:typeof e==`string`?[e]:e}async function resolveOnMessage(e){let t=e.config.onMessage??defaultOnMessage,n;try{let r={caller:e.auth,clientContext:e.clientContext,request:e.request};if(n=await t({eve:e.sessionId===void 0?e.invocation===void 0?r:{...r,invocation:e.invocation}:{...r,sessionId:e.sessionId}},e.message),n==null)throw TypeError(`eveChannel onMessage must return an auth result.`)}catch(t){let n=logError(log,`onMessage handler failed`,t,{sessionId:e.sessionId});return Response.json({error:`onMessage handler failed.`,errorId:n,ok:!1},{status:500})}return{auth:n.auth,clientContext:resolveTurnClientContext(n.clientContext,e.clientContext),context:n.context,history:n.history,title:n.title}}function resolveTurnClientContext(e,t){let n=e===void 0?toContextEntries(t).map(e=>`Client context:
2
+ ${e}`):toContextEntries(e);return n.length===0?void 0:n}function toContextEntries(e){return e===void 0||e===``?[]:typeof e==`string`?[e]:Array.isArray(e)?e:[JSON.stringify(e)]}function defaultOnMessage(e){return{auth:defaultEveAuth(e)}}export{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage,resolveTurnClientContext,strandedSessionResponse};
@@ -4,8 +4,10 @@ import type { TrustedForwarders } from "#channel/forwarded-principal.js";
4
4
  import type { AuthFn } from "#public/channels/auth.js";
5
5
  import type { UploadPolicyInput } from "#public/channels/upload-policy.js";
6
6
  import type { FetchFileFunction } from "#shared/channel-definition.js";
7
+ import type { JsonObject } from "#shared/json.js";
7
8
  import type { AudienceContext, Channel, ChannelContinuationOps, ChannelEvents, ChannelMethod } from "#public/definitions/channel.js";
8
9
  import type { ChannelAudience } from "#shared/channel-audience.js";
10
+ import type { SessionHistoryMessage } from "#shared/session-history.js";
9
11
  export type { ForwardedAssertion, TrustedForwarders } from "#channel/forwarded-principal.js";
10
12
  /**
11
13
  * Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
@@ -39,10 +41,17 @@ export interface EveChannelCorsOptions {
39
41
  * fully permissive browser access, or pass an options object to narrow it.
40
42
  */
41
43
  export type EveChannelCors = boolean | EveChannelCorsOptions;
44
+ /**
45
+ * Turn-scoped context: a string, an array of strings, or a JSON object. The same
46
+ * shape the eve client sends as `clientContext`.
47
+ */
48
+ export type ClientContextValue = string | readonly string[] | JsonObject;
42
49
  /** Low-level eve HTTP handle exposed to `eveChannel({ onMessage })`. */
43
50
  export interface EveHandle {
44
51
  /** Route-auth result for the request; `onMessage` chooses session auth by returning `{ auth }`. */
45
52
  readonly caller: SessionAuthContext | null;
53
+ /** The request's `clientContext`, exactly as the client sent it. `undefined` when it sent none. */
54
+ readonly clientContext?: ClientContextValue;
46
55
  /** Replay-stable identity of a trusted remote-subagent create operation. */
47
56
  readonly invocation?: {
48
57
  readonly operationId: string;
@@ -61,7 +70,23 @@ export interface EveMessageContext {
61
70
  */
62
71
  export type EveMessageResult = {
63
72
  readonly auth: SessionAuthContext | null;
73
+ /** Context strings prepended as user messages and kept in session history. */
64
74
  readonly context?: readonly string[];
75
+ /**
76
+ * Context for this turn only, replacing the request's `clientContext`. Like
77
+ * request `clientContext`, it reaches every model call in the turn and is not
78
+ * kept in session history. It takes the same shape as request `clientContext`
79
+ * and becomes model messages the same way, without the `Client context:` label
80
+ * eve adds to client-supplied entries. Return `[]` to drop the request's
81
+ * context; omit it to keep the request's context.
82
+ */
83
+ readonly clientContext?: ClientContextValue;
84
+ /**
85
+ * Prior conversation added as user and assistant turns before this message.
86
+ * Resolve it on the server and authorize the caller against the stored
87
+ * conversation.
88
+ */
89
+ readonly history?: readonly SessionHistoryMessage[];
65
90
  /** Sets the title when creating a workflow or sending its first message after prewarming. */
66
91
  readonly title?: string;
67
92
  };