eve 0.66.3 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/src/channel/channel-address.d.ts +0 -2
  3. package/dist/src/channel/channel-address.js +1 -1
  4. package/dist/src/channel/channel-operations.d.ts +0 -5
  5. package/dist/src/channel/channel-operations.js +1 -1
  6. package/dist/src/channel/compiled-channel.d.ts +8 -0
  7. package/dist/src/channel/compiled-channel.js +2 -2
  8. package/dist/src/channel/conversation-context.js +1 -1
  9. package/dist/src/channel/routes.d.ts +1 -2
  10. package/dist/src/channel/schedule.d.ts +2 -2
  11. package/dist/src/channel/schedule.js +1 -1
  12. package/dist/src/channel/types.d.ts +8 -13
  13. package/dist/src/chunks/{use-eve-agent-PbSMyJ6e.js → use-eve-agent-DzdyI97Z.js} +0 -5
  14. package/dist/src/chunks/{use-eve-agent-Di1u2zKu.js → use-eve-agent-OCHP4s0z.js} +0 -5
  15. package/dist/src/cli/acp/command.js +3 -3
  16. package/dist/src/cli/commands/logs.d.ts +3 -3
  17. package/dist/src/cli/commands/logs.js +1 -1
  18. package/dist/src/cli/commands/register-integration-commands.js +1 -1
  19. package/dist/src/cli/commands/trace.js +1 -1
  20. package/dist/src/cli/dev/command.d.ts +9 -5
  21. package/dist/src/cli/dev/command.js +1 -3
  22. package/dist/src/cli/dev/run-interactive-ui.d.ts +0 -1
  23. package/dist/src/cli/dev/run-interactive-ui.js +1 -1
  24. package/dist/src/cli/dev/tui/blocks.js +1 -1
  25. package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
  26. package/dist/src/cli/dev/tui/question-panel.d.ts +4 -4
  27. package/dist/src/cli/dev/tui/question-panel.js +1 -1
  28. package/dist/src/cli/dev/tui/runner.js +2 -2
  29. package/dist/src/cli/dev/tui/terminal-renderer.js +8 -9
  30. package/dist/src/cli/dev/tui/theme.d.ts +1 -1
  31. package/dist/src/cli/dev/url-target.js +1 -1
  32. package/dist/src/cli/invoke/command.d.ts +2 -5
  33. package/dist/src/cli/invoke/command.js +1 -1
  34. package/dist/src/cli/invoke/invoke.d.ts +2 -2
  35. package/dist/src/cli/invoke/invoke.js +1 -1
  36. package/dist/src/cli/invoke/result.d.ts +14 -194
  37. package/dist/src/cli/invoke/result.js +1 -1
  38. package/dist/src/cli/run.d.ts +0 -4
  39. package/dist/src/cli/run.js +2 -2
  40. package/dist/src/cli/telemetry/index.js +1 -1
  41. package/dist/src/client/message-reducer.js +1 -1
  42. package/dist/src/compiled/.vendor-stamp.json +1 -1
  43. package/dist/src/compiler/compile-from-memory.d.ts +0 -1
  44. package/dist/src/compiler/compile-from-memory.js +1 -1
  45. package/dist/src/compiler/extension-compatibility.d.ts +25 -18
  46. package/dist/src/compiler/extension-compatibility.js +1 -1
  47. package/dist/src/compiler/manifest.d.ts +48 -14
  48. package/dist/src/compiler/manifest.js +1 -1
  49. package/dist/src/compiler/normalize-agent-config.js +1 -1
  50. package/dist/src/compiler/normalize-channel.js +1 -1
  51. package/dist/src/compiler/normalize-connection.js +1 -1
  52. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  53. package/dist/src/compiler/normalize-subagent.d.ts +0 -2
  54. package/dist/src/compiler/normalize-subagent.js +1 -1
  55. package/dist/src/compiler/remote-agent-node.d.ts +0 -2
  56. package/dist/src/compiler/remote-agent-node.js +1 -1
  57. package/dist/src/compiler/workspace-resources.js +1 -1
  58. package/dist/src/context/dynamic-subagent-lifecycle.js +1 -1
  59. package/dist/src/context/keys.d.ts +0 -3
  60. package/dist/src/context/keys.js +1 -1
  61. package/dist/src/context/memory-lifecycle.d.ts +1 -0
  62. package/dist/src/context/memory-lifecycle.js +1 -1
  63. package/dist/src/discover/project.js +1 -1
  64. package/dist/src/eve-channel/create-request.d.ts +0 -3
  65. package/dist/src/eve-channel/create-request.js +1 -1
  66. package/dist/src/eve-channel/index.js +1 -1
  67. package/dist/src/eve-channel/request.js +1 -1
  68. package/dist/src/eve-channel/types.d.ts +1 -1
  69. package/dist/src/execution/delegated-session-context.d.ts +2 -0
  70. package/dist/src/execution/delegated-session-context.js +1 -0
  71. package/dist/src/execution/dynamic-connections.d.ts +4 -1
  72. package/dist/src/execution/dynamic-connections.js +1 -1
  73. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  74. package/dist/src/execution/effective-agent-config.js +1 -1
  75. package/dist/src/execution/legacy-session/input.d.ts +0 -2
  76. package/dist/src/execution/legacy-session/input.js +1 -1
  77. package/dist/src/execution/legacy-session/prepare-step.d.ts +0 -1
  78. package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
  79. package/dist/src/execution/node-step.d.ts +4 -2
  80. package/dist/src/execution/node-step.js +1 -1
  81. package/dist/src/execution/proxied-deliver-step.js +1 -1
  82. package/dist/src/execution/publish-channel-event.d.ts +23 -0
  83. package/dist/src/execution/publish-channel-event.js +1 -0
  84. package/dist/src/execution/runtime-context.js +1 -1
  85. package/dist/src/execution/session/entry.js +1 -1
  86. package/dist/src/execution/session/event-sink.d.ts +1 -1
  87. package/dist/src/execution/session/event-sink.js +1 -1
  88. package/dist/src/execution/session/finalization.d.ts +1 -4
  89. package/dist/src/execution/session/finalization.js +1 -1
  90. package/dist/src/execution/session/handoff.d.ts +1 -3
  91. package/dist/src/execution/session/handoff.js +1 -1
  92. package/dist/src/execution/session/input-queue.d.ts +0 -1
  93. package/dist/src/execution/session/input-queue.js +1 -1
  94. package/dist/src/execution/session/next-input.d.ts +0 -1
  95. package/dist/src/execution/session/next-input.js +1 -1
  96. package/dist/src/execution/session/program.d.ts +0 -3
  97. package/dist/src/execution/session/program.js +1 -1
  98. package/dist/src/execution/session/turn-step-result.d.ts +1 -2
  99. package/dist/src/execution/session/turn-step-result.js +1 -1
  100. package/dist/src/execution/session/turn-step.js +1 -1
  101. package/dist/src/execution/session/turn.d.ts +2 -2
  102. package/dist/src/execution/session/turn.js +1 -1
  103. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  104. package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
  105. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  106. package/dist/src/execution/tools/agent-router.d.ts +0 -2
  107. package/dist/src/execution/tools/agent-router.js +1 -1
  108. package/dist/src/execution/tools/ask-question-workflow.js +1 -1
  109. package/dist/src/execution/tools/connection-search.d.ts +1 -0
  110. package/dist/src/execution/tools/connection-search.js +1 -1
  111. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  112. package/dist/src/execution/tools/subagent/invoke-preparation.js +1 -1
  113. package/dist/src/extensions/code/extension/lib/connect-authentication.js +1 -1
  114. package/dist/src/extensions/code/extension/lib/github-shell.js +1 -1
  115. package/dist/src/extensions/code/extension/lib/prwatch-github.js +1 -1
  116. package/dist/src/framework/sources/registry.js +1 -1
  117. package/dist/src/harness/approval-delivery-coordinator.d.ts +3 -13
  118. package/dist/src/harness/approval-delivery-coordinator.js +1 -1
  119. package/dist/src/harness/emission.d.ts +2 -3
  120. package/dist/src/harness/emission.js +1 -1
  121. package/dist/src/harness/input-request-resolution.d.ts +2 -0
  122. package/dist/src/harness/input-request-resolution.js +1 -1
  123. package/dist/src/harness/input-requests.d.ts +3 -3
  124. package/dist/src/harness/input-requests.js +1 -1
  125. package/dist/src/harness/pending-input-batches.d.ts +3 -3
  126. package/dist/src/harness/pending-input-batches.js +1 -1
  127. package/dist/src/harness/proxy-input-requests.d.ts +2 -0
  128. package/dist/src/harness/proxy-input-requests.js +1 -1
  129. package/dist/src/harness/session-limit-enforcement.d.ts +2 -3
  130. package/dist/src/harness/session-limit-enforcement.js +1 -1
  131. package/dist/src/harness/tool-loop.js +2 -2
  132. package/dist/src/harness/tools.js +1 -1
  133. package/dist/src/harness/types.d.ts +11 -13
  134. package/dist/src/instrumentation/session-context.js +1 -1
  135. package/dist/src/instrumentation/session-init.js +1 -1
  136. package/dist/src/internal/application/package.js +1 -1
  137. package/dist/src/internal/authored-definition/core.js +1 -1
  138. package/dist/src/internal/authored-module-loader.js +1 -2
  139. package/dist/src/internal/authored-package-boundary.d.ts +0 -1
  140. package/dist/src/internal/authored-package-boundary.js +1 -1
  141. package/dist/src/internal/authored-relative-extension-resolver.js +1 -1
  142. package/dist/src/internal/external-resources-snapshot.d.ts +46 -0
  143. package/dist/src/internal/external-resources-snapshot.js +1 -0
  144. package/dist/src/internal/external-resources.d.ts +20 -0
  145. package/dist/src/internal/external-resources.js +1 -0
  146. package/dist/src/internal/invocation/workflow-execution.d.ts +0 -2
  147. package/dist/src/internal/invocation/workflow-execution.js +1 -1
  148. package/dist/src/internal/nitro/host/build-application.js +1 -1
  149. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  150. package/dist/src/internal/nitro/host/instrumentation-entry.d.ts +3 -0
  151. package/dist/src/internal/nitro/host/instrumentation-entry.js +2 -0
  152. package/dist/src/internal/nitro/host/start-development-server.d.ts +0 -8
  153. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  154. package/dist/src/internal/nitro/host.d.ts +1 -1
  155. package/dist/src/internal/nitro/host.js +1 -1
  156. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  157. package/dist/src/internal/nitro/routes/index.js +72 -3
  158. package/dist/src/node_modules/.pnpm/{@vercel_cli-config@0.2.7 → @vercel_cli-config@0.3.0}/node_modules/@vercel/cli-config/dist/index.js +1 -1
  159. package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/authorization.js +1 -1
  160. package/dist/src/node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/connector.js +1 -0
  161. package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/installation.js +1 -1
  162. package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/token.js +1 -1
  163. package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/token-util.js +1 -1
  164. package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/token.js +1 -1
  165. package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/version.js +1 -1
  166. package/dist/src/protocol/message.d.ts +4 -0
  167. package/dist/src/protocol/message.js +1 -1
  168. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +0 -1
  169. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
  170. package/dist/src/public/channels/mcp.js +1 -1
  171. package/dist/src/public/channels/slack/app-manifest.d.ts +9 -0
  172. package/dist/src/public/channels/slack/app-manifest.js +1 -0
  173. package/dist/src/public/channels/slack/inbound-content.js +6 -3
  174. package/dist/src/public/channels/slack/slackChannel.d.ts +4 -1
  175. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  176. package/dist/src/public/definitions/remote-agent.d.ts +0 -9
  177. package/dist/src/public/definitions/workspace-agent.d.ts +0 -3
  178. package/dist/src/public/definitions/workspace-agent.js +1 -1
  179. package/dist/src/runtime/agent/bootstrap.d.ts +0 -1
  180. package/dist/src/runtime/agent/bootstrap.js +1 -1
  181. package/dist/src/runtime/connections/mcp-client.js +1 -1
  182. package/dist/src/runtime/connections/mcp-tracing.d.ts +27 -0
  183. package/dist/src/runtime/connections/mcp-tracing.js +1 -0
  184. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  185. package/dist/src/runtime/resolve-agent.js +1 -1
  186. package/dist/src/runtime/subagents/dynamic-agent-config.d.ts +0 -2
  187. package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -1
  188. package/dist/src/runtime/subagents/dynamic-remote-agent-config.d.ts +0 -2
  189. package/dist/src/runtime/subagents/dynamic-remote-agent-config.js +1 -1
  190. package/dist/src/runtime/types.d.ts +1 -2
  191. package/dist/src/services/dev-client/vercel-auth-error.d.ts +1 -1
  192. package/dist/src/setup/scaffold/create/project.js +1 -1
  193. package/dist/src/setup/verified-remote-agent.d.ts +1 -0
  194. package/dist/src/setup/verified-remote-agent.js +1 -1
  195. package/dist/src/shared/action-types.d.ts +2 -2
  196. package/dist/src/shared/agent-definition.d.ts +0 -9
  197. package/dist/src/shared/agent-turn-outcome.d.ts +1 -1
  198. package/dist/src/shared/channel-definition.d.ts +2 -2
  199. package/dist/src/shared/conversation-context.d.ts +0 -4
  200. package/dist/src/shared/conversation-context.js +1 -1
  201. package/dist/src/shared/validate-authorization.js +1 -1
  202. package/dist/src/shared/vercel-connect-metadata.d.ts +12 -0
  203. package/dist/src/shared/vercel-connect-metadata.js +1 -0
  204. package/dist/src/subagents/agent-handle-errors.d.ts +0 -4
  205. package/dist/src/subagents/agent-handle-errors.js +1 -1
  206. package/dist/src/subagents/callback-route.js +1 -1
  207. package/dist/src/subagents/callback-step.d.ts +0 -22
  208. package/dist/src/subagents/callback-step.js +1 -1
  209. package/dist/src/subagents/event-proxy-step.js +1 -1
  210. package/dist/src/subagents/hitl-proxy.d.ts +3 -5
  211. package/dist/src/subagents/hitl-proxy.js +1 -1
  212. package/dist/src/subagents/invocation.d.ts +5 -6
  213. package/dist/src/subagents/parent-notification.d.ts +1 -18
  214. package/dist/src/subagents/parent-notification.js +1 -1
  215. package/dist/src/subagents/remote-dispatch.js +1 -1
  216. package/dist/src/subagents/tool.d.ts +0 -3
  217. package/dist/src/subagents/tool.js +1 -1
  218. package/dist/src/svelte/index.js +1 -1
  219. package/dist/src/svelte/use-eve-agent.js +1 -1
  220. package/dist/src/tools/framework/agent-contract.d.ts +0 -2
  221. package/dist/src/tools/framework/agent-contract.js +1 -1
  222. package/dist/src/tracing/agent-action-instrumentation.js +1 -1
  223. package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
  224. package/dist/src/tracing/agent-memory-instrumentation.js +1 -1
  225. package/dist/src/tracing/agent-otel-provider.js +2 -2
  226. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  227. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  228. package/dist/src/tracing/agent-tool-span-context.d.ts +15 -0
  229. package/dist/src/tracing/agent-tool-span-context.js +1 -0
  230. package/dist/src/tracing/otel-declaration.d.ts +4 -9
  231. package/dist/src/vue/index.js +1 -1
  232. package/dist/src/vue/use-eve-agent.js +1 -1
  233. package/docs/agent-config.md +12 -13
  234. package/docs/channels/chat-sdk.mdx +1 -1
  235. package/docs/channels/custom.mdx +1 -1
  236. package/docs/channels/eve.mdx +4 -4
  237. package/docs/channels/mcp.mdx +10 -10
  238. package/docs/channels/slack.mdx +1 -1
  239. package/docs/concepts/sessions-runs-and-streaming.md +5 -6
  240. package/docs/connections/overview.mdx +22 -0
  241. package/docs/guides/deployment/overview.md +1 -1
  242. package/docs/guides/deployment/self-hosting.md +1 -1
  243. package/docs/guides/deployment/vercel.mdx +2 -2
  244. package/docs/guides/dev-tui.md +6 -6
  245. package/docs/guides/dynamic-capabilities.md +2 -2
  246. package/docs/guides/frontend/overview.mdx +5 -3
  247. package/docs/guides/hooks.md +4 -2
  248. package/docs/guides/instrumentation/agent-runs.mdx +7 -7
  249. package/docs/guides/instrumentation/instrumentation.mdx +22 -5
  250. package/docs/guides/instrumentation/otel.mdx +30 -0
  251. package/docs/guides/remote-agents.md +3 -4
  252. package/docs/guides/self-modification.md +1 -1
  253. package/docs/memory/custom-provider.md +1 -1
  254. package/docs/protocols/acp.md +1 -1
  255. package/docs/reference/cli.md +91 -97
  256. package/docs/schedules.mdx +4 -5
  257. package/docs/subagents/index.mdx +5 -7
  258. package/docs/tools/human-in-the-loop.md +4 -0
  259. package/docs/tools/overview.mdx +2 -0
  260. package/docs/tools/workflows.mdx +1 -1
  261. package/docs/tutorial/remember-definitions.mdx +1 -1
  262. package/docs/tutorial/ship-it.mdx +1 -1
  263. package/package.json +3 -2
  264. package/dist/src/cli/commands/channels.d.ts +0 -9
  265. package/dist/src/cli/commands/channels.js +0 -1
  266. package/dist/src/execution/effective-output-schema.d.ts +0 -22
  267. package/dist/src/execution/effective-output-schema.js +0 -1
  268. package/dist/src/node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/connector.js +0 -1
  269. package/dist/src/shared/run-mode.d.ts +0 -7
  270. package/dist/src/shared/run-mode.js +0 -1
  271. package/dist/src/subagents/parent-result.d.ts +0 -14
  272. package/dist/src/subagents/parent-result.js +0 -1
  273. /package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/index.js +0 -0
  274. /package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/internal/base-url.js +0 -0
  275. /package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/internal/default-scopes.js +0 -0
  276. /package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/internal/env.js +0 -0
  277. /package/dist/src/node_modules/.pnpm/{@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff → @vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494}/node_modules/@vercel/connect/dist/internal/url-validation.js +0 -0
  278. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/auth-errors.js +0 -0
  279. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/exchange-vercel-oidc-token.js +0 -0
  280. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/get-context.js +0 -0
  281. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/get-vercel-oidc-token-sync.js +0 -0
  282. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/get-vercel-oidc-token-with-refresh.js +0 -0
  283. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/index.js +0 -0
  284. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/oauth.js +0 -0
  285. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/token-error.js +0 -0
  286. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/token-io.js +0 -0
  287. /package/dist/src/node_modules/.pnpm/{@vercel_oidc@3.8.8 → @vercel_oidc@3.8.9}/node_modules/@vercel/oidc/dist/verify-vercel-oidc-token.js +0 -0
@@ -1 +1 @@
1
- import{jsonValuesEqual}from"#shared/json.js";import{coalesceDeliveries}from"#harness/messages.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{hasRecordedTaskOutcome,taskIdOfDelivery}from"#tasks/notification.js";var SessionInputQueue=class{entries=[];cancelledTaskIds=new Set;seenTaskDeliveryIds=new Set;nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e,t){if(isStaleNotification(e,t))return;let n=taskDeliveryId(e);if(n!==void 0){let t=terminalTaskId(e),r=t===void 0?n:`${t}:ready`;if(this.seenTaskDeliveryIds.has(r)||this.isCancelledNotification(e))return;this.seenTaskDeliveryIds.add(r)}let r={delivery:e,sequence:this.nextSequence++};return this.entries.push({...r,kind:`delivery`}),r}rememberTask(e){this.seenTaskDeliveryIds.add(e)}isTaskCancelled(e){return this.cancelledTaskIds.has(e)}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}taskDeliveries(){return this.entries.filter(e=>e.kind===`delivery`&&!isNotificationOnly(e.delivery))}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0||this.isCancelledNotification(t)){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}cancelTask(e){this.cancelledTaskIds.add(e),this.discardDeliveries(e=>this.isCancelledNotification(e))}discardStaleNotifications(e){this.discardDeliveries(t=>isStaleNotification(t,e))}takeSteering(e,t){let n=this.entries.filter(n=>n.kind===`delivery`&&e.has(n.sequence)&&isSteeringDelivery(n.delivery,t));if(n.length!==0)return this.retain(e=>e.kind!==`delivery`||!n.includes(e)),{delivery:combine(n),handoffEligible:!1,kind:`turn`,sequences:n.map(({sequence:e})=>e)}}takeNext(e,t){let n=t?.expectedAttemptIds??new Set;if(this.retain(e=>e.kind!==`authorization`||n.has(e.attemptId)),n.size>0){let e=new Map(this.entries.flatMap(e=>e.kind===`authorization`?[[e.attemptId,e.payload]]:[]));if([...n].every(t=>e.has(t)))return this.retain(e=>e.kind!==`authorization`),{kind:`authorization-resume`,payloads:[...n].map(t=>e.get(t))}}let r=getBackgroundTasks(e),i=new Set(r.query({state:`working`}).filter(({taskId:e})=>!this.seenTaskDeliveryIds.has(`${e}:ready`)&&!this.cancelledTaskIds.has(e)).map(e=>e.cohortId)),a=this.nextActionableIndex(r,i,t?.deferDeliveries===!0,t?.taskDeliveryPolicy??`cohort`);if(!(a<0))return this.takeSelectionAt(a,r,t?.freshSequence)}nextActionableIndex(e,t,n,r){return this.entries.findIndex(i=>{if(i.kind===`control`)return!0;if(i.kind===`authorization`||n||this.isCancelledDelivery(i.delivery))return!1;let a=terminalCohort(i.delivery,e);return r===`auto`||a===void 0||!t.has(a)})}takeSelectionAt(e,t,n){let r=this.entries[e];if(r.kind!==`delivery`)return this.entries.splice(e,1),r.kind===`control`?{control:r.control,kind:`control`}:{kind:`authorization-resume`,payloads:[r.payload]};let i=terminalCohort(r.delivery,t);if(i!==void 0){let r=this.entries.findLastIndex(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===i),a=this.entries.findIndex((n,i)=>i>e&&i<r&&(n.kind!==`delivery`||!this.isCancelledDelivery(n.delivery)&&terminalCohort(n.delivery,t)===void 0));if(a>=0)return this.takeSelectionAt(a,t,n)}let a=this.entries.splice(e,1)[0];if(a.kind!==`delivery`)throw Error(`Selected a non-delivery entry as a turn.`);let o=[a],s=terminalCohort(a.delivery,t);if(s!==void 0){let e=this.entries.filter(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===s);o.push(...e),this.retain(t=>t.kind!==`delivery`||!e.includes(t))}else{let t=a.delivery.auth!=null&&a.delivery.auth.principalType!==`anonymous`,n=a.delivery.caller;for(;this.entries.length>e;){let r=this.entries[e];if(r?.kind!==`delivery`||a.delivery.taskDeliveryId!==void 0||r.delivery.taskDeliveryId!==void 0||!t||!jsonValuesEqual(a.delivery.auth,r.delivery.auth)||n!==void 0&&r.delivery.caller!==void 0)break;o.push(this.entries.splice(e,1)[0]),n??=r.delivery.caller}}let c=o.map(({sequence:e})=>e),l=combine(o);return{delivery:l,handoffEligible:c.length===1&&c[0]===n&&l.caller===void 0&&taskDeliveryId(l)===void 0&&this.entries.length===0,kind:`turn`,sequences:c}}isCancelledDelivery(e){let t=taskDeliveryId(e);return t!==void 0&&this.cancelledTaskIds.has(taskIdOfDelivery(t))}isCancelledNotification(e){return isNotificationOnly(e)&&this.isCancelledDelivery(e)}discardDeliveries(e){this.retain(t=>t.kind!==`delivery`||!e(t.delivery))}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isNotificationOnly(e){return e.payloads.every(e=>e.task===void 0)}function isStaleNotification(e,t){return isNotificationOnly(e)&&hasRecordedTaskOutcome(e,t)}function isSteeringDelivery(e,t){return e.taskDeliveryId===void 0&&(e.turnPolicy??`steer`)===`steer`&&(e.caller===void 0||e.caller.callId===t)}function combine(e){if(e.length===1)return e[0].delivery;let t=e.map(({delivery:e})=>e),n=t.flatMap(e=>e.taskDeliveryIds??(e.taskDeliveryId===void 0?[]:[e.taskDeliveryId]));return{...coalesceDeliveries(t),taskDeliveryIds:n.length>0?n:void 0}}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}function taskDeliveryId(e){return e.taskDeliveryId??e.caller?.taskId}function terminalCohort(e,t){let n=terminalTaskId(e);return n===void 0?void 0:t.get(n)?.cohortId}function terminalTaskId(e){if(e.caller===void 0)for(let t of[`completed`,`failed`,`cancelled`]){let n=`:ready:${t}`;if(e.taskDeliveryId?.endsWith(n))return e.taskDeliveryId.slice(0,-n.length)}}export{SessionInputQueue,isSteeringDelivery};
1
+ import{jsonValuesEqual}from"#shared/json.js";import{coalesceDeliveries}from"#harness/messages.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{hasRecordedTaskOutcome,taskIdOfDelivery}from"#tasks/notification.js";var SessionInputQueue=class{entries=[];cancelledTaskIds=new Set;seenTaskDeliveryIds=new Set;nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e,t){if(isStaleNotification(e,t))return;let n=taskDeliveryId(e);if(n!==void 0){let t=terminalTaskId(e),r=t===void 0?n:`${t}:ready`;if(this.seenTaskDeliveryIds.has(r)||this.isCancelledNotification(e))return;this.seenTaskDeliveryIds.add(r)}let r={delivery:e,sequence:this.nextSequence++};return this.entries.push({...r,kind:`delivery`}),r}rememberTask(e){this.seenTaskDeliveryIds.add(e)}isTaskCancelled(e){return this.cancelledTaskIds.has(e)}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}taskDeliveries(){return this.entries.filter(e=>e.kind===`delivery`&&!isNotificationOnly(e.delivery))}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0||this.isCancelledNotification(t)){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}cancelTask(e){this.cancelledTaskIds.add(e),this.discardDeliveries(e=>this.isCancelledNotification(e))}discardStaleNotifications(e){this.discardDeliveries(t=>isStaleNotification(t,e))}takeSteering(e,t){let n=this.entries.filter(n=>n.kind===`delivery`&&e.has(n.sequence)&&isSteeringDelivery(n.delivery,t));if(n.length!==0)return this.retain(e=>e.kind!==`delivery`||!n.includes(e)),{delivery:combine(n),handoffEligible:!1,kind:`turn`,sequences:n.map(({sequence:e})=>e)}}takeNext(e,t){let n=t?.expectedAttemptIds??new Set;if(this.retain(e=>e.kind!==`authorization`||n.has(e.attemptId)),n.size>0){let e=new Map(this.entries.flatMap(e=>e.kind===`authorization`?[[e.attemptId,e.payload]]:[]));if([...n].every(t=>e.has(t)))return this.retain(e=>e.kind!==`authorization`),{kind:`authorization-resume`,payloads:[...n].map(t=>e.get(t))}}let r=getBackgroundTasks(e),i=new Set(r.query({state:`working`}).filter(({taskId:e})=>!this.seenTaskDeliveryIds.has(`${e}:ready`)&&!this.cancelledTaskIds.has(e)).map(e=>e.cohortId)),a=this.nextActionableIndex(r,i,t?.taskDeliveryPolicy??`cohort`);if(!(a<0))return this.takeSelectionAt(a,r,t?.freshSequence)}nextActionableIndex(e,t,n){return this.entries.findIndex(r=>{if(r.kind===`control`)return!0;if(r.kind===`authorization`||this.isCancelledDelivery(r.delivery))return!1;let i=terminalCohort(r.delivery,e);return n===`auto`||i===void 0||!t.has(i)})}takeSelectionAt(e,t,n){let r=this.entries[e];if(r.kind!==`delivery`)return this.entries.splice(e,1),r.kind===`control`?{control:r.control,kind:`control`}:{kind:`authorization-resume`,payloads:[r.payload]};let i=terminalCohort(r.delivery,t);if(i!==void 0){let r=this.entries.findLastIndex(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===i),a=this.entries.findIndex((n,i)=>i>e&&i<r&&(n.kind!==`delivery`||!this.isCancelledDelivery(n.delivery)&&terminalCohort(n.delivery,t)===void 0));if(a>=0)return this.takeSelectionAt(a,t,n)}let a=this.entries.splice(e,1)[0];if(a.kind!==`delivery`)throw Error(`Selected a non-delivery entry as a turn.`);let o=[a],s=terminalCohort(a.delivery,t);if(s!==void 0){let e=this.entries.filter(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===s);o.push(...e),this.retain(t=>t.kind!==`delivery`||!e.includes(t))}else{let t=a.delivery.auth!=null&&a.delivery.auth.principalType!==`anonymous`,n=a.delivery.caller;for(;this.entries.length>e;){let r=this.entries[e];if(r?.kind!==`delivery`||a.delivery.taskDeliveryId!==void 0||r.delivery.taskDeliveryId!==void 0||!t||!jsonValuesEqual(a.delivery.auth,r.delivery.auth)||n!==void 0&&r.delivery.caller!==void 0)break;o.push(this.entries.splice(e,1)[0]),n??=r.delivery.caller}}let c=o.map(({sequence:e})=>e),l=combine(o);return{delivery:l,handoffEligible:c.length===1&&c[0]===n&&l.caller===void 0&&taskDeliveryId(l)===void 0&&this.entries.length===0,kind:`turn`,sequences:c}}isCancelledDelivery(e){let t=taskDeliveryId(e);return t!==void 0&&this.cancelledTaskIds.has(taskIdOfDelivery(t))}isCancelledNotification(e){return isNotificationOnly(e)&&this.isCancelledDelivery(e)}discardDeliveries(e){this.retain(t=>t.kind!==`delivery`||!e(t.delivery))}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isNotificationOnly(e){return e.payloads.every(e=>e.task===void 0)}function isStaleNotification(e,t){return isNotificationOnly(e)&&hasRecordedTaskOutcome(e,t)}function isSteeringDelivery(e,t){return e.taskDeliveryId===void 0&&(e.turnPolicy??`steer`)===`steer`&&(e.caller===void 0||e.caller.callId===t)}function combine(e){if(e.length===1)return e[0].delivery;let t=e.map(({delivery:e})=>e),n=t.flatMap(e=>e.taskDeliveryIds??(e.taskDeliveryId===void 0?[]:[e.taskDeliveryId]));return{...coalesceDeliveries(t),taskDeliveryIds:n.length>0?n:void 0}}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}function taskDeliveryId(e){return e.taskDeliveryId??e.caller?.taskId}function terminalCohort(e,t){let n=terminalTaskId(e);return n===void 0?void 0:t.get(n)?.cohortId}function terminalTaskId(e){if(e.caller===void 0)for(let t of[`completed`,`failed`,`cancelled`]){let n=`:ready:${t}`;if(e.taskDeliveryId?.endsWith(n))return e.taskDeliveryId.slice(0,-n.length)}}export{SessionInputQueue,isSteeringDelivery};
@@ -26,7 +26,6 @@ export type NextTurnInstruction = {
26
26
  export declare function nextTurnDelivery(input: {
27
27
  readonly inbox: SessionInboxReader;
28
28
  readonly cursor: SessionStateCursor;
29
- readonly deferDeliveries?: boolean;
30
29
  readonly expectedAttemptIds?: ReadonlySet<string>;
31
30
  readonly queue: SessionInputQueue;
32
31
  }): Promise<NextTurnInstruction>;
@@ -1 +1 @@
1
- import{TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME}from"#context/key-names.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";async function nextTurnDelivery(e){let{inbox:t,cursor:n,queue:r}=e,i;for(;;){for(let{delivery:e,sequence:t}of r.taskDeliveries()){let i=await routeDeliverToChildren({delivery:e,sessionWritable:n.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});if(await n.apply(i),r.replaceDelivery(t,i.kind===`cancel-turn`?void 0:i.remainder),i.kind===`cancel-turn`)return i}let a=r.takeNext(n.sessionState.snapshot.session.state,{deferDeliveries:e.deferDeliveries,taskDeliveryPolicy:n.serializedContext[TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME]===`auto`?`auto`:`cohort`,expectedAttemptIds:e.expectedAttemptIds,freshSequence:t.hasPending()?void 0:i});if(a?.kind===`control`)return{kind:a.control};if(a?.kind===`authorization-resume`)return a;if(a?.kind===`turn`){let e=await routeSelectedDelivery(a,n);if(e.kind===`cancel-turn`)return e;if(e.kind===`consumed`)continue;return e}let o=r.pendingCount===0,s=await t.next();if(s===void 0)return{kind:`closed`};let c=await admitSessionInboxPayload(s,e);switch(i=o&&c.kind===`delivery`?c.admission.sequence:void 0,c.kind){case`workflow`:return{kind:`workflow`,message:c.message};case`cancel`:await applySessionCancellation(c.command,e)}}}export{nextTurnDelivery};
1
+ import{TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME}from"#context/key-names.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";async function nextTurnDelivery(e){let{inbox:t,cursor:n,queue:r}=e,i;for(;;){for(let{delivery:e,sequence:t}of r.taskDeliveries()){let i=await routeDeliverToChildren({delivery:e,sessionWritable:n.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});if(await n.apply(i),r.replaceDelivery(t,i.kind===`cancel-turn`?void 0:i.remainder),i.kind===`cancel-turn`)return i}let a=r.takeNext(n.sessionState.snapshot.session.state,{taskDeliveryPolicy:n.serializedContext[TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME]===`auto`?`auto`:`cohort`,expectedAttemptIds:e.expectedAttemptIds,freshSequence:t.hasPending()?void 0:i});if(a?.kind===`control`)return{kind:a.control};if(a?.kind===`authorization-resume`)return a;if(a?.kind===`turn`){let e=await routeSelectedDelivery(a,n);if(e.kind===`cancel-turn`)return e;if(e.kind===`consumed`)continue;return e}let o=r.pendingCount===0,s=await t.next();if(s===void 0)return{kind:`closed`};let c=await admitSessionInboxPayload(s,e);switch(i=o&&c.kind===`delivery`?c.admission.sequence:void 0,c.kind){case`workflow`:return{kind:`workflow`,message:c.message};case`cancel`:await applySessionCancellation(c.command,e)}}}export{nextTurnDelivery};
@@ -1,6 +1,5 @@
1
1
  import type { DeliverHookPayload, SessionCapabilities, TurnCaller } from "#channel/types.js";
2
2
  import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.js";
3
- import type { RunMode } from "#shared/run-mode.js";
4
3
  import type { DurableSessionState } from "#execution/durable-session-store.js";
5
4
  import { type SessionInboxHandle } from "#execution/session-inbox/inbox.js";
6
5
  import type { WorkflowEntryResult } from "#execution/session/entry-input.js";
@@ -24,7 +23,6 @@ export interface SessionBoot {
24
23
  readonly initialInput: DeliverHookPayload | undefined;
25
24
  /** Parks on the inbox before any session-scoped lifecycle work. */
26
25
  readonly awaitFirstMessage: boolean;
27
- readonly mode: RunMode;
28
26
  readonly retention?: AgentWorkflowRetentionDefinition;
29
27
  readonly serializedContext: Record<string, unknown>;
30
28
  readonly sessionId: string;
@@ -41,7 +39,6 @@ export declare function runPreparedSession(boot: SessionBoot, inbox: SessionInbo
41
39
  */
42
40
  export declare function failSession(input: {
43
41
  readonly error: unknown;
44
- readonly mode: RunMode;
45
42
  readonly serializedContext: Record<string, unknown>;
46
43
  readonly sessionId: string;
47
44
  readonly sessionState: DurableSessionState | undefined;
@@ -1 +1 @@
1
- import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,mode:e.mode,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0},o;try{try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i,o)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,mode:e.mode,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async t=>{for(;;){let r=await nextTurnDelivery({cursor:n,deferDeliveries:e.mode===`task`&&t.size>0,expectedAttemptIds:t,inbox:i,queue:o});if(r.kind!==`workflow`)return r;await s.handleWorkflowMessage(r.message)}},l=0,runTurn=async e=>{let t=a.caller;return t?.taskId!==void 0&&o.rememberTask(t.taskId),t!==void 0&&await n.apply({serializedContext:await bindTurnCallerContextStep({caller:t,serializedContext:n.serializedContext})}),a.turnId=`turn_${String(l++)}`,await s.runTurn(e)},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,{serializedContext:n.serializedContext,sessionState:n.sessionState});return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async()=>{let t=await settleCancelledTurnStep({sessionWritable:e.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});return await n.apply(t),a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity(new Set);switch(e.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:case`authorization-resume`:continue}}},runInitialAction=async()=>e.awaitFirstMessage?await awaitPrewarmedAction():{action:await runTurn(e.initialInput===void 0?void 0:{delivery:e.initialInput}),kind:`action`};try{let[t,r]=await Promise.allSettled([runInitialAction(),c?.start()]);if(r.status===`rejected`)throw r.reason;if(t.status===`rejected`)throw t.reason;let i=t.value;if(i.kind!==`action`)return i;let o=i.action;for(;;){if(o.kind===`done`)return{kind:`terminal`,outcome:{action:o,kind:`done`}};if(o.cancelled===!0){let t={caller:a.caller,sessionId:e.sessionId},n=await settleCancelledTurn();await notifyCancelledTaskCallerStep(n.usage===void 0?t:{...t,usage:n.usage})}else o.settled?.notifyCaller===!0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:o.settled}),a.caller=void 0);let t=await nextParkedActivity(new Set(o.authorizationAttemptIds??[]));switch(t.kind){case`authorization-resume`:o=await runTurn({delivery:{kind:`deliver`,payloads:t.payloads}});continue;case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:o=await runTurn({control:t.kind});continue;case`cancel-turn`:await cancelDescendantTurnsStep({serializedContext:n.serializedContext,sessionState:n.sessionState}),await settleCancelledTurn(),o={...o,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(t);if(e.kind!==`action`)return e;o=e.action;continue}}}}finally{await c?.dispose()}}export{failSession,runPreparedSession};
1
+ import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0},o;try{try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i,o)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async e=>{for(;;){let t=await nextTurnDelivery({cursor:n,expectedAttemptIds:e,inbox:i,queue:o});if(t.kind!==`workflow`)return t;await s.handleWorkflowMessage(t.message)}},l=0,runTurn=async e=>{let t=a.caller;return t?.taskId!==void 0&&o.rememberTask(t.taskId),t!==void 0&&await n.apply({serializedContext:await bindTurnCallerContextStep({caller:t,serializedContext:n.serializedContext})}),a.turnId=`turn_${String(l++)}`,await s.runTurn(e)},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,{serializedContext:n.serializedContext,sessionState:n.sessionState});return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async()=>{let t=await settleCancelledTurnStep({sessionWritable:e.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});return await n.apply(t),a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity(new Set);switch(e.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:case`authorization-resume`:continue}}},runInitialAction=async()=>e.awaitFirstMessage?await awaitPrewarmedAction():{action:await runTurn(e.initialInput===void 0?void 0:{delivery:e.initialInput}),kind:`action`};try{let[t,r]=await Promise.allSettled([runInitialAction(),c?.start()]);if(r.status===`rejected`)throw r.reason;if(t.status===`rejected`)throw t.reason;let i=t.value;if(i.kind!==`action`)return i;let o=i.action;for(;;){if(o.kind===`done`)return{kind:`terminal`,outcome:{action:o,kind:`done`}};if(o.cancelled===!0){let t={caller:a.caller,sessionId:e.sessionId},n=await settleCancelledTurn();await notifyCancelledTaskCallerStep(n.usage===void 0?t:{...t,usage:n.usage})}else o.settled?.notifyCaller===!0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:o.settled}),a.caller=void 0);let t=await nextParkedActivity(new Set(o.authorizationAttemptIds??[]));switch(t.kind){case`authorization-resume`:o=await runTurn({delivery:{kind:`deliver`,payloads:t.payloads}});continue;case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:o=await runTurn({control:t.kind});continue;case`cancel-turn`:await cancelDescendantTurnsStep({serializedContext:n.serializedContext,sessionState:n.sessionState}),await settleCancelledTurn(),o={...o,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(t);if(e.kind!==`action`)return e;o=e.action;continue}}}}finally{await c?.dispose()}}export{failSession,runPreparedSession};
@@ -1,6 +1,5 @@
1
1
  import type { DurableStepResult } from "#execution/session/turn-step-types.js";
2
2
  import type { StepResult } from "#harness/types.js";
3
- import type { RunMode } from "#shared/run-mode.js";
4
- export declare function resolveSessionStepResult(stepResult: StepResult, nextSerializedContext: Record<string, unknown>, mode: RunMode, beforeStepContext: Record<string, unknown>,
3
+ export declare function resolveSessionStepResult(stepResult: StepResult, nextSerializedContext: Record<string, unknown>, beforeStepContext: Record<string, unknown>,
5
4
  /** The turn this step belongs to. */
6
5
  turnId: string): DurableStepResult;
@@ -1 +1 @@
1
- import{createDurableSessionState}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{preserveSerializedBackgroundTaskObservabilityState}from"#shared/serialized-observability-state.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{hasPendingInputBatch}from"#harness/input-requests.js";function resolveSessionStepResult(e,t,n,r,i){let a=createDurableSessionState({session:e.session});if(e.steered)return{action:`steered`,serializedContext:t,sessionState:a};let o=e.backgroundTasks===void 0||e.backgroundTaskSession===void 0?{}:{backgroundTaskContext:preserveSerializedBackgroundTaskObservabilityState(r,t,e.backgroundTasks),backgroundTaskState:createDurableSessionState({session:e.backgroundTaskSession}),backgroundTasks:e.backgroundTasks};if(e.next!==null&&typeof e.next==`object`&&`done`in e.next){if(n===`task`&&hasPendingInputBatch(e.session.state))throw Error(`Task mode cannot complete while input requests remain pending.`);let r=getTurnUsageState(e.session.state)?.session;return{action:`done`,...o,output:e.next.output,isError:e.next.isError,serializedContext:t,sessionState:a,usage:r===void 0?void 0:toUsage(r),usageDelta:takeSessionUsageDelta(e.session).delta}}if(e.next===null){let n=derivePendingState(e.session);if(e.settledTurn!==void 0){if(e.settledTurn.isError!==!0&&getBackgroundTasks(e.session.state).query({state:`working`,turnId:i}).length>0)return{action:`park`,...o,...n,settled:{...e.settledTurn,notifyCaller:!1},serializedContext:t,sessionState:a};let{delta:r,session:s}=takeSessionUsageDelta(e.session);return{action:`park`,...o,...n,serializedContext:t,sessionState:createDurableSessionState({session:s}),settled:{notifyCaller:!0,output:e.settledTurn.output,isError:e.settledTurn.isError,usage:r}}}return{action:`park`,...o,...n,serializedContext:t,sessionState:a}}return{action:`continue`,...o,serializedContext:t,sessionState:a}}export{resolveSessionStepResult};
1
+ import{createDurableSessionState}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{preserveSerializedBackgroundTaskObservabilityState}from"#shared/serialized-observability-state.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";function resolveSessionStepResult(e,t,n,r){let i=createDurableSessionState({session:e.session});if(e.steered)return{action:`steered`,serializedContext:t,sessionState:i};let a=e.backgroundTasks===void 0||e.backgroundTaskSession===void 0?{}:{backgroundTaskContext:preserveSerializedBackgroundTaskObservabilityState(n,t,e.backgroundTasks),backgroundTaskState:createDurableSessionState({session:e.backgroundTaskSession}),backgroundTasks:e.backgroundTasks};if(e.next!==null&&typeof e.next==`object`&&`done`in e.next){let n=getTurnUsageState(e.session.state)?.session;return{action:`done`,...a,output:e.next.output,isError:e.next.isError,serializedContext:t,sessionState:i,usage:n===void 0?void 0:toUsage(n),usageDelta:takeSessionUsageDelta(e.session).delta}}if(e.next===null){let n=derivePendingState(e.session);if(e.settledTurn!==void 0){if(e.settledTurn.isError!==!0&&getBackgroundTasks(e.session.state).query({state:`working`,turnId:r}).length>0)return{action:`park`,...a,...n,settled:{...e.settledTurn,notifyCaller:!1},serializedContext:t,sessionState:i};let{delta:o,session:s}=takeSessionUsageDelta(e.session);return{action:`park`,...a,...n,serializedContext:t,sessionState:createDurableSessionState({session:s}),settled:{notifyCaller:!0,output:e.settledTurn.output,isError:e.settledTurn.isError,usage:o}}}return{action:`park`,...a,...n,serializedContext:t,sessionState:i}}return{action:`continue`,...a,serializedContext:t,sessionState:i}}export{resolveSessionStepResult};
@@ -1 +1 @@
1
- import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TaskDeliveryPolicyKey,TurnDeliveryIdsKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import*as activityCohort from"#execution/activity-cohort.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createSessionEventSink}from"#execution/session/event-sink.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{getBackgroundTaskDelivery,markBackgroundTaskStepInput,resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return runSessionStep(e)}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState),a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a),l=t?.taskDeliveryPolicy??a.get(TaskDeliveryPolicyKey)??`auto`;a.set(TaskDeliveryPolicyKey,l);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let u=getPendingAuthorization(i.state),d;if(u&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,n.payloads);if(n={...n,payloads:t},e.length>0){let r=activityCohort.restoreAuthorizationActivity({ctx:a,matches:e,pending:u}),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},d=e,t.length===0&&(n=void 0)}}let f=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=getBackgroundTaskDelivery(n),m=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=getHarnessEmissionState(m.state);if(!_.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},v=createSessionEventSink({adapter:o,ctx:a,isFirstTurn:_.sequence===0,sessionWritable:e.sessionWritable,sessionId:m.sessionId}),{adapterCtx:y}=v;try{let b=bindDynamicConnections(a,s.resolvedAgent),x={...s.graph.root,turnAgent:c.turnAgent},S=createTurnEventHandler({abortSignal:e.abortSignal,bundle:s,ctx:a,dynamicConnections:b,effectiveAgent:c,effectiveNode:x,instrumentation:g,sink:v}),C=n!==void 0&&!isHarnessBetweenTurns(m)?structuredClone(y.state):void 0,w;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,y):defaultDeliverResult(t);n!=null&&e.push(p===void 0?n:markBackgroundTaskStepInput(n))}}catch(e){throw await failChannelDeliveries(e),e}w=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let T=n!==void 0&&w===void 0&&!isHarnessBetweenTurns(m);if(T)f===void 0?a.delete(AuthKey):a.set(AuthKey,f),y.state=C;else if(t!==void 0&&a.set(TurnTaskDeliveryKey,`none`),t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),w={...w,runtimeActionResults:r.results});let E;if(w!==void 0&&p!==void 0){let e=resolveTaskDeliveryContext({state:i.state,taskDeliveryIds:p.taskDeliveryIds??[p.taskDeliveryId],taskDeliveryPolicy:l});e!==void 0&&(a.set(TurnTaskDeliveryKey,e.phase),E=e.rootTurnId,w={...w,context:[...w.context??[],e.context]})}activityCohort.updateActivityRootForDelivery({activeTurnId:activeTurnId(_),ctx:a,delivery:T?void 0:t,sessionState:i.state,taskRootTurnId:E});let D=a.get(TurnTaskDeliveryKey);if(D===`none`||D===`initiating`){let e=resolveInitiatingTaskContext({state:i.state,turnId:activeTurnId(_)});e!==void 0&&a.set(TurnTaskDeliveryKey,e.phase)}if(t!==void 0){let e={...o,state:{...y.state}};setChannelContext(a,e)}if(n!==void 0&&w===void 0&&isHarnessBetweenTurns(m)){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=reconcileSessionContinuationToken(a,m),n=serializeContext(a),r=t===m?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let O=s.subagentRegistry.dynamicResolvers??[],k=s.resolvedAgent.dynamicToolResolvers??[],A=buildRuntimeIdentity(x);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:A});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:k,event:e,messages:h.initial.messages,runtimeRevision:t}))]),await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:k})}}catch(e){throw await failChannelDeliveries(e),e}let j=a.require(ModeKey),M=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,N=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:N,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent:S,historyProjector:h.projector,historyView:h.prepare(r),instrumentation:g,mode:j,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:x})(r,n)},P,F;try{throwIfTurnAborted(e.abortSignal),F=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:w,initialSession:m,modelCallsPerStep:M,runStep:async({firstCall:t,session:n,stepInput:r})=>{let i=await runBackgroundStep(a,n,async e=>{a.setVirtualContext(HandleEventKey,S),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let n=t?resolveEffectiveOutputSchema({agentOutputSchema:c.turnAgent.outputSchema,input:w,mode:j,session:e}):e;if(await b.rehydrate(getHarnessEmissionState(n.state),A,isHarnessBetweenTurns(n)),t&&d){let e=getHarnessEmissionState(n.state);if(isHarnessBetweenTurns(n)){let t=createTurnInputMessages(consumeDeferredStepInput({session:n,input:r}).input);prepareDynamicInstructionPreamble(a,h.messages(n)),prepareMemoryPreamble(a,{history:n.history,input:t,projector:h.projector,state:n.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:g});try{e=await emitTurnPreamble(S,{},e,h.projector({messages:[...n.history,...t],state:n.state}),A,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);n={...n,history:validateHarnessModelMessages([...e?.history??n.history,...i]),state:e?.state??n.state}}n=setHarnessEmissionState(n,e)}for(let{authorization:t,result:n}of d){let r=u?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await S(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}return runHarnessStep(n,r)});return i.settledTurn===void 0&&throwIfTurnAborted(e.abortSignal),P={result:i,serializedContext:serializeContext(a)},i}})}catch(t){if(!isTurnCancellation(t)&&e.abortSignal?.aborted!==!0)throw await failChannelDeliveries(t),t;let n=readRetainedBackgroundToolResult(a);return g?.rememberBackgroundTasks(n?.backgroundTasks??[]),createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:P,ctx:a,initialSession:m,stepInput:w})}g?.rememberBackgroundTasks(F.backgroundTasks??[]);let I=reconcileSessionContinuationToken(a,F.session);agentTraceState.pruneAgentTraceState(a,I.sessionId,I.state);let L=serializeContext(a);F={...F,session:I};let R=resolveSessionStepResult(F,L,j,e.serializedContext,activeTurnId(_));return R.action===`done`&&await v.close(),R}finally{v.release()}}function createTurnEventHandler(e){let{abortSignal:t,bundle:n,ctx:r,effectiveAgent:i,effectiveNode:a}=e;return async(o,s)=>{let c=await e.sink.emit(o),l=await dispatchMemoryLifecycleEvent({abortSignal:t,appRoot:a.agent?.metadata?.appRoot??``,ctx:r,event:o,instrumentation:e.instrumentation?.memory,memories:a.agent?.memories??[],messages:s,nodeId:n.nodeId??`__root__`});c.suppressed||await dispatchStreamEventHooks({ctx:r,registry:n.hookRegistry,event:c.event}),c.event.type!==`step.started`&&await dispatchDynamicModelEvent({abortSignal:t,ctx:r,dynamicModel:i.turnAgent.dynamicModel,event:c.event,messages:l,scope:{moduleMap:n.moduleMap,nodeId:n.nodeId}}),await e.dynamicConnections.dispatch(c.event),await dispatchDynamicSubagentEvent({ctx:r,resolvers:n.subagentRegistry.dynamicResolvers??[],event:c.event,messages:l}),await dispatchDynamicToolEvent({ctx:r,resolvers:n.resolvedAgent.dynamicToolResolvers??[],event:c.event,messages:l}),await dispatchDynamicSkillEvent({ctx:r,resolvers:n.resolvedAgent.dynamicSkillResolvers??[],event:c.event,messages:l}),await dispatchDynamicInstructionEvent({ctx:r,resolvers:n.resolvedAgent.dynamicInstructionsResolvers??[],event:c.event,messages:l})}}export{turnStep};
1
+ import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TaskDeliveryPolicyKey,TurnDeliveryIdsKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import*as activityCohort from"#execution/activity-cohort.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchMemoryLifecycleEvent}from"#context/memory-event-lifecycle.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createSessionEventSink}from"#execution/session/event-sink.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{getBackgroundTaskDelivery,markBackgroundTaskStepInput,resolveInitiatingTaskContext,resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return runSessionStep(e)}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState),a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a),l=t?.taskDeliveryPolicy??a.get(TaskDeliveryPolicyKey)??`auto`;a.set(TaskDeliveryPolicyKey,l);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let u=getPendingAuthorization(i.state),d;if(u&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(u,n.payloads);if(n={...n,payloads:t},e.length>0){let r=activityCohort.restoreAuthorizationActivity({ctx:a,matches:e,pending:u}),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},d=e,t.length===0&&(n=void 0)}}let f=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=getBackgroundTaskDelivery(n),m=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=getHarnessEmissionState(m.state);if(!_.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},v=createSessionEventSink({adapter:o,ctx:a,isFirstTurn:_.sequence===0,sessionWritable:e.sessionWritable,sessionId:m.sessionId}),{adapterCtx:y}=v;try{let u=bindDynamicConnections(a,s.resolvedAgent),b={...s.graph.root,turnAgent:c.turnAgent},x=createTurnEventHandler({abortSignal:e.abortSignal,bundle:s,ctx:a,dynamicConnections:u,effectiveAgent:c,effectiveNode:b,instrumentation:g,sink:v}),S=n!==void 0&&!isHarnessBetweenTurns(m)?structuredClone(y.state):void 0,C;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,y):defaultDeliverResult(t);n!=null&&e.push(p===void 0?n:markBackgroundTaskStepInput(n))}}catch(e){throw await failChannelDeliveries(e),e}C=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let w=n!==void 0&&C===void 0&&!isHarnessBetweenTurns(m);if(w)f===void 0?a.delete(AuthKey):a.set(AuthKey,f),y.state=S;else if(t!==void 0&&a.set(TurnTaskDeliveryKey,`none`),t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),C={...C,runtimeActionResults:r.results});let T;if(C!==void 0&&p!==void 0){let e=resolveTaskDeliveryContext({state:i.state,taskDeliveryIds:p.taskDeliveryIds??[p.taskDeliveryId],taskDeliveryPolicy:l});e!==void 0&&(a.set(TurnTaskDeliveryKey,e.phase),T=e.rootTurnId,C={...C,context:[...C.context??[],e.context]})}activityCohort.updateActivityRootForDelivery({activeTurnId:activeTurnId(_),ctx:a,delivery:w?void 0:t,sessionState:i.state,taskRootTurnId:T});let E=a.get(TurnTaskDeliveryKey);if(E===`none`||E===`initiating`){let e=resolveInitiatingTaskContext({state:i.state,turnId:activeTurnId(_)});e!==void 0&&a.set(TurnTaskDeliveryKey,e.phase)}if(t!==void 0){let e={...o,state:{...y.state}};setChannelContext(a,e)}if(n!==void 0&&C===void 0&&isHarnessBetweenTurns(m)){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=reconcileSessionContinuationToken(a,m),n=serializeContext(a),r=t===m?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let D=s.subagentRegistry.dynamicResolvers??[],O=s.resolvedAgent.dynamicToolResolvers??[],k=buildRuntimeIdentity(b);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:D,event:e,messages:h.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}))]),await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:O})}}catch(e){throw await failChannelDeliveries(e),e}let A=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,j=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:j,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent:x,prepareApprovalTurn:e=>u.dispatch(createTurnStartedEvent(e)),historyProjector:h.projector,historyView:h.prepare(r),instrumentation:g,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:b})(r,n)},M,N;try{throwIfTurnAborted(e.abortSignal),N=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:C,initialSession:m,modelCallsPerStep:A,runStep:async({firstCall:t,session:n,stepInput:r})=>{let i=await runBackgroundStep(a,n,async e=>{a.setVirtualContext(HandleEventKey,x),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let n=t&&C?.outputSchema!==void 0?{...e,outputSchema:C.outputSchema}:e,i=getHarnessEmissionState(n.state);if(await u.rehydrate(i,k,isHarnessBetweenTurns(n)?void 0:{sequence:i.sequence,turnId:activeTurnId(i)}),t&&d){let e=getHarnessEmissionState(n.state);if(d.some(({candidateId:e})=>e===void 0)&&isHarnessBetweenTurns(n)){let t=createTurnInputMessages(consumeDeferredStepInput({session:n,input:r}).input);prepareDynamicInstructionPreamble(a,h.messages(n)),prepareMemoryPreamble(a,{history:n.history,input:t,projector:h.projector,state:n.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:g});try{e=await emitTurnPreamble(x,{},e,h.projector({messages:[...n.history,...t],state:n.state}),k,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);n={...n,history:validateHarnessModelMessages([...e?.history??n.history,...i]),state:e?.state??n.state}}n=setHarnessEmissionState(n,e)}for(let{authorization:t,result:n,candidateId:r}of d)await x(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}return runHarnessStep(n,r)});return i.settledTurn===void 0&&throwIfTurnAborted(e.abortSignal),M={result:i,serializedContext:serializeContext(a)},i}})}catch(t){if(!isTurnCancellation(t)&&e.abortSignal?.aborted!==!0)throw await failChannelDeliveries(t),t;let n=readRetainedBackgroundToolResult(a);return g?.rememberBackgroundTasks(n?.backgroundTasks??[]),createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:M,ctx:a,initialSession:m,stepInput:C})}g?.rememberBackgroundTasks(N.backgroundTasks??[]);let P=reconcileSessionContinuationToken(a,N.session);agentTraceState.pruneAgentTraceState(a,P.sessionId,P.state);let F=serializeContext(a);N={...N,session:P};let I=resolveSessionStepResult(N,F,e.serializedContext,activeTurnId(_));return I.action===`done`&&await v.close(),I}finally{v.release()}}function createTurnEventHandler(e){let{abortSignal:t,bundle:n,ctx:r,effectiveAgent:i,effectiveNode:a}=e;return async(o,s)=>{let c=await e.sink.emit(o),l=await dispatchMemoryLifecycleEvent({abortSignal:t,appRoot:a.agent?.metadata?.appRoot??``,ctx:r,event:o,instrumentation:e.instrumentation?.memory,memories:a.agent?.memories??[],messages:s,nodeId:n.nodeId??`__root__`});c.suppressed||await dispatchStreamEventHooks({ctx:r,registry:n.hookRegistry,event:c.event}),c.event.type!==`step.started`&&await dispatchDynamicModelEvent({abortSignal:t,ctx:r,dynamicModel:i.turnAgent.dynamicModel,event:c.event,messages:l,scope:{moduleMap:n.moduleMap,nodeId:n.nodeId}}),await e.dynamicConnections.dispatch(c.event),await dispatchDynamicSubagentEvent({ctx:r,resolvers:n.subagentRegistry.dynamicResolvers??[],event:c.event,messages:l}),await dispatchDynamicToolEvent({ctx:r,resolvers:n.resolvedAgent.dynamicToolResolvers??[],event:c.event,messages:l}),await dispatchDynamicSkillEvent({ctx:r,resolvers:n.resolvedAgent.dynamicSkillResolvers??[],event:c.event,messages:l}),await dispatchDynamicInstructionEvent({ctx:r,resolvers:n.resolvedAgent.dynamicInstructionsResolvers??[],event:c.event,messages:l})}}export{turnStep};
@@ -4,13 +4,13 @@ import type { SessionInboxReader } from "#execution/session-inbox/inbox.js";
4
4
  import type { SessionStateCursor } from "#execution/session/state-cursor.js";
5
5
  import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
6
6
  import type { TurnOutcome, TurnStepPayload } from "#execution/session/turn-step-types.js";
7
- import type { RunMode } from "#shared/run-mode.js";
8
7
  import type { RuntimeActionResult } from "#shared/action-types.js";
8
+ /** True when a delegating parent (local or remote) receives this session's input requests. */
9
+ export declare function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean;
9
10
  export interface SessionExecutionInput {
10
11
  readonly capabilities?: SessionCapabilities;
11
12
  readonly cursor: SessionStateCursor;
12
13
  readonly inbox: SessionInboxReader;
13
- readonly mode: RunMode;
14
14
  readonly queue: SessionInputQueue;
15
15
  readonly sessionId: string;
16
16
  }
@@ -1 +1 @@
1
- import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{coalesceDeliveries}from"#harness/messages.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{activeTurnId}from"#harness/active-turn-id.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#subagents/handles/query.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{isSteeringDelivery}from"#execution/session/input-queue.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{handleWorkflowToolRunMessage}from"#execution/session-workflow-tool-run.js";import{turnStep}from"#execution/session/turn-step.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e){let t=new ActiveTurn(this.input,e?.delivery?.caller?.callId);try{return await this.runTurnSteps(t,e)}finally{t.dispose()}}async runTurnSteps(e,t){let n=t;for(;;){let{cursor:t}=this.input,r=t.serializedContext,i=await turnStep(t.createStepInput(n,{abortSignal:e.signal,steeringSignal:e.steeringSignal})),a=i.action===`park`?i.pendingCoordinationCallIds:void 0,o=(i.backgroundTasks?.length??0)>0,s=i.action===`park`&&i.settled!==void 0;if(o){if(i.backgroundTaskState===void 0)throw Error(`Background tasks were returned without their committed session state.`);await t.apply({serializedContext:i.backgroundTaskContext??r,sessionState:i.backgroundTaskState}),await acknowledgeDelegatedTasksStep({tasks:i.backgroundTasks??[]})}if(await t.apply({serializedContext:i.serializedContext,sessionState:i.action===`cancelled`||!s&&e.signal.aborted?i.backgroundTaskState??i.sessionState:i.sessionState}),await e.admitBoundary(),e.resetSteering(),i.action===`cancelled`||!s&&e.signal.aborted&&(a===void 0||o))return await this.finishCancelledTurn();if(i.action===`done`)return{isError:i.isError,kind:`done`,output:i.output??``,usage:i.usage,usageDelta:i.usageDelta};if(a!==void 0&&i.action===`park`){let r=await dispatchCoordinationStep({action:i.action,callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))},sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),o=r.results.length===0?void 0:Date.now();await t.apply(r);let s=await this.waitForRuntimeActionResults({initialAcceptedAtMs:o,initialResults:r.results,pendingCallIds:a,turn:e});if(s===`cancelled`)return await this.finishCancelledTurn();n={delivery:await e.takeSteering(),runtimeResults:s};continue}if(i.action===`park`){if(!(i.hasPendingAuthorization||i.hasPendingInputBatch&&this.input.capabilities?.requestInput===!0||i.settled?.notifyCaller===!1||this.input.mode===`conversation`))throw Error("Task mode cannot wait for follow-up input (`next: null`).");return{authorizationAttemptIds:i.authorizationAttemptIds,kind:`park`,settled:i.settled}}let c=await e.takeSteering();n=c===void 0?void 0:{delivery:c}}}async handleWorkflowMessage(e){return await handleWorkflowToolRunMessage({callbackMetadataUrl:getWorkflowMetadata().url,cursor:this.input.cursor,message:e})}async finishCancelledTurn(){let{cursor:e}=this.input;return await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),{cancelled:!0,kind:`park`}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=new Map;if(e.initialAcceptedAtMs!==void 0)for(let r of t)n.set(r.callId,e.initialAcceptedAtMs);for(;;){let r=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(r!==void 0)return{acceptedAtMsByCallId:Object.fromEntries(r.map(e=>[e.callId,n.get(e.callId)])),results:r};let i=await e.turn.nextRuntimeEvent();if(i===`cancelled`)return i;if(i.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,r=i.results.filter(t=>t.kind===`tool-result`?isInboxToolResultFromRecordedWorkflowToolRun(e,t):t.kind===`subagent-result`&&t.origin===`child`&&isInboxSubagentResultFromRunningHandle(e,t));if(r.length>0){let e=Date.now();t.push(...r);for(let t of r)n.set(t.callId,e)}continue}let a=await this.handleWorkflowMessage(i.message);a!==void 0&&(t.push(a),n.set(a.callId,Date.now()))}}},ActiveTurn=class{admitted=new Set;routedToChildren=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;callerCallId;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;constructor(e,t){this.input=e,this.callerCallId=t,this.expectedTurnId=activeTurnId(e.cursor.sessionState.emissionState),this.unsubscribe=e.inbox.onInterrupt(e=>{this.cancelsThisTurn(e)&&this.abort()}),this.unsubscribeDelivery=e.inbox.onDelivery(this.signalSteering)}signalSteering=e=>{let t;try{t=decodeSessionInboxPayload(e)}catch{return}t.kind===`deliver`&&isSteeringDelivery(t,this.callerCallId)&&!this.input.cursor.sessionState.hasProxyInputRequests&&t.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0&&e.task===void 0)&&this.steeringController.abort()};get signal(){return this.controller.signal}dispose(){this.unsubscribe(),this.unsubscribeDelivery()}get steeringSignal(){return this.steeringController.signal}resetSteering(){this.steeringController.signal.aborted&&(this.unsubscribeDelivery(),this.steeringController=new AbortController,this.unsubscribeDelivery=this.input.inbox.onDelivery(this.signalSteering))}async admitBoundary(){let e=this.input.inbox.drain();for(let t of e)await this.admit(t)}async takeSteering(){let e=[];for(;;){let t=this.input.queue.takeSteering(this.admitted,this.callerCallId);if(t===void 0)break;for(let e of t.sequences)this.admitted.delete(e);let n=await routeSelectedDelivery(t,this.input.cursor);if(n.kind===`cancel-turn`){this.abort();break}n.kind===`turn`&&e.push(n.delivery)}if(e.length!==0)return e.length===1?e[0]:coalesceDeliveries(e)}async nextRuntimeEvent(){for(;;){if(this.signal.aborted)return`cancelled`;let e=this.runtimeResults.shift();if(e!==void 0)return e;let t=await this.input.inbox.next();if(t===void 0)throw Error(`Session inbox closed before runtime actions completed.`);await this.admit(t),await this.routeAdmittedToChildren()}}cancelsThisTurn(e){return e.kind===`reset`?!0:e.kind===`cancel`?e.turnId===void 0||e.turnId===this.expectedTurnId:!1}async admit(e){let t=await admitSessionInboxPayload(e,this.input);switch(t.kind){case`delivery`:this.admitted.add(t.admission.sequence);return;case`runtime-action-result`:this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results});return;case`workflow`:this.runtimeResults.push({kind:`workflow`,message:t.message});return;case`cancel`:if(!this.cancelsThisTurn(e))return;await applySessionCancellation(t.command,this.input),this.abort();return;case`consumed`:return}}async routeAdmittedToChildren(){for(let e of this.admitted){if(this.routedToChildren.has(e))continue;let t=this.input.queue.delivery(e);if(t===void 0){this.admitted.delete(e);continue}this.routedToChildren.add(e);let n=await routeDeliverToChildren({delivery:t,sessionWritable:this.input.cursor.sessionWritable,serializedContext:this.input.cursor.serializedContext,sessionState:this.input.cursor.sessionState});if(await this.input.cursor.apply(n),n.kind===`cancel-turn`){this.input.queue.replaceDelivery(e,void 0),this.admitted.delete(e),this.abort();return}this.input.queue.replaceDelivery(e,n.remainder),n.remainder===void 0&&this.admitted.delete(e)}}abort(){this.controller.signal.aborted||this.controller.abort(new TurnCancelledError)}};export{SessionExecution};
1
+ import{sessionCommandHookToken,sessionInboxHookToken}from"#execution/session-inbox/address.js";import{coalesceDeliveries}from"#harness/messages.js";import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{activeTurnId}from"#harness/active-turn-id.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#subagents/handles/query.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{isSteeringDelivery}from"#execution/session/input-queue.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{dispatchCoordinationStep}from"#execution/coordination-dispatch-step.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{handleWorkflowToolRunMessage}from"#execution/session-workflow-tool-run.js";import{turnStep}from"#execution/session/turn-step.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";function hasDelegatedCallerContext(e){if(e[`eve.sessionCallback`]!==void 0)return!0;let t=e[`eve.channel`];return typeof t==`object`&&!!t&&Reflect.get(t,`kind`)===`subagent`}var SessionExecution=class{input;constructor(e){this.input=e}get cursor(){return this.input.cursor}async runTurn(e){let t=new ActiveTurn(this.input,e?.delivery?.caller?.callId);try{return await this.runTurnSteps(t,e)}finally{t.dispose()}}async runTurnSteps(e,t){let n=t;for(;;){let{cursor:t}=this.input,r=t.serializedContext,i=await turnStep(t.createStepInput(n,{abortSignal:e.signal,steeringSignal:e.steeringSignal})),a=i.action===`park`?i.pendingCoordinationCallIds:void 0,o=(i.backgroundTasks?.length??0)>0,s=i.action===`park`&&i.settled!==void 0;if(o){if(i.backgroundTaskState===void 0)throw Error(`Background tasks were returned without their committed session state.`);await t.apply({serializedContext:i.backgroundTaskContext??r,sessionState:i.backgroundTaskState}),await acknowledgeDelegatedTasksStep({tasks:i.backgroundTasks??[]})}if(await t.apply({serializedContext:i.serializedContext,sessionState:i.action===`cancelled`||!s&&e.signal.aborted?i.backgroundTaskState??i.sessionState:i.sessionState}),await e.admitBoundary(),e.resetSteering(),i.action===`cancelled`||!s&&e.signal.aborted&&(a===void 0||o))return await this.finishCancelledTurn();if(i.action===`done`)return{isError:i.isError,kind:`done`,output:i.output??``,usage:i.usage,usageDelta:i.usageDelta};if(a!==void 0&&i.action===`park`){let r=await dispatchCoordinationStep({action:i.action,callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),workflowToolRunOwner:{inbox:sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId))},sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),o=r.results.length===0?void 0:Date.now();await t.apply(r);let s=await this.waitForRuntimeActionResults({initialAcceptedAtMs:o,initialResults:r.results,pendingCallIds:a,turn:e});if(s===`cancelled`)return await this.finishCancelledTurn();n={delivery:await e.takeSteering(),runtimeResults:s};continue}if(i.action===`park`){if(i.hasPendingInputBatch&&this.input.capabilities?.requestInput!==!0&&!hasDelegatedCallerContext(this.input.cursor.serializedContext))throw Error("This session cannot request human input, so it cannot wait for a tool approval or question. Sessions started without `capabilities.requestInput`, such as schedules, must not use approval-gated tools.");return{authorizationAttemptIds:i.authorizationAttemptIds,kind:`park`,settled:i.settled}}let c=await e.takeSteering();n=c===void 0?void 0:{delivery:c}}}async handleWorkflowMessage(e){return await handleWorkflowToolRunMessage({callbackMetadataUrl:getWorkflowMetadata().url,cursor:this.input.cursor,message:e})}async finishCancelledTurn(){let{cursor:e}=this.input;return await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),{cancelled:!0,kind:`park`}}async waitForRuntimeActionResults(e){let t=[...e.initialResults],n=new Map;if(e.initialAcceptedAtMs!==void 0)for(let r of t)n.set(r.callId,e.initialAcceptedAtMs);for(;;){let r=resolveRuntimeActionResultsForCallIds({pendingCallIds:e.pendingCallIds,results:t});if(r!==void 0)return{acceptedAtMsByCallId:Object.fromEntries(r.map(e=>[e.callId,n.get(e.callId)])),results:r};let i=await e.turn.nextRuntimeEvent();if(i===`cancelled`)return i;if(i.kind===`runtime-action-result`){let e=this.input.cursor.sessionState.snapshot.session.state,r=i.results.filter(t=>t.kind===`tool-result`?isInboxToolResultFromRecordedWorkflowToolRun(e,t):t.kind===`subagent-result`&&t.origin===`child`&&isInboxSubagentResultFromRunningHandle(e,t));if(r.length>0){let e=Date.now();t.push(...r);for(let t of r)n.set(t.callId,e)}continue}let a=await this.handleWorkflowMessage(i.message);a!==void 0&&(t.push(a),n.set(a.callId,Date.now()))}}},ActiveTurn=class{admitted=new Set;routedToChildren=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;callerCallId;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;constructor(e,t){this.input=e,this.callerCallId=t,this.expectedTurnId=activeTurnId(e.cursor.sessionState.emissionState),this.unsubscribe=e.inbox.onInterrupt(e=>{this.cancelsThisTurn(e)&&this.abort()}),this.unsubscribeDelivery=e.inbox.onDelivery(this.signalSteering)}signalSteering=e=>{let t;try{t=decodeSessionInboxPayload(e)}catch{return}t.kind===`deliver`&&isSteeringDelivery(t,this.callerCallId)&&!this.input.cursor.sessionState.hasProxyInputRequests&&t.payloads.some(e=>e.message!==void 0&&e.inputResponses===void 0&&e.task===void 0)&&this.steeringController.abort()};get signal(){return this.controller.signal}dispose(){this.unsubscribe(),this.unsubscribeDelivery()}get steeringSignal(){return this.steeringController.signal}resetSteering(){this.steeringController.signal.aborted&&(this.unsubscribeDelivery(),this.steeringController=new AbortController,this.unsubscribeDelivery=this.input.inbox.onDelivery(this.signalSteering))}async admitBoundary(){let e=this.input.inbox.drain();for(let t of e)await this.admit(t)}async takeSteering(){let e=[];for(;;){let t=this.input.queue.takeSteering(this.admitted,this.callerCallId);if(t===void 0)break;for(let e of t.sequences)this.admitted.delete(e);let n=await routeSelectedDelivery(t,this.input.cursor);if(n.kind===`cancel-turn`){this.abort();break}n.kind===`turn`&&e.push(n.delivery)}if(e.length!==0)return e.length===1?e[0]:coalesceDeliveries(e)}async nextRuntimeEvent(){for(;;){if(this.signal.aborted)return`cancelled`;let e=this.runtimeResults.shift();if(e!==void 0)return e;let t=await this.input.inbox.next();if(t===void 0)throw Error(`Session inbox closed before runtime actions completed.`);await this.admit(t),await this.routeAdmittedToChildren()}}cancelsThisTurn(e){return e.kind===`reset`?!0:e.kind===`cancel`?e.turnId===void 0||e.turnId===this.expectedTurnId:!1}async admit(e){let t=await admitSessionInboxPayload(e,this.input);switch(t.kind){case`delivery`:this.admitted.add(t.admission.sequence);return;case`runtime-action-result`:this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results});return;case`workflow`:this.runtimeResults.push({kind:`workflow`,message:t.message});return;case`cancel`:if(!this.cancelsThisTurn(e))return;await applySessionCancellation(t.command,this.input),this.abort();return;case`consumed`:return}}async routeAdmittedToChildren(){for(let e of this.admitted){if(this.routedToChildren.has(e))continue;let t=this.input.queue.delivery(e);if(t===void 0){this.admitted.delete(e);continue}this.routedToChildren.add(e);let n=await routeDeliverToChildren({delivery:t,sessionWritable:this.input.cursor.sessionWritable,serializedContext:this.input.cursor.serializedContext,sessionState:this.input.cursor.sessionState});if(await this.input.cursor.apply(n),n.kind===`cancel-turn`){this.input.queue.replaceDelivery(e,void 0),this.admitted.delete(e),this.abort();return}this.input.queue.replaceDelivery(e,n.remainder),n.remainder===void 0&&this.admitted.delete(e)}}abort(){this.controller.signal.aborted||this.controller.abort(new TurnCancelledError)}};export{SessionExecution,hasDelegatedCallerContext};
@@ -1 +1 @@
1
- import{callAdapterEventHandler}from"#channel/adapter.js";import{TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{clearPendingCoordinationBatch,getPendingCoordinationBatch}from"#harness/coordination.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{getBlockingWorkflowToolRuns,removeBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession}from"#execution/session.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{withContextScope}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{abandonAgentInvocationOwners,abandonRunningAgentTurns}from"#subagents/handles/transitions.js";async function settleCancelledTurnStep(e){"use step";let t=readDurableSession(e.sessionState),n=await deserializeContext(e.serializedContext),r=n.require(ChannelKey),i=buildAdapterContext(r,n),a=n.require(BundleKey),o=resolveEffectiveAgentRuntime(a,n),s=hydrateDurableSession({compactionOverrides:{thresholdPercent:o.thresholdPercent},durable:t,turnAgent:o.turnAgent}),c=bindSessionInstrumentation({agentName:o.turnAgent.id,ctx:n,rootSessionId:s.rootSessionId??s.sessionId,sessionId:s.sessionId}),l=getHarnessEmissionState(t.state),u=[...getProxyInputRequests(t.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(s)&&hasProxyInputRequests(t.state)&&!u)){let t=e.sessionWritable.getWriter();try{let e=await withContextScope(n,s,async e=>{let baseEmit=async e=>{let o=await callAdapterEventHandler(r,e,i);setChannelContext(n,{...r,state:{...i.state}});let c=stampMessageStreamEvent(o,n.get(TurnDeliveryIdsKey));await t.write(encodeMessageStreamEvent(c)),observeSessionActivity({ctx:n,event:c,sessionId:s.sessionId}),await dispatchStreamEventHooks({ctx:n,event:c,registry:a.hookRegistry})},o=c?.createHandleEvent({handleEvent:baseEmit,turnId:activeTurnId(l)})??baseEmit;return{result:await emitCancelledTurn(o,l),session:e}});l=e.result,s=e.session}finally{await c?.flush(),t.releaseLock()}}let d=getPendingCoordinationBatch(s.state)?.event.turnId??e.sessionState.emissionState.turnId,f=getBlockingWorkflowToolRuns(s.state,d);s=abandonAgentInvocationOwners(s,new Set(f.map(e=>e.address.runId)));let p=reconcileSessionContinuationToken(n,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingCoordinationBatch(removeBlockingWorkflowToolRuns(abandonRunningAgentTurns({...s,outputSchema:void 0}),d)))),l)),m=getTurnUsageState(s.state)?.session,h={serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:p})};return m===void 0?h:{...h,usage:toUsage(m)}}export{settleCancelledTurnStep};
1
+ import{TurnDeliveryIdsKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{clearPendingCoordinationBatch,getPendingCoordinationBatch}from"#harness/coordination.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{getBlockingWorkflowToolRuns,removeBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession}from"#execution/session.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{withContextScope}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{publishChannelEvent}from"#execution/publish-channel-event.js";import{observeSessionActivity}from"#execution/session-activity-projection.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{abandonAgentInvocationOwners,abandonRunningAgentTurns}from"#subagents/handles/transitions.js";async function settleCancelledTurnStep(e){"use step";let t=readDurableSession(e.sessionState),n=await deserializeContext(e.serializedContext),r=n.require(ChannelKey),i=buildAdapterContext(r,n),a=n.require(BundleKey),o=resolveEffectiveAgentRuntime(a,n),s=hydrateDurableSession({compactionOverrides:{thresholdPercent:o.thresholdPercent},durable:t,turnAgent:o.turnAgent}),c=bindSessionInstrumentation({agentName:o.turnAgent.id,ctx:n,rootSessionId:s.rootSessionId??s.sessionId,sessionId:s.sessionId}),l=getHarnessEmissionState(t.state),u=[...getProxyInputRequests(t.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(s)&&hasProxyInputRequests(t.state)&&!u)){let t=e.sessionWritable.getWriter();try{let e=await withContextScope(n,s,async e=>{let baseEmit=async e=>{let a=await publishChannelEvent({adapter:r,adapterCtx:i,ctx:n,writer:t,event:e,deliveryIds:n.get(TurnDeliveryIdsKey)});observeSessionActivity({ctx:n,event:a,sessionId:s.sessionId})},a=c?.createHandleEvent({handleEvent:baseEmit,turnId:activeTurnId(l)})??baseEmit;return{result:await emitCancelledTurn(a,l),session:e}});l=e.result,s=e.session}finally{await c?.flush(),t.releaseLock()}}let d=getPendingCoordinationBatch(s.state)?.event.turnId??e.sessionState.emissionState.turnId,f=getBlockingWorkflowToolRuns(s.state,d);s=abandonAgentInvocationOwners(s,new Set(f.map(e=>e.address.runId)));let p=reconcileSessionContinuationToken(n,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingCoordinationBatch(removeBlockingWorkflowToolRuns(abandonRunningAgentTurns({...s,outputSchema:void 0}),d)))),l)),m=getTurnUsageState(s.state)?.session,h={serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:p})};return m===void 0?h:{...h,usage:toUsage(m)}}export{settleCancelledTurnStep};
@@ -1 +1 @@
1
- import{createEveTaskInputRoutePath}from"#protocol/routes.js";import{createLogger}from"#internal/logging.js";import{isInputRequest}from"#shared/input.js";import{contextStorage}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getBackgroundTasks,recordWorkflowTaskView}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{clearProxyInputRequestsForTask,createTaskInputRequestId,upsertProxyInputRequestState}from"#harness/proxy-input-requests.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{createRemoteTaskInputCallbackUrl}from"#execution/workflow-callback-url.js";import{submitActivity}from"#execution/submit-activity.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{createTaskInputCapabilityToken}from"#execution/task-input-capability.js";import{projectTaskActivity}from"#execution/tasks/child/notify.js";const log=createLogger(`execution.tasks.parent`);async function recordTaskInputRequestStep(e){"use step";let t=readDurableSession(e.sessionState),n=getBackgroundTasks(t.state).get(e.request.taskId),r=e.request.requests??[e.request.request];if(n?.status!==`working`||r.length===0||!r.every(isInputRequest))return{accepted:!1,sessionState:e.sessionState};let i=r.map(t=>({...t,requestId:createTaskInputRequestId(e.request.taskId,t.requestId)})),a=getAgentHandleStore(t.state)?.handles.find(t=>t.phase===`claimed`&&t.ownerId===e.request.taskId),o=a?.phase===`claimed`&&a.address.kind===`agent/remote`?createRemoteTaskInputCallbackUrl(a.address.url,createEveTaskInputRoutePath(createTaskInputCapabilityToken(e.request.replyTo))):void 0,s=r.map((t,n)=>{let r=i[n],a={childContinuationToken:e.request.replyTo,childRequestId:t.requestId,kind:t.kind,taskId:e.request.taskId};return o!==void 0&&(a.childResponseUrl=o),[r.requestId,a]}),c=upsertProxyInputRequestState({entries:s,forChildContinuationToken:e.request.replyTo,state:t.state});return{accepted:!0,request:e.request.requests===void 0?{...e.request,request:i[0]}:{...e.request,request:void 0,requests:i},sessionState:replaceDurableSessionSnapshot({session:{...t,state:c},state:e.sessionState})}}async function recordTerminalTaskViewsStep(e){"use step";let t=readDurableSession(e.sessionState),n=t,r=[],i=[],a=[];for(let t of e.views){let e=getBackgroundTasks(n.state).get(t.taskId)?.run;if(e===void 0)continue;let o=recordWorkflowTaskView(n.state,t);n={...n,state:o.state},o.firstOutcome&&o.view.metadata.kind===`subagent`&&o.view.status===`completed`&&a.push({type:`subagent.completed`,data:{callId:e.callId,subagentName:e.toolName,output:typeof o.view.lastOutput.data==`string`?o.view.lastOutput.data:JSON.stringify(o.view.lastOutput.data)}}),r.push(o.view),o.firstOutcome&&i.push(o.view),n=clearProxyInputRequestsForTask(n,t.taskId),n=applyTaskAgentHandleCommand(n,{kind:`release-owner`,ownerId:t.taskId}).session}return{serializedContext:await settleBackgroundTaskActions({serializedContext:e.serializedContext,session:n,views:r}),sessionState:n===t?e.sessionState:replaceDurableSessionSnapshot({session:n,state:e.sessionState}),views:i,subagentCompletions:a}}async function settleBackgroundTaskActions(e){if(e.views.length===0)return e.serializedContext;try{let t=await deserializeContext(e.serializedContext),n=t.get(ActivityObserverKey),r=new Date().toISOString(),i=getBackgroundTasks(e.session.state),a=e.views.flatMap(e=>{let t=i.get(e.taskId)?.run;return projectTaskActivity({activityObserver:n===void 0?void 0:{sink:n.sink,workIdentity:t?.task.activityWorkIdentity},settledAt:r,view:e})});await submitActivity({events:a,sink:n?.sink});let o=t.get(BundleKey);if(o===void 0)return e.serializedContext;let s=bindSessionInstrumentation({agentName:o.turnAgent.id,ctx:t,rootSessionId:e.session.rootSessionId??e.session.sessionId,sessionId:e.session.sessionId});if(s===void 0)return e.serializedContext;try{await contextStorage.run(t,()=>s.publishBackgroundTaskSettlements({acceptedAtMs:Date.now(),views:e.views}))}finally{await s.flush()}return serializeContext(t)}catch(t){return log.warn(`failed to settle background task instrumentation`,{error:t,sessionId:e.session.sessionId,taskIds:e.views.map(e=>e.taskId)}),e.serializedContext}}export{recordTaskInputRequestStep,recordTerminalTaskViewsStep};
1
+ import{createEveTaskInputRoutePath}from"#protocol/routes.js";import{createLogger}from"#internal/logging.js";import{isInputRequest}from"#shared/input.js";import{contextStorage}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getBackgroundTasks,recordWorkflowTaskView}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{clearProxyInputRequestsForTask,createTaskInputRequestId,upsertProxyInputRequestState}from"#harness/proxy-input-requests.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{createRemoteTaskInputCallbackUrl}from"#execution/workflow-callback-url.js";import{submitActivity}from"#execution/submit-activity.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{createTaskInputCapabilityToken}from"#execution/task-input-capability.js";import{projectTaskActivity}from"#execution/tasks/child/notify.js";const log=createLogger(`execution.tasks.parent`);async function recordTaskInputRequestStep(e){"use step";let t=readDurableSession(e.sessionState),n=getBackgroundTasks(t.state).get(e.request.taskId),r=e.request.requests??[e.request.request];if(n?.status!==`working`||r.length===0||!r.every(isInputRequest))return{accepted:!1,sessionState:e.sessionState};let i=r.map(t=>({...t,requestId:createTaskInputRequestId(e.request.taskId,t.requestId)})),a=getAgentHandleStore(t.state)?.handles.find(t=>t.phase===`claimed`&&t.ownerId===e.request.taskId),o=a?.phase===`claimed`&&a.address.kind===`agent/remote`?createRemoteTaskInputCallbackUrl(a.address.url,createEveTaskInputRoutePath(createTaskInputCapabilityToken(e.request.replyTo))):void 0,s=r.map((t,n)=>{let r=i[n],a={childContinuationToken:e.request.replyTo,childRequestId:t.requestId,kind:t.kind,taskId:e.request.taskId};return t.kind===`question`&&(a.question={...t.allowFreeform!==void 0&&{allowFreeform:t.allowFreeform},...t.options!==void 0&&{options:[...t.options]}}),o!==void 0&&(a.childResponseUrl=o),[r.requestId,a]}),c=upsertProxyInputRequestState({entries:s,forChildContinuationToken:e.request.replyTo,state:t.state});return{accepted:!0,request:e.request.requests===void 0?{...e.request,request:i[0]}:{...e.request,request:void 0,requests:i},sessionState:replaceDurableSessionSnapshot({session:{...t,state:c},state:e.sessionState})}}async function recordTerminalTaskViewsStep(e){"use step";let t=readDurableSession(e.sessionState),n=t,r=[],i=[],a=[];for(let t of e.views){let e=getBackgroundTasks(n.state).get(t.taskId)?.run;if(e===void 0)continue;let o=recordWorkflowTaskView(n.state,t);n={...n,state:o.state},o.firstOutcome&&o.view.metadata.kind===`subagent`&&o.view.status===`completed`&&a.push({type:`subagent.completed`,data:{callId:e.callId,subagentName:e.toolName,output:typeof o.view.lastOutput.data==`string`?o.view.lastOutput.data:JSON.stringify(o.view.lastOutput.data)}}),r.push(o.view),o.firstOutcome&&i.push(o.view),n=clearProxyInputRequestsForTask(n,t.taskId),n=applyTaskAgentHandleCommand(n,{kind:`release-owner`,ownerId:t.taskId}).session}return{serializedContext:await settleBackgroundTaskActions({serializedContext:e.serializedContext,session:n,views:r}),sessionState:n===t?e.sessionState:replaceDurableSessionSnapshot({session:n,state:e.sessionState}),views:i,subagentCompletions:a}}async function settleBackgroundTaskActions(e){if(e.views.length===0)return e.serializedContext;try{let t=await deserializeContext(e.serializedContext),n=t.get(ActivityObserverKey),r=new Date().toISOString(),i=getBackgroundTasks(e.session.state),a=e.views.flatMap(e=>{let t=i.get(e.taskId)?.run;return projectTaskActivity({activityObserver:n===void 0?void 0:{sink:n.sink,workIdentity:t?.task.activityWorkIdentity},settledAt:r,view:e})});await submitActivity({events:a,sink:n?.sink});let o=t.get(BundleKey);if(o===void 0)return e.serializedContext;let s=bindSessionInstrumentation({agentName:o.turnAgent.id,ctx:t,rootSessionId:e.session.rootSessionId??e.session.sessionId,sessionId:e.session.sessionId});if(s===void 0)return e.serializedContext;try{await contextStorage.run(t,()=>s.publishBackgroundTaskSettlements({acceptedAtMs:Date.now(),views:e.views}))}finally{await s.flush()}return serializeContext(t)}catch(t){return log.warn(`failed to settle background task instrumentation`,{error:t,sessionId:e.session.sessionId,taskIds:e.views.map(e=>e.taskId)}),e.serializedContext}}export{recordTaskInputRequestStep,recordTerminalTaskViewsStep};
@@ -1 +1 @@
1
- import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,e.outputSchema===void 0?{message:e.message}:{message:e.message,outputSchema:e.outputSchema})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.66.3//executeAgentRouterTool`;export{executeAgentRouterTool};
1
+ import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,{message:e.message})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.67.0//executeAgentRouterTool`;export{executeAgentRouterTool};
@@ -1,8 +1,6 @@
1
- import type { JsonObject } from "#shared/json.js";
2
1
  export { executeAgentRouterTool } from "#execution/tools/agent-router-workflow.js";
3
2
  export declare const AGENT_ROUTER_TOOL_DESCRIPTION = "Route a task to the best available subagent based on each subagent's declared description.";
4
3
  export interface AgentRouterInput {
5
4
  readonly message: string;
6
- readonly outputSchema?: JsonObject;
7
5
  }
8
6
  export declare const AGENT_ROUTER_INPUT_SCHEMA: import("#tools/schema.js").ToolSchema<AgentRouterInput, AgentRouterInput>;
@@ -1 +1 @@
1
- import{defineJsonSchema}from"#tools/schema.js";import{executeAgentRouterTool}from"#execution/tools/agent-router-workflow.js";const AGENT_ROUTER_TOOL_DESCRIPTION=`Route a task to the best available subagent based on each subagent's declared description.`,AGENT_ROUTER_INPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{message:{type:`string`,minLength:1,description:`The complete task to send to the selected agent.`},outputSchema:{type:`object`,description:`Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The selected agent must match a provided schema, and that structured output becomes the tool result.`}},required:[`message`],additionalProperties:!1});export{AGENT_ROUTER_INPUT_SCHEMA,AGENT_ROUTER_TOOL_DESCRIPTION,executeAgentRouterTool};
1
+ import{defineJsonSchema}from"#tools/schema.js";import{executeAgentRouterTool}from"#execution/tools/agent-router-workflow.js";const AGENT_ROUTER_TOOL_DESCRIPTION=`Route a task to the best available subagent based on each subagent's declared description.`,AGENT_ROUTER_INPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{message:{type:`string`,minLength:1,description:`The complete task to send to the selected agent.`}},required:[`message`],additionalProperties:!1});export{AGENT_ROUTER_INPUT_SCHEMA,AGENT_ROUTER_TOOL_DESCRIPTION,executeAgentRouterTool};
@@ -1 +1 @@
1
- async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,dismissible:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){return e.status===`answered`?{answer:e.optionId??e.text??``,status:`answered`}:{status:e.status}}executeAskQuestionTool.workflowId=`workflow//eve@0.66.3//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
1
+ async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,dismissible:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){return e.status===`answered`?{answer:e.optionId??e.text??``,status:`answered`}:{status:e.status}}executeAskQuestionTool.workflowId=`workflow//eve@0.67.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
@@ -1 +1,2 @@
1
+ export declare function connectionToolReplayIdentity(toolName: string): string | undefined;
1
2
  export declare function resolveConnectionSearchDynamicTools(): Promise<Record<string, object> | null>;
@@ -1,2 +1,2 @@
1
1
  import{createLogger}from"#internal/logging.js";import{loadContext}from"#context/container.js";import{toError}from"#shared/errors.js";import{defineJsonSchema}from"#tools/schema.js";import{defineTool}from"#tools/definition.js";import{stampDurableDynamicToolCallbacks}from"#tools/durable-callbacks.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{getAuthorizationResults,requestAuthorization}from"#harness/authorization.js";import{createAuthorizationExecution}from"#runtime/connections/scoped-authorization.js";import{isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=defineJsonSchema({type:`object`,properties:{connection:{type:`string`,description:`Optional: limit search to a specific connection name.`},keywords:{type:`string`,description:`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`},limit:{type:`number`,description:`Max results to return. Default 10.`}},required:[`keywords`],additionalProperties:!1}),CONNECTION_SEARCH_OUTPUT_SCHEMA=defineJsonSchema({type:`array`,items:{type:`object`,properties:{connection:{type:`string`},description:{type:`string`},error:{type:`string`},inputSchema:{type:`object`},needsAuthorization:{type:`boolean`},outputSchema:{type:`object`},qualifiedName:{type:`string`},tool:{type:`string`}},required:[`connection`,`description`],additionalProperties:!1}}),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(r!==void 0&&supportsInteractiveAuthorization(r))return{scope:n.connectionName,instanceId:n.instanceId,connection:{url:n.url??``},authorization:r}}async function completePendingAuthorizations(e,t,n){assertPendingConnectionAuthorizationInstances(e);for(let r of t){if(!getAuthorizationResults().some(e=>e.name===r.connectionName))continue;let t=await resolveInteractiveAuth(e,r.connectionName);t!==void 0&&await n.complete(t)}}async function executeConnectionSearch(e){let t=loadContext(),n=t.get(ConnectionRegistryKey);if(n===void 0)return[];let r=e.limit??10,i=tokenize(e.keywords),a=[],o=[],s=e.connection!==void 0&&e.connection!==``?n.getConnections().filter(t=>t.connectionName===e.connection):n.getConnections();if(e.connection&&s.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${n.getConnectionNames().join(`, `)}.`);let c=createAuthorizationExecution();await completePendingAuthorizations(n,s,c);let l=[];for(let e of s){let t;try{t=await n.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){let r=await resolveInteractiveAuth(n,e.connectionName);if(r!==void 0)try{let e=await c.handleError(t,r);l.push(...e.challenges)}catch(t){let n=toError(t);logger.warn(`connection authorization failed`,{connection:e.connectionName,error:n}),o.push({connection:e.connectionName,description:e.description,error:isConnectionAuthorizationFailedError(n)?n.message:`Failed to start authorization for "${e.connectionName}": ${n.message}`});continue}o.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),o.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),o.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(i,n);t>0&&a.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(l.length>0)return requestAuthorization(l);let u=o.filter(e=>e.error!==void 0);if(s.length>0&&u.length===s.length)throw Error(u.map(e=>e.error).join(`
2
- `));a.sort((e,t)=>t.score-e.score);let d=a.slice(0,r).map(e=>e.item);if(d.length>0){let e=[...d,...o],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of d)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return s.map(e=>o.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:r,toolName:i}=readDiscoveredToolClosure(e),a=loadContext().get(ConnectionRegistryKey);if(a===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);assertPendingConnectionAuthorizationInstances(a);let o=await resolveInteractiveAuth(a,r),s=createAuthorizationExecution();o!==void 0&&await s.complete(o);try{return await a.getClient(r).executeTool(i,t,{abortSignal:n.abortSignal,callId:n.callId})}catch(e){return await s.handleError(e,o)}}function assertPendingConnectionAuthorizationInstances(e){let t=new Map(e.getConnections().map(e=>[e.connectionName,e]));for(let e of getAuthorizationResults())if(e.instanceId!==void 0&&t.get(e.name)?.instanceId!==e.instanceId)throw Error(`Authorization for "${e.name}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`)}async function requestDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n);return r===void 0?`not-applicable`:await resolveApprovalPolicy(r)(t)}async function authorizeDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n),i=r===void 0||typeof r==`function`?void 0:r.response;return i===void 0?{reason:`Approval response authorization is unavailable.`,status:`rejected`}:await i(t)}async function resolveConnectionSearchDynamicTools(){let e=loadContext().get(ConnectionRegistryKey);if(!e||e.getConnections().length===0)return null;let t=e.getConnections().map(e=>e.connectionName),n=new Set(t),r=(loadContext().get(ConnectionSearchResultsKey)??[]).filter(e=>n.has(e.connection)),i={},a=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${t.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});stampDurableDynamicToolCallbacks(a,{inputSchema:{callback:()=>CONNECTION_SEARCH_INPUT_SCHEMA,closure:{}},outputSchema:{callback:()=>CONNECTION_SEARCH_OUTPUT_SCHEMA,closure:{}},execute:{callback:(e,t)=>executeConnectionSearch(t),closure:{}}}),i.connection_search=a;for(let t of r){let n=t.connection,r=t.tool,a=e.getConnectionApproval(n),o={connectionName:n,toolName:r},s=defineTool({description:t.description,inputSchema:t.inputSchema??{type:`object`},approval:a,outputSchema:t.outputSchema,async execute(e,t){return await executeDiscoveredConnectionTool(o,e,t)}});stampDurableDynamicToolCallbacks(s,{execute:{callback:executeDiscoveredConnectionTool,closure:o},...a===void 0?{}:{approvalRequest:{callback:requestDiscoveredConnectionToolApproval,closure:o}},...a===void 0||typeof a==`function`||a.response===void 0?{}:{approvalResponse:{callback:authorizeDiscoveredConnectionToolApproval,closure:o}}}),i[qualifiedConnectionToolName(n,r)]=s}return i}export{resolveConnectionSearchDynamicTools};
2
+ `));a.sort((e,t)=>t.score-e.score);let d=a.slice(0,r).map(e=>e.item);if(d.length>0){let e=[...d,...o],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of d)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return s.map(e=>o.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function connectionToolReplayIdentity(e){let t=loadContext(),n=t.get(ConnectionSearchResultsKey)?.find(t=>t.qualifiedName===e);if(n!==void 0)return t.get(ConnectionRegistryKey)?.getConnections().find(e=>e.connectionName===n.connection)?.instanceId}function assertConnectionToolInstance(e){if(typeof e.instanceId!=`string`)return;let{connectionName:t}=readDiscoveredToolClosure(e);if(loadContext().get(ConnectionRegistryKey)?.getConnections().find(e=>e.connectionName===t)?.instanceId!==e.instanceId)throw Error(`The connection for this tool call changed or is unavailable. Request a new tool call and approval.`)}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:r,toolName:i}=readDiscoveredToolClosure(e),a=loadContext().get(ConnectionRegistryKey);if(a===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);assertConnectionToolInstance(e),assertPendingConnectionAuthorizationInstances(a);let o=await resolveInteractiveAuth(a,r),s=createAuthorizationExecution();o!==void 0&&await s.complete(o);try{return await a.getClient(r).executeTool(i,t,{abortSignal:n.abortSignal,callId:n.callId})}catch(e){return await s.handleError(e,o)}}function assertPendingConnectionAuthorizationInstances(e){let t=new Map(e.getConnections().map(e=>[e.connectionName,e]));for(let e of getAuthorizationResults())if(e.instanceId!==void 0&&t.get(e.name)?.instanceId!==e.instanceId)throw Error(`Authorization for "${e.name}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`)}async function requestDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e);assertConnectionToolInstance(e);let r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n);return r===void 0?`not-applicable`:await resolveApprovalPolicy(r)(t)}async function authorizeDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e);assertConnectionToolInstance(e);let r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n),i=r===void 0||typeof r==`function`?void 0:r.response;return i===void 0?{reason:`Approval response authorization is unavailable.`,status:`rejected`}:await i(t)}async function resolveConnectionSearchDynamicTools(){let e=loadContext().get(ConnectionRegistryKey);if(!e||e.getConnections().length===0)return null;let t=e.getConnections(),n=t.map(e=>e.connectionName),r=new Set(n),i=(loadContext().get(ConnectionSearchResultsKey)??[]).filter(e=>r.has(e.connection)),a={},o=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${n.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});stampDurableDynamicToolCallbacks(o,{inputSchema:{callback:()=>CONNECTION_SEARCH_INPUT_SCHEMA,closure:{}},outputSchema:{callback:()=>CONNECTION_SEARCH_OUTPUT_SCHEMA,closure:{}},execute:{callback:(e,t)=>executeConnectionSearch(t),closure:{}}}),a.connection_search=o;for(let n of i){let r=n.connection,i=n.tool,o=e.getConnectionApproval(r),s=t.find(e=>e.connectionName===r)?.instanceId,c={connectionName:r,toolName:i};s!==void 0&&(c.instanceId=s);let l=defineTool({description:n.description,inputSchema:n.inputSchema??{type:`object`},approval:o,outputSchema:n.outputSchema,async execute(e,t){return await executeDiscoveredConnectionTool(c,e,t)}});stampDurableDynamicToolCallbacks(l,{execute:{callback:executeDiscoveredConnectionTool,closure:c},...o===void 0?{}:{approvalRequest:{callback:requestDiscoveredConnectionToolApproval,closure:c}},...o===void 0||typeof o==`function`||o.response===void 0?{}:{approvalResponse:{callback:authorizeDiscoveredConnectionToolApproval,closure:c}}}),a[qualifiedConnectionToolName(r,i)]=l}return a}export{connectionToolReplayIdentity,resolveConnectionSearchDynamicTools};
@@ -1 +1 @@
1
- import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.66.3//executeSleepTool`;export{executeSleepTool};
1
+ import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.67.0//executeSleepTool`;export{executeSleepTool};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{activeTurnId}from"#harness/active-turn-id.js";import{prepareActionDispatch}from"#execution/coordination-dispatch-shared.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";import{isAgentHandleAction}from"#subagents/handle-dispatch.js";import{createRecursiveAgentRootOnlyResult,createUnavailableDynamicSubagentResult,getSubagentName}from"#execution/dispatch-action-failures.js";const log=createLogger(`execution.agent-invocation`);async function prepareOwnerAgentInvocation(e){let t=readDurableSession(e.sessionState),n=await deserializeContext(e.serializedContext),r=getHarnessEmissionState(t.state),i=e.taskId===void 0?void 0:getBackgroundTasks(t.state).get(e.taskId)?.run,a=resolveAgentInvocationAction({ctx:n,input:e.invocation,invocationId:e.invocationId});return await prepareActionDispatch({batch:{requests:[a],event:{...r,stepIndex:i?.origin.stepIndex??r.stepIndex,turnId:i?.origin.turnId??activeTurnId(r)}},ctx:n,durableSession:t,fanoutSize:1,plan:({bundle:t,ctx:n,session:r})=>[planAgentDispatch({action:a,bundle:t,ctx:n,knownAgentIds:e.knownAgentIds,session:r})],planReusesOwnerSandbox:({bundle:e,plan:t})=>ownerPlanReusesSandbox({bundle:e,plan:t}),serializedContext:e.serializedContext})}function planAgentDispatch(e){let t=new Set(e.knownAgentIds??(getAgentHandleStore(e.session.state)?.handles??[]).map(e=>e.identity.id)),n=e.action.input.agentId,r=typeof n==`string`&&n.trim()!==``?n:void 0;if(r!==void 0&&isAgentHandleAction(e.action)){if(t.has(r)){let t=e.bundle.subagentRegistry.dynamicNodeIds?.has(e.action.nodeId)===!0?getDynamicSubagentSelection(e.ctx,e.action.nodeId):void 0;return{action:e.action,agentId:r,dynamicRemoteAgent:e.action.kind===`remote-agent-call`&&t?.kind===`remote`?t.remoteAgent:void 0,kind:`resume`}}log.warn(`unknown agentId on subagent call; starting a new agent`,{agentId:r,callId:e.action.callId})}return classifyFreshStart(e)}function classifyFreshStart(e){let{action:t}=e,n=e.bundle.subagentRegistry.subagentsByNodeId,r=e.bundle.subagentRegistry.dynamicNodeIds?.has(t.nodeId)===!0,i=r?getDynamicSubagentSelection(e.ctx,t.nodeId):void 0;if(r&&(i===void 0||t.kind===`subagent-call`&&i.kind!==`subagent`||t.kind===`remote-agent-call`&&i.kind!==`remote`))return log.warn(`dynamic subagent call blocked after availability changed`,{callId:t.callId,nodeId:t.nodeId,subagentName:getSubagentName(t)}),{kind:`reject`,result:createUnavailableDynamicSubagentResult(t)};if(isRecursiveAgentAction(t,n)&&e.session.rootSessionId!==void 0)return log.warn(`recursive agent call blocked outside the root session`,{callId:t.callId,nodeId:t.nodeId,rootSessionId:e.session.rootSessionId,subagentName:t.subagentName}),{kind:`reject`,result:createRecursiveAgentRootOnlyResult(t)};if(t.kind===`remote-agent-call`)return{kind:`start`,target:{action:t,dynamicRemoteAgent:i?.kind===`remote`?i.remoteAgent:void 0,kind:`remote`}};let a=i?.kind===`subagent`?i.agentConfig:void 0,o=n.get(t.nodeId),s=a?.description??(o?.definition.kind===`subagent`?o.definition.description:void 0);return{kind:`start`,target:{action:t,dynamicSubagentAgentConfig:a,kind:`local`,source:s===void 0?{outputSchema:e.bundle.turnAgent.outputSchema,type:`runtime`}:{description:s,outputSchema:a?.outputSchema??e.bundle.graph?.nodesByNodeId.get(t.nodeId)?.turnAgent?.outputSchema,type:`local`}}}}function ownerPlanReusesSandbox(e){return e.plan.some(t=>{if(t.kind!==`start`||t.target.kind!==`local`)return!1;let n=t.target.action;return n.subagentName===`agent`&&!e.bundle.subagentRegistry.subagentsByNodeId.has(n.nodeId)||e.bundle.graph?.nodesByNodeId.get(n.nodeId)?.sandboxRegistry.sandbox.definition.kind===`parent`})}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}function resolveAgentInvocationAction(e){let t=e.ctx.require(BundleKey),n=t.subagentRegistry.subagentsByName.get(e.input.target),r=n===void 0?Object.values({...e.ctx.get(SessionDynamicSubagentSelectionsKey),...e.ctx.get(TurnDynamicSubagentSelectionsKey)}).find(t=>t!==null&&t.prepared?.name===e.input.target):void 0,i=n?.definition??r?.prepared??(e.input.target===AGENT_TOOL_NAME&&t.nodeId===void 0?{description:AGENT_TOOL_DESCRIPTION,kind:`subagent`,name:AGENT_TOOL_NAME,nodeId:ROOT_RUNTIME_AGENT_NODE_ID}:void 0);if(i===void 0)throw Error(`Agent target "${e.input.target}" is not available to this agent.`);let a={message:e.input.message};e.input.agentId!==void 0&&(a.agentId=e.input.agentId),e.input.outputSchema!==void 0&&(a.outputSchema=e.input.outputSchema);let o={callId:e.invocationId,description:i.description??``,input:a,name:i.name,nodeId:i.nodeId};return i.kind===`remote`?{...o,kind:`remote-agent-call`,remoteAgentName:i.name}:{...o,kind:`subagent-call`,subagentName:i.name}}export{planAgentDispatch,prepareOwnerAgentInvocation,resolveAgentInvocationAction};
1
+ import{createLogger}from"#internal/logging.js";import{SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{activeTurnId}from"#harness/active-turn-id.js";import{prepareActionDispatch}from"#execution/coordination-dispatch-shared.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME}from"#tools/framework/agent-contract.js";import{isAgentHandleAction}from"#subagents/handle-dispatch.js";import{createRecursiveAgentRootOnlyResult,createUnavailableDynamicSubagentResult,getSubagentName}from"#execution/dispatch-action-failures.js";const log=createLogger(`execution.agent-invocation`);async function prepareOwnerAgentInvocation(e){let t=readDurableSession(e.sessionState),n=await deserializeContext(e.serializedContext),r=getHarnessEmissionState(t.state),i=e.taskId===void 0?void 0:getBackgroundTasks(t.state).get(e.taskId)?.run,a=resolveAgentInvocationAction({ctx:n,input:e.invocation,invocationId:e.invocationId});return await prepareActionDispatch({batch:{requests:[a],event:{...r,stepIndex:i?.origin.stepIndex??r.stepIndex,turnId:i?.origin.turnId??activeTurnId(r)}},ctx:n,durableSession:t,fanoutSize:1,plan:({bundle:t,ctx:n,session:r})=>[planAgentDispatch({action:a,bundle:t,ctx:n,knownAgentIds:e.knownAgentIds,session:r})],planReusesOwnerSandbox:({bundle:e,plan:t})=>ownerPlanReusesSandbox({bundle:e,plan:t}),serializedContext:e.serializedContext})}function planAgentDispatch(e){let t=new Set(e.knownAgentIds??(getAgentHandleStore(e.session.state)?.handles??[]).map(e=>e.identity.id)),n=e.action.input.agentId,r=typeof n==`string`&&n.trim()!==``?n:void 0;if(r!==void 0&&isAgentHandleAction(e.action)){if(t.has(r)){let t=e.bundle.subagentRegistry.dynamicNodeIds?.has(e.action.nodeId)===!0?getDynamicSubagentSelection(e.ctx,e.action.nodeId):void 0;return{action:e.action,agentId:r,dynamicRemoteAgent:e.action.kind===`remote-agent-call`&&t?.kind===`remote`?t.remoteAgent:void 0,kind:`resume`}}log.warn(`unknown agentId on subagent call; starting a new agent`,{agentId:r,callId:e.action.callId})}return classifyFreshStart(e)}function classifyFreshStart(e){let{action:t}=e,n=e.bundle.subagentRegistry.subagentsByNodeId,r=e.bundle.subagentRegistry.dynamicNodeIds?.has(t.nodeId)===!0,i=r?getDynamicSubagentSelection(e.ctx,t.nodeId):void 0;if(r&&(i===void 0||t.kind===`subagent-call`&&i.kind!==`subagent`||t.kind===`remote-agent-call`&&i.kind!==`remote`))return log.warn(`dynamic subagent call blocked after availability changed`,{callId:t.callId,nodeId:t.nodeId,subagentName:getSubagentName(t)}),{kind:`reject`,result:createUnavailableDynamicSubagentResult(t)};if(isRecursiveAgentAction(t,n)&&e.session.rootSessionId!==void 0)return log.warn(`recursive agent call blocked outside the root session`,{callId:t.callId,nodeId:t.nodeId,rootSessionId:e.session.rootSessionId,subagentName:t.subagentName}),{kind:`reject`,result:createRecursiveAgentRootOnlyResult(t)};if(t.kind===`remote-agent-call`)return{kind:`start`,target:{action:t,dynamicRemoteAgent:i?.kind===`remote`?i.remoteAgent:void 0,kind:`remote`}};let a=i?.kind===`subagent`?i.agentConfig:void 0,o=n.get(t.nodeId),s=a?.description??(o?.definition.kind===`subagent`?o.definition.description:void 0);return{kind:`start`,target:{action:t,dynamicSubagentAgentConfig:a,kind:`local`,source:s===void 0?{type:`runtime`}:{description:s,type:`local`}}}}function ownerPlanReusesSandbox(e){return e.plan.some(t=>{if(t.kind!==`start`||t.target.kind!==`local`)return!1;let n=t.target.action;return n.subagentName===`agent`&&!e.bundle.subagentRegistry.subagentsByNodeId.has(n.nodeId)||e.bundle.graph?.nodesByNodeId.get(n.nodeId)?.sandboxRegistry.sandbox.definition.kind===`parent`})}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}function resolveAgentInvocationAction(e){let t=e.ctx.require(BundleKey),n=t.subagentRegistry.subagentsByName.get(e.input.target),r=n===void 0?Object.values({...e.ctx.get(SessionDynamicSubagentSelectionsKey),...e.ctx.get(TurnDynamicSubagentSelectionsKey)}).find(t=>t!==null&&t.prepared?.name===e.input.target):void 0,i=n?.definition??r?.prepared??(e.input.target===AGENT_TOOL_NAME&&t.nodeId===void 0?{description:AGENT_TOOL_DESCRIPTION,kind:`subagent`,name:AGENT_TOOL_NAME,nodeId:ROOT_RUNTIME_AGENT_NODE_ID}:void 0);if(i===void 0)throw Error(`Agent target "${e.input.target}" is not available to this agent.`);let a={message:e.input.message};e.input.agentId!==void 0&&(a.agentId=e.input.agentId),e.input.outputSchema!==void 0&&(a.outputSchema=e.input.outputSchema);let o={callId:e.invocationId,description:i.description??``,input:a,name:i.name,nodeId:i.nodeId};return i.kind===`remote`?{...o,kind:`remote-agent-call`,remoteAgentName:i.name}:{...o,kind:`subagent-call`,subagentName:i.name}}export{planAgentDispatch,prepareOwnerAgentInvocation,resolveAgentInvocationAction};
@@ -1 +1 @@
1
- import"../extension.js";import{ConnectError,ConnectorInstallationRequiredError,getToken}from"../../../../node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/token.js";import"../../../../node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/index.js";import{authenticateVercel}from"./credentials.js";async function authenticateTurn(e,t,n=getToken){if(e.vercel===void 0)return;let r=await t(),i=await resolveToken(e.vercel.connector,{subject:{type:`app`}},n);await authenticateVercel(r,{token:i,delivery:e.vercel.delivery,broker:e.broker})}async function resolveToken(e,t,n){try{let r=await n(e,t);if(r.length===0)throw Error(`Connect returned an empty token`);return r}catch(t){let n=t instanceof ConnectorInstallationRequiredError?`connector installation is required`:t instanceof ConnectError?`Connect rejected the token request`:`Connect token request failed`,r=t instanceof Error?t.message:String(t);throw Error(`${n} for ${JSON.stringify(e)}: ${r}`,{cause:t})}}export{authenticateTurn};
1
+ import"../extension.js";import{ConnectError,ConnectorInstallationRequiredError,getToken}from"../../../../node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/token.js";import"../../../../node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/index.js";import{authenticateVercel}from"./credentials.js";async function authenticateTurn(e,t,n=getToken){if(e.vercel===void 0)return;let r=await t(),i=await resolveToken(e.vercel.connector,{subject:{type:`app`}},n);await authenticateVercel(r,{token:i,delivery:e.vercel.delivery,broker:e.broker})}async function resolveToken(e,t,n){try{let r=await n(e,t);if(r.length===0)throw Error(`Connect returned an empty token`);return r}catch(t){let n=t instanceof ConnectorInstallationRequiredError?`connector installation is required`:t instanceof ConnectError?`Connect rejected the token request`:`Connect token request failed`,r=t instanceof Error?t.message:String(t);throw Error(`${n} for ${JSON.stringify(e)}: ${r}`,{cause:t})}}export{authenticateTurn};
@@ -1 +1 @@
1
- import{getToken}from"../../../../node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/token.js";import"../../../../node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/index.js";import{shellQuote}from"./shell.js";import{toolingPaths}from"./tooling.js";import{validateRepositoryRoot}from"./repository-root.js";import{posix}from"node:path";const MAX_OUTPUT_BYTES=1e5,leaseQueues=new Map,ALLOWED_GIT_REMOTE_COMMANDS=new Set([`fetch`,`ls-remote`,`pull`,`push`]);function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let r=validateGitHubShellInput(e),i=await n.getSandbox(),a=resolveWorkingDirectory(i,e.workingDirectory);(r[0]===`git`||r[0]===`gh-signed-commit`)&&(a=await validateRepositoryRoot(i,a));let o=e.permissions[0].repositories,s=await assertCommandTargets(r,o,a,i),c=repositoryNames(o,t.org),l={authorizationDetails:[{type:`github_app_installation`,org:t.org,repositories:c}],subject:{type:`app`}},u=await(n.getConnectToken??getToken)(t.connector,l);if(!u)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);let d=executablePath(r[0],i),f=s?[`-c`,`protocol.allow=never`,`-c`,`protocol.https.allow=always`,r[1],`https://github.com/${s}.git`,...r.slice(3)]:r.slice(1),p=`cd ${shellQuote(a)} && exec ${shellQuote(d)} ${f.map(shellQuote).join(` `)}`,m=`Basic ${Buffer.from(`x-access-token:${u}`).toString(`base64`)}`,h=crypto.randomUUID(),g=`eve-github-${h}`,_=`/tmp/eve-code-gh-${h}`,v=`Basic ${Buffer.from(`x-access-token:${g}`).toString(`base64`)}`,y;try{y=await withGitHubCredentialLease(i,n.sessionId,{authorization:m,placeholder:g,placeholderAuthorization:v,token:u},()=>{let e={GH_CONFIG_DIR:_,GH_PROMPT_DISABLED:`1`};return r[0]!==`git`&&(e.GH_TOKEN=g),e.GIT_CONFIG_COUNT=`2`,e.GIT_CONFIG_KEY_0=`http.https://github.com/.extraheader`,e.GIT_CONFIG_VALUE_0=`Authorization: ${v}`,e.GIT_CONFIG_KEY_1=`core.hooksPath`,e.GIT_CONFIG_VALUE_1=`/dev/null`,e.GIT_TERMINAL_PROMPT=`0`,e.PATH=`/usr/local/bin:/usr/bin:/bin`,i.run({command:p,env:e})},t.broker)}finally{await i.removePath({path:_,recursive:!0,force:!0})}let b=sanitizeOutput(y.stdout,u,m),x=sanitizeOutput(y.stderr,u,m);return{exitCode:y.exitCode,stdout:b.value,stderr:x.value,truncated:b.truncated||x.truncated}}async function withGitHubCredentialLease(e,t,n,r,i){let a=leaseQueues.get(t)??Promise.resolve(),o,s=new Promise(e=>{o=e}),c=a.then(()=>s);leaseQueues.set(t,c),await a;try{return await i(e,{"api.github.com":[{match:{headers:[{key:{exact:`authorization`},value:{regex:`^(?:token|Bearer) ${n.placeholder}$`}}]},transform:[{headers:{authorization:`Bearer ${n.token}`}}]}],"github.com":[{match:{headers:[{key:{exact:`authorization`},value:{exact:n.placeholderAuthorization}}]},transform:[{headers:{authorization:n.authorization}}]}]}),await r()}finally{try{await i(e,null)}finally{o(),leaseQueues.get(t)===c&&leaseQueues.delete(t)}}}function parseCommand(e){let t=e.trim();if(!t)throw Error(`GitHub command must not be empty.`);let n=[],r=``,i=null,a=!1,o=!1;for(let e of t){if(a){r+=e,a=!1,o=!0;continue}if(e===`\\`&&i!==`single`){a=!0,o=!0;continue}if(i===`single`){e===`'`?i=null:r+=e;continue}if(i===`double`){if(e===`"`)i=null;else if(e===`$`||e==="`")throw unsupportedSyntax();else r+=e;continue}if(e===`'`)i=`single`,o=!0;else if(e===`"`)i=`double`,o=!0;else if(/\s/u.test(e))o&&=(n.push(r),r=``,!1);else if(";&|<>$`(){}".includes(e))throw unsupportedSyntax();else r+=e,o=!0}if(a||i)throw Error(`GitHub command contains an unfinished quote or escape.`);if(o&&n.push(r),n.length===0)throw Error(`GitHub command must not be empty.`);return n}function validateGitHubShellInput(e){let t=parseCommand(e.command),n=e.permissions[0];if(e.permissions.length!==1||n?.provider!==`github`)throw Error(`Exactly one GitHub permission is required.`);if(n.access!==`write`)throw Error(`GitHub App commands require explicit write-capable access.`);if(!e.description.trim())throw Error(`description must describe the intended result.`);let[r,i]=t;if(r===`gh`){if(!i)throw Error(`A gh subcommand is required.`)}else if(r===`git`){if(!i||!ALLOWED_GIT_REMOTE_COMMANDS.has(i))throw Error(`Authenticated git supports only fetch, ls-remote, pull, and push; clone with gh repo clone.`)}else if(r!==`gh-signed-commit`)throw Error(`GitHub commands must use gh, an authenticated git remote command, or gh-signed-commit.`);return t}async function assertCommandTargets(e,t,n,r){let i=new Set(t.map(e=>e.toLowerCase())),a,o;if(e[0]===`git`){if(e[2]!==`origin`)throw Error(`Authenticated git commands must use the validated origin remote.`);let t=e[1]===`push`,i=await r.run({command:`cd ${shellQuote(n)} && git remote get-url ${t?`--push `:``}origin`,env:{GIT_TERMINAL_PROMPT:`0`,PATH:`/usr/bin:/bin`}});if(i.exitCode!==0)throw Error(`Could not resolve the origin GitHub repository.`);a=repositoryFromRemote(i.stdout.trim()),o=[a]}else if(e[0]===`gh-signed-commit`){if(o=repoFlagTargets(e.slice(1)),o.length===0)throw Error(`gh-signed-commit requires an explicit --repo owner/repository target.`)}else o=repoFlagTargets(e.slice(1)),e[1]===`repo`&&(e[2]===`clone`||e[2]===`view`||e[2]===`fork`)&&e[3]&&!e[3].startsWith(`-`)&&o.push(canonicalRepository(e[3]));for(let e of o)if(!i.has(e.toLowerCase()))throw Error(`Command target ${JSON.stringify(e)} is not in the declared repositories.`);return a}function repoFlagTargets(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`--repo`||r===`-R`){let i=e[n+1];if(!i)throw Error(`${r} requires an owner/repository value.`);t.push(canonicalRepository(i)),n+=1}else r?.startsWith(`--repo=`)&&t.push(canonicalRepository(r.slice(7)))}return t}function repositoryFromRemote(e){let t=/^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(t?.[1])return canonicalRepository(t[1]);let n=/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(n?.[1])return canonicalRepository(n[1]);throw Error(`The origin remote is not a canonical GitHub repository URL.`)}function canonicalRepository(e){let t=e.replace(/\.git$/iu,``);if(!/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u.test(t))throw Error(`Invalid GitHub repository ${JSON.stringify(e)}.`);return t}function repositoryNames(e,t){if(e.length!==1)throw Error(`Exactly one GitHub repository is required.`);let n=new Set;for(let r of e){let e=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)$/u.exec(r);if(!e)throw Error(`Invalid GitHub repository ${JSON.stringify(r)}.`);if(e[1]?.toLowerCase()!==t.toLowerCase())throw Error(`Repository ${JSON.stringify(r)} is outside ${t}.`);n.add(e[2])}if(n.size!==1)throw Error(`Exactly one GitHub repository is required.`);return[...n]}function executablePath(e,t){return e===`gh`?toolingPaths(t).ghReal:e===`gh-signed-commit`?toolingPaths(t).trustedSignedCommit:`git`}function resolveWorkingDirectory(e,t){let n=posix.resolve(`/`,e.resolvePath(``)),r=posix.resolve(`/`,e.resolvePath(t?.trim()||``));if(r!==n&&!r.startsWith(`${n}/`))throw Error(`GitHub command workingDirectory must stay inside the sandbox workspace.`);return r}function sanitizeOutput(e,t,n){let r=e.replaceAll(t,`[redacted]`).replaceAll(n,`[redacted]`);return Buffer.byteLength(r)<=MAX_OUTPUT_BYTES?{value:r,truncated:!1}:{value:`[output truncated: showing final ${MAX_OUTPUT_BYTES} bytes]\n${Buffer.from(r).subarray(-1e5).toString()}`,truncated:!0}}function unsupportedSyntax(){return Error(`GitHub commands support argv syntax only, not pipes, redirects, substitutions, or shell operators.`)}export{executeGitHubShell,githubShellApproval,parseCommand};
1
+ import{getToken}from"../../../../node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/token.js";import"../../../../node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/index.js";import{shellQuote}from"./shell.js";import{toolingPaths}from"./tooling.js";import{validateRepositoryRoot}from"./repository-root.js";import{posix}from"node:path";const MAX_OUTPUT_BYTES=1e5,leaseQueues=new Map,ALLOWED_GIT_REMOTE_COMMANDS=new Set([`fetch`,`ls-remote`,`pull`,`push`]);function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let r=validateGitHubShellInput(e),i=await n.getSandbox(),a=resolveWorkingDirectory(i,e.workingDirectory);(r[0]===`git`||r[0]===`gh-signed-commit`)&&(a=await validateRepositoryRoot(i,a));let o=e.permissions[0].repositories,s=await assertCommandTargets(r,o,a,i),c=repositoryNames(o,t.org),l={authorizationDetails:[{type:`github_app_installation`,org:t.org,repositories:c}],subject:{type:`app`}},u=await(n.getConnectToken??getToken)(t.connector,l);if(!u)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);let d=executablePath(r[0],i),f=s?[`-c`,`protocol.allow=never`,`-c`,`protocol.https.allow=always`,r[1],`https://github.com/${s}.git`,...r.slice(3)]:r.slice(1),p=`cd ${shellQuote(a)} && exec ${shellQuote(d)} ${f.map(shellQuote).join(` `)}`,m=`Basic ${Buffer.from(`x-access-token:${u}`).toString(`base64`)}`,h=crypto.randomUUID(),g=`eve-github-${h}`,_=`/tmp/eve-code-gh-${h}`,v=`Basic ${Buffer.from(`x-access-token:${g}`).toString(`base64`)}`,y;try{y=await withGitHubCredentialLease(i,n.sessionId,{authorization:m,placeholder:g,placeholderAuthorization:v,token:u},()=>{let e={GH_CONFIG_DIR:_,GH_PROMPT_DISABLED:`1`};return r[0]!==`git`&&(e.GH_TOKEN=g),e.GIT_CONFIG_COUNT=`2`,e.GIT_CONFIG_KEY_0=`http.https://github.com/.extraheader`,e.GIT_CONFIG_VALUE_0=`Authorization: ${v}`,e.GIT_CONFIG_KEY_1=`core.hooksPath`,e.GIT_CONFIG_VALUE_1=`/dev/null`,e.GIT_TERMINAL_PROMPT=`0`,e.PATH=`/usr/local/bin:/usr/bin:/bin`,i.run({command:p,env:e})},t.broker)}finally{await i.removePath({path:_,recursive:!0,force:!0})}let b=sanitizeOutput(y.stdout,u,m),x=sanitizeOutput(y.stderr,u,m);return{exitCode:y.exitCode,stdout:b.value,stderr:x.value,truncated:b.truncated||x.truncated}}async function withGitHubCredentialLease(e,t,n,r,i){let a=leaseQueues.get(t)??Promise.resolve(),o,s=new Promise(e=>{o=e}),c=a.then(()=>s);leaseQueues.set(t,c),await a;try{return await i(e,{"api.github.com":[{match:{headers:[{key:{exact:`authorization`},value:{regex:`^(?:token|Bearer) ${n.placeholder}$`}}]},transform:[{headers:{authorization:`Bearer ${n.token}`}}]}],"github.com":[{match:{headers:[{key:{exact:`authorization`},value:{exact:n.placeholderAuthorization}}]},transform:[{headers:{authorization:n.authorization}}]}]}),await r()}finally{try{await i(e,null)}finally{o(),leaseQueues.get(t)===c&&leaseQueues.delete(t)}}}function parseCommand(e){let t=e.trim();if(!t)throw Error(`GitHub command must not be empty.`);let n=[],r=``,i=null,a=!1,o=!1;for(let e of t){if(a){r+=e,a=!1,o=!0;continue}if(e===`\\`&&i!==`single`){a=!0,o=!0;continue}if(i===`single`){e===`'`?i=null:r+=e;continue}if(i===`double`){if(e===`"`)i=null;else if(e===`$`||e==="`")throw unsupportedSyntax();else r+=e;continue}if(e===`'`)i=`single`,o=!0;else if(e===`"`)i=`double`,o=!0;else if(/\s/u.test(e))o&&=(n.push(r),r=``,!1);else if(";&|<>$`(){}".includes(e))throw unsupportedSyntax();else r+=e,o=!0}if(a||i)throw Error(`GitHub command contains an unfinished quote or escape.`);if(o&&n.push(r),n.length===0)throw Error(`GitHub command must not be empty.`);return n}function validateGitHubShellInput(e){let t=parseCommand(e.command),n=e.permissions[0];if(e.permissions.length!==1||n?.provider!==`github`)throw Error(`Exactly one GitHub permission is required.`);if(n.access!==`write`)throw Error(`GitHub App commands require explicit write-capable access.`);if(!e.description.trim())throw Error(`description must describe the intended result.`);let[r,i]=t;if(r===`gh`){if(!i)throw Error(`A gh subcommand is required.`)}else if(r===`git`){if(!i||!ALLOWED_GIT_REMOTE_COMMANDS.has(i))throw Error(`Authenticated git supports only fetch, ls-remote, pull, and push; clone with gh repo clone.`)}else if(r!==`gh-signed-commit`)throw Error(`GitHub commands must use gh, an authenticated git remote command, or gh-signed-commit.`);return t}async function assertCommandTargets(e,t,n,r){let i=new Set(t.map(e=>e.toLowerCase())),a,o;if(e[0]===`git`){if(e[2]!==`origin`)throw Error(`Authenticated git commands must use the validated origin remote.`);let t=e[1]===`push`,i=await r.run({command:`cd ${shellQuote(n)} && git remote get-url ${t?`--push `:``}origin`,env:{GIT_TERMINAL_PROMPT:`0`,PATH:`/usr/bin:/bin`}});if(i.exitCode!==0)throw Error(`Could not resolve the origin GitHub repository.`);a=repositoryFromRemote(i.stdout.trim()),o=[a]}else if(e[0]===`gh-signed-commit`){if(o=repoFlagTargets(e.slice(1)),o.length===0)throw Error(`gh-signed-commit requires an explicit --repo owner/repository target.`)}else o=repoFlagTargets(e.slice(1)),e[1]===`repo`&&(e[2]===`clone`||e[2]===`view`||e[2]===`fork`)&&e[3]&&!e[3].startsWith(`-`)&&o.push(canonicalRepository(e[3]));for(let e of o)if(!i.has(e.toLowerCase()))throw Error(`Command target ${JSON.stringify(e)} is not in the declared repositories.`);return a}function repoFlagTargets(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`--repo`||r===`-R`){let i=e[n+1];if(!i)throw Error(`${r} requires an owner/repository value.`);t.push(canonicalRepository(i)),n+=1}else r?.startsWith(`--repo=`)&&t.push(canonicalRepository(r.slice(7)))}return t}function repositoryFromRemote(e){let t=/^https:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(t?.[1])return canonicalRepository(t[1]);let n=/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/iu.exec(e);if(n?.[1])return canonicalRepository(n[1]);throw Error(`The origin remote is not a canonical GitHub repository URL.`)}function canonicalRepository(e){let t=e.replace(/\.git$/iu,``);if(!/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u.test(t))throw Error(`Invalid GitHub repository ${JSON.stringify(e)}.`);return t}function repositoryNames(e,t){if(e.length!==1)throw Error(`Exactly one GitHub repository is required.`);let n=new Set;for(let r of e){let e=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)$/u.exec(r);if(!e)throw Error(`Invalid GitHub repository ${JSON.stringify(r)}.`);if(e[1]?.toLowerCase()!==t.toLowerCase())throw Error(`Repository ${JSON.stringify(r)} is outside ${t}.`);n.add(e[2])}if(n.size!==1)throw Error(`Exactly one GitHub repository is required.`);return[...n]}function executablePath(e,t){return e===`gh`?toolingPaths(t).ghReal:e===`gh-signed-commit`?toolingPaths(t).trustedSignedCommit:`git`}function resolveWorkingDirectory(e,t){let n=posix.resolve(`/`,e.resolvePath(``)),r=posix.resolve(`/`,e.resolvePath(t?.trim()||``));if(r!==n&&!r.startsWith(`${n}/`))throw Error(`GitHub command workingDirectory must stay inside the sandbox workspace.`);return r}function sanitizeOutput(e,t,n){let r=e.replaceAll(t,`[redacted]`).replaceAll(n,`[redacted]`);return Buffer.byteLength(r)<=MAX_OUTPUT_BYTES?{value:r,truncated:!1}:{value:`[output truncated: showing final ${MAX_OUTPUT_BYTES} bytes]\n${Buffer.from(r).subarray(-1e5).toString()}`,truncated:!0}}function unsupportedSyntax(){return Error(`GitHub commands support argv syntax only, not pipes, redirects, substitutions, or shell operators.`)}export{executeGitHubShell,githubShellApproval,parseCommand};
@@ -1 +1 @@
1
- import extension_default from"../extension.js";import{deleteTokenCacheEntry,getToken}from"../../../../node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/token.js";import"../../../../node_modules/.pnpm/@vercel_connect@2.2.0_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_3fe44d656b2dcd93a04011e80966afff/node_modules/@vercel/connect/dist/index.js";import{z}from"#compiled/zod/index.js";const RepoSchema=z.string().trim().regex(/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u).transform(e=>e.toLowerCase()),PullRequestWatchInputSchema=z.object({repo:RepoSchema,pullRequestNumber:z.number().int().positive(),reviewOwner:z.string().trim().min(1),redHeadOid:z.string().regex(/^[0-9a-f]{40}$/iu).transform(e=>e.toLowerCase())}),PrwatchDeleteInputSchema=z.object({repo:RepoSchema,pullRequestNumber:z.number().int().positive()}),PullRequestSchema=z.object({head:z.object({sha:z.string().min(1)}),html_url:z.string().url(),merged:z.boolean().optional().default(!1),state:z.enum([`open`,`closed`])}),ReviewSchema=z.object({commit_id:z.string().nullable(),state:z.string(),submitted_at:z.string().nullable(),user:z.object({login:z.string()}).nullable()});function initialPullRequestWatchNotificationState(){return{previousSnapshot:null,redHeadPolls:0,redHeadWakeSent:!1}}function framePullRequestWatchWake(e){return`${e}\n\nThis is an internal watch wake, not a request for a progress report. Continue any necessary work. Send a user-facing response only when the original request is complete or a new blocker requires human input. Otherwise, finish by replying with exactly <eve-empty-delivery/> and no other text. Do not report that nothing changed or that work is still in progress.`}function reviewFingerprint(e){return e?.ownerReviewState===null||e===null?null:`${e.ownerReviewState}:${e.ownerReviewSubmittedAt??``}`}function advancePullRequestWatchNotification(e){let t=e.state.previousSnapshot,n=e.snapshot.headOid!==(t?.headOid??e.redHeadOid),r=t!==null&&reviewFingerprint(e.snapshot)!==reviewFingerprint(t),i=e.snapshot.headOid===e.redHeadOid,a=i?e.state.redHeadPolls+1:0,o=null;return n?o=`head_changed`:r?o=`owner_review_changed`:i&&!e.state.redHeadWakeSent&&a===e.staleAfterPolls&&(o=`red_head_stalled`),{state:{previousSnapshot:e.snapshot,redHeadPolls:a,redHeadWakeSent:e.state.redHeadWakeSent||o===`red_head_stalled`},wakeReason:o}}var RetryablePullRequestWatchError=class extends Error{},GitHubWatchResponseError=class extends Error{status;constructor(e,t){super(t),this.name=`GitHubWatchResponseError`,this.status=e}};function errorStatus(e){return typeof e!=`object`||!e||!(`status`in e)?null:typeof e.status==`number`?e.status:null}function shouldRefreshPullRequestWatchToken(e){return errorStatus(e)===401}function isRetryablePullRequestWatchError(e){let t=errorStatus(e);return t===429||t!==null&&t>=500||e instanceof RetryablePullRequestWatchError||e instanceof TypeError||e instanceof Error&&(/^GitHub watch (?:request|token request) failed:/u.test(e.message)||/\((?:429|5\d{2})\b/u.test(e.message))}function pullRequestWatchSnapshot(e){let t=e.reviewOwner.toLowerCase(),n=e.pullRequest.head.sha.toLowerCase(),r=e.reviews.filter(e=>e.commit_id?.toLowerCase()===n&&e.user?.login.toLowerCase()===t).at(-1);return{headOid:n,ownerApprovedCurrentHead:r?.state.toUpperCase()===`APPROVED`,ownerReviewState:r?.state.toUpperCase()??null,ownerReviewSubmittedAt:r?.submitted_at??null,state:e.pullRequest.merged?`merged`:e.pullRequest.state,url:e.pullRequest.html_url}}function repoParts(e){let[t,n]=e.split(`/`);if(t===void 0||n===void 0)throw Error(`Invalid GitHub repository: ${e}`);return{owner:t,name:n}}function repoFullName(e){let t=repoParts(e);return`${t.owner}/${t.name}`}function repoApiPath(e){let t=repoParts(e);return`/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.name)}`}function redactGithubToken(e,t){return t.length===0?e:e.split(t).join(`[redacted]`)}function githubHeaders(e){return{Accept:`application/vnd.github+json`,Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":`2022-11-28`}}function githubTokenParams(e,t){return{authorizationDetails:[{org:e,repositories:[t],type:`github_app_installation`}],subject:{type:`app`}}}async function mintWatchToken(e){let t=extension_default.config.github;if(t===void 0)throw Error(`GitHub is not configured for this agent.`);let n=repoParts(e);if(n.owner!==t.org.toLowerCase())throw Error(`Repository ${e} is outside ${t.org}.`);let r=await getToken(t.connector,githubTokenParams(t.org,n.name));if(r.length===0)throw Error(`Connect returned an empty GitHub token for ${e}.`);return r}async function invalidateWatchToken(e){let t=extension_default.config.github;if(t===void 0)return;let n=repoParts(e);deleteTokenCacheEntry(t.connector,githubTokenParams(t.org,n.name))}async function githubJson(e,t){let n;try{n=await fetch(e,{headers:githubHeaders(t)})}catch(e){throw new RetryablePullRequestWatchError(`GitHub watch request failed: ${e instanceof Error?e.message:String(e)}`)}if(n.ok)return n.json();let r=await n.text().catch(()=>``),i=`GitHub request failed (${n.status} ${n.statusText})`+(r.length>0?`: ${redactGithubToken(r,t)}`:``);throw n.status===429||n.status>=500?new RetryablePullRequestWatchError(i):new GitHubWatchResponseError(n.status,i)}async function readPullRequestWatchSnapshotWithToken(e,t){let n=`https://api.github.com${repoApiPath(e.repo)}/pulls/${e.pullRequestNumber}`,r=PullRequestSchema.parse(await githubJson(n,t));if(r.state===`closed`||r.merged)return pullRequestWatchSnapshot({pullRequest:r,reviewOwner:e.reviewOwner,reviews:[]});let i=[];for(let r=1;r<=20;r+=1){let a=z.array(ReviewSchema).parse(await githubJson(`${n}/reviews?per_page=100&page=${r}`,t));if(i.push(...a),a.length<100)break;if(r===20)throw Error(`PR #${e.pullRequestNumber} has too many reviews to verify`)}return pullRequestWatchSnapshot({pullRequest:r,reviewOwner:e.reviewOwner,reviews:i})}async function readPullRequestWatchSnapshot(e){for(let t=0;t<2;t+=1){let n;try{n=await mintWatchToken(e.repo)}catch(e){throw isRetryablePullRequestWatchError(e)?new RetryablePullRequestWatchError(`GitHub watch token request failed: ${e instanceof Error?e.message:String(e)}`):e}try{return await readPullRequestWatchSnapshotWithToken(e,n)}catch(n){if(t>0||!shouldRefreshPullRequestWatchToken(n))throw n;await invalidateWatchToken(e.repo)}}throw Error(`Pull request watch token refresh exhausted unexpectedly.`)}export{PrwatchDeleteInputSchema,PullRequestWatchInputSchema,RepoSchema,advancePullRequestWatchNotification,framePullRequestWatchWake,initialPullRequestWatchNotificationState,isRetryablePullRequestWatchError,pullRequestWatchSnapshot,readPullRequestWatchSnapshot,repoFullName,shouldRefreshPullRequestWatchToken};
1
+ import extension_default from"../extension.js";import{deleteTokenCacheEntry,getToken}from"../../../../node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/token.js";import"../../../../node_modules/.pnpm/@vercel_connect@2.3.3_@ai-sdk_mcp@2.0.52_zod@4.5.4__@auth_core@0.41.2_@chat-adapter_sla_a37674779346d612fa7d2ca9bd316494/node_modules/@vercel/connect/dist/index.js";import{z}from"#compiled/zod/index.js";const RepoSchema=z.string().trim().regex(/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u).transform(e=>e.toLowerCase()),PullRequestWatchInputSchema=z.object({repo:RepoSchema,pullRequestNumber:z.number().int().positive(),reviewOwner:z.string().trim().min(1),redHeadOid:z.string().regex(/^[0-9a-f]{40}$/iu).transform(e=>e.toLowerCase())}),PrwatchDeleteInputSchema=z.object({repo:RepoSchema,pullRequestNumber:z.number().int().positive()}),PullRequestSchema=z.object({head:z.object({sha:z.string().min(1)}),html_url:z.string().url(),merged:z.boolean().optional().default(!1),state:z.enum([`open`,`closed`])}),ReviewSchema=z.object({commit_id:z.string().nullable(),state:z.string(),submitted_at:z.string().nullable(),user:z.object({login:z.string()}).nullable()});function initialPullRequestWatchNotificationState(){return{previousSnapshot:null,redHeadPolls:0,redHeadWakeSent:!1}}function framePullRequestWatchWake(e){return`${e}\n\nThis is an internal watch wake, not a request for a progress report. Continue any necessary work. Send a user-facing response only when the original request is complete or a new blocker requires human input. Otherwise, finish by replying with exactly <eve-empty-delivery/> and no other text. Do not report that nothing changed or that work is still in progress.`}function reviewFingerprint(e){return e?.ownerReviewState===null||e===null?null:`${e.ownerReviewState}:${e.ownerReviewSubmittedAt??``}`}function advancePullRequestWatchNotification(e){let t=e.state.previousSnapshot,n=e.snapshot.headOid!==(t?.headOid??e.redHeadOid),r=t!==null&&reviewFingerprint(e.snapshot)!==reviewFingerprint(t),i=e.snapshot.headOid===e.redHeadOid,a=i?e.state.redHeadPolls+1:0,o=null;return n?o=`head_changed`:r?o=`owner_review_changed`:i&&!e.state.redHeadWakeSent&&a===e.staleAfterPolls&&(o=`red_head_stalled`),{state:{previousSnapshot:e.snapshot,redHeadPolls:a,redHeadWakeSent:e.state.redHeadWakeSent||o===`red_head_stalled`},wakeReason:o}}var RetryablePullRequestWatchError=class extends Error{},GitHubWatchResponseError=class extends Error{status;constructor(e,t){super(t),this.name=`GitHubWatchResponseError`,this.status=e}};function errorStatus(e){return typeof e!=`object`||!e||!(`status`in e)?null:typeof e.status==`number`?e.status:null}function shouldRefreshPullRequestWatchToken(e){return errorStatus(e)===401}function isRetryablePullRequestWatchError(e){let t=errorStatus(e);return t===429||t!==null&&t>=500||e instanceof RetryablePullRequestWatchError||e instanceof TypeError||e instanceof Error&&(/^GitHub watch (?:request|token request) failed:/u.test(e.message)||/\((?:429|5\d{2})\b/u.test(e.message))}function pullRequestWatchSnapshot(e){let t=e.reviewOwner.toLowerCase(),n=e.pullRequest.head.sha.toLowerCase(),r=e.reviews.filter(e=>e.commit_id?.toLowerCase()===n&&e.user?.login.toLowerCase()===t).at(-1);return{headOid:n,ownerApprovedCurrentHead:r?.state.toUpperCase()===`APPROVED`,ownerReviewState:r?.state.toUpperCase()??null,ownerReviewSubmittedAt:r?.submitted_at??null,state:e.pullRequest.merged?`merged`:e.pullRequest.state,url:e.pullRequest.html_url}}function repoParts(e){let[t,n]=e.split(`/`);if(t===void 0||n===void 0)throw Error(`Invalid GitHub repository: ${e}`);return{owner:t,name:n}}function repoFullName(e){let t=repoParts(e);return`${t.owner}/${t.name}`}function repoApiPath(e){let t=repoParts(e);return`/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.name)}`}function redactGithubToken(e,t){return t.length===0?e:e.split(t).join(`[redacted]`)}function githubHeaders(e){return{Accept:`application/vnd.github+json`,Authorization:`Bearer ${e}`,"X-GitHub-Api-Version":`2022-11-28`}}function githubTokenParams(e,t){return{authorizationDetails:[{org:e,repositories:[t],type:`github_app_installation`}],subject:{type:`app`}}}async function mintWatchToken(e){let t=extension_default.config.github;if(t===void 0)throw Error(`GitHub is not configured for this agent.`);let n=repoParts(e);if(n.owner!==t.org.toLowerCase())throw Error(`Repository ${e} is outside ${t.org}.`);let r=await getToken(t.connector,githubTokenParams(t.org,n.name));if(r.length===0)throw Error(`Connect returned an empty GitHub token for ${e}.`);return r}async function invalidateWatchToken(e){let t=extension_default.config.github;if(t===void 0)return;let n=repoParts(e);deleteTokenCacheEntry(t.connector,githubTokenParams(t.org,n.name))}async function githubJson(e,t){let n;try{n=await fetch(e,{headers:githubHeaders(t)})}catch(e){throw new RetryablePullRequestWatchError(`GitHub watch request failed: ${e instanceof Error?e.message:String(e)}`)}if(n.ok)return n.json();let r=await n.text().catch(()=>``),i=`GitHub request failed (${n.status} ${n.statusText})`+(r.length>0?`: ${redactGithubToken(r,t)}`:``);throw n.status===429||n.status>=500?new RetryablePullRequestWatchError(i):new GitHubWatchResponseError(n.status,i)}async function readPullRequestWatchSnapshotWithToken(e,t){let n=`https://api.github.com${repoApiPath(e.repo)}/pulls/${e.pullRequestNumber}`,r=PullRequestSchema.parse(await githubJson(n,t));if(r.state===`closed`||r.merged)return pullRequestWatchSnapshot({pullRequest:r,reviewOwner:e.reviewOwner,reviews:[]});let i=[];for(let r=1;r<=20;r+=1){let a=z.array(ReviewSchema).parse(await githubJson(`${n}/reviews?per_page=100&page=${r}`,t));if(i.push(...a),a.length<100)break;if(r===20)throw Error(`PR #${e.pullRequestNumber} has too many reviews to verify`)}return pullRequestWatchSnapshot({pullRequest:r,reviewOwner:e.reviewOwner,reviews:i})}async function readPullRequestWatchSnapshot(e){for(let t=0;t<2;t+=1){let n;try{n=await mintWatchToken(e.repo)}catch(e){throw isRetryablePullRequestWatchError(e)?new RetryablePullRequestWatchError(`GitHub watch token request failed: ${e instanceof Error?e.message:String(e)}`):e}try{return await readPullRequestWatchSnapshotWithToken(e,n)}catch(n){if(t>0||!shouldRefreshPullRequestWatchToken(n))throw n;await invalidateWatchToken(e.repo)}}throw Error(`Pull request watch token refresh exhausted unexpectedly.`)}export{PrwatchDeleteInputSchema,PullRequestWatchInputSchema,RepoSchema,advancePullRequestWatchNotification,framePullRequestWatchWake,initialPullRequestWatchNotificationState,isRetryablePullRequestWatchError,pullRequestWatchSnapshot,readPullRequestWatchSnapshot,repoFullName,shouldRefreshPullRequestWatchToken};
@@ -1 +1 @@
1
- import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createAgentSourceRegistry,defineProgrammaticAgentSource,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";const revision=`eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v50`,localDefaults=defineProgrammaticAgentSource({id:`eve:defaults`,revision,modules:[{logicalPath:`agent.ts`,loadNamespace:()=>import(`#framework/sources/modules/agent.js`)},{logicalPath:`sandbox.ts`,semanticRevision:`eve:default-sandbox:v1`,loadNamespace:()=>import(`#framework/sources/modules/sandbox.js`)},{logicalPath:`tools/bash.ts`,loadNamespace:()=>import(`#tools/provided/bash.js`)},{logicalPath:`tools/read_file.ts`,loadNamespace:()=>import(`#tools/provided/read-file.js`)},{logicalPath:`tools/write_file.ts`,loadNamespace:()=>import(`#tools/provided/write-file.js`)},{logicalPath:`tools/web_fetch.ts`,loadNamespace:()=>import(`#tools/provided/web-fetch.js`)},{logicalPath:`tools/load_skill.ts`,loadNamespace:()=>import(`#tools/provided/load-skill.js`)},{logicalPath:`tools/connection_search.ts`,loadNamespace:()=>import(`#tools/framework/connection-search.js`)},{logicalPath:`tools/task_cancel.ts`,loadNamespace:()=>import(`#tools/framework/task-cancel.js`)},{logicalPath:`tools/web_search.ts`,loadNamespace:()=>import(`#tools/provided/web-search.js`)}]}),rootDefaults=defineProgrammaticAgentSource({id:`eve:root-defaults`,revision,modules:[{logicalPath:`tools/agent.ts`,loadNamespace:()=>import(`#tools/framework/agent.js`)},{logicalPath:`channels/eve.ts`,loadNamespace:()=>import(`#framework/sources/modules/eve-channel.js`)},{logicalPath:`channels/home.ts`,loadNamespace:()=>import(`#framework/sources/modules/home-channel.js`)}]}),memoryWrapperTemplateSource=defineProgrammaticAgentSource({id:`eve:memory-wrapper`,revision,modules:[{logicalPath:`tools/memory-wrapper.ts`,loadNamespace:async e=>{let{loadMemoryWrapperNamespace:t}=await import(`#framework/sources/modules/memory-wrapper.js`);return await t(e)}}]}),frameworkAgentSourceRegistry=createAgentSourceRegistry([{applyTo:`all-local-nodes`,source:localDefaults},{applyTo:`root`,source:rootDefaults}],{templates:[memoryWrapperTemplateSource]}),memoryWrapperTemplate=frameworkAgentSourceRegistry.templates.get(memoryWrapperTemplateSource.id);async function loadFrameworkProgrammaticModule(e,t){return memoizeModuleNamespaceFactories(await loadProgrammaticModuleNamespace({backing:e,dependencyNamespaces:t,registries:[frameworkAgentSourceRegistry]}))}export{frameworkAgentSourceRegistry,loadFrameworkProgrammaticModule,memoryWrapperTemplate};
1
+ import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createAgentSourceRegistry,defineProgrammaticAgentSource,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";const revision=`eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v52`,localDefaults=defineProgrammaticAgentSource({id:`eve:defaults`,revision,modules:[{logicalPath:`agent.ts`,loadNamespace:()=>import(`#framework/sources/modules/agent.js`)},{logicalPath:`sandbox.ts`,semanticRevision:`eve:default-sandbox:v1`,loadNamespace:()=>import(`#framework/sources/modules/sandbox.js`)},{logicalPath:`tools/bash.ts`,loadNamespace:()=>import(`#tools/provided/bash.js`)},{logicalPath:`tools/read_file.ts`,loadNamespace:()=>import(`#tools/provided/read-file.js`)},{logicalPath:`tools/write_file.ts`,loadNamespace:()=>import(`#tools/provided/write-file.js`)},{logicalPath:`tools/web_fetch.ts`,loadNamespace:()=>import(`#tools/provided/web-fetch.js`)},{logicalPath:`tools/load_skill.ts`,loadNamespace:()=>import(`#tools/provided/load-skill.js`)},{logicalPath:`tools/connection_search.ts`,loadNamespace:()=>import(`#tools/framework/connection-search.js`)},{logicalPath:`tools/task_cancel.ts`,loadNamespace:()=>import(`#tools/framework/task-cancel.js`)},{logicalPath:`tools/web_search.ts`,loadNamespace:()=>import(`#tools/provided/web-search.js`)}]}),rootDefaults=defineProgrammaticAgentSource({id:`eve:root-defaults`,revision,modules:[{logicalPath:`tools/agent.ts`,loadNamespace:()=>import(`#tools/framework/agent.js`)},{logicalPath:`channels/eve.ts`,loadNamespace:()=>import(`#framework/sources/modules/eve-channel.js`)},{logicalPath:`channels/home.ts`,loadNamespace:()=>import(`#framework/sources/modules/home-channel.js`)}]}),memoryWrapperTemplateSource=defineProgrammaticAgentSource({id:`eve:memory-wrapper`,revision,modules:[{logicalPath:`tools/memory-wrapper.ts`,loadNamespace:async e=>{let{loadMemoryWrapperNamespace:t}=await import(`#framework/sources/modules/memory-wrapper.js`);return await t(e)}}]}),frameworkAgentSourceRegistry=createAgentSourceRegistry([{applyTo:`all-local-nodes`,source:localDefaults},{applyTo:`root`,source:rootDefaults}],{templates:[memoryWrapperTemplateSource]}),memoryWrapperTemplate=frameworkAgentSourceRegistry.templates.get(memoryWrapperTemplateSource.id);async function loadFrameworkProgrammaticModule(e,t){return memoizeModuleNamespaceFactories(await loadProgrammaticModuleNamespace({backing:e,dependencyNamespaces:t,registries:[frameworkAgentSourceRegistry]}))}export{frameworkAgentSourceRegistry,loadFrameworkProgrammaticModule,memoryWrapperTemplate};
@@ -1,9 +1,10 @@
1
1
  import { type AuthorizationChallenge } from "#harness/authorization.js";
2
2
  import type { HarnessSession, HarnessToolMap, StepInput } from "#harness/types.js";
3
+ import type { InputRequest } from "#shared/input.js";
3
4
  export interface ApprovalDeliveryResult {
4
5
  readonly challenges: readonly AuthorizationChallenge[];
5
6
  readonly feedback: readonly string[];
6
- readonly kind: "continue" | "continue-coordination" | "authorization-required" | "park";
7
+ readonly kind: "continue" | "continue-coordination" | "authorization-required" | "responses-completed" | "park";
7
8
  readonly session: HarnessSession;
8
9
  readonly stepInput?: StepInput;
9
10
  }
@@ -25,21 +26,10 @@ export interface ApprovalDeliveryResult {
25
26
  * creation commit before long-running policy execution. Candidate results also
26
27
  * commit before lifecycle events are projected by the next stack layer.
27
28
  */
28
- /** Returns whether this invocation should prepare tools for persisted policy work. */
29
- export declare function shouldPrepareApprovalPolicyTools(input: {
30
- readonly now?: number;
31
- readonly session: HarnessSession;
32
- readonly stepInput?: StepInput;
33
- }): boolean;
34
- /** Returns whether this invocation can replay a previously approved tool call. */
35
- export declare function shouldPrepareApprovalReplayTools(input: {
36
- readonly now?: number;
37
- readonly session: HarnessSession;
38
- readonly stepInput?: StepInput;
39
- }): boolean;
40
29
  export declare function coordinateApprovalDelivery(input: {
41
30
  readonly now?: number;
42
31
  readonly session: HarnessSession;
43
32
  readonly stepInput?: StepInput;
44
33
  readonly tools: HarnessToolMap;
34
+ readonly prepareTools?: (request: InputRequest) => Promise<HarnessToolMap>;
45
35
  }): Promise<ApprovalDeliveryResult>;