eve 0.69.0 → 0.70.1

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 (361) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/src/acp/adapter.js +1 -1
  3. package/dist/src/channel/task-card.d.ts +3 -3
  4. package/dist/src/channel/task-card.js +1 -1
  5. package/dist/src/channel/types.d.ts +18 -0
  6. package/dist/src/chunks/{use-eve-agent-Dab2MnT2.js → use-eve-agent-CJQeE7-t.js} +1873 -1236
  7. package/dist/src/chunks/{use-eve-agent-D_5129A9.js → use-eve-agent-DdemtY6C.js} +1874 -1234
  8. package/dist/src/cli/dev/command.js +1 -1
  9. package/dist/src/cli/dev/console-records-preload.d.ts +1 -0
  10. package/dist/src/cli/dev/console-records-preload.js +1 -0
  11. package/dist/src/cli/dev/console-records.d.ts +17 -0
  12. package/dist/src/cli/dev/console-records.js +3 -0
  13. package/dist/src/cli/dev/diagnostic-sink.d.ts +1 -0
  14. package/dist/src/cli/dev/local-server-process.js +1 -1
  15. package/dist/src/cli/dev/tui/blocks.d.ts +2 -1
  16. package/dist/src/cli/dev/tui/blocks.js +3 -3
  17. package/dist/src/cli/dev/tui/conversation-view.d.ts +54 -0
  18. package/dist/src/cli/dev/tui/conversation-view.js +1 -0
  19. package/dist/src/cli/dev/tui/flow-drawer.d.ts +5 -2
  20. package/dist/src/cli/dev/tui/flow-drawer.js +1 -1
  21. package/dist/src/cli/dev/tui/log-display-mode.d.ts +4 -10
  22. package/dist/src/cli/dev/tui/log-display-mode.js +1 -1
  23. package/dist/src/cli/dev/tui/message-queue.d.ts +7 -63
  24. package/dist/src/cli/dev/tui/message-queue.js +3 -1
  25. package/dist/src/cli/dev/tui/prompt-commands.d.ts +7 -7
  26. package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
  27. package/dist/src/cli/dev/tui/question-panel.d.ts +3 -1
  28. package/dist/src/cli/dev/tui/question-panel.js +1 -1
  29. package/dist/src/cli/dev/tui/runner.d.ts +58 -195
  30. package/dist/src/cli/dev/tui/runner.js +3 -3
  31. package/dist/src/cli/dev/tui/task-activity.d.ts +11 -24
  32. package/dist/src/cli/dev/tui/task-activity.js +1 -1
  33. package/dist/src/cli/dev/tui/task-records.d.ts +17 -0
  34. package/dist/src/cli/dev/tui/task-records.js +1 -0
  35. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +15 -37
  36. package/dist/src/cli/dev/tui/terminal-renderer.js +10 -13
  37. package/dist/src/cli/dev/tui/terminal-tool-part.d.ts +2 -0
  38. package/dist/src/cli/dev/tui/terminal-tool-part.js +1 -0
  39. package/dist/src/cli/dev/tui/test/fake-eve-server.d.ts +34 -0
  40. package/dist/src/cli/dev/tui/test/fake-eve-server.js +1 -0
  41. package/dist/src/cli/dev/tui/test/index.d.ts +1 -0
  42. package/dist/src/cli/dev/tui/test/index.js +1 -1
  43. package/dist/src/cli/dev/tui/tool-block-groups.js +1 -1
  44. package/dist/src/cli/dev/tui/tool-presentation.d.ts +1 -0
  45. package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
  46. package/dist/src/cli/dev/tui/tool-rows.d.ts +1 -0
  47. package/dist/src/cli/dev/tui/tool-rows.js +2 -2
  48. package/dist/src/cli/dev/tui/transcript-parts.d.ts +81 -0
  49. package/dist/src/cli/dev/tui/transcript-parts.js +3 -0
  50. package/dist/src/cli/dev/tui/transcript.d.ts +47 -0
  51. package/dist/src/cli/dev/tui/transcript.js +1 -0
  52. package/dist/src/cli/dev/tui/tui.js +1 -1
  53. package/dist/src/cli/dev/tui/turn-clock.d.ts +11 -26
  54. package/dist/src/cli/dev/tui/turn-clock.js +1 -1
  55. package/dist/src/cli/dev/tui/types.d.ts +2 -4
  56. package/dist/src/cli/dev/ui-options.js +1 -1
  57. package/dist/src/client/agent-stream-follower.d.ts +26 -0
  58. package/dist/src/client/agent-stream-follower.js +1 -0
  59. package/dist/src/client/authorization-message-parts.js +1 -1
  60. package/dist/src/client/conversation-client.d.ts +40 -0
  61. package/dist/src/client/conversation-client.js +1 -0
  62. package/dist/src/client/conversation-reducer.d.ts +29 -0
  63. package/dist/src/client/conversation-reducer.js +1 -0
  64. package/dist/src/client/conversation-state.d.ts +110 -0
  65. package/dist/src/client/conversation-state.js +1 -0
  66. package/dist/src/client/eve-agent-projection.d.ts +24 -7
  67. package/dist/src/client/eve-agent-projection.js +1 -1
  68. package/dist/src/client/eve-agent-store-helpers.d.ts +21 -2
  69. package/dist/src/client/eve-agent-store-helpers.js +2 -2
  70. package/dist/src/client/eve-agent-store-state.d.ts +15 -3
  71. package/dist/src/client/eve-agent-store.d.ts +10 -1
  72. package/dist/src/client/eve-agent-store.js +1 -1
  73. package/dist/src/client/index.d.ts +4 -1
  74. package/dist/src/client/index.js +1 -1
  75. package/dist/src/client/message-reducer-primitives.d.ts +1 -2
  76. package/dist/src/client/message-reducer-primitives.js +1 -1
  77. package/dist/src/client/message-reducer-types.d.ts +9 -2
  78. package/dist/src/client/message-reducer.js +1 -1
  79. package/dist/src/client/message-response.js +1 -1
  80. package/dist/src/client/message-run-parts.d.ts +10 -6
  81. package/dist/src/client/message-run-parts.js +1 -1
  82. package/dist/src/client/optimistic-message-submissions.d.ts +6 -4
  83. package/dist/src/client/optimistic-message-submissions.js +1 -1
  84. package/dist/src/client/reducer.d.ts +5 -1
  85. package/dist/src/client/session-turn-dispatch.d.ts +15 -0
  86. package/dist/src/client/session-turn-dispatch.js +1 -0
  87. package/dist/src/client/session-utils.d.ts +27 -10
  88. package/dist/src/client/session-utils.js +1 -1
  89. package/dist/src/client/session.js +1 -1
  90. package/dist/src/client/types.d.ts +2 -1
  91. package/dist/src/compiled/.vendor-stamp.json +2 -2
  92. package/dist/src/compiled/{gray-matter → js-yaml}/LICENSE +2 -2
  93. package/dist/src/compiled/js-yaml/index.d.ts +12 -0
  94. package/dist/src/compiled/js-yaml/index.js +34 -0
  95. package/dist/src/compiler/extension-compatibility.d.ts +18 -18
  96. package/dist/src/compiler/extension-compatibility.js +1 -1
  97. package/dist/src/compiler/load-binding-namespace.js +1 -1
  98. package/dist/src/context/keys.d.ts +5 -2
  99. package/dist/src/context/keys.js +1 -1
  100. package/dist/src/context/provider.d.ts +5 -9
  101. package/dist/src/context/run-step.d.ts +4 -4
  102. package/dist/src/context/run-step.js +1 -1
  103. package/dist/src/context/serialize.d.ts +5 -1
  104. package/dist/src/context/serialize.js +1 -1
  105. package/dist/src/evals/loaders/yaml.js +1 -1
  106. package/dist/src/evals/runner/derive-run-facts.js +1 -1
  107. package/dist/src/evals/runner/execute-task.js +1 -1
  108. package/dist/src/evals/session.js +2 -2
  109. package/dist/src/evals/types.d.ts +16 -0
  110. package/dist/src/eve-channel/index.js +1 -1
  111. package/dist/src/execution/agent-sessions/context.d.ts +4 -2
  112. package/dist/src/execution/agent-sessions/context.js +1 -1
  113. package/dist/src/execution/agent-sessions/steps.js +1 -1
  114. package/dist/src/execution/cancelled-model-call-batch.js +1 -1
  115. package/dist/src/execution/coordination-dispatch-shared.d.ts +6 -4
  116. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  117. package/dist/src/execution/create-session-step.d.ts +4 -2
  118. package/dist/src/execution/create-session-step.js +1 -1
  119. package/dist/src/execution/durable-session-store.d.ts +10 -4
  120. package/dist/src/execution/durable-session-store.js +1 -1
  121. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  122. package/dist/src/execution/legacy-remote-agent/protocol.d.ts +8 -0
  123. package/dist/src/execution/legacy-remote-agent/protocol.js +1 -1
  124. package/dist/src/execution/legacy-session/completion-step.d.ts +2 -0
  125. package/dist/src/execution/legacy-session/completion-step.js +1 -1
  126. package/dist/src/execution/legacy-session/interrupt-step.js +1 -1
  127. package/dist/src/execution/legacy-session/prepare-step.d.ts +1 -0
  128. package/dist/src/execution/legacy-session/prepare-step.js +1 -1
  129. package/dist/src/execution/legacy-session/snapshot.d.ts +8 -4
  130. package/dist/src/execution/legacy-session/snapshot.js +1 -1
  131. package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
  132. package/dist/src/execution/proxied-deliver-step.js +1 -1
  133. package/dist/src/execution/publish-session-events.d.ts +27 -7
  134. package/dist/src/execution/publish-session-events.js +1 -1
  135. package/dist/src/execution/reconcile-session-continuation-token.d.ts +2 -2
  136. package/dist/src/execution/runtime-context.js +1 -1
  137. package/dist/src/execution/session/active-turn.d.ts +97 -0
  138. package/dist/src/execution/session/active-turn.js +1 -0
  139. package/dist/src/execution/session/checkpoint-migrations.d.ts +23 -0
  140. package/dist/src/execution/session/checkpoint-migrations.js +1 -0
  141. package/dist/src/execution/session/entry.js +1 -1
  142. package/dist/src/execution/session/finalization.js +1 -1
  143. package/dist/src/execution/session/handoff-steps.d.ts +24 -5
  144. package/dist/src/execution/session/handoff-steps.js +1 -1
  145. package/dist/src/execution/session/handoff.d.ts +10 -6
  146. package/dist/src/execution/session/handoff.js +1 -1
  147. package/dist/src/execution/session/input-queue.d.ts +19 -13
  148. package/dist/src/execution/session/input-queue.js +1 -1
  149. package/dist/src/execution/session/next-input.d.ts +2 -10
  150. package/dist/src/execution/session/next-input.js +1 -1
  151. package/dist/src/execution/session/pending-turn-state.d.ts +2 -0
  152. package/dist/src/execution/session/pending-turn-state.js +1 -1
  153. package/dist/src/execution/session/program.d.ts +2 -0
  154. package/dist/src/execution/session/program.js +1 -1
  155. package/dist/src/execution/session/state-cursor.d.ts +22 -16
  156. package/dist/src/execution/session/state-cursor.js +1 -1
  157. package/dist/src/execution/session/state-delta.d.ts +8 -1
  158. package/dist/src/execution/session/state-delta.js +1 -1
  159. package/dist/src/execution/session/turn-event-handler.js +1 -1
  160. package/dist/src/execution/session/turn-step-result.js +1 -1
  161. package/dist/src/execution/session/turn-step-types.d.ts +20 -4
  162. package/dist/src/execution/session/turn-step.js +1 -1
  163. package/dist/src/execution/session/turn-waiting-step.js +1 -1
  164. package/dist/src/execution/session/turn.d.ts +22 -3
  165. package/dist/src/execution/session/turn.js +1 -1
  166. package/dist/src/execution/session.d.ts +5 -5
  167. package/dist/src/execution/session.js +2 -2
  168. package/dist/src/execution/settle-cancelled-turn-step.d.ts +5 -4
  169. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  170. package/dist/src/execution/tasks/start.d.ts +2 -2
  171. package/dist/src/execution/tasks/task-id-input.d.ts +1 -1
  172. package/dist/src/execution/tasks/task-id-input.js +1 -1
  173. package/dist/src/execution/terminal-session-completion-step.d.ts +2 -0
  174. package/dist/src/execution/terminal-session-completion-step.js +1 -1
  175. package/dist/src/execution/terminal-session-failure-step.d.ts +2 -0
  176. package/dist/src/execution/terminal-session-failure-step.js +1 -1
  177. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  178. package/dist/src/execution/tools/connection-target.d.ts +5 -0
  179. package/dist/src/execution/tools/connection-target.js +1 -1
  180. package/dist/src/execution/tools/connection-tools.js +2 -2
  181. package/dist/src/execution/tools/workflow/start.d.ts +3 -3
  182. package/dist/src/harness/authorization.d.ts +15 -2
  183. package/dist/src/harness/authorization.js +1 -1
  184. package/dist/src/harness/cancelled-turn-emission.d.ts +2 -1
  185. package/dist/src/harness/cancelled-turn-emission.js +1 -1
  186. package/dist/src/harness/coordination.d.ts +5 -3
  187. package/dist/src/harness/emission.d.ts +5 -2
  188. package/dist/src/harness/emission.js +1 -1
  189. package/dist/src/harness/held-requests.d.ts +18 -0
  190. package/dist/src/harness/held-requests.js +1 -0
  191. package/dist/src/harness/hitl/approval-input-requests.d.ts +16 -0
  192. package/dist/src/harness/hitl/approval-input-requests.js +1 -1
  193. package/dist/src/harness/input-extraction.js +1 -1
  194. package/dist/src/harness/input-requests.d.ts +0 -4
  195. package/dist/src/harness/input-requests.js +1 -1
  196. package/dist/src/harness/model-call-error.js +1 -1
  197. package/dist/src/harness/proxy-input-requests.d.ts +4 -4
  198. package/dist/src/harness/session-limit-enforcement.js +1 -1
  199. package/dist/src/harness/stale-input-responses.js +1 -1
  200. package/dist/src/harness/tool-loop.js +2 -2
  201. package/dist/src/harness/turn-tag-state.d.ts +2 -0
  202. package/dist/src/harness/turn-tag-state.js +1 -1
  203. package/dist/src/harness/types.d.ts +23 -11
  204. package/dist/src/instrumentation/channel-delivery.d.ts +1 -0
  205. package/dist/src/instrumentation/channel-delivery.js +1 -1
  206. package/dist/src/instrumentation/lifecycle.d.ts +4 -0
  207. package/dist/src/instrumentation/memory.d.ts +2 -0
  208. package/dist/src/instrumentation/memory.js +1 -1
  209. package/dist/src/instrumentation/native-events.d.ts +1 -0
  210. package/dist/src/instrumentation/native-events.js +1 -1
  211. package/dist/src/instrumentation/runtime.d.ts +4 -3
  212. package/dist/src/instrumentation/runtime.js +1 -1
  213. package/dist/src/instrumentation/session-init.js +1 -1
  214. package/dist/src/internal/application/package.js +1 -1
  215. package/dist/src/internal/authored-module-loader.d.ts +14 -6
  216. package/dist/src/internal/authored-module-loader.js +1 -1
  217. package/dist/src/internal/authored-package-boundary.d.ts +1 -1
  218. package/dist/src/internal/authored-package-boundary.js +1 -1
  219. package/dist/src/internal/bundler/extension-mount-plugin.js +1 -1
  220. package/dist/src/internal/helpers/frontmatter.d.ts +24 -0
  221. package/dist/src/internal/helpers/frontmatter.js +1 -0
  222. package/dist/src/internal/helpers/markdown.js +1 -3
  223. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  224. package/dist/src/internal/nitro/host/nitro-bundler-config.js +1 -1
  225. package/dist/src/internal/node-esm-compat-banner.js +1 -1
  226. package/dist/src/internal/workflow-bundle/dynamic-remote-agent-transform.js +1 -1
  227. package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +27 -1
  228. package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.js +1 -1
  229. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +2 -2
  230. package/dist/src/protocol/message.d.ts +41 -3
  231. package/dist/src/protocol/message.js +2 -2
  232. package/dist/src/public/channels/slack/action-status.d.ts +2 -2
  233. package/dist/src/public/channels/slack/action-status.js +1 -1
  234. package/dist/src/public/channels/slack/approval-cards.d.ts +15 -0
  235. package/dist/src/public/channels/slack/approval-cards.js +2 -0
  236. package/dist/src/public/channels/slack/auth.d.ts +2 -0
  237. package/dist/src/public/channels/slack/auth.js +1 -1
  238. package/dist/src/public/channels/slack/connections.d.ts +15 -11
  239. package/dist/src/public/channels/slack/connections.js +1 -1
  240. package/dist/src/public/channels/slack/defaults.d.ts +1 -15
  241. package/dist/src/public/channels/slack/defaults.js +3 -4
  242. package/dist/src/public/channels/slack/hitl.js +1 -1
  243. package/dist/src/public/channels/slack/inbound.d.ts +10 -2
  244. package/dist/src/public/channels/slack/inbound.js +1 -1
  245. package/dist/src/public/channels/slack/index.d.ts +2 -0
  246. package/dist/src/public/channels/slack/index.js +1 -1
  247. package/dist/src/public/channels/slack/input-response.js +1 -1
  248. package/dist/src/public/channels/slack/interaction-cards.js +1 -1
  249. package/dist/src/public/channels/slack/interactions.js +1 -1
  250. package/dist/src/public/channels/slack/limits.d.ts +5 -3
  251. package/dist/src/public/channels/slack/private-approval-delivery.js +1 -1
  252. package/dist/src/public/channels/slack/renderers.d.ts +1 -1
  253. package/dist/src/public/channels/slack/renderers.js +1 -1
  254. package/dist/src/public/channels/slack/reply-delivery.d.ts +72 -0
  255. package/dist/src/public/channels/slack/reply-delivery.js +1 -0
  256. package/dist/src/public/channels/slack/sign-in-cancel.d.ts +20 -0
  257. package/dist/src/public/channels/slack/sign-in-cancel.js +1 -0
  258. package/dist/src/public/channels/slack/slackChannel.d.ts +15 -0
  259. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  260. package/dist/src/public/channels/slack/task-card.js +1 -1
  261. package/dist/src/public/channels/teams/defaults.d.ts +1 -1
  262. package/dist/src/public/channels/teams/defaults.js +2 -2
  263. package/dist/src/public/definitions/channel.d.ts +1 -0
  264. package/dist/src/public/definitions/channel.js +1 -1
  265. package/dist/src/public/definitions/state.d.ts +2 -0
  266. package/dist/src/public/definitions/state.js +1 -1
  267. package/dist/src/public/next/index.js +1 -1
  268. package/dist/src/public/next/server.d.ts +2 -0
  269. package/dist/src/public/next/server.js +1 -2
  270. package/dist/src/public/nuxt/module.d.ts +6 -0
  271. package/dist/src/public/nuxt/module.js +1 -1
  272. package/dist/src/react/index.d.ts +3 -0
  273. package/dist/src/react/index.js +1 -1
  274. package/dist/src/react/use-eve-agent.d.ts +7 -5
  275. package/dist/src/react/use-eve-agent.js +1 -1
  276. package/dist/src/runtime/connections/openapi-spec.d.ts +1 -4
  277. package/dist/src/runtime/connections/openapi-spec.js +1 -1
  278. package/dist/src/runtime/connections/scoped-authorization.d.ts +2 -0
  279. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  280. package/dist/src/setup/boxes/deploy-project.js +1 -1
  281. package/dist/src/setup/integrations/web/setup.js +6 -2
  282. package/dist/src/setup/scaffold/create/project.js +1 -1
  283. package/dist/src/setup/scaffold/create/web-template.d.ts +5 -5
  284. package/dist/src/setup/scaffold/create/web-template.js +61 -35
  285. package/dist/src/setup/vercel-project-framework.js +1 -1
  286. package/dist/src/shared/display-name.d.ts +15 -0
  287. package/dist/src/shared/display-name.js +1 -0
  288. package/dist/src/shared/framework-eve-server.d.ts +43 -0
  289. package/dist/src/shared/framework-eve-server.js +2 -0
  290. package/dist/src/shared/token-usage.d.ts +2 -0
  291. package/dist/src/shared/token-usage.js +1 -1
  292. package/dist/src/shared/trace-root.d.ts +8 -0
  293. package/dist/src/shared/trace-root.js +1 -0
  294. package/dist/src/subagents/callback-route.js +1 -1
  295. package/dist/src/subagents/hitl-proxy.d.ts +3 -3
  296. package/dist/src/subagents/hitl-proxy.js +1 -1
  297. package/dist/src/subagents/invocation.d.ts +3 -1
  298. package/dist/src/subagents/parent-notification.d.ts +7 -7
  299. package/dist/src/subagents/parent-notification.js +1 -1
  300. package/dist/src/subagents/tool.js +1 -1
  301. package/dist/src/svelte/index.d.ts +3 -0
  302. package/dist/src/svelte/index.js +2 -2
  303. package/dist/src/svelte/use-eve-agent.d.ts +7 -4
  304. package/dist/src/svelte/use-eve-agent.js +1 -1
  305. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  306. package/dist/src/tools/provided/load-skill.js +1 -1
  307. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  308. package/dist/src/tracing/agent-action-instrumentation.js +1 -1
  309. package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
  310. package/dist/src/tracing/agent-memory-instrumentation.js +1 -1
  311. package/dist/src/tracing/agent-otel-attributes.d.ts +6 -0
  312. package/dist/src/tracing/agent-otel-attributes.js +1 -1
  313. package/dist/src/tracing/agent-otel-provider.js +2 -2
  314. package/dist/src/tracing/agent-otel-runtime-context.d.ts +1 -1
  315. package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
  316. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  317. package/dist/src/tracing/agent-span-contract.js +1 -1
  318. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  319. package/dist/src/tracing/agent-trace-context-codec.d.ts +4 -0
  320. package/dist/src/tracing/agent-trace-context-codec.js +1 -1
  321. package/dist/src/tracing/agent-trace-span-processor.js +1 -1
  322. package/dist/src/tracing/agent-trace-state.d.ts +3 -0
  323. package/dist/src/tracing/conversation-context.d.ts +10 -0
  324. package/dist/src/tracing/conversation-context.js +1 -1
  325. package/dist/src/tracing/otel-registration.js +1 -1
  326. package/dist/src/vue/index.d.ts +3 -0
  327. package/dist/src/vue/index.js +2 -2
  328. package/dist/src/vue/use-eve-agent.d.ts +7 -3
  329. package/dist/src/vue/use-eve-agent.js +1 -1
  330. package/docs/channels/slack.mdx +60 -13
  331. package/docs/concepts/built-in-tools.md +3 -2
  332. package/docs/concepts/execution-model-and-durability.mdx +3 -1
  333. package/docs/concepts/sessions-runs-and-streaming.md +4 -4
  334. package/docs/connections/overview.mdx +9 -3
  335. package/docs/evals/reporters.mdx +4 -0
  336. package/docs/extensions.md +15 -3
  337. package/docs/guides/client/streaming.mdx +7 -6
  338. package/docs/guides/deployment/vercel.mdx +2 -1
  339. package/docs/guides/dev-tui.md +17 -17
  340. package/docs/guides/dynamic-capabilities.md +1 -1
  341. package/docs/guides/frontend/nuxt.mdx +24 -4
  342. package/docs/guides/frontend/overview.mdx +44 -38
  343. package/docs/guides/frontend/use-eve-agent-svelte.mdx +4 -10
  344. package/docs/guides/frontend/use-eve-agent-vue.mdx +4 -10
  345. package/docs/guides/instrumentation/otel.mdx +24 -6
  346. package/docs/guides/remote-agents.md +26 -8
  347. package/docs/reference/cli.md +4 -4
  348. package/docs/tools/human-in-the-loop.md +4 -4
  349. package/docs/tools/overview.mdx +1 -1
  350. package/docs/tools/tasks.md +8 -8
  351. package/package.json +2 -2
  352. package/dist/src/cli/dev/tui/steering-stream.d.ts +0 -15
  353. package/dist/src/cli/dev/tui/steering-stream.js +0 -1
  354. package/dist/src/cli/dev/tui/subagent-pump.d.ts +0 -134
  355. package/dist/src/cli/dev/tui/subagent-pump.js +0 -1
  356. package/dist/src/compiled/gray-matter/index.d.ts +0 -62
  357. package/dist/src/compiled/gray-matter/index.js +0 -48
  358. package/dist/src/internal/helpers/gray-matter.d.ts +0 -25
  359. package/dist/src/internal/helpers/gray-matter.js +0 -1
  360. package/dist/src/public/nuxt/dev-server.d.ts +0 -25
  361. package/dist/src/public/nuxt/dev-server.js +0 -1
@@ -1,2 +1,2 @@
1
- import{readFile}from"node:fs/promises";import{basename}from"node:path";import{isTurnFailureEvent}from"#protocol/message.js";import{isTurnSegmentBoundary,summarizeTurnEvents,updatePendingInputRequests}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o;#s;#c=[];#l=new Set;#u;#d=!1;#f=[];constructor(e){this.#i=e.collector,this.#s=e.onSessionStart,this.#o=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#u}get pendingInputRequests(){return this.#f}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}agent(e){let t=this.#e.agent(e),n=this.#r;return{name:t.name,sessionId:t.sessionId,stream:(e={})=>t.stream({...e,signal:e.signal??n}),taskId:t.taskId}}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#f.length===0&&this.#v(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#f.filter(t=>inputRequestMatches(t,e));return(this.#f.length!==1||t.length!==1)&&this.#v(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#f.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#p({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#p({...t,inputResponses:e})}async respondAll(e){let t=this.#f;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#p({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#p({turnPolicy:`queue`,...t,message:e})}async#p(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.consume(i,n)}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#m(n,e),record:e=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
- `)),this.#g(n,e)),session:this,sessionId:n})}async sendFile(e,t,n){let r=await readFile(t),i=createTextWithFileContent({bytes:r,filename:basename(t),mediaType:n??inferMediaType(t),text:e});return await this.send(i)}async readTurn(e){return await this.watchTurn(e).result()}watchTurn(e){return this.consume(this.#e.stream({signal:this.#r,startIndex:e?.startIndex}))}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],primary:this.#o,sessionId:e,state:this.#e.state,traceContexts:[...this.#c]}}#m(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#l.has(r)||(this.#l.add(r),this.#c.push(n),!this.#d&&(this.#d=!0,this.#s?.({primary:this.#o,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#h(e){this.#a.push(...e.events),this.#f=e.status===`waiting`?e.inputRequests:[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n=new EvalTurn({collector:this.#i,data:e.data,derived:t,events:e.events,inputRequests:e.inputRequests,message:e.message,session:this,sessionId:e.sessionId,status:e.status,toolCalls:t.toolCalls});return this.#u=n,this.#t(this),n}#g(e,t){let n=summarizeTurnEvents(t);return this.#h({data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:e,status:n.status})}#_(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],output:outputOf(this.#u),status:this.#u?.status??`completed`}}#v(e,t){throw this.#i.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=new Set;#r;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#i(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#r!==void 0)throw this.#r;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#n.add(n)})}async#i(e,t,n){try{let r=!1,i=new Set;for await(let n of e)if(this.#t.push(n),updatePendingInputRequests(i,n),t(n),this.#a(n),isTurnFailureEvent(n)&&this.#o(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),isTurnSegmentBoundary(n,i)){r=!0,this.#o(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}if(!r)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#o(t),e}}#a(e){for(let t of this.#n)t.matches(e)&&(this.#n.delete(t),t.resolve(e))}#o(e){if(this.#r===void 0){this.#r=e;for(let t of this.#n)t.reject(e);this.#n.clear()}}},EvalTurn=class{data;events;inputRequests;message;session;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.session=e.session,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}export{EvalSessionDriver,EveEvalTurnFailedError};
1
+ import{readFile}from"node:fs/promises";import{basename}from"node:path";import{TurnSegment,summarizeTurnEvents}from"#client/session-utils.js";import{isTurnFailureEvent}from"#protocol/message.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o;#s;#c=[];#l=new Set;#u;#d=!1;#f=[];constructor(e){this.#i=e.collector,this.#s=e.onSessionStart,this.#o=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#u}get pendingInputRequests(){return this.#f}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}agent(e){let t=this.#e.agent(e),n=this.#r;return{name:t.name,sessionId:t.sessionId,stream:(e={})=>t.stream({...e,signal:e.signal??n}),taskId:t.taskId}}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#f.length===0&&this.#v(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#f.filter(t=>inputRequestMatches(t,e));return(this.#f.length!==1||t.length!==1)&&this.#v(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#f.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#p({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#p({...t,inputResponses:e})}async respondAll(e){let t=this.#f;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#p({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#p({turnPolicy:`queue`,...t,message:e})}async#p(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.consume(i,n)}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#m(n,e),record:e=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+ `)),this.#g(n,e)),session:this,sessionId:n})}async sendFile(e,t,n){let r=await readFile(t),i=createTextWithFileContent({bytes:r,filename:basename(t),mediaType:n??inferMediaType(t),text:e});return await this.send(i)}async readTurn(e){return await this.watchTurn(e).result()}watchTurn(e){return this.consume(this.#e.stream({signal:this.#r,startIndex:e?.startIndex}))}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],primary:this.#o,sessionId:e,state:this.#e.state,traceContexts:[...this.#c]}}#m(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#l.has(r)||(this.#l.add(r),this.#c.push(n),!this.#d&&(this.#d=!0,this.#s?.({primary:this.#o,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#h(e){this.#a.push(...e.events),this.#f=e.status===`waiting`?e.inputRequests:[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n=new EvalTurn({collector:this.#i,data:e.data,derived:t,events:e.events,inputRequests:e.inputRequests,message:e.message,session:this,sessionId:e.sessionId,status:e.status,toolCalls:t.toolCalls});return this.#u=n,this.#t(this),n}#g(e,t){let n=summarizeTurnEvents(t);return this.#h({data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:e,status:n.status})}#_(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],output:outputOf(this.#u),status:this.#u?.status??`completed`}}#v(e,t){throw this.#i.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=new Set;#r;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#i(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#r!==void 0)throw this.#r;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#n.add(n)})}async#i(e,t,n){try{let r=!1,i=new TurnSegment;for await(let n of e){this.#t.push(n);let e=i.observe(n);if(t(n),this.#a(n),isTurnFailureEvent(n)&&this.#o(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),e){r=!0,this.#o(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}}if(!r)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#o(t),e}}#a(e){for(let t of this.#n)t.matches(e)&&(this.#n.delete(t),t.resolve(e))}#o(e){if(this.#r===void 0){this.#r=e;for(let t of this.#n)t.reject(e);this.#n.clear()}}},EvalTurn=class{data;events;inputRequests;message;session;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.session=e.session,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}export{EvalSessionDriver,EveEvalTurnFailedError};
@@ -1,3 +1,4 @@
1
+ import type { TokenUsage } from "#shared/token-usage.js";
1
2
  import type { Experimental_EvaluationModel as EvaluationModel } from "ai";
2
3
  import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
3
4
  import type { ClientAgentSession } from "#client/agent-session.js";
@@ -65,6 +66,21 @@ export interface EveEvalDerivedFacts {
65
66
  readonly parked: boolean;
66
67
  readonly messageCount: number;
67
68
  readonly reasoningBlockCount: number;
69
+ /**
70
+ * Distinct ids of the models the steps started with (`step.started`): in first-use order for one
71
+ * session, and in session order for an eval. Covers only the sessions the eval created or
72
+ * attached: a delegated subagent runs in its own session, so its models appear only when the eval
73
+ * attaches that session. Compaction and `auto` routing calls are not included.
74
+ */
75
+ readonly models: readonly string[];
76
+ /**
77
+ * Token usage from the latest `session.waiting`, `turn.waiting`, `session.failed`, or
78
+ * `session.completed`: the
79
+ * session's own model calls plus what the agents it delegated to spent, so on a turn it is the
80
+ * session's total so far. For an eval, each captured session counts once, by its latest usage,
81
+ * except sessions another captured session opened. Absent when a counted session reported none.
82
+ */
83
+ readonly usage?: TokenUsage;
68
84
  readonly failureCode?: string;
69
85
  }
70
86
  /**
@@ -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_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.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{readConversationBaggage}from"#tracing/conversation-context.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}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=await parseOptionalJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;c.callback!==void 0&&c.legacyRemoteAgentCaller!==void 0&&log.info(`serving a remote agent protocol 1 caller`,{callerOrigin:new URL(c.callback.url).origin,forwarder:i.principalId});let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i,{})}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?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json(createdSessionBody(e.id,c),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=c.message===void 0?{auth:s.auth}:await resolveOnMessage({auth:s.auth,config:e,invocation:u===void 0||c.operationId===void 0?void 0:{operationId:c.operationId},message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({audienceAuth:i,auth:v.auth,capabilities:c.capabilities??{requestInput:!0},callback:c.callback,legacyRemoteAgentCaller:c.legacyRemoteAgentCaller,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,title:v.title})}catch(e){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(b.sessionId,c),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.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: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=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,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=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,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_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_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=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
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_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.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{readConversationBaggage}from"#tracing/conversation-context.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}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=await parseOptionalJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;c.callback!==void 0&&c.legacyRemoteAgentCaller!==void 0&&log.info(`serving a remote agent protocol 1 caller`,{callerOrigin:new URL(c.callback.url).origin,forwarder:i.principalId});let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i,{})}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?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json(createdSessionBody(e.id,c),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=c.message===void 0?{auth:s.auth}:await resolveOnMessage({auth:s.auth,config:e,invocation:u===void 0||c.operationId===void 0?void 0:{operationId:c.operationId},message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({audienceAuth:i,auth:v.auth,capabilities:c.capabilities??{requestInput:!0},callback:c.callback,legacyRemoteAgentCaller:c.legacyRemoteAgentCaller,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,traceRoot:u===void 0?void 0:{kind:`own`},title:v.title})}catch(e){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(b.sessionId,c),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.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: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=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,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=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,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_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_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=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
@@ -1,4 +1,4 @@
1
- import type { ChannelInstrumentationProjection, RunSessionLimits, SessionCapabilities, SessionParent } from "#channel/types.js";
1
+ import type { ChannelInstrumentationProjection, RunSessionLimits, SessionCapabilities, SessionParent, SessionTraceRoot } from "#channel/types.js";
2
2
  import type { LocalDevRequestProvenance } from "#context/keys.js";
3
3
  import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";
4
4
  import type { PreparedCoordinationDispatch } from "#execution/coordination-dispatch-shared.js";
@@ -32,6 +32,8 @@ export interface AgentSessionContext {
32
32
  readonly localDevRequest?: LocalDevRequestProvenance;
33
33
  /** The calling session, turn, and tool call, recorded as each session's lineage. */
34
34
  readonly parent: SessionParent;
35
+ /** Present when the caller's trace root differs from `parent.rootSessionId`. */
36
+ readonly traceRoot?: SessionTraceRoot;
35
37
  readonly sandbox: AgentSessionSandbox;
36
38
  readonly trace: AgentChildTraceDispatch;
37
39
  }
@@ -45,7 +47,7 @@ export interface AgentSessionSandbox {
45
47
  readonly sessionId: string;
46
48
  readonly state?: SandboxState;
47
49
  }
48
- type CallerDispatch = Pick<PreparedCoordinationDispatch<unknown>, "batch" | "bundle" | "capabilities" | "channelMetadata" | "dynamicSubagentSelections" | "inheritedConversation" | "localDevRequest" | "sandboxSessionId" | "serializedContext" | "session" | "workflowAgents">;
50
+ type CallerDispatch = Pick<PreparedCoordinationDispatch<unknown>, "batch" | "bundle" | "capabilities" | "channelMetadata" | "dynamicSubagentSelections" | "inheritedConversation" | "localDevRequest" | "sandboxSessionId" | "serializedContext" | "session" | "traceRoot" | "workflowAgents">;
49
51
  /**
50
52
  * The token budget every session a model step's calls open inherits: the
51
53
  * caller's remaining quota split evenly across the agent tasks the step
@@ -1 +1 @@
1
- import{serializeDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{findTask,readTaskTable}from"#execution/tasks/table.js";import{resolveRemainingSessionTokenLimits}from"#subagents/token-budget.js";import{resolveToolCallAgentTrace}from"#tracing/agent-invocation-coordinator.js";function resolveStepAgentLimits(e){let t=readTaskTable(e.session.state),n=e.plan.filter(({entry:e})=>e.entryPoint===`serve`&&findTask(t,e.taskId)?.kind===`agent`).length;return resolveRemainingSessionTokenLimits(e.session,n)}function captureAgentSessionContext(e,t,n){let{batch:r,session:i}=e;return{agents:e.workflowAgents,bundle:{nodeId:e.bundle.nodeId,source:serializeDurableCompiledArtifactsSource(e.bundle.compiledArtifactsSource)},capabilities:e.capabilities,channelMetadata:e.channelMetadata,conversation:e.inheritedConversation,dynamicSelections:e.dynamicSubagentSelections,limits:n,localDevRequest:e.localDevRequest,parent:{callId:t,rootSessionId:i.rootSessionId??i.sessionId,sessionId:i.sessionId,turn:{id:r.event.turnId,sequence:r.event.sequence}},sandbox:{sessionId:e.sandboxSessionId,state:i.sandboxState},trace:resolveToolCallAgentTrace({callId:t,conversation:e.inheritedConversation,serializedContext:e.serializedContext,sessionId:i.sessionId,turnId:r.event.turnId})}}export{captureAgentSessionContext,resolveStepAgentLimits};
1
+ import{serializeDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{findTask,readTaskTable}from"#execution/tasks/table.js";import{resolveRemainingSessionTokenLimits}from"#subagents/token-budget.js";import{resolveToolCallAgentTrace}from"#tracing/agent-invocation-coordinator.js";function resolveStepAgentLimits(e){let t=readTaskTable(e.session.state),n=e.plan.filter(({entry:e})=>e.entryPoint===`serve`&&findTask(t,e.taskId)?.kind===`agent`).length;return resolveRemainingSessionTokenLimits(e.session,n)}function captureAgentSessionContext(e,t,n){let{batch:r,session:i}=e;return{agents:e.workflowAgents,bundle:{nodeId:e.bundle.nodeId,source:serializeDurableCompiledArtifactsSource(e.bundle.compiledArtifactsSource)},capabilities:e.capabilities,channelMetadata:e.channelMetadata,conversation:e.inheritedConversation,dynamicSelections:e.dynamicSubagentSelections,limits:n,localDevRequest:e.localDevRequest,parent:{callId:t,rootSessionId:i.rootSessionId??i.sessionId,sessionId:i.sessionId,turn:{id:r.event.turnId,sequence:r.event.sequence}},sandbox:{sessionId:e.sandboxSessionId,state:i.sandboxState},traceRoot:e.traceRoot,trace:resolveToolCallAgentTrace({callId:t,conversation:e.inheritedConversation,serializedContext:e.serializedContext,sessionId:i.sessionId,turnId:r.event.turnId})}}export{captureAgentSessionContext,resolveStepAgentLimits};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{sessionInboxHookToken}from"#execution/session-inbox/address.js";import{ContextContainer,contextStorage}from"#context/container.js";import{createEveCallbackRoutePath}from"#protocol/routes.js";import{createWorkflowRuntime,dispatchWorkflowSessionCommand,requestWorkflowTurnCancellation,waitForCommandHookOwner}from"#execution/workflow-runtime.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{createWorkflowCallbackUrl,resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{resolveAgentAction,resolveAgentStartTarget}from"#execution/agent-sessions/target.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{cancelRemoteAgentTurn,continueRemoteAgentSession,resetRemoteAgentSession,resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/agent-sessions/remote.js";import{buildSubagentRunInput}from"#subagents/tool.js";import{resolveConversationId}from"#shared/conversation-identity.js";const log=createLogger(`execution.agent-sessions`),RUN_FINISHED_REASON=`The workflow run that opened this session finished.`;async function openAgentSessionStep(e){"use step";let{context:t}=e,n=await loadAgentSessionBundle(t),r=resolveAgentAction({bundle:n,callId:t.parent.callId,dynamicSelections:t.dynamicSelections,input:{message:e.message,outputSchema:e.outputSchema,target:e.name}}),i=resolveAgentStartTarget({action:r,bundle:n,dynamicSelections:t.dynamicSelections,isRootSession:t.parent.rootSessionId===t.parent.sessionId}),a={auth:e.auth,bundle:n,context:t,key:e.key,replyTo:e.replyTo};return i.kind===`remote`?await startRemoteSession({...a,target:i}):await startLocalSession({...a,target:i})}async function sendAgentSessionMessageStep(e){"use step";let{address:t,context:n}=e;if(t.kind===`remote`){let r=await resolveSessionRemote(n,t);await continueRemoteAgentSession({auth:e.auth.current,callback:{callId:n.parent.callId,subagentName:t.name,token:e.replyTo,url:createWorkflowCallbackUrl(t.callbackBaseUrl,createEveCallbackRoutePath(e.replyTo))},message:e.message,outputSchema:e.outputSchema,remote:r,sessionId:t.sessionId});return}if((await dispatchWorkflowSessionCommand({command:{auth:e.auth.current,caller:{callId:n.parent.callId,replyTo:{kind:`hook`,token:e.replyTo},subagentName:t.name},kind:`send`,payload:{message:e.message,outputSchema:e.outputSchema}},sessionId:t.sessionId})).status!==`accepted`)throw Error(`Agent "${t.name}" can no longer receive messages; its session ended.`)}async function cancelAgentSessionTurnStep(e){"use step";let{address:t}=e;try{if(t.kind===`remote`){let n=await resolveSessionRemote(e.context,t);await cancelRemoteAgentTurn({remote:n,sessionId:t.sessionId});return}await requestWorkflowTurnCancellation({sessionId:t.sessionId})}catch(e){logError(log,`failed to cancel an agent session turn`,e,{name:t.name,sessionId:t.sessionId})}}async function endAgentSessionsStep(e){"use step";await Promise.all(e.sessions.map(endAgentSession))}async function endAgentSession({address:e,context:t}){try{if(e.kind===`remote`){let n=await resolveSessionRemote(t,e);await resetRemoteAgentSession({reason:RUN_FINISHED_REASON,remote:n,sessionId:e.sessionId});return}await dispatchWorkflowSessionCommand({command:{kind:`reset`,reason:RUN_FINISHED_REASON},sessionId:e.sessionId})}catch(t){logError(log,`failed to end an agent session`,t,{name:e.name,sessionId:e.sessionId})}}async function startLocalSession(e){let{auth:t,bundle:n,context:r,target:i}=e,{action:a}=i,{childContinuationToken:o,runInput:s}=buildSubagentRunInput({action:a,auth:t.current,capabilities:r.capabilities,channelMetadata:r.channelMetadata,continuationKey:e.key,graph:n.graph,inheritedConversation:r.conversation,initiatorAuth:t.initiator,limits:r.limits,parent:createParentContext(r,e.replyTo),sandboxSessionId:r.sandbox.sessionId,selfAgent:i.source.type===`runtime`,session:{continuationToken:e.replyTo,sandboxState:r.sandbox.state,sessionId:r.parent.sessionId},source:i.source}),c=createWorkflowRuntime({compiledArtifactsSource:n.compiledArtifactsSource,dynamicSubagentAgentConfig:i.dynamicSubagentAgentConfig,nodeId:a.nodeId});await contextStorage.run(new ContextContainer({localDevRequest:r.localDevRequest}),()=>c.createSession(s));let l=await waitForCommandHookOwner(sessionInboxHookToken(o));return{kind:`local`,name:a.name,nodeId:a.nodeId,sessionId:l.runId}}async function startRemoteSession(e){let{auth:t,bundle:n,context:r,target:i}=e,{action:a}=i,o=resolveRemoteAgentForAction({dynamicRemoteAgent:i.dynamicRemoteAgent,nodeId:a.nodeId,registry:n.subagentRegistry.subagentsByNodeId,remoteAgentName:a.remoteAgentName}),s=resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),c=await startRemoteAgentSession({action:a,auth:t.current,callbackBaseUrl:s,capabilities:r.capabilities,initiatorAuth:t.initiator,operationId:`agent-session:${e.key}`,originAudience:r.trace.originAudience,parent:createParentContext(r,e.replyTo),remote:o,session:{continuationToken:e.replyTo}});return{callbackBaseUrl:s,kind:`remote`,forwardPrincipal:o.forwardPrincipal,name:a.remoteAgentName,nodeId:a.nodeId,resolverId:i.dynamicRemoteAgent?.credentialsStepId??a.nodeId,sessionId:c.sessionId,url:o.url}}function createParentContext(e,t){return{continuationToken:t,conversationId:e.trace.conversationId??resolveConversationId(e.parent.rootSessionId),lineage:e.parent,originAudience:e.trace.originAudience,traceContext:e.trace.parentTraceContext}}async function resolveSessionRemote(e,t){let n=await loadAgentSessionBundle(e),r=e.dynamicSelections[t.nodeId];return{...resolveRemoteAgentForAction({dynamicRemoteAgent:r?.kind===`remote`?r.remoteAgent:void 0,nodeId:t.nodeId,registry:n.subagentRegistry.subagentsByNodeId,remoteAgentName:t.name}),url:t.url}}async function loadAgentSessionBundle(e){return await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(e.bundle.source),nodeId:e.bundle.nodeId})}export{cancelAgentSessionTurnStep,endAgentSessionsStep,openAgentSessionStep,sendAgentSessionMessageStep};
1
+ import{createLogger,logError}from"#internal/logging.js";import{sessionInboxHookToken}from"#execution/session-inbox/address.js";import{ContextContainer,contextStorage}from"#context/container.js";import{createEveCallbackRoutePath}from"#protocol/routes.js";import{createWorkflowRuntime,dispatchWorkflowSessionCommand,requestWorkflowTurnCancellation,waitForCommandHookOwner}from"#execution/workflow-runtime.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{createWorkflowCallbackUrl,resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{resolveAgentAction,resolveAgentStartTarget}from"#execution/agent-sessions/target.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{cancelRemoteAgentTurn,continueRemoteAgentSession,resetRemoteAgentSession,resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/agent-sessions/remote.js";import{buildSubagentRunInput}from"#subagents/tool.js";import{resolveConversationId}from"#shared/conversation-identity.js";const log=createLogger(`execution.agent-sessions`),RUN_FINISHED_REASON=`The workflow run that opened this session finished.`;async function openAgentSessionStep(e){"use step";let{context:t}=e,n=await loadAgentSessionBundle(t),r=resolveAgentAction({bundle:n,callId:t.parent.callId,dynamicSelections:t.dynamicSelections,input:{message:e.message,outputSchema:e.outputSchema,target:e.name}}),i=resolveAgentStartTarget({action:r,bundle:n,dynamicSelections:t.dynamicSelections,isRootSession:t.parent.rootSessionId===t.parent.sessionId}),a={auth:e.auth,bundle:n,context:t,key:e.key,replyTo:e.replyTo};return i.kind===`remote`?await startRemoteSession({...a,target:i}):await startLocalSession({...a,target:i})}async function sendAgentSessionMessageStep(e){"use step";let{address:t,context:n}=e;if(t.kind===`remote`){let r=await resolveSessionRemote(n,t);await continueRemoteAgentSession({auth:e.auth.current,callback:{callId:n.parent.callId,subagentName:t.name,token:e.replyTo,url:createWorkflowCallbackUrl(t.callbackBaseUrl,createEveCallbackRoutePath(e.replyTo))},message:e.message,outputSchema:e.outputSchema,remote:r,sessionId:t.sessionId});return}if((await dispatchWorkflowSessionCommand({command:{auth:e.auth.current,caller:{callId:n.parent.callId,replyTo:{kind:`hook`,token:e.replyTo},subagentName:t.name},kind:`send`,payload:{message:e.message,outputSchema:e.outputSchema}},sessionId:t.sessionId})).status!==`accepted`)throw Error(`Agent "${t.name}" can no longer receive messages; its session ended.`)}async function cancelAgentSessionTurnStep(e){"use step";let{address:t}=e;try{if(t.kind===`remote`){let n=await resolveSessionRemote(e.context,t);await cancelRemoteAgentTurn({remote:n,sessionId:t.sessionId});return}await requestWorkflowTurnCancellation({sessionId:t.sessionId})}catch(e){logError(log,`failed to cancel an agent session turn`,e,{name:t.name,sessionId:t.sessionId})}}async function endAgentSessionsStep(e){"use step";await Promise.all(e.sessions.map(endAgentSession))}async function endAgentSession({address:e,context:t}){try{if(e.kind===`remote`){let n=await resolveSessionRemote(t,e);await resetRemoteAgentSession({reason:RUN_FINISHED_REASON,remote:n,sessionId:e.sessionId});return}await dispatchWorkflowSessionCommand({command:{kind:`reset`,reason:RUN_FINISHED_REASON},sessionId:e.sessionId})}catch(t){logError(log,`failed to end an agent session`,t,{name:e.name,sessionId:e.sessionId})}}async function startLocalSession(e){let{auth:t,bundle:n,context:r,target:i}=e,{action:a}=i,{childContinuationToken:o,runInput:s}=buildSubagentRunInput({action:a,auth:t.current,capabilities:r.capabilities,channelMetadata:r.channelMetadata,continuationKey:e.key,graph:n.graph,inheritedConversation:r.conversation,initiatorAuth:t.initiator,limits:r.limits,parent:createParentContext(r,e.replyTo),sandboxSessionId:r.sandbox.sessionId,selfAgent:i.source.type===`runtime`,session:{continuationToken:e.replyTo,sandboxState:r.sandbox.state,sessionId:r.parent.sessionId},source:i.source}),c=createWorkflowRuntime({compiledArtifactsSource:n.compiledArtifactsSource,dynamicSubagentAgentConfig:i.dynamicSubagentAgentConfig,nodeId:a.nodeId});await contextStorage.run(new ContextContainer({localDevRequest:r.localDevRequest}),()=>c.createSession(s));let l=await waitForCommandHookOwner(sessionInboxHookToken(o));return{kind:`local`,name:a.name,nodeId:a.nodeId,sessionId:l.runId}}async function startRemoteSession(e){let{auth:t,bundle:n,context:r,target:i}=e,{action:a}=i,o=resolveRemoteAgentForAction({dynamicRemoteAgent:i.dynamicRemoteAgent,nodeId:a.nodeId,registry:n.subagentRegistry.subagentsByNodeId,remoteAgentName:a.remoteAgentName}),s=resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),c=await startRemoteAgentSession({action:a,auth:t.current,callbackBaseUrl:s,capabilities:r.capabilities,initiatorAuth:t.initiator,operationId:`agent-session:${e.key}`,originAudience:r.trace.originAudience,parent:createParentContext(r,e.replyTo),remote:o,session:{continuationToken:e.replyTo}});return{callbackBaseUrl:s,kind:`remote`,forwardPrincipal:o.forwardPrincipal,name:a.remoteAgentName,nodeId:a.nodeId,resolverId:i.dynamicRemoteAgent?.credentialsStepId??a.nodeId,sessionId:c.sessionId,url:o.url}}function createParentContext(e,t){return{continuationToken:t,conversationId:e.trace.conversationId??resolveConversationId(e.parent.rootSessionId),lineage:e.parent,originAudience:e.trace.originAudience,traceContext:e.trace.parentTraceContext,traceRoot:e.traceRoot}}async function resolveSessionRemote(e,t){let n=await loadAgentSessionBundle(e),r=e.dynamicSelections[t.nodeId];return{...resolveRemoteAgentForAction({dynamicRemoteAgent:r?.kind===`remote`?r.remoteAgent:void 0,nodeId:t.nodeId,registry:n.subagentRegistry.subagentsByNodeId,remoteAgentName:t.name}),url:t.url}}async function loadAgentSessionBundle(e){return await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(e.bundle.source),nodeId:e.bundle.nodeId})}export{cancelAgentSessionTurnStep,endAgentSessionsStep,openAgentSessionStep,sendAgentSessionMessageStep};
@@ -1 +1 @@
1
- import{contextStorage}from"#context/container.js";import{TurnDeliveryIdsKey}from"#context/keys.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{serializeContext}from"#context/serialize.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";async function createCancelledModelCallBatchResult(e){let t=serializeContext(e.ctx),n=e.checkpoint?.result.session??e.initialSession,r=e.checkpoint===void 0?await contextStorage.run(e.ctx,()=>preserveCancelledTurnMessage(n,e.stepInput)):n,i={...e.checkpoint?.serializedContext??e.beforeBatchContext,[TurnDeliveryIdsKey.name]:t[TurnDeliveryIdsKey.name]};return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(i,t),t),t),sessionState:createDurableSessionState({session:r})}}export{createCancelledModelCallBatchResult};
1
+ import{contextStorage}from"#context/container.js";import{TurnDeliveryIdsKey}from"#context/keys.js";import{createDurableSessionValues}from"#execution/durable-session-store.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{serializeContext}from"#context/serialize.js";import{preserveCancelledTurnMessage}from"#execution/cancelled-turn-message.js";import{preserveSerializedInstrumentationState}from"#instrumentation/state.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";async function createCancelledModelCallBatchResult(e){let t=serializeContext(e.ctx),n=e.checkpoint?.result.session??e.initialSession,r=e.checkpoint===void 0?await contextStorage.run(e.ctx,()=>preserveCancelledTurnMessage(n,e.stepInput)):n,i={...e.checkpoint?.serializedContext??e.beforeBatchContext,[TurnDeliveryIdsKey.name]:t[TurnDeliveryIdsKey.name]};return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(i,t),t),t),...createDurableSessionValues(r)}}export{createCancelledModelCallBatchResult};
@@ -3,9 +3,9 @@ import { type ChannelAdapter, type ChannelAdapterContext } from "#channel/adapte
3
3
  import { type LocalDevRequestProvenance } from "#context/keys.js";
4
4
  import { ContextContainer } from "#context/container.js";
5
5
  import { type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
6
- import type { HarnessSession } from "#harness/types.js";
6
+ import type { HarnessSessionBase } from "#harness/types.js";
7
7
  import type { RuntimeActionResult, RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
8
- import type { SessionParent } from "#channel/types.js";
8
+ import type { SessionParent, SessionTraceRoot } from "#channel/types.js";
9
9
  import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
10
10
  import { buildSubagentRunInput } from "#subagents/tool.js";
11
11
  import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
@@ -43,8 +43,10 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReq
43
43
  readonly sandboxSessionId: string;
44
44
  readonly serializedContext: Record<string, unknown>;
45
45
  readonly plan: readonly PlanEntry[];
46
- readonly session: HarnessSession;
46
+ readonly session: HarnessSessionBase;
47
47
  readonly sessionState: DurableSessionState;
48
+ /** Trace root that this session's local children inherit, when it isn't the lineage root. */
49
+ readonly traceRoot?: SessionTraceRoot;
48
50
  readonly workflowAgents: Readonly<Record<string, WorkflowAgentMetadata>>;
49
51
  }
50
52
  /**
@@ -76,7 +78,7 @@ export declare function prepareActionDispatch<PlanEntry>(input: {
76
78
  readonly bundle: CompiledBundle;
77
79
  readonly ctx: ContextContainer;
78
80
  readonly requests: DispatchBatch["requests"];
79
- readonly session: HarnessSession;
81
+ readonly session: HarnessSessionBase;
80
82
  }) => readonly PlanEntry[];
81
83
  readonly serializedContext: Record<string, unknown>;
82
84
  }): Promise<Omit<PreparedCoordinationDispatch<PlanEntry>, "sessionState">>;
@@ -1 +1 @@
1
- import{ConversationContextKey}from"#shared/conversation-context.js";import"#channel/adapter.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import"#subagents/tool.js";import{assertUniqueCoordinationCallIds,getPendingCoordinationBatch,setPendingCoordinationBatch}from"#harness/coordination.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";import{readDynamicSubagentSelections}from"#context/dynamic-subagent-lifecycle.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=getPendingCoordinationBatch(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(e.sessionState.emissionState),a=n.event.turnId===i?n.event:{...n.event,turnId:i},o=await deserializeContext(e.serializedContext),s=await prepareActionDispatch({batch:{event:a,requests:r},ctx:o,durableSession:t,plan:()=>r,serializedContext:e.serializedContext});if(a===n.event)return{...s,sessionState:e.sessionState};let c=setPendingCoordinationBatch({...n,event:a,session:s.session});return{...s,session:c,sessionState:createDurableSessionState({session:c})}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx,i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,serializedContext:e.serializedContext,session:o,workflowAgents:resolveWorkflowAgentMetadata(r)}}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
1
+ import{ConversationContextKey}from"#shared/conversation-context.js";import"#channel/adapter.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey,TraceRootKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import"#subagents/tool.js";import{assertUniqueCoordinationCallIds,getPendingCoordinationBatch,setPendingCoordinationBatch}from"#harness/coordination.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";import{readDynamicSubagentSelections}from"#context/dynamic-subagent-lifecycle.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=getPendingCoordinationBatch(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(e.sessionState.emissionState),a=n.event.turnId===i?n.event:{...n.event,turnId:i},o=await deserializeContext(e.serializedContext),s=await prepareActionDispatch({batch:{event:a,requests:r},ctx:o,durableSession:t,plan:()=>r,serializedContext:e.serializedContext});if(a===n.event)return{...s,sessionState:e.sessionState};let c=setPendingCoordinationBatch({...n,event:a,session:s.session});return{...s,session:c,sessionState:createDurableSessionState({session:c})}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx,i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,serializedContext:e.serializedContext,session:o,traceRoot:childTraceRoot(r,o.sessionId),workflowAgents:resolveWorkflowAgentMetadata(r)}}function childTraceRoot(e,t){if(e.get(TraceRootKey)!==void 0)return{kind:`inherited`,sessionId:resolveTraceRootSessionId(e,t)}}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
@@ -1,15 +1,17 @@
1
1
  import { type DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";
2
2
  import { type DurableSessionState } from "#execution/durable-session-store.js";
3
+ import type { HarnessModelMessage } from "#harness/messages.js";
3
4
  import type { RunSessionLimits } from "#channel/types.js";
4
5
  import type { JsonObject } from "#shared/json.js";
5
6
  import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
6
7
  /**
7
8
  * Result returned by {@link createSessionStep}.
8
9
  *
9
- * Exposes the projected {@link DurableSessionState} the owner needs to
10
- * drive the turn loop.
10
+ * Exposes the projected {@link DurableSessionState} and the history the
11
+ * owner needs to drive the turn loop.
11
12
  */
12
13
  export interface CreateSessionStepResult {
14
+ readonly history: HarnessModelMessage[];
13
15
  readonly state: DurableSessionState;
14
16
  }
15
17
  /**
@@ -1 +1 @@
1
- import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";import{resolveEffectiveAgentRuntimeFromConfig}from"#execution/effective-agent-config.js";import{resolveInheritedTokenLimit}from"#execution/run-session-limits.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(e.compiledArtifactsSource),nodeId:e.nodeId}),n=resolveEffectiveAgentRuntimeFromConfig(t,e.dynamicSubagentAgentConfig),r=createSession({compactionOverrides:{thresholdPercent:n.thresholdPercent},continuationToken:e.continuationToken,limits:{maxInputTokensPerSession:resolveInheritedTokenLimit({configured:n.limits?.maxInputTokensPerSession,inherited:e.inheritedLimits?.maxInputTokensPerSession}),maxOutputTokensPerSession:resolveInheritedTokenLimit({configured:n.limits?.maxOutputTokensPerSession,inherited:e.inheritedLimits?.maxOutputTokensPerSession}),maxTokenCostUsdPerSession:resolveInheritedTokenLimit({configured:n.limits?.maxTokenCostUsdPerSession,inherited:e.inheritedLimits?.maxTokenCostUsdPerSession})},outputSchema:e.outputSchema,rootSessionId:e.rootSessionId,sessionId:e.sessionId,turnAgent:n.turnAgent});return{state:createDurableSessionState({session:r})}}export{createSessionStep};
1
+ import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createDurableSessionValues}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";import{resolveEffectiveAgentRuntimeFromConfig}from"#execution/effective-agent-config.js";import{resolveInheritedTokenLimit}from"#execution/run-session-limits.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(e.compiledArtifactsSource),nodeId:e.nodeId}),n=resolveEffectiveAgentRuntimeFromConfig(t,e.dynamicSubagentAgentConfig),r=createSession({compactionOverrides:{thresholdPercent:n.thresholdPercent},continuationToken:e.continuationToken,limits:{maxInputTokensPerSession:resolveInheritedTokenLimit({configured:n.limits?.maxInputTokensPerSession,inherited:e.inheritedLimits?.maxInputTokensPerSession}),maxOutputTokensPerSession:resolveInheritedTokenLimit({configured:n.limits?.maxOutputTokensPerSession,inherited:e.inheritedLimits?.maxOutputTokensPerSession}),maxTokenCostUsdPerSession:resolveInheritedTokenLimit({configured:n.limits?.maxTokenCostUsdPerSession,inherited:e.inheritedLimits?.maxTokenCostUsdPerSession})},outputSchema:e.outputSchema,rootSessionId:e.rootSessionId,sessionId:e.sessionId,turnAgent:n.turnAgent}),{history:i,sessionState:a}=createDurableSessionValues(r);return{history:i,state:a}}export{createSessionStep};
@@ -1,10 +1,10 @@
1
1
  import { type HarnessEmissionState } from "#harness/emission.js";
2
2
  import type { HarnessModelMessage } from "#harness/messages.js";
3
- import type { HarnessSession, SessionStateMap } from "#harness/types.js";
3
+ import type { HarnessSession, HarnessSessionBase, SessionStateMap } from "#harness/types.js";
4
4
  import type { SandboxState } from "#sandbox/state.js";
5
5
  import type { JsonObject } from "#shared/json.js";
6
6
  /** Explicit checkpoint contract shared by deployment handoffs. */
7
- export declare const DURABLE_SESSION_VERSION = 1;
7
+ export declare const DURABLE_SESSION_VERSION = 2;
8
8
  /**
9
9
  * Serializable handle to a durable session.
10
10
  *
@@ -35,6 +35,8 @@ export interface DurableSessionState {
35
35
  * `agent.compactionModelReference`, and the `compaction` thresholds —
36
36
  * those are rebuilt every turn from `bundle.turnAgent` by
37
37
  * {@link import("#execution/session.js").hydrateDurableSession}.
38
+ * Omits `history` too: the session workflow carries it as its own value, so
39
+ * only the steps that read or change it receive it as input.
38
40
  * `agent.system` is the last applied prompt snapshot. Before each model step,
39
41
  * the execution layer replaces it from the current deployment's
40
42
  * `bundle.turnAgent`.
@@ -49,7 +51,6 @@ export interface DurableSession {
49
51
  */
50
52
  readonly rootSessionId?: string;
51
53
  readonly continuationToken: string;
52
- readonly history: HarnessModelMessage[];
53
54
  readonly limits?: HarnessSession["limits"];
54
55
  readonly outputSchema?: JsonObject;
55
56
  readonly state?: SessionStateMap;
@@ -73,8 +74,13 @@ export declare function readDurableSession(state: DurableSessionState): DurableS
73
74
  * snapshot embedded in the Workflow step result.
74
75
  */
75
76
  export declare function createDurableSessionState(input: {
76
- readonly session: HarnessSession;
77
+ readonly session: HarnessSessionBase;
77
78
  }): DurableSessionState;
79
+ /** The session state and history a step that ran with the history leaves. */
80
+ export declare function createDurableSessionValues(session: HarnessSession): {
81
+ readonly history: HarnessModelMessage[];
82
+ readonly sessionState: DurableSessionState;
83
+ };
78
84
  /** Replaces session program memory and refreshes its workflow projections. */
79
85
  export declare function replaceDurableSessionSnapshot(input: {
80
86
  readonly session: DurableSession;
@@ -1 +1 @@
1
- import{getHarnessEmissionState}from"#harness/emission.js";import{projectToDurableSession}from"#execution/session.js";import{hasProxyInputRequests}from"#harness/proxy-input-requests.js";const DURABLE_SESSION_VERSION=1;function readDurableSession(e){if(e.version!==1||e.snapshot?.session===void 0)throw Error(`Unsupported session checkpoint. Start a new session on this deployment.`);return e.snapshot.session}function createDurableSessionState(e){return projectDurableSessionState(projectToDurableSession(e.session))}function replaceDurableSessionSnapshot(e){return{...e.state,...projectDurableSessionState(e.session)}}function projectDurableSessionState(e){return{continuationToken:e.continuationToken,emissionState:getHarnessEmissionState(e.state),hasProxyInputRequests:hasProxyInputRequests(e.state),sessionId:e.sessionId,version:1,snapshot:{session:e}}}export{DURABLE_SESSION_VERSION,createDurableSessionState,readDurableSession,replaceDurableSessionSnapshot};
1
+ import{getHarnessEmissionState}from"#harness/emission.js";import{projectToDurableSession}from"#execution/session.js";import{hasProxyInputRequests}from"#harness/proxy-input-requests.js";const DURABLE_SESSION_VERSION=2;function readDurableSession(e){if(e.version!==2||e.snapshot?.session===void 0)throw Error(`Unsupported session checkpoint. Start a new session on this deployment.`);return e.snapshot.session}function createDurableSessionState(e){return projectDurableSessionState(projectToDurableSession(e.session))}function createDurableSessionValues(e){return{history:e.history,sessionState:createDurableSessionState({session:e})}}function replaceDurableSessionSnapshot(e){return{...e.state,...projectDurableSessionState(e.session)}}function projectDurableSessionState(e){return{continuationToken:e.continuationToken,emissionState:getHarnessEmissionState(e.state),hasProxyInputRequests:hasProxyInputRequests(e.state),sessionId:e.sessionId,version:2,snapshot:{session:e}}}export{DURABLE_SESSION_VERSION,createDurableSessionState,createDurableSessionValues,readDurableSession,replaceDurableSessionSnapshot};
@@ -1 +1 @@
1
- import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.69.0//runWorkflowProgramTask`;export{runWorkflowProgramTask};
1
+ import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.70.1//runWorkflowProgramTask`;export{runWorkflowProgramTask};
@@ -27,6 +27,14 @@ export declare function splitLegacyTaskFields(input: Record<string, unknown>): {
27
27
  * must stay off this session's own channel.
28
28
  */
29
29
  export declare function forwardLegacySessionInput(ctx: ContextContainer, caller: LegacyRemoteAgentCaller, event: UnstampedMessageStreamEvent): Promise<boolean>;
30
+ /**
31
+ * Renames a `task.*` callback that a remote agent sends a protocol-1 caller to
32
+ * the payload kind the caller's session reads. The callback URL resolves to the
33
+ * caller's newest deployment, while the session waiting on it may still run on
34
+ * an eve 0.66–0.68 build; both read the renamed kinds. The caller still
35
+ * validates the result.
36
+ */
37
+ export declare function renameLegacyTaskCallback(body: unknown): unknown;
30
38
  /** Route a protocol-1 caller posts its answers to a remote agent's question or approval. */
31
39
  export declare const legacyTaskInputRoute: {
32
40
  readonly handler: typeof handleLegacyTaskInputRequest;
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{isInputResponse}from"#shared/input.js";import{ContinuationTokenKey,SessionCallbackKey,SessionIdKey}from"#context/keys.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";const log=createLogger(`execution.legacy-remote-agent`),LEGACY_REMOTE_AGENT_PROTOCOL_VERSION=1,TASK_INPUT_TOKEN_RE=/^eve:task-input:([a-f0-9]{32})$/;function splitLegacyTaskFields(e){let{callback:t}=e;if(!isObject(t)||!(`taskId`in t))return{payload:e};let{taskId:n,...r}=t,i={...e,callback:r};return typeof n==`string`&&n.length>0?{payload:i,taskId:n}:{payload:i}}async function forwardLegacySessionInput(e,t,n){let r=e.get(SessionCallbackKey),i=e.get(ContinuationTokenKey);if(t.taskId===void 0||r===void 0||!i)return!1;let a;if(n.type===`input.requested`)a={event:n.data,kind:`task.input-requested`};else if(n.type===`authorization.required`||n.type===`authorization.completed`)a={event:n,kind:`task.authorization`};else return!1;let o=await postSessionCallbackRequest({body:{callId:r.callId,childContinuationToken:i,childSessionId:e.require(SessionIdKey),event:a.event,kind:a.kind,subagentName:r.subagentName,taskId:t.taskId},url:r.url});if(!o.ok)throw Error(`Remote task event callback failed with HTTP ${o.status}.`);return!0}const legacyTaskInputRoute={handler:handleLegacyTaskInputRequest,path:`${EVE_ROUTE_PREFIX}/task-input/:token`};async function handleLegacyTaskInputRequest(e,t){let n=TASK_INPUT_TOKEN_RE.exec(t.params.token??``)?.[1];if(n===void 0)return Response.json({error:`Invalid task input token.`,ok:!1},{status:403});let r;try{r=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}let i=isObject(r)?r.inputResponses:void 0;if(!Array.isArray(i)||i.length===0||!i.every(isInputResponse))return Response.json({error:`Expected a non-empty inputResponses array.`,ok:!1},{status:400});try{await resumeSessionInbox(`eve:eve:op:${n}`,{kind:`send`,payload:{inputResponses:i}})}catch(e){if(HookNotFoundError.is(e))return Response.json({error:`Task input target is not pending.`,ok:!1},{status:404});let t=logError(log,`legacy task input delivery failed`,e);return Response.json({error:`Failed to deliver the task input.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0},{status:202})}export{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,forwardLegacySessionInput,legacyTaskInputRoute,splitLegacyTaskFields};
1
+ import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{isInputResponse}from"#shared/input.js";import{ContinuationTokenKey,SessionCallbackKey,SessionIdKey}from"#context/keys.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";const log=createLogger(`execution.legacy-remote-agent`),LEGACY_REMOTE_AGENT_PROTOCOL_VERSION=1,TASK_INPUT_TOKEN_RE=/^eve:task-input:([a-f0-9]{32})$/;function splitLegacyTaskFields(e){let{callback:t}=e;if(!isObject(t)||!(`taskId`in t))return{payload:e};let{taskId:n,...r}=t,i={...e,callback:r};return typeof n==`string`&&n.length>0?{payload:i,taskId:n}:{payload:i}}async function forwardLegacySessionInput(e,t,n){let r=e.get(SessionCallbackKey),i=e.get(ContinuationTokenKey);if(t.taskId===void 0||r===void 0||!i)return!1;let a;if(n.type===`input.requested`)a={event:n.data,kind:`task.input-requested`};else if(n.type===`authorization.required`||n.type===`authorization.completed`)a={event:n,kind:`task.authorization`};else return!1;let o=await postSessionCallbackRequest({body:{callId:r.callId,childContinuationToken:i,childSessionId:e.require(SessionIdKey),event:a.event,kind:a.kind,subagentName:r.subagentName,taskId:t.taskId},url:r.url});if(!o.ok)throw Error(`Remote task event callback failed with HTTP ${o.status}.`);return!0}function renameLegacyTaskCallback(e){if(!isObject(e))return e;let{taskId:t,...n}=e;return e.kind===`task.input-requested`?{...n,kind:`subagent-input-request`}:e.kind===`task.authorization`?{...n,kind:`subagent-authorization-event`}:e}const legacyTaskInputRoute={handler:handleLegacyTaskInputRequest,path:`${EVE_ROUTE_PREFIX}/task-input/:token`};async function handleLegacyTaskInputRequest(e,t){let n=TASK_INPUT_TOKEN_RE.exec(t.params.token??``)?.[1];if(n===void 0)return Response.json({error:`Invalid task input token.`,ok:!1},{status:403});let r;try{r=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}let i=isObject(r)?r.inputResponses:void 0;if(!Array.isArray(i)||i.length===0||!i.every(isInputResponse))return Response.json({error:`Expected a non-empty inputResponses array.`,ok:!1},{status:400});try{await resumeSessionInbox(`eve:eve:op:${n}`,{kind:`send`,payload:{inputResponses:i}})}catch(e){if(HookNotFoundError.is(e))return Response.json({error:`Task input target is not pending.`,ok:!1},{status:404});let t=logError(log,`legacy task input delivery failed`,e);return Response.json({error:`Failed to deliver the task input.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0},{status:202})}export{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,forwardLegacySessionInput,legacyTaskInputRoute,renameLegacyTaskCallback,splitLegacyTaskFields};
@@ -1,8 +1,10 @@
1
1
  import type { DurableSessionState } from "#execution/durable-session-store.js";
2
+ import type { HarnessModelMessage } from "#harness/messages.js";
2
3
  import type { WorkflowEntryResult } from "#execution/session/entry-input.js";
3
4
  /** The old driver owns final notifications for the dispatch that became this session. */
4
5
  export declare function completeLegacyDriverStep(input: {
5
6
  readonly completionToken: string;
7
+ readonly history: HarnessModelMessage[];
6
8
  readonly result: WorkflowEntryResult;
7
9
  readonly serializedContext: Record<string, unknown>;
8
10
  readonly sessionState: DurableSessionState;
@@ -1 +1 @@
1
- import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{resumeHook}from"#internal/workflow/runtime.js";async function completeLegacyDriverStep(e){"use step";let t=e.sessionWritable.getWriter();try{await t.close()}finally{t.releaseLock()}try{await resumeHook(e.completionToken,{kind:`turn-result`,action:{kind:`done`,...e.result,serializedContext:e.serializedContext,sessionState:{...e.sessionState,snapshot:{version:1,session:e.sessionState.snapshot.session}}}})}catch(e){if(!HookNotFoundError.is(e))throw e}}export{completeLegacyDriverStep};
1
+ import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{resumeHook}from"#internal/workflow/runtime.js";async function completeLegacyDriverStep(e){"use step";let t=e.sessionWritable.getWriter();try{await t.close()}finally{t.releaseLock()}try{await resumeHook(e.completionToken,{kind:`turn-result`,action:{kind:`done`,...e.result,serializedContext:e.serializedContext,sessionState:{...e.sessionState,snapshot:{version:1,session:{...e.sessionState.snapshot.session,history:e.history}}}}})}catch(e){if(!HookNotFoundError.is(e))throw e}}export{completeLegacyDriverStep};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{walkCauseChain}from"#shared/errors.js";import{EntityConflictError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{cancelRun,getWorld}from"#internal/workflow/runtime.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{settleCancelledTurn}from"#execution/settle-cancelled-turn-step.js";async function interruptLegacySessionStep(e){"use step";let t={...e.sessionState,snapshot:{session:{...e.originalSession,history:e.sessionState.snapshot.session.history}}};try{await terminateChildSessionsStep({sessionState:t})}catch(e){logError(createLogger(`execution.legacy-session`),`could not cooperatively stop legacy children`,e)}let n=await getWorld(),r=e.originalSession.state,i=new Set,a=r?.[`eve.runtime.workflowToolRuns`];if(Array.isArray(a))for(let e of a)isObject(e)&&typeof e.runId==`string`&&i.add(e.runId);let o=r?.[`eve.agent.handles`];if(isObject(o)&&Array.isArray(o.handles))for(let e of o.handles)isObject(e)&&isObject(e.address)&&(e.address.kind===`agent/local`||e.address.kind===`agent/self`)&&typeof e.address.sessionId==`string`&&i.add(e.address.sessionId);let s=r?.[`eve.tasks`];if(isObject(s)&&Array.isArray(s.tasks))for(let e of s.tasks)isObject(e)&&typeof e.taskRunId==`string`&&i.add(e.taskRunId);for(let t of i)if(t&&t!==e.sessionState.sessionId)try{await cancelRun(n,t,{cancelReason:`Session upgraded`})}catch(e){if(![...walkCauseChain(e)].some(e=>EntityConflictError.is(e)||RunExpiredError.is(e)||WorkflowRunNotFoundError.is(e)))throw e}return e.input.inputCommitted||e.sessionState.emissionState.turnId===``?{sessionState:e.sessionState,serializedContext:e.serializedContext}:await settleCancelledTurn({reportUsage:!1,sessionWritable:e.input.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState})}export{interruptLegacySessionStep};
1
+ import{createLogger,logError}from"#internal/logging.js";import{isObject}from"#shared/guards.js";import{walkCauseChain}from"#shared/errors.js";import{EntityConflictError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{cancelRun,getWorld}from"#internal/workflow/runtime.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{settleCancelledTurn}from"#execution/settle-cancelled-turn-step.js";async function interruptLegacySessionStep(e){"use step";let{history:t,...n}=e.originalSession,r={...e.sessionState,snapshot:{session:n}};try{await terminateChildSessionsStep({sessionState:r})}catch(e){logError(createLogger(`execution.legacy-session`),`could not cooperatively stop legacy children`,e)}let i=await getWorld(),a=e.originalSession.state,o=new Set,s=a?.[`eve.runtime.workflowToolRuns`];if(Array.isArray(s))for(let e of s)isObject(e)&&typeof e.runId==`string`&&o.add(e.runId);let c=a?.[`eve.agent.handles`];if(isObject(c)&&Array.isArray(c.handles))for(let e of c.handles)isObject(e)&&isObject(e.address)&&(e.address.kind===`agent/local`||e.address.kind===`agent/self`)&&typeof e.address.sessionId==`string`&&o.add(e.address.sessionId);let l=a?.[`eve.tasks`];if(isObject(l)&&Array.isArray(l.tasks))for(let e of l.tasks)isObject(e)&&typeof e.taskRunId==`string`&&o.add(e.taskRunId);for(let t of o)if(t&&t!==e.sessionState.sessionId)try{await cancelRun(i,t,{cancelReason:`Session upgraded`})}catch(e){if(![...walkCauseChain(e)].some(e=>EntityConflictError.is(e)||RunExpiredError.is(e)||WorkflowRunNotFoundError.is(e)))throw e}return e.input.inputCommitted||e.sessionState.emissionState.turnId===``?{history:e.history,sessionState:e.sessionState,serializedContext:e.serializedContext}:await settleCancelledTurn({history:e.history,reportUsage:!1,sessionWritable:e.input.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState})}export{interruptLegacySessionStep};
@@ -13,6 +13,7 @@ export declare function prepareLegacySessionStep(rawInput: unknown): Promise<{
13
13
  inputCommitted: boolean;
14
14
  retention: "default" | 0 | undefined;
15
15
  };
16
+ history: import("../../harness/messages.ts").HarnessModelMessage[];
16
17
  originalSession: import("./snapshot.js").LegacySession;
17
18
  sessionState: import("../durable-session-store.ts").DurableSessionState;
18
19
  serializedContext: Record<string, unknown>;
@@ -1 +1 @@
1
- import{readLegacyTurnInput}from"./input.js";import{importConversation,readLegacySnapshot}from"./snapshot.js";import{isObject}from"#shared/guards.js";import{SESSION_INBOX_CONTEXT_KEY}from"#execution/session-inbox/address.js";import{getWorld,resolveRunEncryptionKey}from"#internal/workflow/runtime.js";import{hydrateWorkflowArguments}from"#compiled/@workflow/core/serialization.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session/timeout.js";async function prepareLegacySessionStep(e){"use step";let t=readLegacyTurnInput(e),n=readLegacySnapshot(t.sessionState),r=importConversation(n),i=await getWorld(),a=await i.runs.get(r.sessionId),o=await hydrateWorkflowArguments(a.input,a.runId,await resolveRunEncryptionKey(i,a)),s=Array.isArray(o)&&isObject(o[0])?o[0]:void 0;if(s===void 0)throw Error(`Cannot read the original session timeout.`);let c=s.sessionTimeoutMs;if(c!==void 0&&c!==!1&&(typeof c!=`number`||!Number.isFinite(c)||c<0))throw Error(`Invalid original session timeout.`);let l=c??DEFAULT_SESSION_TIMEOUT_MS,u={...t.serializedContext,"eve.sessionId":r.sessionId,[SESSION_INBOX_CONTEXT_KEY]:{sessionId:r.sessionId}};delete u[`eve.sessionCallback`];let d=u[`eve.channel`];return isObject(d)&&d.kind===`subagent`&&isObject(d.state)&&(u[`eve.channel`]={...d,state:{...d.state,parentContinuationToken:``}}),{input:{...t,retention:t.retention??s.retention},originalSession:n,sessionState:r,serializedContext:u,sessionTimeoutMs:l,deploymentId:process.env.VERCEL_DEPLOYMENT_ID?.trim()||await i.getDeploymentId()}}export{prepareLegacySessionStep};
1
+ import{readLegacyTurnInput}from"./input.js";import{importConversation,readLegacySnapshot}from"./snapshot.js";import{isObject}from"#shared/guards.js";import{SESSION_INBOX_CONTEXT_KEY}from"#execution/session-inbox/address.js";import{getWorld,resolveRunEncryptionKey}from"#internal/workflow/runtime.js";import{hydrateWorkflowArguments}from"#compiled/@workflow/core/serialization.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session/timeout.js";async function prepareLegacySessionStep(e){"use step";let t=readLegacyTurnInput(e),n=readLegacySnapshot(t.sessionState),{history:r,sessionState:i}=importConversation(n),a=await getWorld(),o=await a.runs.get(i.sessionId),s=await hydrateWorkflowArguments(o.input,o.runId,await resolveRunEncryptionKey(a,o)),c=Array.isArray(s)&&isObject(s[0])?s[0]:void 0;if(c===void 0)throw Error(`Cannot read the original session timeout.`);let l=c.sessionTimeoutMs;if(l!==void 0&&l!==!1&&(typeof l!=`number`||!Number.isFinite(l)||l<0))throw Error(`Invalid original session timeout.`);let u=l??DEFAULT_SESSION_TIMEOUT_MS,d={...t.serializedContext,"eve.sessionId":i.sessionId,[SESSION_INBOX_CONTEXT_KEY]:{sessionId:i.sessionId}};delete d[`eve.sessionCallback`];let f=d[`eve.channel`];return isObject(f)&&f.kind===`subagent`&&isObject(f.state)&&(d[`eve.channel`]={...f,state:{...f.state,parentContinuationToken:``}}),{input:{...t,retention:t.retention??c.retention},history:r,originalSession:n,sessionState:i,serializedContext:d,sessionTimeoutMs:u,deploymentId:process.env.VERCEL_DEPLOYMENT_ID?.trim()||await a.getDeploymentId()}}export{prepareLegacySessionStep};
@@ -1,6 +1,7 @@
1
1
  import type { ModelMessage } from "ai";
2
- import type { DurableSession, DurableSessionState } from "#execution/durable-session-store.js";
3
- export type LegacySession = Omit<DurableSession, "history"> & {
2
+ import { type DurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
3
+ import type { HarnessModelMessage } from "#harness/messages.js";
4
+ export type LegacySession = DurableSession & {
4
5
  readonly history: ModelMessage[];
5
6
  };
6
7
  /** Reads the driver's embedded snapshot; every supported driver carries one. */
@@ -8,5 +9,8 @@ export declare function readLegacySnapshot(state: Record<string, unknown> & {
8
9
  sessionId: string;
9
10
  }): LegacySession;
10
11
  /** Keep committed conversation data, but no pre-cutover execution registries. */
11
- export declare function importConversation(session: LegacySession): DurableSessionState;
12
- export declare function normalizeHistory(messages: readonly ModelMessage[]): import("#harness/messages.js").HarnessModelMessage[];
12
+ export declare function importConversation(session: LegacySession): {
13
+ readonly history: HarnessModelMessage[];
14
+ readonly sessionState: DurableSessionState;
15
+ };
16
+ export declare function normalizeHistory(messages: readonly ModelMessage[]): HarnessModelMessage[];
@@ -1 +1 @@
1
- import{isObject}from"#shared/guards.js";import{isUserMessageKind,validateHarnessModelMessages}from"#harness/messages.js";import{getHarnessEmissionState}from"#harness/emission.js";const PRESERVED_FRAMEWORK_STATE=new Set([`eve.harness.emission`,`eve.harness.turnUsage`,`eve.harness.reportedSessionUsage`,`eve.harness.sessionRuntimeTokenLimit`]);function readLegacySnapshot(e){let t=e.snapshot;if(!isObject(t)||t.version!==1||!isObject(t.session)||t.session.sessionId!==e.sessionId||!Array.isArray(t.session.history))throw Error(`Unsupported legacy session snapshot.`);return t.session}function importConversation(e){let t=Object.fromEntries(Object.entries(e.state??{}).filter(([e])=>!e.startsWith(`eve.`)||PRESERVED_FRAMEWORK_STATE.has(e))),n=normalizeHistory(e.history),r=getHarnessEmissionState(t),i={...e,history:n,state:t};return{version:1,sessionId:e.sessionId,continuationToken:e.continuationToken,hasProxyInputRequests:!1,emissionState:r,snapshot:{session:i}}}function normalizeHistory(e){let t=[],n=new Map,settle=()=>{n.size!==0&&(t.push({role:`tool`,content:[...n].map(([e,t])=>({type:`tool-result`,toolCallId:e,toolName:t,output:{type:`error-text`,value:`Interrupted by the session upgrade. Start this work again if it is still needed.`}}))}),n.clear())};for(let r of e){let e=r;if(e.role===`assistant`&&Array.isArray(e.content))e={...e,content:e.content.filter(e=>e.type!==`tool-approval-request`)};else if(e.role===`tool`&&(e={...e,content:e.content.filter(e=>e.type!==`tool-approval-response`)},e.content.length===0))continue;if(e.role!==`tool`&&settle(),e.role===`assistant`&&Array.isArray(e.content))for(let t of e.content)t.type===`tool-call`&&n.set(t.toolCallId,t.toolName);if(e.role===`tool`)for(let t of e.content)t.type===`tool-result`&&n.delete(t.toolCallId);let i=e.kind;t.push(e.role===`user`&&!isUserMessageKind(i)?{...e,kind:`user`}:e)}return settle(),validateHarnessModelMessages(t)}export{importConversation,normalizeHistory,readLegacySnapshot};
1
+ import{isObject}from"#shared/guards.js";import{isUserMessageKind,validateHarnessModelMessages}from"#harness/messages.js";import{getHarnessEmissionState}from"#harness/emission.js";import{DURABLE_SESSION_VERSION}from"#execution/durable-session-store.js";const PRESERVED_FRAMEWORK_STATE=new Set([`eve.harness.emission`,`eve.harness.turnUsage`,`eve.harness.reportedSessionUsage`,`eve.harness.sessionRuntimeTokenLimit`]);function readLegacySnapshot(e){let t=e.snapshot;if(!isObject(t)||t.version!==1||!isObject(t.session)||t.session.sessionId!==e.sessionId||!Array.isArray(t.session.history))throw Error(`Unsupported legacy session snapshot.`);return t.session}function importConversation(e){let{history:t,...n}=e,r=Object.fromEntries(Object.entries(e.state??{}).filter(([e])=>!e.startsWith(`eve.`)||PRESERVED_FRAMEWORK_STATE.has(e)));return{history:normalizeHistory(t),sessionState:{version:DURABLE_SESSION_VERSION,sessionId:e.sessionId,continuationToken:e.continuationToken,hasProxyInputRequests:!1,emissionState:getHarnessEmissionState(r),snapshot:{session:{...n,state:r}}}}}function normalizeHistory(e){let t=[],n=new Map,settle=()=>{n.size!==0&&(t.push({role:`tool`,content:[...n].map(([e,t])=>({type:`tool-result`,toolCallId:e,toolName:t,output:{type:`error-text`,value:`Interrupted by the session upgrade. Start this work again if it is still needed.`}}))}),n.clear())};for(let r of e){let e=r;if(e.role===`assistant`&&Array.isArray(e.content))e={...e,content:e.content.filter(e=>e.type!==`tool-approval-request`)};else if(e.role===`tool`&&(e={...e,content:e.content.filter(e=>e.type!==`tool-approval-response`)},e.content.length===0))continue;if(e.role!==`tool`&&settle(),e.role===`assistant`&&Array.isArray(e.content))for(let t of e.content)t.type===`tool-call`&&n.set(t.toolCallId,t.toolName);if(e.role===`tool`)for(let t of e.content)t.type===`tool-result`&&n.delete(t.toolCallId);let i=e.kind;t.push(e.role===`user`&&!isUserMessageKind(i)?{...e,kind:`user`}:e)}return settle(),validateHarnessModelMessages(t)}export{importConversation,normalizeHistory,readLegacySnapshot};
@@ -1 +1 @@
1
- import{completeLegacyDriverStep}from"./completion-step.js";import{interruptLegacySessionStep}from"./interrupt-step.js";import{prepareLegacySessionStep}from"./prepare-step.js";import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{sessionTimeoutDeadline}from"#execution/session/timeout.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{createSessionInbox}from"#execution/session-inbox/inbox.js";import{failSession,runPreparedSession}from"#execution/session/program.js";async function turnWorkflow(e){"use workflow";let t=await prepareLegacySessionStep(e),{sessionId:n}=t.sessionState,r=createSessionInbox(n);try{await r.claimSessionHook(sessionCommandHookToken(n))}catch(e){if(isHookConflictError(e))return;throw e}let{sessionWritable:i}=t.input,a;try{await r.claimSessionHooks(sessionHookTokens(t)),a=await interruptLegacySessionStep(t)}catch(e){return await r.dispose(),await failSession({error:e,serializedContext:t.serializedContext,sessionId:n,sessionState:t.sessionState,sessionWritable:i})}await runPreparedSession({anchor:{kind:`self`,notify:e=>completeLegacyDriverStep({completionToken:t.input.completionToken,result:e,serializedContext:t.serializedContext,sessionState:t.sessionState,sessionWritable:i})},caller:void 0,capabilities:t.input.capabilities,deploymentId:t.deploymentId,initialInput:t.input.delivery===void 0?void 0:{...t.input.delivery,caller:void 0},awaitFirstMessage:!1,retention:t.input.retention,serializedContext:a.serializedContext,sessionId:n,sessionState:a.sessionState,sessionTimeoutMs:t.sessionTimeoutMs,sessionTimeoutDeadline:sessionTimeoutDeadline(t.sessionTimeoutMs,Date.now()),sessionWritable:i},r)}turnWorkflow.workflowId=`workflow//eve//turnWorkflow`;export{turnWorkflow};
1
+ import{completeLegacyDriverStep}from"./completion-step.js";import{interruptLegacySessionStep}from"./interrupt-step.js";import{prepareLegacySessionStep}from"./prepare-step.js";import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{sessionTimeoutDeadline}from"#execution/session/timeout.js";import{sessionHookTokens}from"#execution/session/hook-tokens.js";import{createSessionInbox}from"#execution/session-inbox/inbox.js";import{failSession,runPreparedSession}from"#execution/session/program.js";async function turnWorkflow(e){"use workflow";let t=await prepareLegacySessionStep(e),{sessionId:n}=t.sessionState,r=createSessionInbox(n);try{await r.claimSessionHook(sessionCommandHookToken(n))}catch(e){if(isHookConflictError(e))return;throw e}let{sessionWritable:i}=t.input,a;try{await r.claimSessionHooks(sessionHookTokens(t)),a=await interruptLegacySessionStep(t)}catch(e){return await r.dispose(),await failSession({error:e,serializedContext:t.serializedContext,sessionId:n,sessionState:t.sessionState,sessionWritable:i})}await runPreparedSession({anchor:{kind:`self`,notify:e=>completeLegacyDriverStep({completionToken:t.input.completionToken,history:t.history,result:e,serializedContext:t.serializedContext,sessionState:t.sessionState,sessionWritable:i})},caller:void 0,capabilities:t.input.capabilities,deploymentId:t.deploymentId,history:a.history,initialInput:t.input.delivery===void 0?void 0:{...t.input.delivery,caller:void 0},awaitFirstMessage:!1,retention:t.input.retention,serializedContext:a.serializedContext,sessionId:n,sessionState:a.sessionState,sessionTimeoutMs:t.sessionTimeoutMs,sessionTimeoutDeadline:sessionTimeoutDeadline(t.sessionTimeoutMs,Date.now()),sessionWritable:i},r)}turnWorkflow.workflowId=`workflow//eve//turnWorkflow`;export{turnWorkflow};
@@ -1 +1 @@
1
- import{createInputResolvedEvent}from"#protocol/message.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveRemoteAgentStreamHeaders,respondToRemoteAgentSession}from"#execution/agent-sessions/remote.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{relaySessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{hasDelegatedSessionContext}from"#execution/delegated-session-context.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendWorkflowAskAnswers,toToolInputResponseResponder}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";return await withSessionStateDelta(e,routeProxiedDeliver)}async function routeProxiedDeliver(e){let t=readDurableSession(e.sessionState),n=e.delivery,r=new Map,i=new Map,a,o=!hasDelegatedSessionContext(e.serializedContext)&&n.caller===void 0,s=new Set;for(let[e,c]of n.payloads.entries()){let l=routeDeliverPayload({allowRoute:e=>!s.has(e),payload:c,resolveMessage:o,state:t.state});a??=l.parentAction,l.forSelf!==void 0&&r.set(e,l.forSelf);for(let[t,r]of l.forChildren.entries()){if(r.workflowAsk!==void 0)for(let{requestId:e}of r.resolved.resolutions)s.add(e);let a=JSON.stringify([r.childContinuationToken,r.childSessionInbox?.sessionId??``,r.remote?.sessionId??``,r.resolved.event.sequence,r.resolved.event.stepIndex,r.resolved.event.turnId,r.inputSource??null]),o=i.get(a)??{workflowAsk:r.workflowAsk,remote:r.remote,childContinuationToken:r.childContinuationToken,childSessionInbox:r.childSessionInbox,event:r.resolved.event,metadata:[],payloads:[],resolutions:new Map},c=o.payloads.length;o.payloads.push(r.payload);for(let e of r.resolved.resolutions)o.resolutions.has(e.requestId)||o.resolutions.set(e.requestId,e);if(l.forSelf===void 0&&t===0)for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&o.metadata.push({...t,payloadIndex:c});i.set(a,o)}}let c=!1,l=[];for(let r of i.values()){if(r.workflowAsk!==void 0){let e=coalesceDeliverPayloads(r.payloads).inputResponses??[];await sendWorkflowAskAnswers(r.workflowAsk,e,toToolInputResponseResponder(n.auth))}else{let t={...n,deliveryMetadata:r.metadata.length===0?void 0:r.metadata,payloads:r.payloads},i=r.remote;if(i!==void 0){let t=await deserializeContext(e.serializedContext),a=await resolveRemoteAgentStreamHeaders({bundle:t.require(BundleKey),name:i.name,resolverId:i.resolverId,url:i.url});await respondToRemoteAgentSession({remote:i,headers:a,auth:n.auth,responses:coalesceDeliverPayloads(r.payloads).inputResponses??[]})}else await resumeSessionInbox(r.childSessionInbox??r.childContinuationToken,t)}r.resolutions.size>0&&l.push(createInputResolvedEvent({resolutions:[...r.resolutions.values()],...r.event})),t=retireProxyInputRequests(t,[...r.resolutions.keys()]),c=!0}let u=await relaySessionEvents({serializedContext:e.serializedContext,sessionState:c?replaceDurableSessionSnapshot({session:t,state:e.sessionState}):e.sessionState,sessionWritable:e.sessionWritable},l);if(a!==void 0)return{...u,...a};let d=[...r].sort(([e],[t])=>e-t),f=d.flatMap(([e],t)=>(n.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),p=d.length===0?void 0:{...n,deliveryMetadata:f.length===0?void 0:f,payloads:d.map(([,e])=>e)};return{...u,kind:`continue`,remainder:p}}export{routeProxiedDeliverStep};
1
+ import{AuthKey}from"#context/keys.js";import{createInputResolvedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveRemoteAgentStreamHeaders,respondToRemoteAgentSession}from"#execution/agent-sessions/remote.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{relaySessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{getProxyInputRequests,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{hasDelegatedSessionContext}from"#execution/delegated-session-context.js";import{setChannelContext}from"#execution/channel-context.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendWorkflowAskAnswers,toToolInputResponseResponder}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";return await withSessionStateDelta(e,routeProxiedDeliver)}async function routeProxiedDeliver(e){let{delivery:t,serializedContext:n}=await deliverChannelInputResponses(e),r=readDurableSession(e.sessionState),i=new Map,a=new Map,o,s=!hasDelegatedSessionContext(n)&&t.caller===void 0,c=new Set;for(let[e,n]of t.payloads.entries()){let l=routeDeliverPayload({allowRoute:e=>!c.has(e),payload:n,resolveMessage:s,state:r.state});o??=l.parentAction,l.forSelf!==void 0&&i.set(e,l.forSelf);for(let[n,r]of l.forChildren.entries()){if(r.workflowAsk!==void 0)for(let{requestId:e}of r.resolved.resolutions)c.add(e);let i=JSON.stringify([r.childContinuationToken,r.childSessionInbox?.sessionId??``,r.remote?.sessionId??``,r.resolved.event.sequence,r.resolved.event.stepIndex,r.resolved.event.turnId,r.inputSource??null]),o=a.get(i)??{workflowAsk:r.workflowAsk,remote:r.remote,childContinuationToken:r.childContinuationToken,childSessionInbox:r.childSessionInbox,event:r.resolved.event,metadata:[],payloads:[],resolutions:new Map},s=o.payloads.length;o.payloads.push(r.payload);for(let e of r.resolved.resolutions)o.resolutions.has(e.requestId)||o.resolutions.set(e.requestId,e);if(l.forSelf===void 0&&n===0)for(let n of t.deliveryMetadata??[])n.payloadIndex===e&&o.metadata.push({...n,payloadIndex:s});a.set(i,o)}}let l=!1,u=[];for(let e of a.values()){if(e.workflowAsk!==void 0){let n=coalesceDeliverPayloads(e.payloads).inputResponses??[];await sendWorkflowAskAnswers(e.workflowAsk,n,toToolInputResponseResponder(t.auth))}else{let r={...t,deliveryMetadata:e.metadata.length===0?void 0:e.metadata,payloads:e.payloads},i=e.remote;if(i!==void 0){let r=await deserializeContext(n),a=await resolveRemoteAgentStreamHeaders({bundle:r.require(BundleKey),name:i.name,resolverId:i.resolverId,url:i.url});await respondToRemoteAgentSession({remote:i,headers:a,auth:t.auth,responses:coalesceDeliverPayloads(e.payloads).inputResponses??[]})}else await resumeSessionInbox(e.childSessionInbox??e.childContinuationToken,r)}e.resolutions.size>0&&u.push(createInputResolvedEvent({resolutions:[...e.resolutions.values()],...e.event})),r=retireProxyInputRequests(r,[...e.resolutions.keys()]),l=!0}let d=await relaySessionEvents({serializedContext:n,sessionState:l?replaceDurableSessionSnapshot({session:r,state:e.sessionState}):e.sessionState,sessionWritable:e.sessionWritable},u);if(o!==void 0)return{...d,...o};let f=[...i].sort(([e],[t])=>e-t),p=f.flatMap(([e],n)=>(t.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:n}))),m=f.length===0?void 0:{...t,deliveryMetadata:p.length===0?void 0:p,payloads:f.map(([,e])=>e)};return{...d,kind:`continue`,remainder:m}}async function deliverChannelInputResponses(e){let t=getProxyInputRequests(readDurableSession(e.sessionState).state),routable=e=>t.has(e.requestId);if(!e.delivery.payloads.some(e=>e.inputResponses?.some(e=>!routable(e))===!0))return e;let n=await deserializeContext(e.serializedContext),r=n.require(ChannelKey);if(r.deliver===void 0)return e;e.delivery.auth!==void 0&&n.set(AuthKey,e.delivery.auth??null);let i=buildAdapterContext(r,n),a=!1,o=[];for(let t of e.delivery.payloads){if(t.inputResponses===void 0){o.push(t);continue}let e=[];for(let n of t.inputResponses){if(routable(n)){e.push(n);continue}let o=(await r.deliver({...t,inputResponses:[n],message:void 0},i))?.inputResponses?.filter(routable)??[];a||=o.length>0,e.push(...o.length>0?o:[n])}o.push({...t,inputResponses:e})}if(!a)return e;let s=await deserializeContext(e.serializedContext);return setChannelContext(s,{...r,state:{...i.state}}),{delivery:{...e.delivery,payloads:o},serializedContext:serializeContext(s)}}export{routeProxiedDeliverStep};