eve 0.76.0 → 0.76.3

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 (174) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/src/channel/channel-address.d.ts +3 -1
  3. package/dist/src/channel/channel-address.js +1 -1
  4. package/dist/src/channel/session-stranded-error.d.ts +25 -0
  5. package/dist/src/channel/session-stranded-error.js +1 -0
  6. package/dist/src/channel/session.d.ts +13 -6
  7. package/dist/src/channel/types.d.ts +29 -1
  8. package/dist/src/chunks/{use-eve-agent-QmriPA-w.js → use-eve-agent-BtKWTEpm.js} +31 -14
  9. package/dist/src/chunks/{use-eve-agent-D2V9UhLt.js → use-eve-agent-jI6EsYAu.js} +31 -14
  10. package/dist/src/cli/commands/registry-project.d.ts +10 -3
  11. package/dist/src/cli/commands/registry-project.js +2 -2
  12. package/dist/src/cli/commands/registry.js +1 -1
  13. package/dist/src/cli/dev/tui/runner.js +3 -3
  14. package/dist/src/cli/dev/tui/stranded-session.d.ts +9 -0
  15. package/dist/src/cli/dev/tui/stranded-session.js +1 -0
  16. package/dist/src/client/client-error.d.ts +16 -0
  17. package/dist/src/client/client-error.js +1 -1
  18. package/dist/src/client/client.js +1 -1
  19. package/dist/src/client/index.d.ts +3 -2
  20. package/dist/src/client/index.js +1 -1
  21. package/dist/src/client/open-stream.d.ts +5 -3
  22. package/dist/src/client/open-stream.js +1 -1
  23. package/dist/src/client/session-controls.js +1 -1
  24. package/dist/src/client/session.js +1 -1
  25. package/dist/src/client/transcript-reducer.d.ts +46 -0
  26. package/dist/src/client/transcript-reducer.js +2 -0
  27. package/dist/src/compiled/.vendor-stamp.json +1 -1
  28. package/dist/src/compiler/extension-compatibility.d.ts +20 -20
  29. package/dist/src/compiler/extension-compatibility.js +1 -1
  30. package/dist/src/compiler/manifest.js +1 -1
  31. package/dist/src/compiler/normalize-agent-config.js +1 -1
  32. package/dist/src/context/accessors.d.ts +1 -1
  33. package/dist/src/context/build-callback-context.js +1 -1
  34. package/dist/src/context/dynamic-resolve-context.js +1 -1
  35. package/dist/src/context/keys.d.ts +5 -0
  36. package/dist/src/context/keys.js +1 -1
  37. package/dist/src/context/providers/session.d.ts +1 -0
  38. package/dist/src/context/providers/session.js +1 -1
  39. package/dist/src/context/session-context.d.ts +8 -2
  40. package/dist/src/dynamic/definition.d.ts +7 -1
  41. package/dist/src/evals/types.d.ts +2 -1
  42. package/dist/src/eve-channel/index.js +1 -1
  43. package/dist/src/eve-channel/request.js +2 -2
  44. package/dist/src/eve-channel/support.d.ts +2 -0
  45. package/dist/src/eve-channel/support.js +1 -1
  46. package/dist/src/execution/agent-sessions/steps.js +1 -1
  47. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  48. package/dist/src/execution/eve-workflow-attributes.d.ts +15 -0
  49. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  50. package/dist/src/execution/install-workflow-world.d.ts +7 -0
  51. package/dist/src/execution/install-workflow-world.js +1 -0
  52. package/dist/src/execution/legacy-session/authorization.js +1 -1
  53. package/dist/src/execution/legacy-session/inbox.js +1 -1
  54. package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
  55. package/dist/src/execution/session/entry.js +1 -1
  56. package/dist/src/execution/session/handoff-steps.d.ts +11 -0
  57. package/dist/src/execution/session/handoff-steps.js +1 -1
  58. package/dist/src/execution/session/program.js +1 -1
  59. package/dist/src/execution/session/timeout-steps.js +1 -1
  60. package/dist/src/execution/session-event-stream.d.ts +6 -0
  61. package/dist/src/execution/session-event-stream.js +1 -1
  62. package/dist/src/execution/session-inbox/address.d.ts +4 -0
  63. package/dist/src/execution/session-inbox/address.js +1 -1
  64. package/dist/src/execution/session-inbox/end-stranded-session.d.ts +22 -0
  65. package/dist/src/execution/session-inbox/end-stranded-session.js +1 -0
  66. package/dist/src/execution/session-inbox/hook-release.d.ts +4 -0
  67. package/dist/src/execution/session-inbox/hook-release.js +1 -0
  68. package/dist/src/execution/session-inbox/owner.d.ts +48 -0
  69. package/dist/src/execution/session-inbox/owner.js +1 -0
  70. package/dist/src/execution/session-inbox/resume.d.ts +12 -0
  71. package/dist/src/execution/session-inbox/resume.js +1 -1
  72. package/dist/src/execution/session-inbox/runnable-owner.d.ts +13 -0
  73. package/dist/src/execution/session-inbox/runnable-owner.js +1 -0
  74. package/dist/src/execution/session-inbox/stranded-replay-guard.d.ts +16 -0
  75. package/dist/src/execution/session-inbox/stranded-replay-guard.js +1 -0
  76. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  77. package/dist/src/execution/workflow-runtime.d.ts +5 -1
  78. package/dist/src/execution/workflow-runtime.js +1 -1
  79. package/dist/src/harness/compaction/step.js +1 -1
  80. package/dist/src/harness/input-request-resolution.js +1 -1
  81. package/dist/src/harness/model-call/call.d.ts +1 -1
  82. package/dist/src/harness/model-call/call.js +1 -1
  83. package/dist/src/harness/model-call/errors.d.ts +5 -6
  84. package/dist/src/harness/model-call/errors.js +1 -1
  85. package/dist/src/harness/model-call/recovery.d.ts +4 -3
  86. package/dist/src/harness/model-call/request.d.ts +2 -1
  87. package/dist/src/harness/model-call/request.js +1 -1
  88. package/dist/src/harness/model-call/tools.js +1 -1
  89. package/dist/src/harness/model-profile.d.ts +10 -3
  90. package/dist/src/harness/model-profile.js +1 -1
  91. package/dist/src/harness/prompt-cache.d.ts +6 -3
  92. package/dist/src/harness/prompt-cache.js +1 -1
  93. package/dist/src/harness/provider-safety.d.ts +2 -1
  94. package/dist/src/harness/provider-safety.js +1 -1
  95. package/dist/src/harness/provider-tools.d.ts +1 -1
  96. package/dist/src/harness/provider-tools.js +1 -1
  97. package/dist/src/harness/session-machine/transitions.d.ts +3 -1
  98. package/dist/src/harness/session-machine/transitions.js +1 -1
  99. package/dist/src/harness/step/context.js +1 -1
  100. package/dist/src/harness/step-hooks.js +1 -1
  101. package/dist/src/internal/application/compiled-artifacts.js +4 -4
  102. package/dist/src/internal/application/package.d.ts +1 -1
  103. package/dist/src/internal/application/package.js +1 -1
  104. package/dist/src/internal/application/stamped-package-version.d.ts +5 -0
  105. package/dist/src/internal/application/stamped-package-version.js +1 -0
  106. package/dist/src/internal/authored-definition/core.d.ts +3 -0
  107. package/dist/src/internal/authored-definition/core.js +1 -1
  108. package/dist/src/internal/model-auth/available-models.js +1 -1
  109. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  110. package/dist/src/internal/workflow/development-run-unavailable-error.d.ts +15 -0
  111. package/dist/src/internal/workflow/development-run-unavailable-error.js +1 -0
  112. package/dist/src/internal/workflow/development-world-server.js +1 -1
  113. package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +0 -4
  114. package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.js +1 -1
  115. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +2 -2
  116. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  117. package/dist/src/protocol/message.d.ts +14 -0
  118. package/dist/src/protocol/message.js +1 -1
  119. package/dist/src/public/channels/index.d.ts +1 -1
  120. package/dist/src/public/channels/index.js +1 -1
  121. package/dist/src/public/context/index.d.ts +1 -1
  122. package/dist/src/public/definitions/callback-context.d.ts +1 -1
  123. package/dist/src/public/definitions/channel.d.ts +1 -0
  124. package/dist/src/public/definitions/channel.js +1 -1
  125. package/dist/src/public/models/openai/chatgpt/model.js +1 -1
  126. package/dist/src/public/models/openai/chatgpt/transport.js +1 -1
  127. package/dist/src/public/tanstack/index.d.ts +40 -0
  128. package/dist/src/public/tanstack/index.js +1 -0
  129. package/dist/src/runtime/agent/resolve-model.js +1 -1
  130. package/dist/src/runtime/resolve-agent.js +1 -1
  131. package/dist/src/setup/flows/model-login.js +1 -1
  132. package/dist/src/setup/integrations/web/framework.d.ts +8 -0
  133. package/dist/src/setup/integrations/web/framework.js +1 -0
  134. package/dist/src/setup/integrations/web/hosting.d.ts +43 -0
  135. package/dist/src/setup/integrations/web/hosting.js +15 -0
  136. package/dist/src/setup/integrations/web/setup.d.ts +6 -10
  137. package/dist/src/setup/integrations/web/setup.js +23 -17
  138. package/dist/src/setup/scaffold/create/project.js +1 -1
  139. package/dist/src/setup/scaffold/create/web-template.d.ts +6 -2
  140. package/dist/src/setup/scaffold/create/web-template.js +39 -2
  141. package/dist/src/setup/scaffold/update/channels.js +1 -1
  142. package/dist/src/setup/vercel-project-framework.js +1 -1
  143. package/dist/src/shared/agent-definition.d.ts +25 -0
  144. package/dist/src/shared/agent-definition.js +1 -1
  145. package/dist/src/shared/chatgpt-model.d.ts +8 -0
  146. package/dist/src/shared/chatgpt-model.js +1 -1
  147. package/dist/src/subagents/callback-route.js +1 -1
  148. package/dist/src/svelte/index.js +1 -1
  149. package/dist/src/svelte/use-eve-agent.js +1 -1
  150. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  151. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  152. package/dist/src/vue/index.js +1 -1
  153. package/dist/src/vue/use-eve-agent.js +1 -1
  154. package/docs/agent-config.md +32 -1
  155. package/docs/channels/custom.mdx +26 -0
  156. package/docs/channels/eve.mdx +8 -5
  157. package/docs/concepts/built-in-tools.md +17 -0
  158. package/docs/concepts/execution-model-and-durability.mdx +100 -0
  159. package/docs/concepts/project-structure.mdx +2 -2
  160. package/docs/concepts/sessions-runs-and-streaming.md +36 -34
  161. package/docs/guides/client/messages.mdx +10 -1
  162. package/docs/guides/deployment/overview.md +2 -2
  163. package/docs/guides/dev-tui.md +2 -0
  164. package/docs/guides/frontend/meta.json +9 -1
  165. package/docs/guides/frontend/nextjs.mdx +1 -1
  166. package/docs/guides/frontend/overview.mdx +9 -8
  167. package/docs/guides/frontend/tanstack.mdx +201 -0
  168. package/docs/guides/session-context.md +1 -0
  169. package/docs/install-integrations.mdx +1 -1
  170. package/docs/instructions.mdx +1 -1
  171. package/docs/reference/typescript-api.md +1 -1
  172. package/docs/tools/human-in-the-loop.md +2 -0
  173. package/docs/tutorial/ship-it.mdx +1 -1
  174. package/package.json +7 -1
@@ -1 +1 @@
1
- import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:84,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,29,30,31,32,34,35,76,77,78,80,81,82,84],dropped:{14:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,15:`TaskExec replaces stageEffect with send`,16:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,17:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,18:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,19:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,20:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,21:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,22:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,33:`ctx.agent now accepts the subagent name as its first argument, derives invocation identity internally, and infers structured output types`,36:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,37:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,38:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,39:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,40:`runWorkflowProgram was made internal; use the workflow factory from eve/tools/workflow`,41:`workflow no longer accepts agents and its options argument is optional; use workflow() or workflow({ maxSubagents })`,42:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,43:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,44:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,45:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,46:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,47:`eve/experimental/evaluate was removed; import decide from eve/ai`,48:`eve/experimental/evaluate was removed; import decide from eve/ai`,49:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,50:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,51:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,52:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,53:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,54:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,55:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,56:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,57:`agentRouter() no longer accepts a model-facing outputSchema; structured subagent output is requested only through ctx.agent().`,58:`Workflow tools no longer accept execution or return background task receipts; every call blocks until it settles.`,59:`Workflow tools no longer accept execution or return background task receipts, and every call blocks until it settles. ctx.ask() no longer accepts dismissible and reports a withdrawn request as cancelled, workflow tool contexts carry interruptSignal, and ctx.agent(name) returns a session handle whose send() delivers a message and whose result() resolves the turn; ctx.agent(name, { message, agentId }) and AgentInput were removed. A ctx.ask() question parks the open turn with turn.waiting instead of ending it.`,60:`Workflow tools define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx): a task() call returns a receipt and runs as a task, a serve() call reaches a resumable task through receive() and its model input gains taskId, and stream events gained task.started and task.settled. Agent tools are serve() tools with taskId in place of agentId, and the subagent.* stream events were removed. ctx.interruptSignal and WorkflowTaskContext were removed: a steering message aborts the abortSignal of an execute call the turn waits on.`,61:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,62:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,63:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,64:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,65:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,66:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,67:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,68:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,69:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,70:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,71:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,72:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,73:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,74:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,75:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,79:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`,83:`webSearch provider "openai" was replaced by "native" before it shipped in a release`}},dynamicTool:{current:77,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,31,32,33,52,54,60,61,62,63,64,65,66,67,68,69,70,72,73,75,76,77],dropped:{21:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,29:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,30:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,34:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,35:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,36:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,37:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,38:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,39:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,40:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,41:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,42:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,43:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,44:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,45:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,46:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,47:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,48:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,49:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,50:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,51:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,53:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,55:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,56:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,57:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,58:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,59:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,71:`AI SDK evaluation models became decision models; auto() accepts decision models only`,74:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},channel:{current:56,supported:[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,29,31,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,54,55,56],dropped:{12:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,19:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,20:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,21:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,22:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,23:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,24:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,25:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,26:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,27:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,28:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,30:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,32:`Run mode and caller-supplied output schemas were removed from channel operations; sessions always park, and send options, audience inputs, and ConversationContext no longer carry mode, while from().send() and from().respond() no longer accept outputSchema.`,33:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text.`,34:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,35:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,53:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},schedule:{current:29,supported:[1,2,3,4,6,7,8,9,10,11,12,13,14,15,18,19,20,21,22,23,24,25,26,27,28,29],dropped:{5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,16:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,17:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},subagent:{current:33,supported:[3,4,6,7,8,9,10,11,12,13,14,15,16,19,23,24,25,26,27,28,29,30,31,32,33],dropped:{1:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,2:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,18:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,20:`Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.`,21:`Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,22:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},connection:{current:45,supported:[1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18,19,20,21,22,24,26,32,33,34,35,36,37,38,39,40,41,43,44,45],dropped:{9:`Dynamic connection resolvers no longer receive conversation or channel continuation data`,10:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,25:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,27:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,29:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,30:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,31:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,42:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},hook:{current:43,supported:[20,21,22,23,25,27,31,32,33,34,35,36,37,38,39,41,42,43],dropped:{1:`Model identity moved from session.started runtime metadata to step.started call attribution.`,2:`Model identity moved from session.started runtime metadata to step.started call attribution.`,3:`Model identity moved from session.started runtime metadata to step.started call attribution.`,4:`Model identity moved from session.started runtime metadata to step.started call attribution.`,5:`Model identity moved from session.started runtime metadata to step.started call attribution.`,6:`Model identity moved from session.started runtime metadata to step.started call attribution.`,7:`Model identity moved from session.started runtime metadata to step.started call attribution.`,8:`Model identity moved from session.started runtime metadata to step.started call attribution.`,9:`Model identity moved from session.started runtime metadata to step.started call attribution.`,10:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,11:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,12:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,13:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,14:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,15:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,16:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,18:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,19:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,24:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,26:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text.`,29:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,30:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,40:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},skill:{current:3,supported:[1,2,3],dropped:{}},dynamicSkill:{current:35,supported:[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,25,26,27,28,29,30,31,32,33,34,35],dropped:{13:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,22:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,23:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,24:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:36,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,26,27,28,29,30,31,32,33,34,35,36],dropped:{14:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,24:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,25:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},config:{current:1,supported:[1],dropped:{}},state:{current:12,supported:[1,2,3,4,5,7,9,10,12],dropped:{6:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,8:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,11:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestV1Schema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict(),extensionCompatibilityManifestV2Schema=extensionCompatibilityManifestV1Schema.extend({formatVersion:z.literal(2),build:z.object({externalDependencies:z.array(z.string().min(1)).readonly()}).strict().optional()}),extensionCompatibilityManifestSchema=z.union([extensionCompatibilityManifestV1Schema,extensionCompatibilityManifestV2Schema]);function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,t){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(t),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
1
+ import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:85,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,29,30,31,32,34,35,76,77,78,80,81,82,84,85],dropped:{14:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,15:`TaskExec replaces stageEffect with send`,16:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,17:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,18:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,19:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,20:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,21:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,22:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,33:`ctx.agent now accepts the subagent name as its first argument, derives invocation identity internally, and infers structured output types`,36:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,37:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,38:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,39:`experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow`,40:`runWorkflowProgram was made internal; use the workflow factory from eve/tools/workflow`,41:`workflow no longer accepts agents and its options argument is optional; use workflow() or workflow({ maxSubagents })`,42:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,43:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,44:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,45:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,46:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,47:`eve/experimental/evaluate was removed; import decide from eve/ai`,48:`eve/experimental/evaluate was removed; import decide from eve/ai`,49:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,50:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,51:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,52:`Background defineTool and TaskExec were removed; use defineWorkflowTool for durable background work.`,53:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,54:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,55:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,56:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,57:`agentRouter() no longer accepts a model-facing outputSchema; structured subagent output is requested only through ctx.agent().`,58:`Workflow tools no longer accept execution or return background task receipts; every call blocks until it settles.`,59:`Workflow tools no longer accept execution or return background task receipts, and every call blocks until it settles. ctx.ask() no longer accepts dismissible and reports a withdrawn request as cancelled, workflow tool contexts carry interruptSignal, and ctx.agent(name) returns a session handle whose send() delivers a message and whose result() resolves the turn; ctx.agent(name, { message, agentId }) and AgentInput were removed. A ctx.ask() question parks the open turn with turn.waiting instead of ending it.`,60:`Workflow tools define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx): a task() call returns a receipt and runs as a task, a serve() call reaches a resumable task through receive() and its model input gains taskId, and stream events gained task.started and task.settled. Agent tools are serve() tools with taskId in place of agentId, and the subagent.* stream events were removed. ctx.interruptSignal and WorkflowTaskContext were removed: a steering message aborts the abortSignal of an execute call the turn waits on.`,61:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,62:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,63:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,64:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,65:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,66:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,67:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,68:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,69:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,70:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,71:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,72:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,73:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,74:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,75:`eve/ai evaluate was renamed to decide and AI SDK evaluation models became decision models; import decide from eve/ai`,79:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`,83:`webSearch provider "openai" was replaced by "native" before it shipped in a release`}},dynamicTool:{current:79,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,31,32,33,52,54,60,61,62,63,64,65,66,67,68,69,70,72,73,75,76,77,78,79],dropped:{21:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,28:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,29:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,30:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,34:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,35:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,36:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,37:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,38:`workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory`,39:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,40:`Legacy session history migration was removed; user-role messages require current provenance kinds.`,41:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,42:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,43:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,44:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,45:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,46:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,47:`autoModel and eve/experimental/evaluate were removed; import auto from eve/models`,48:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,49:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,50:`Background dynamic tools were removed; use a static defineWorkflowTool for durable background work.`,51:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,53:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,55:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,56:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,57:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,58:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,59:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,71:`AI SDK evaluation models became decision models; auto() accepts decision models only`,74:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},channel:{current:58,supported:[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,29,31,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,54,55,56,57,58],dropped:{12:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,19:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,20:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,21:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,22:`Continuation rekey was removed; channel extensions must use additive continuation.alias instead.`,23:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,24:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,25:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,26:`Task views no longer expose executor bindings; background work is owned by workflow runs.`,27:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,28:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,30:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,32:`Run mode and caller-supplied output schemas were removed from channel operations; sessions always park, and send options, audience inputs, and ConversationContext no longer carry mode, while from().send() and from().respond() no longer accept outputSchema.`,33:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text.`,34:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,35:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,53:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},schedule:{current:31,supported:[1,2,3,4,6,7,8,9,10,11,12,13,14,15,18,19,20,21,22,23,24,25,26,27,28,29,30,31],dropped:{5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,16:`Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,17:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},subagent:{current:35,supported:[3,4,6,7,8,9,10,11,12,13,14,15,16,19,23,24,25,26,27,28,29,30,31,32,33,34,35],dropped:{1:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,2:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,18:`Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.`,20:`Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.`,21:`Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,22:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},connection:{current:46,supported:[1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18,19,20,21,22,24,26,32,33,34,35,36,37,38,39,40,41,43,44,45,46],dropped:{9:`Dynamic connection resolvers no longer receive conversation or channel continuation data`,10:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,25:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,27:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,29:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`,30:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,31:`Approval response policies now run for Cancel as well as Approve; a policy written for Approve only could reject every Cancel.`,42:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},hook:{current:44,supported:[20,21,22,23,25,27,31,32,33,34,35,36,37,38,39,41,42,43,44],dropped:{1:`Model identity moved from session.started runtime metadata to step.started call attribution.`,2:`Model identity moved from session.started runtime metadata to step.started call attribution.`,3:`Model identity moved from session.started runtime metadata to step.started call attribution.`,4:`Model identity moved from session.started runtime metadata to step.started call attribution.`,5:`Model identity moved from session.started runtime metadata to step.started call attribution.`,6:`Model identity moved from session.started runtime metadata to step.started call attribution.`,7:`Model identity moved from session.started runtime metadata to step.started call attribution.`,8:`Model identity moved from session.started runtime metadata to step.started call attribution.`,9:`Model identity moved from session.started runtime metadata to step.started call attribution.`,10:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,11:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,12:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,13:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,14:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,15:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,16:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,17:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,18:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,19:`The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,24:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,26:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,28:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text.`,29:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,30:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.`,40:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}},skill:{current:3,supported:[1,2,3],dropped:{}},dynamicSkill:{current:36,supported:[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,25,26,27,28,29,30,31,32,33,34,35,36],dropped:{13:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,22:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,23:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,24:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:37,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,26,27,28,29,30,31,32,33,34,35,36,37],dropped:{14:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`Run mode was removed; sessions always park and ConversationContext no longer carries mode.`,24:`Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.`,25:`Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.`}},config:{current:1,supported:[1],dropped:{}},state:{current:13,supported:[1,2,3,4,5,7,9,10,12,13],dropped:{6:`Sandbox sessions no longer expose core identity and mutable networking is provider-specific.`,8:`SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities`,11:`Sandbox provider handle hooks were renamed to onSandboxStop and onSandboxDelete.`}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestV1Schema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict(),extensionCompatibilityManifestV2Schema=extensionCompatibilityManifestV1Schema.extend({formatVersion:z.literal(2),build:z.object({externalDependencies:z.array(z.string().min(1)).readonly()}).strict().optional()}),extensionCompatibilityManifestSchema=z.union([extensionCompatibilityManifestV1Schema,extensionCompatibilityManifestV2Schema]);function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,t){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(t),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{mountIdSchema}from"#shared/extension-mount.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";import{WEB_SEARCH_FALLBACK_PROVIDERS,WEB_SEARCH_PROVIDERS}from"#shared/web-search.js";import{AGENT_WORKFLOW_RETENTION_VALUES}from"#shared/agent-definition.js";import{validateCompiledAgentManifest,validateCompiledAgentResources}from"#compiler/validate-artifact.js";const COMPILED_AGENT_MANIFEST_KIND=`eve-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=54,agentSourceOwnerSchema=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string().min(1),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),mountId:mountIdSchema,namespace:z.string().min(1),packageName:z.string().min(1)}).strict()]),moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),filesystemModuleBackingSchema=z.object({externalDependencies:z.array(z.string()).readonly(),extensionScope:z.object({namespace:z.string(),sourceRoot:z.string()}).strict().optional(),mountId:z.string().optional(),kind:z.literal(`filesystem`),sourcePath:z.string()}).strict(),programmaticModuleBackingSchema=z.object({dependencies:z.record(z.string(),z.string()).readonly().optional(),kind:z.literal(`programmatic`),mountId:z.string().optional(),moduleId:z.string(),parameters:jsonObjectSchema.optional(),registryId:z.string(),revision:z.string(),semanticRevision:z.string().optional()}).strict(),resourceSourceBackingSchema=z.object({kind:z.literal(`resource`),sourcePath:z.string()}).strict(),agentModuleBackingSchema=z.discriminatedUnion(`kind`,[filesystemModuleBackingSchema,programmaticModuleBackingSchema]),compiledModuleBindingSchema=z.object({backing:agentModuleBackingSchema,logicalPath:z.string(),owner:agentSourceOwnerSchema,usage:z.object({compile:z.boolean(),runtimeEntry:z.boolean()}).strict()}).strict(),agentSourceDescriptorSchema=z.object({backing:z.discriminatedUnion(`kind`,[filesystemModuleBackingSchema,programmaticModuleBackingSchema,resourceSourceBackingSchema]),form:z.enum([`derived`,`direct`]),layer:z.enum([`framework-default`,`extension-package`,`extension-override`,`application`]),logicalPath:z.string(),owner:agentSourceOwnerSchema,sourceId:z.string()}).strict(),agentSourceCompositionSchema=z.object({entries:z.array(z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`shadowed`),source:agentSourceDescriptorSchema,winnerSourceId:z.string()}).strict(),z.object({kind:z.literal(`disabled`),source:agentSourceDescriptorSchema}).strict()])).readonly()}).strict(),compiledDynamicModelDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`HEAD`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`OPTIONS`),z.literal(`WEBSOCKET`)]),compiledChannelCorsSchema=z.object({origin:z.union([z.literal(`*`),z.literal(`null`),z.array(z.string())]).optional(),methods:z.union([z.literal(`*`),z.array(z.string())]).optional(),allowHeaders:z.union([z.literal(`*`),z.array(z.string())]).optional(),exposeHeaders:z.union([z.literal(`*`),z.array(z.string())]).optional(),credentials:z.boolean().optional(),maxAge:z.union([z.string(),z.literal(!1)]).optional(),preflight:z.object({statusCode:z.number().int().min(100).max(599).optional()}).strict().optional()}).strict(),compiledVercelConnectMetadataSchema=z.object({connector:z.string(),requirement:z.object({method:z.string().optional(),reference:z.string(),service:z.string(),subjectTypes:z.array(z.enum([`app`,`user`])).readonly()}).strict().optional()}).strict(),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional(),cors:compiledChannelCorsSchema.optional(),manifest:jsonObjectSchema.optional(),vercelConnect:compiledVercelConnectMetadataSchema.optional()}).strict(),compiledChannelPreflightDefinitionSchema=z.object({cors:compiledChannelCorsSchema,method:z.literal(`OPTIONS`),sourceIds:z.array(z.string()).readonly(),urlPath:z.string()}).strict(),compiledShadowedChannelRouteSchema=z.object({method:channelMethodSchema,source:agentSourceDescriptorSchema,urlPath:z.string(),winnerSourceId:z.string()}).strict(),compiledChannelRoutePlanSchema=z.object({effective:z.array(compiledChannelDefinitionSchema).readonly(),preflight:z.array(compiledChannelPreflightDefinitionSchema).readonly(),shadowed:z.array(compiledShadowedChannelRouteSchema).readonly()}).strict(),modelRoutingSchema=z.union([z.object({kind:z.literal(`gateway`),target:z.string(),byok:z.string().optional()}).strict(),z.object({kind:z.literal(`external`),provider:z.string()}).strict()]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),maxOutputTokens:z.number().int().positive().optional(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional(),routing:modelRoutingSchema}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentWorkflowWorldDefinitionSchema=z.string(),compiledAgentWorkflowDefinitionSchema=z.object({modelCallsPerStep:z.number().int().positive().optional(),retention:z.literal(AGENT_WORKFLOW_RETENTION_VALUES).optional(),world:compiledAgentWorkflowWorldDefinitionSchema.optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),sessionTokenLimitSchema=z.union([z.number().int().positive(),z.literal(!1)]),sessionTokenCostLimitSchema=z.union([z.number().finite().positive(),z.literal(!1)]),sessionTimeoutSchema=z.union([z.number().int().positive(),z.literal(!1)]),compiledAgentLimitsDefinitionSchema=z.object({maxInputTokensPerSession:sessionTokenLimitSchema.optional(),maxOutputTokensPerSession:sessionTokenLimitSchema.optional(),maxTokenCostUsdPerSession:sessionTokenCostLimitSchema.optional(),sessionTimeoutMs:sessionTimeoutSchema.optional()}).strict(),compiledAgentConfigBaseFields={build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),defaultTools:z.boolean().optional(),description:z.string().optional(),experimental:z.object({workflow:compiledAgentWorkflowDefinitionSchema.optional()}).strict().optional(),name:z.string(),reasoning:z.enum([`provider-default`,`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),source:moduleSourceRefSchema,tool:z.union([z.boolean(),z.literal(`deferred`)]).optional(),limits:compiledAgentLimitsDefinitionSchema.optional()},compiledAgentConfigSchema=z.union([z.object({...compiledAgentConfigBaseFields,model:compiledRuntimeModelReferenceSchema}).strict(),z.object({...compiledAgentConfigBaseFields,dynamicModel:compiledDynamicModelDefinitionSchema}).strict()]),compiledInstructionsBaseFields={content:z.string(),name:z.string(),logicalPath:z.string(),role:z.enum([`system`,`user`]),sourceId:z.string()},compiledInstructionsSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledInstructionsBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledInstructionsBaseFields,sourceKind:z.literal(`module`)}).strict()]),compiledSkillBaseFields={name:z.string(),deferred:z.boolean().optional(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleBaseFields={cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string()},compiledScheduleDefinitionSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledScheduleBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledScheduleBaseFields,sourceKind:z.literal(`module`)}).strict()]),compiledScheduleCollectionDefinitionSchema=z.object({description:z.string().optional(),logicalPath:z.string(),name:z.string(),providerKind:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),tools:z.boolean().optional()}).strict(),compiledSandboxDefinitionSchema=z.object({providerName:z.string().optional(),environmentExportName:z.string().optional(),inheritsParent:z.boolean().optional(),exportName:z.string().optional(),logicalPath:z.string(),revisionHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),protocol:z.enum([`mcp`,`openapi`]).default(`mcp`),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:compiledVercelConnectMetadataSchema.optional()}).strict(),compiledDynamicConnectionDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),extensionNamespace:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledToolBehaviorSchema=z.object({availability:z.array(z.literal(`root-session`)).readonly(),handling:z.discriminatedUnion(`kind`,[z.object({action:z.literal(`self-agent`),kind:z.literal(`dispatch`)}).strict(),z.object({fallback:z.enum(WEB_SEARCH_FALLBACK_PROVIDERS).optional(),kind:z.literal(`provider-tool`),provider:z.enum(WEB_SEARCH_PROVIDERS)}).strict(),z.object({entryPoint:z.enum([`execute`,`task`,`serve`]),kind:z.literal(`workflow-tool`),workflowId:z.string()}).strict()]).optional(),shape:z.object({suspend:z.enum([`none`,`workflow`])}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({availableInSubagents:z.boolean().optional(),behavior:compiledToolBehaviorSchema.optional(),deferred:z.boolean().optional(),description:z.string(),exportName:z.string().optional(),hasExecute:z.boolean(),hasModelOutputProjection:z.boolean(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),modelInputSchema:jsonObjectSchema.optional(),name:z.string(),outputSchema:jsonObjectSchema.optional(),requiresApproval:z.boolean(),sourceId:z.string(),sourceKind:z.literal(`module`),workflowProgram:z.object({maxSubagents:z.number().int().positive()}).strict().optional()}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),extensionNamespace:z.string().optional(),logicalPath:z.string(),rebindMissingCallbacks:z.boolean().optional(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledMemoryDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),slot:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),visibility:z.enum([`scope`,`session`])}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),extensionNamespace:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledExtensionMountSchema=z.object({externalDependencies:z.array(z.string()).readonly(),namespace:z.string(),packageName:z.string(),specifier:z.string(),mountId:mountIdSchema,sourceRoot:z.string(),mountSourceId:z.string(),mountSourcePath:z.string(),mountLogicalPath:z.string(),programmaticImport:z.object({specifier:z.string(),entryPath:z.string(),config:jsonObjectSchema}).strict().optional()}).strict(),compiledAgentResourceFields={agentRoot:z.string(),appRoot:z.string(),bindings:z.record(z.string(),compiledModuleBindingSchema),channelRoutes:compiledChannelRoutePlanSchema,connections:z.array(compiledConnectionDefinitionSchema),dynamicConnections:z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary:discoverDiagnosticsSummarySchema,sourceComposition:agentSourceCompositionSchema,dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),extensionMounts:z.array(compiledExtensionMountSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),memories:z.array(compiledMemoryDefinitionSchema).default([]),sandbox:compiledSandboxDefinitionSchema,sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),scheduleCollections:z.array(compiledScheduleCollectionDefinitionSchema).default([]),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:z.array(compiledInstructionsSchema).readonly().default([]),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema},compiledAgentResourcesSchema=z.object(compiledAgentResourceFields).strict(),compiledAgentNodeManifestSchema=z.object({...compiledAgentResourceFields,config:compiledAgentConfigSchema}).strict(),compiledSubagentNodeBaseFields={backing:resourceSourceBackingSchema,entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),owner:agentSourceOwnerSchema,parentNodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()},compiledDynamicSubagentDefinitionSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSubagentNodeSchema=z.union([z.object({...compiledSubagentNodeBaseFields,agent:compiledAgentNodeManifestSchema,description:z.string()}).strict(),z.object({...compiledSubagentNodeBaseFields,agent:compiledAgentResourcesSchema,configResolver:compiledDynamicSubagentDefinitionSchema}).strict()]),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),bindings:z.record(z.string(),compiledModuleBindingSchema),extensionMounts:z.array(compiledExtensionMountSchema).default([]),channelRoutes:compiledChannelRoutePlanSchema,config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),dynamicConnections:z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary:discoverDiagnosticsSummarySchema,sourceComposition:agentSourceCompositionSchema,dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),memories:z.array(compiledMemoryDefinitionSchema).default([]),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema,sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),scheduleCollections:z.array(compiledScheduleCollectionDefinitionSchema).default([]),skills:z.array(compiledSkillSourceSchema).readonly(),subagents:z.array(compiledSubagentNodeSchema),instructions:z.array(compiledInstructionsSchema).readonly().default([]),tools:z.array(compiledToolDefinitionSchema),version:z.literal(54),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentResources(e){return{agentRoot:e.agentRoot,appRoot:e.appRoot,bindings:{...e.bindings},channelRoutes:{effective:[...e.channelRoutes.effective],preflight:[...e.channelRoutes.preflight],shadowed:[...e.channelRoutes.shadowed]},connections:[...e.connections??[]],dynamicConnections:[...e.dynamicConnections??[]],diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},sourceComposition:{entries:[...e.sourceComposition.entries]},dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],extensionMounts:[...e.extensionMounts??[]],hooks:[...e.hooks??[]],memories:[...e.memories??[]],instructions:[...e.instructions??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],scheduleCollections:[...e.scheduleCollections??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}}function createCompiledAgentNodeManifest(e){let t={...createCompiledAgentResources(e),config:cloneCompiledAgentDefinition(e.config)};return validateCompiledAgentResources(t,{allowUnknownResourceWinners:!0}),t}function cloneCompiledAgentDefinition(e){let t={build:e.build===void 0?void 0:{externalDependencies:e.build.externalDependencies===void 0?void 0:[...e.build.externalDependencies]},compaction:{model:e.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.compaction.model),thresholdPercent:e.compaction?.thresholdPercent},defaultTools:e.defaultTools,description:e.description,experimental:e.experimental===void 0?void 0:{workflow:e.experimental.workflow===void 0?void 0:{modelCallsPerStep:e.experimental.workflow.modelCallsPerStep,retention:e.experimental.workflow.retention,world:e.experimental.workflow.world}},name:e.name,reasoning:e.reasoning,limits:e.limits===void 0?void 0:{maxInputTokensPerSession:e.limits.maxInputTokensPerSession,maxOutputTokensPerSession:e.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:e.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:e.limits.sessionTimeoutMs},source:{...e.source},tool:e.tool};return e.dynamicModel===void 0?{...t,model:cloneCompiledRuntimeModelReference(e.model)}:{...t,dynamicModel:{...e.dynamicModel}}}function deriveResourceRootEntries(e){let t=new Set;for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){let t={...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,extensionMounts:[...e.extensionMounts??[]],subagents:[...e.subagents??[]],version:54};return validateCompiledAgentManifest(t),t}function cloneCompiledRuntimeModelReference(e){let t={id:e.id,routing:cloneModelRouting(e.routing)};return e.contextWindowTokens!==void 0&&(t.contextWindowTokens=e.contextWindowTokens),e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.providerOptions!==void 0&&(t.providerOptions={...e.providerOptions}),e.source!==void 0&&(t.source={...e.source}),t}function cloneModelRouting(e){return e.kind===`external`?{kind:`external`,provider:e.provider}:e.byok===void 0?{kind:`gateway`,target:e.target}:{kind:`gateway`,target:e.target,byok:e.byok}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId,deriveResourceRootEntries};
1
+ import{z}from"#compiled/zod/index.js";import{mountIdSchema}from"#shared/extension-mount.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";import{WEB_SEARCH_FALLBACK_PROVIDERS,WEB_SEARCH_PROVIDERS}from"#shared/web-search.js";import{AGENT_WORKFLOW_RETENTION_VALUES,ANTHROPIC_PROMPT_CACHE_TTLS}from"#shared/agent-definition.js";import{validateCompiledAgentManifest,validateCompiledAgentResources}from"#compiler/validate-artifact.js";const COMPILED_AGENT_MANIFEST_KIND=`eve-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=54,agentSourceOwnerSchema=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string().min(1),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),mountId:mountIdSchema,namespace:z.string().min(1),packageName:z.string().min(1)}).strict()]),moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),filesystemModuleBackingSchema=z.object({externalDependencies:z.array(z.string()).readonly(),extensionScope:z.object({namespace:z.string(),sourceRoot:z.string()}).strict().optional(),mountId:z.string().optional(),kind:z.literal(`filesystem`),sourcePath:z.string()}).strict(),programmaticModuleBackingSchema=z.object({dependencies:z.record(z.string(),z.string()).readonly().optional(),kind:z.literal(`programmatic`),mountId:z.string().optional(),moduleId:z.string(),parameters:jsonObjectSchema.optional(),registryId:z.string(),revision:z.string(),semanticRevision:z.string().optional()}).strict(),resourceSourceBackingSchema=z.object({kind:z.literal(`resource`),sourcePath:z.string()}).strict(),agentModuleBackingSchema=z.discriminatedUnion(`kind`,[filesystemModuleBackingSchema,programmaticModuleBackingSchema]),compiledModuleBindingSchema=z.object({backing:agentModuleBackingSchema,logicalPath:z.string(),owner:agentSourceOwnerSchema,usage:z.object({compile:z.boolean(),runtimeEntry:z.boolean()}).strict()}).strict(),agentSourceDescriptorSchema=z.object({backing:z.discriminatedUnion(`kind`,[filesystemModuleBackingSchema,programmaticModuleBackingSchema,resourceSourceBackingSchema]),form:z.enum([`derived`,`direct`]),layer:z.enum([`framework-default`,`extension-package`,`extension-override`,`application`]),logicalPath:z.string(),owner:agentSourceOwnerSchema,sourceId:z.string()}).strict(),agentSourceCompositionSchema=z.object({entries:z.array(z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`shadowed`),source:agentSourceDescriptorSchema,winnerSourceId:z.string()}).strict(),z.object({kind:z.literal(`disabled`),source:agentSourceDescriptorSchema}).strict()])).readonly()}).strict(),compiledDynamicModelDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`HEAD`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`OPTIONS`),z.literal(`WEBSOCKET`)]),compiledChannelCorsSchema=z.object({origin:z.union([z.literal(`*`),z.literal(`null`),z.array(z.string())]).optional(),methods:z.union([z.literal(`*`),z.array(z.string())]).optional(),allowHeaders:z.union([z.literal(`*`),z.array(z.string())]).optional(),exposeHeaders:z.union([z.literal(`*`),z.array(z.string())]).optional(),credentials:z.boolean().optional(),maxAge:z.union([z.string(),z.literal(!1)]).optional(),preflight:z.object({statusCode:z.number().int().min(100).max(599).optional()}).strict().optional()}).strict(),compiledVercelConnectMetadataSchema=z.object({connector:z.string(),requirement:z.object({method:z.string().optional(),reference:z.string(),service:z.string(),subjectTypes:z.array(z.enum([`app`,`user`])).readonly()}).strict().optional()}).strict(),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional(),cors:compiledChannelCorsSchema.optional(),manifest:jsonObjectSchema.optional(),vercelConnect:compiledVercelConnectMetadataSchema.optional()}).strict(),compiledChannelPreflightDefinitionSchema=z.object({cors:compiledChannelCorsSchema,method:z.literal(`OPTIONS`),sourceIds:z.array(z.string()).readonly(),urlPath:z.string()}).strict(),compiledShadowedChannelRouteSchema=z.object({method:channelMethodSchema,source:agentSourceDescriptorSchema,urlPath:z.string(),winnerSourceId:z.string()}).strict(),compiledChannelRoutePlanSchema=z.object({effective:z.array(compiledChannelDefinitionSchema).readonly(),preflight:z.array(compiledChannelPreflightDefinitionSchema).readonly(),shadowed:z.array(compiledShadowedChannelRouteSchema).readonly()}).strict(),modelRoutingSchema=z.union([z.object({kind:z.literal(`gateway`),target:z.string(),byok:z.string().optional()}).strict(),z.object({kind:z.literal(`external`),provider:z.string()}).strict()]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),maxOutputTokens:z.number().int().positive().optional(),source:moduleSourceRefSchema.optional(),promptCache:z.object({anthropic:z.object({ttl:z.literal(ANTHROPIC_PROMPT_CACHE_TTLS).optional()}).strict().optional()}).strict().optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional(),routing:modelRoutingSchema}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentWorkflowWorldDefinitionSchema=z.string(),compiledAgentWorkflowDefinitionSchema=z.object({modelCallsPerStep:z.number().int().positive().optional(),retention:z.literal(AGENT_WORKFLOW_RETENTION_VALUES).optional(),world:compiledAgentWorkflowWorldDefinitionSchema.optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),sessionTokenLimitSchema=z.union([z.number().int().positive(),z.literal(!1)]),sessionTokenCostLimitSchema=z.union([z.number().finite().positive(),z.literal(!1)]),sessionTimeoutSchema=z.union([z.number().int().positive(),z.literal(!1)]),compiledAgentLimitsDefinitionSchema=z.object({maxInputTokensPerSession:sessionTokenLimitSchema.optional(),maxOutputTokensPerSession:sessionTokenLimitSchema.optional(),maxTokenCostUsdPerSession:sessionTokenCostLimitSchema.optional(),sessionTimeoutMs:sessionTimeoutSchema.optional()}).strict(),compiledAgentConfigBaseFields={build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),defaultTools:z.boolean().optional(),description:z.string().optional(),experimental:z.object({workflow:compiledAgentWorkflowDefinitionSchema.optional()}).strict().optional(),name:z.string(),reasoning:z.enum([`provider-default`,`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),source:moduleSourceRefSchema,tool:z.union([z.boolean(),z.literal(`deferred`)]).optional(),limits:compiledAgentLimitsDefinitionSchema.optional()},compiledAgentConfigSchema=z.union([z.object({...compiledAgentConfigBaseFields,model:compiledRuntimeModelReferenceSchema}).strict(),z.object({...compiledAgentConfigBaseFields,dynamicModel:compiledDynamicModelDefinitionSchema}).strict()]),compiledInstructionsBaseFields={content:z.string(),name:z.string(),logicalPath:z.string(),role:z.enum([`system`,`user`]),sourceId:z.string()},compiledInstructionsSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledInstructionsBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledInstructionsBaseFields,sourceKind:z.literal(`module`)}).strict()]),compiledSkillBaseFields={name:z.string(),deferred:z.boolean().optional(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleBaseFields={cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string()},compiledScheduleDefinitionSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledScheduleBaseFields,owner:agentSourceOwnerSchema,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledScheduleBaseFields,sourceKind:z.literal(`module`)}).strict()]),compiledScheduleCollectionDefinitionSchema=z.object({description:z.string().optional(),logicalPath:z.string(),name:z.string(),providerKind:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),tools:z.boolean().optional()}).strict(),compiledSandboxDefinitionSchema=z.object({providerName:z.string().optional(),environmentExportName:z.string().optional(),inheritsParent:z.boolean().optional(),exportName:z.string().optional(),logicalPath:z.string(),revisionHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),protocol:z.enum([`mcp`,`openapi`]).default(`mcp`),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:compiledVercelConnectMetadataSchema.optional()}).strict(),compiledDynamicConnectionDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),extensionNamespace:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledToolBehaviorSchema=z.object({availability:z.array(z.literal(`root-session`)).readonly(),handling:z.discriminatedUnion(`kind`,[z.object({action:z.literal(`self-agent`),kind:z.literal(`dispatch`)}).strict(),z.object({fallback:z.enum(WEB_SEARCH_FALLBACK_PROVIDERS).optional(),kind:z.literal(`provider-tool`),provider:z.enum(WEB_SEARCH_PROVIDERS)}).strict(),z.object({entryPoint:z.enum([`execute`,`task`,`serve`]),kind:z.literal(`workflow-tool`),workflowId:z.string()}).strict()]).optional(),shape:z.object({suspend:z.enum([`none`,`workflow`])}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({availableInSubagents:z.boolean().optional(),behavior:compiledToolBehaviorSchema.optional(),deferred:z.boolean().optional(),description:z.string(),exportName:z.string().optional(),hasExecute:z.boolean(),hasModelOutputProjection:z.boolean(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),modelInputSchema:jsonObjectSchema.optional(),name:z.string(),outputSchema:jsonObjectSchema.optional(),requiresApproval:z.boolean(),sourceId:z.string(),sourceKind:z.literal(`module`),workflowProgram:z.object({maxSubagents:z.number().int().positive()}).strict().optional()}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),extensionNamespace:z.string().optional(),logicalPath:z.string(),rebindMissingCallbacks:z.boolean().optional(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledMemoryDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),slot:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),visibility:z.enum([`scope`,`session`])}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),extensionNamespace:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledExtensionMountSchema=z.object({externalDependencies:z.array(z.string()).readonly(),namespace:z.string(),packageName:z.string(),specifier:z.string(),mountId:mountIdSchema,sourceRoot:z.string(),mountSourceId:z.string(),mountSourcePath:z.string(),mountLogicalPath:z.string(),programmaticImport:z.object({specifier:z.string(),entryPath:z.string(),config:jsonObjectSchema}).strict().optional()}).strict(),compiledAgentResourceFields={agentRoot:z.string(),appRoot:z.string(),bindings:z.record(z.string(),compiledModuleBindingSchema),channelRoutes:compiledChannelRoutePlanSchema,connections:z.array(compiledConnectionDefinitionSchema),dynamicConnections:z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary:discoverDiagnosticsSummarySchema,sourceComposition:agentSourceCompositionSchema,dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),extensionMounts:z.array(compiledExtensionMountSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),memories:z.array(compiledMemoryDefinitionSchema).default([]),sandbox:compiledSandboxDefinitionSchema,sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),scheduleCollections:z.array(compiledScheduleCollectionDefinitionSchema).default([]),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:z.array(compiledInstructionsSchema).readonly().default([]),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema},compiledAgentResourcesSchema=z.object(compiledAgentResourceFields).strict(),compiledAgentNodeManifestSchema=z.object({...compiledAgentResourceFields,config:compiledAgentConfigSchema}).strict(),compiledSubagentNodeBaseFields={backing:resourceSourceBackingSchema,entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),owner:agentSourceOwnerSchema,parentNodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()},compiledDynamicSubagentDefinitionSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSubagentNodeSchema=z.union([z.object({...compiledSubagentNodeBaseFields,agent:compiledAgentNodeManifestSchema,description:z.string()}).strict(),z.object({...compiledSubagentNodeBaseFields,agent:compiledAgentResourcesSchema,configResolver:compiledDynamicSubagentDefinitionSchema}).strict()]),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),bindings:z.record(z.string(),compiledModuleBindingSchema),extensionMounts:z.array(compiledExtensionMountSchema).default([]),channelRoutes:compiledChannelRoutePlanSchema,config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),dynamicConnections:z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary:discoverDiagnosticsSummarySchema,sourceComposition:agentSourceCompositionSchema,dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),memories:z.array(compiledMemoryDefinitionSchema).default([]),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema,sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),scheduleCollections:z.array(compiledScheduleCollectionDefinitionSchema).default([]),skills:z.array(compiledSkillSourceSchema).readonly(),subagents:z.array(compiledSubagentNodeSchema),instructions:z.array(compiledInstructionsSchema).readonly().default([]),tools:z.array(compiledToolDefinitionSchema),version:z.literal(54),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentResources(e){return{agentRoot:e.agentRoot,appRoot:e.appRoot,bindings:{...e.bindings},channelRoutes:{effective:[...e.channelRoutes.effective],preflight:[...e.channelRoutes.preflight],shadowed:[...e.channelRoutes.shadowed]},connections:[...e.connections??[]],dynamicConnections:[...e.dynamicConnections??[]],diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},sourceComposition:{entries:[...e.sourceComposition.entries]},dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],extensionMounts:[...e.extensionMounts??[]],hooks:[...e.hooks??[]],memories:[...e.memories??[]],instructions:[...e.instructions??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],scheduleCollections:[...e.scheduleCollections??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}}function createCompiledAgentNodeManifest(e){let t={...createCompiledAgentResources(e),config:cloneCompiledAgentDefinition(e.config)};return validateCompiledAgentResources(t,{allowUnknownResourceWinners:!0}),t}function cloneCompiledAgentDefinition(e){let t={build:e.build===void 0?void 0:{externalDependencies:e.build.externalDependencies===void 0?void 0:[...e.build.externalDependencies]},compaction:{model:e.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.compaction.model),thresholdPercent:e.compaction?.thresholdPercent},defaultTools:e.defaultTools,description:e.description,experimental:e.experimental===void 0?void 0:{workflow:e.experimental.workflow===void 0?void 0:{modelCallsPerStep:e.experimental.workflow.modelCallsPerStep,retention:e.experimental.workflow.retention,world:e.experimental.workflow.world}},name:e.name,reasoning:e.reasoning,limits:e.limits===void 0?void 0:{maxInputTokensPerSession:e.limits.maxInputTokensPerSession,maxOutputTokensPerSession:e.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:e.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:e.limits.sessionTimeoutMs},source:{...e.source},tool:e.tool};return e.dynamicModel===void 0?{...t,model:cloneCompiledRuntimeModelReference(e.model)}:{...t,dynamicModel:{...e.dynamicModel}}}function deriveResourceRootEntries(e){let t=new Set;for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){let t={...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,extensionMounts:[...e.extensionMounts??[]],subagents:[...e.subagents??[]],version:54};return validateCompiledAgentManifest(t),t}function cloneCompiledRuntimeModelReference(e){let t={id:e.id,routing:cloneModelRouting(e.routing)};return e.contextWindowTokens!==void 0&&(t.contextWindowTokens=e.contextWindowTokens),e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.providerOptions!==void 0&&(t.providerOptions={...e.providerOptions}),e.promptCache!==void 0&&(t.promptCache=structuredClone(e.promptCache)),e.source!==void 0&&(t.source={...e.source}),t}function cloneModelRouting(e){return e.kind===`external`?{kind:`external`,provider:e.provider}:e.byok===void 0?{kind:`gateway`,target:e.target}:{kind:`gateway`,target:e.target,byok:e.byok}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId,deriveResourceRootEntries};
@@ -1 +1 @@
1
- import{isAbsolute,relative,resolve}from"node:path";import{normalizeLogicalPath}from"#discover/filesystem.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonObject}from"#shared/json.js";import{isDynamicModelDefinition}from"#shared/agent-definition.js";import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{classifyModelRouting}from"#internal/classify-model-routing.js";import{isChatGptModelRouting}from"#shared/chatgpt-model.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileAgentConfig(e,t,n){let r=n.source,i=formatAgentConfigModulePath(e,r,n.binding),a=normalizeAgentDefinition(Object.hasOwn(n,`definition`)?n.definition:await loadModuleBackedDefinition({binding:n.binding,displayPath:i,kind:`agent config`,loadNamespace:createCompiledBindingNamespaceLoader({appRoot:e.appRoot,bindings:{[r.sourceId]:n.binding},registries:t.registries}),source:r}),`Expected the agent config export "${r.exportName??`default`}" from "${i}" to match the public eve shape.`),o=isDynamicModelDefinition(a.model)?a.model:void 0,s=o===void 0?await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:a.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.model}):void 0,c={},l={compaction:c,name:e.agentId,source:{...r}};a.defaultTools!==void 0&&(l.defaultTools=a.defaultTools),a.description!==void 0&&(l.description=a.description);let u;o!==void 0&&(u={eventNames:Object.keys(o.events),exportName:r.exportName,sourceKind:`module`,logicalPath:r.logicalPath,sourceId:r.sourceId});let d=normalizeExperimentalDefinition(a.experimental);if(d!==void 0&&(l.experimental=d),a.build!==void 0&&(l.build={externalDependencies:a.build.externalDependencies===void 0?void 0:[...a.build.externalDependencies]}),a.reasoning!==void 0&&(l.reasoning=a.reasoning),a.tool!==void 0&&(l.tool=a.tool),a.limits!==void 0&&(l.limits={maxInputTokensPerSession:a.limits.maxInputTokensPerSession,maxOutputTokensPerSession:a.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:a.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:a.limits.sessionTimeoutMs}),a.compaction?.model!==void 0&&(c.model=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:a.compaction.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.compaction.model})),a.compaction?.thresholdPercent!==void 0&&(c.thresholdPercent=a.compaction.thresholdPercent),u!==void 0)return{...l,dynamicModel:u};if(s===void 0)throw Error(`Expected a static agent model to compile to a concrete model reference.`);return{...l,model:s}}function normalizeExperimentalDefinition(e){if(e===void 0)return;let t={};return e.workflow!==void 0&&(t.workflow={modelCallsPerStep:e.workflow.modelCallsPerStep,retention:e.workflow.retention,world:e.workflow.world}),t}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`)return await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:classifyModelRouting(e.value,e.providerOptions)},e);let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${e.sourcePath??t.logicalPath}" to provide a valid AI SDK language model.`);let i={id:formatLanguageModelGatewayId(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:classifyModelRouting(n,e.providerOptions)};if(e.contextWindowTokens===void 0){if(isChatGptModelRouting(i.routing))return{...i,contextWindowTokens:2e5};try{let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...i,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens,maxOutputTokens:t.limits.maxOutputTokens}}catch{}}return await withCompiledRuntimeModelLimits(i,e)}function formatAgentConfigModulePath(e,t,n){return n.backing.kind===`programmatic`?t.logicalPath:normalizeLogicalPath(relative(resolveTopLevelAgentRoot(e),n.backing.sourcePath))}function resolveTopLevelAgentRoot(e){let t=resolve(e.appRoot),n=resolve(t,`agent`);return isPathInsideOrEqual(n,resolve(e.agentRoot))?n:t}function isPathInsideOrEqual(e,t){let n=relative(e,t);return n===``||!n.startsWith(`..`)&&!isAbsolute(n)}async function withCompiledRuntimeModelLimits(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${toErrorMessage(n)}`)}if(n===null)throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`);return{...e,contextWindowTokens:n.contextWindowTokens,maxOutputTokens:n.maxOutputTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=parseJsonObject(r);return t}export{compileAgentConfig};
1
+ import{isAbsolute,relative,resolve}from"node:path";import{normalizeLogicalPath}from"#discover/filesystem.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonObject}from"#shared/json.js";import{isDynamicModelDefinition}from"#shared/agent-definition.js";import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{classifyModelRouting}from"#internal/classify-model-routing.js";import{isChatGptModelRouting}from"#shared/chatgpt-model.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileAgentConfig(e,t,n){let r=n.source,i=formatAgentConfigModulePath(e,r,n.binding),a=normalizeAgentDefinition(Object.hasOwn(n,`definition`)?n.definition:await loadModuleBackedDefinition({binding:n.binding,displayPath:i,kind:`agent config`,loadNamespace:createCompiledBindingNamespaceLoader({appRoot:e.appRoot,bindings:{[r.sourceId]:n.binding},registries:t.registries}),source:r}),`Expected the agent config export "${r.exportName??`default`}" from "${i}" to match the public eve shape.`),o=isDynamicModelDefinition(a.model)?a.model:void 0,s=o===void 0?await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:a.modelContextWindowTokens,promptCache:a.modelOptions?.promptCache,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.model}):void 0,c={},l={compaction:c,name:e.agentId,source:{...r}};a.defaultTools!==void 0&&(l.defaultTools=a.defaultTools),a.description!==void 0&&(l.description=a.description);let u;o!==void 0&&(u={eventNames:Object.keys(o.events),exportName:r.exportName,sourceKind:`module`,logicalPath:r.logicalPath,sourceId:r.sourceId});let d=normalizeExperimentalDefinition(a.experimental);if(d!==void 0&&(l.experimental=d),a.build!==void 0&&(l.build={externalDependencies:a.build.externalDependencies===void 0?void 0:[...a.build.externalDependencies]}),a.reasoning!==void 0&&(l.reasoning=a.reasoning),a.tool!==void 0&&(l.tool=a.tool),a.limits!==void 0&&(l.limits={maxInputTokensPerSession:a.limits.maxInputTokensPerSession,maxOutputTokensPerSession:a.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:a.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:a.limits.sessionTimeoutMs}),a.compaction?.model!==void 0&&(c.model=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:a.compaction.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:r,sourcePath:i,value:a.compaction.model})),a.compaction?.thresholdPercent!==void 0&&(c.thresholdPercent=a.compaction.thresholdPercent),u!==void 0)return{...l,dynamicModel:u};if(s===void 0)throw Error(`Expected a static agent model to compile to a concrete model reference.`);return{...l,model:s}}function normalizeExperimentalDefinition(e){if(e===void 0)return;let t={};return e.workflow!==void 0&&(t.workflow={modelCallsPerStep:e.workflow.modelCallsPerStep,retention:e.workflow.retention,world:e.workflow.world}),t}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`){let t=classifyModelRouting(e.value,e.providerOptions);return rejectGatewayPromptCache(e,t),await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:t},e)}let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${e.sourcePath??t.logicalPath}" to provide a valid AI SDK language model.`);let i=classifyModelRouting(n,e.providerOptions);rejectGatewayPromptCache(e,i);let a={id:formatLanguageModelGatewayId(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:i};if(e.promptCache!==void 0&&(a.promptCache=e.promptCache),e.contextWindowTokens===void 0){if(isChatGptModelRouting(a.routing))return{...a,contextWindowTokens:2e5};try{let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...a,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens,maxOutputTokens:t.limits.maxOutputTokens}}catch{}}return await withCompiledRuntimeModelLimits(a,e)}function rejectGatewayPromptCache(e,t){if(e.promptCache!==void 0&&t.kind===`gateway`)throw Error(`${e.sourcePath??`agent.ts`}: modelOptions.promptCache applies only to models eve calls directly, but "${formatLanguageModelGatewayId(e.value)}" routes through AI Gateway, which manages its own prompt caching. Remove promptCache, or configure Gateway caching with providerOptions.gateway.caching.`)}function formatAgentConfigModulePath(e,t,n){return n.backing.kind===`programmatic`?t.logicalPath:normalizeLogicalPath(relative(resolveTopLevelAgentRoot(e),n.backing.sourcePath))}function resolveTopLevelAgentRoot(e){let t=resolve(e.appRoot),n=resolve(t,`agent`);return isPathInsideOrEqual(n,resolve(e.agentRoot))?n:t}function isPathInsideOrEqual(e,t){let n=relative(e,t);return n===``||!n.startsWith(`..`)&&!isAbsolute(n)}async function withCompiledRuntimeModelLimits(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${toErrorMessage(n)}`)}if(n===null)throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`);return{...e,contextWindowTokens:n.contextWindowTokens,maxOutputTokens:n.maxOutputTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=parseJsonObject(r);return t}export{compileAgentConfig};
@@ -1,5 +1,5 @@
1
1
  import type { ContextKey } from "#context/key.js";
2
- export type { Session, SessionAuth, SessionAuthContext, SessionParent, SessionTurn, } from "#context/keys.js";
2
+ export type { Session, SessionAuth, SessionAuthContext, SessionParent, SessionPredecessor, SessionTurn, } from "#context/keys.js";
3
3
  /**
4
4
  * Returns the current value of a context key, or `undefined` when unset.
5
5
  *
@@ -1 +1 @@
1
- import{loadContext}from"#context/container.js";import{DynamicSkillSandboxKey,SandboxKey,SessionKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";function buildCallbackContext(){let e=loadContext(),t=e.require(SessionKey);return{session:{id:t.sessionId,auth:t.auth,turn:t.turn,parent:t.parent,schedule:readSessionSchedule(e)},getSandbox(t){let n=e.get(SandboxKey);if(n===void 0)throw Error(`eve sandbox runtime access is unavailable in the current async context. Call ctx.getSandbox() only from authored runtime functions such as tools, hooks, and channel events.`);if(t!==void 0&&n.environment!==t)throw Error(`The requested sandbox environment is not active for the current session.`);return n.get().then(t=>{if(t===null)throw Error(`The sandbox is not available in the current authored runtime context.`);return withRuntimeSandboxLifecycle(t,async t=>{if(n.delete===void 0)throw Error(`The active sandbox runtime does not support deletion.`);await n.delete(t),e.delete(DynamicSkillSandboxKey)},async()=>await n.stop())})}}}function withRuntimeSandboxLifecycle(e,t,n){return new Proxy(Object.create(null),{get(r,i){if(i===`delete`)return t;if(i===`stop`)return n;let a=Reflect.get(e,i,e);return typeof a==`function`?a.bind(e):a},getOwnPropertyDescriptor(t,n){if(n===`delete`||n===`stop`)return{configurable:!0,enumerable:!0,writable:!1};let r=Reflect.getOwnPropertyDescriptor(e,n);return r===void 0?void 0:{...r,configurable:!0}},has(t,n){return n===`delete`||n===`stop`||Reflect.has(e,n)},ownKeys(){return[...new Set([...Reflect.ownKeys(e),`delete`,`stop`])]}})}export{buildCallbackContext,withRuntimeSandboxLifecycle};
1
+ import{loadContext}from"#context/container.js";import{DynamicSkillSandboxKey,SandboxKey,SessionKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";function buildCallbackContext(){let e=loadContext(),t=e.require(SessionKey);return{session:{id:t.sessionId,auth:t.auth,turn:t.turn,parent:t.parent,schedule:readSessionSchedule(e),predecessor:t.predecessor},getSandbox(t){let n=e.get(SandboxKey);if(n===void 0)throw Error(`eve sandbox runtime access is unavailable in the current async context. Call ctx.getSandbox() only from authored runtime functions such as tools, hooks, and channel events.`);if(t!==void 0&&n.environment!==t)throw Error(`The requested sandbox environment is not active for the current session.`);return n.get().then(t=>{if(t===null)throw Error(`The sandbox is not available in the current authored runtime context.`);return withRuntimeSandboxLifecycle(t,async t=>{if(n.delete===void 0)throw Error(`The active sandbox runtime does not support deletion.`);await n.delete(t),e.delete(DynamicSkillSandboxKey)},async()=>await n.stop())})}}}function withRuntimeSandboxLifecycle(e,t,n){return new Proxy(Object.create(null),{get(r,i){if(i===`delete`)return t;if(i===`stop`)return n;let a=Reflect.get(e,i,e);return typeof a==`function`?a.bind(e):a},getOwnPropertyDescriptor(t,n){if(n===`delete`||n===`stop`)return{configurable:!0,enumerable:!0,writable:!1};let r=Reflect.getOwnPropertyDescriptor(e,n);return r===void 0?void 0:{...r,configurable:!0}},has(t,n){return n===`delete`||n===`stop`||Reflect.has(e,n)},ownKeys(){return[...new Set([...Reflect.ownKeys(e),`delete`,`stop`])]}})}export{buildCallbackContext,withRuntimeSandboxLifecycle};
@@ -1 +1 @@
1
- import{ConversationContextKey}from"#shared/conversation-context.js";import{getAdapterKind}from"#channel/adapter.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getEffectiveModelSelection}from"#context/effective-model.js";function buildResolveContext(e,t){let n=e.get(SessionIdKey)??``,r=e.get(AuthKey)??null,i=e.get(InitiatorAuthKey)??null,a=e.get(ChannelKey),o=e.get(ContinuationTokenKey),s=e.get(ChannelInstrumentationKey),c=getEffectiveModelSelection(e);return{model:c===null?null:{id:c.reference.id},session:{id:n,schedule:readSessionSchedule(e),auth:{current:r,initiator:i}},channel:{kind:a===void 0?void 0:getAdapterKind(a),continuationToken:o,metadata:s?.metadata},...e.get(ConversationContextKey)===void 0?void 0:{conversation:e.get(ConversationContextKey)},messages:t}}export{buildResolveContext};
1
+ import{ConversationContextKey}from"#shared/conversation-context.js";import{getAdapterKind}from"#channel/adapter.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey,SessionPredecessorKey}from"#context/keys.js";import{readSessionSchedule}from"#context/session-schedule.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getEffectiveModelSelection}from"#context/effective-model.js";function buildResolveContext(e,t){let n=e.get(SessionIdKey)??``,r=e.get(AuthKey)??null,i=e.get(InitiatorAuthKey)??null,a=e.get(ChannelKey),o=e.get(ContinuationTokenKey),s=e.get(ChannelInstrumentationKey),c=getEffectiveModelSelection(e);return{model:c===null?null:{id:c.reference.id},session:{id:n,schedule:readSessionSchedule(e),auth:{current:r,initiator:i},predecessor:e.get(SessionPredecessorKey)},channel:{kind:a===void 0?void 0:getAdapterKind(a),continuationToken:o,metadata:s?.metadata},...e.get(ConversationContextKey)===void 0?void 0:{conversation:e.get(ConversationContextKey)},messages:t}}export{buildResolveContext};
@@ -20,7 +20,9 @@ import type { HistoryViewProjector } from "#shared/history-view.js";
20
20
  import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
21
21
  import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";
22
22
  import type { MemoryScope, MemoryTurnContext } from "#public/memory/index.js";
23
+ import type { SessionPredecessor } from "#protocol/message.js";
23
24
  export type { SessionAuthContext, SessionParent, SessionTraceRoot, SessionTurn, } from "#channel/types.js";
25
+ export type { SessionPredecessor } from "#protocol/message.js";
24
26
  /**
25
27
  * Auth metadata on the active session.
26
28
  *
@@ -42,6 +44,7 @@ export interface SessionAuth {
42
44
  export interface Session {
43
45
  readonly auth: SessionAuth;
44
46
  readonly parent?: SessionParent;
47
+ readonly predecessor?: SessionPredecessor;
45
48
  readonly sessionId: string;
46
49
  readonly turn: SessionTurn;
47
50
  }
@@ -94,6 +97,8 @@ export interface ActiveChannelDelivery {
94
97
  export declare const ActiveChannelDeliveriesKey: ContextKey<readonly ActiveChannelDelivery[]>;
95
98
  export declare const ChannelInstrumentationKey: ContextKey<ChannelInstrumentationProjection>;
96
99
  export declare const ParentSessionKey: ContextKey<SessionParent>;
100
+ /** Set only on a session eve started in place of one that could no longer run. */
101
+ export declare const SessionPredecessorKey: ContextKey<SessionPredecessor>;
97
102
  /** Set only when the trace root differs from `ParentSessionKey`'s root; see {@link SessionTraceRoot}. */
98
103
  export declare const TraceRootKey: ContextKey<SessionTraceRoot>;
99
104
  /** Separate from {@link ParentSessionKey} so it stays out of what extensions read. */
@@ -1 +1 @@
1
- import{SESSION_INBOX_CONTEXT_KEY}from"#execution/session-inbox/address.js";import{ContextKey}from"#context/key.js";import{STUB_CONTEXT_KEY}from"#tool-stubs/types.js";import{SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";const AuthKey=new ContextKey(`eve.auth`),ToolStubsKey=new ContextKey(STUB_CONTEXT_KEY),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ConversationIdKey=new ContextKey(`eve.conversationId`),SessionInboxKey=new ContextKey(SESSION_INBOX_CONTEXT_KEY),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ContinuationHookTokensKey=new ContextKey(`eve.continuationHookTokens`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),LocalDevRequestKey=new ContextKey(`eve.internal.localDevRequest`),OccurrenceIdKey=new ContextKey(`eve.scheduleOccurrenceId`),ScheduleIdKey=new ContextKey(`eve.scheduleId`),ScheduleInstanceKey=new ContextKey(`eve.scheduleInstance`),SessionTitleKey=new ContextKey(`eve.sessionTitle`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnDeliveryIdsKey=new ContextKey(`eve.turnDeliveryIds`),HistoryStateKey=new ContextKey(`eve.historyState`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ParentSessionKey=new ContextKey(`eve.parentSession`),TraceRootKey=new ContextKey(`eve.traceRoot`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SessionTraceSeedKey=new ContextKey(`eve.sessionTraceSeed`),OtelTraceEnabledKey=new ContextKey(`eve.otelTraceEnabled`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(SESSION_CALLBACK_CONTEXT_KEY_NAME),LegacyRemoteAgentCallerKey=new ContextKey(`eve.legacyRemoteAgentCaller`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),SandboxTerminalCleanupKey=new ContextKey(`eve.internal.sandboxTerminalCleanup`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),StaticModelReferenceKey=new ContextKey(`eve.staticModelReference`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),TurnMemoryLocksKey=new ContextKey(`eve.memory.turnLocks`),PreparedMemoryPreambleKey=new ContextKey(`eve.memory.preparedPreamble`),PendingMemoryCommitKey=new ContextKey(`eve.memory.pendingCommit`),PreparedMemoryCompactionKey=new ContextKey(`eve.memory.preparedCompaction`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),DynamicSkillSandboxKey=new ContextKey(`eve.dynamicSkillSandbox`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSkillSandboxKey,DynamicSubagentAgentConfigKey,HandleEventKey,HistoryStateKey,InitiatorAuthKey,LegacyRemoteAgentCallerKey,LiveStepDynamicModelSelectionKey,LocalDevRequestKey,OccurrenceIdKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,PendingMemoryCommitKey,PreparedMemoryCompactionKey,PreparedMemoryPreambleKey,RuntimeModelMetadataCacheKey,SandboxKey,SandboxTerminalCleanupKey,ScheduleIdKey,ScheduleInstanceKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionInboxKey,SessionKey,SessionTitleKey,SessionTraceSeedKey,StaticModelReferenceKey,StepDynamicToolMetadataKey,ToolStubsKey,TraceRootKey,TurnDeliveryIdsKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnMemoryLocksKey};
1
+ import{SESSION_INBOX_CONTEXT_KEY}from"#execution/session-inbox/address.js";import{ContextKey}from"#context/key.js";import{STUB_CONTEXT_KEY}from"#tool-stubs/types.js";import{SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";const AuthKey=new ContextKey(`eve.auth`),ToolStubsKey=new ContextKey(STUB_CONTEXT_KEY),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ConversationIdKey=new ContextKey(`eve.conversationId`),SessionInboxKey=new ContextKey(SESSION_INBOX_CONTEXT_KEY),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ContinuationHookTokensKey=new ContextKey(`eve.continuationHookTokens`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),LocalDevRequestKey=new ContextKey(`eve.internal.localDevRequest`),OccurrenceIdKey=new ContextKey(`eve.scheduleOccurrenceId`),ScheduleIdKey=new ContextKey(`eve.scheduleId`),ScheduleInstanceKey=new ContextKey(`eve.scheduleInstance`),SessionTitleKey=new ContextKey(`eve.sessionTitle`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnDeliveryIdsKey=new ContextKey(`eve.turnDeliveryIds`),HistoryStateKey=new ContextKey(`eve.historyState`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ParentSessionKey=new ContextKey(`eve.parentSession`),SessionPredecessorKey=new ContextKey(`eve.sessionPredecessor`),TraceRootKey=new ContextKey(`eve.traceRoot`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SessionTraceSeedKey=new ContextKey(`eve.sessionTraceSeed`),OtelTraceEnabledKey=new ContextKey(`eve.otelTraceEnabled`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(SESSION_CALLBACK_CONTEXT_KEY_NAME),LegacyRemoteAgentCallerKey=new ContextKey(`eve.legacyRemoteAgentCaller`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),SandboxTerminalCleanupKey=new ContextKey(`eve.internal.sandboxTerminalCleanup`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),StaticModelReferenceKey=new ContextKey(`eve.staticModelReference`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),TurnMemoryLocksKey=new ContextKey(`eve.memory.turnLocks`),PreparedMemoryPreambleKey=new ContextKey(`eve.memory.preparedPreamble`),PendingMemoryCommitKey=new ContextKey(`eve.memory.pendingCommit`),PreparedMemoryCompactionKey=new ContextKey(`eve.memory.preparedCompaction`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),DynamicSkillSandboxKey=new ContextKey(`eve.dynamicSkillSandbox`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationHookTokensKey,ContinuationTokenKey,ConversationIdKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSkillSandboxKey,DynamicSubagentAgentConfigKey,HandleEventKey,HistoryStateKey,InitiatorAuthKey,LegacyRemoteAgentCallerKey,LiveStepDynamicModelSelectionKey,LocalDevRequestKey,OccurrenceIdKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,PendingMemoryCommitKey,PreparedMemoryCompactionKey,PreparedMemoryPreambleKey,RuntimeModelMetadataCacheKey,SandboxKey,SandboxTerminalCleanupKey,ScheduleIdKey,ScheduleInstanceKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionInboxKey,SessionKey,SessionPredecessorKey,SessionTitleKey,SessionTraceSeedKey,StaticModelReferenceKey,StepDynamicToolMetadataKey,ToolStubsKey,TraceRootKey,TurnDeliveryIdsKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnMemoryLocksKey};
@@ -10,6 +10,7 @@ export declare const sessionProvider: {
10
10
  initiator: import("#context/keys.js").SessionAuthContext | null;
11
11
  };
12
12
  parent: import("#context/keys.js").SessionParent | undefined;
13
+ predecessor: import("#context/keys.js").SessionPredecessor | undefined;
13
14
  sessionId: string;
14
15
  turn: {
15
16
  id: string;
@@ -1 +1 @@
1
- import{projectionFor}from"#harness/session-machine/current.js";import{AuthKey,InitiatorAuthKey,ParentSessionKey,SessionIdKey,SessionKey}from"#context/keys.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";const sessionProvider={key:SessionKey,create(e,t){let n=e.require(AuthKey),r=turnPosition(projectionFor(e,t.state)),i=activeTurnId(r);return{value:Object.freeze({auth:{current:n,initiator:e.get(InitiatorAuthKey)??n},parent:e.get(ParentSessionKey),sessionId:e.require(SessionIdKey),turn:{id:i,sequence:r.sequence}})}}};export{sessionProvider};
1
+ import{projectionFor}from"#harness/session-machine/current.js";import{AuthKey,InitiatorAuthKey,ParentSessionKey,SessionIdKey,SessionKey,SessionPredecessorKey}from"#context/keys.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";const sessionProvider={key:SessionKey,create(e,t){let n=e.require(AuthKey),r=turnPosition(projectionFor(e,t.state)),i=activeTurnId(r);return{value:Object.freeze({auth:{current:n,initiator:e.get(InitiatorAuthKey)??n},parent:e.get(ParentSessionKey),predecessor:e.get(SessionPredecessorKey),sessionId:e.require(SessionIdKey),turn:{id:i,sequence:r.sequence}})}}};export{sessionProvider};
@@ -1,8 +1,8 @@
1
1
  import type { SandboxEnvironment } from "#shared/sandbox-environment.js";
2
2
  import type { RuntimeSandboxSession, RuntimeSandboxSessionFor, SandboxSession } from "#shared/sandbox-session.js";
3
- import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";
3
+ import type { SessionAuth, SessionParent, SessionPredecessor, SessionTurn } from "#context/keys.js";
4
4
  import type { SessionSchedule } from "#context/session-schedule.js";
5
- export type { SessionAuth, SessionParent, SessionTurn, SessionSchedule };
5
+ export type { SessionAuth, SessionParent, SessionPredecessor, SessionSchedule, SessionTurn };
6
6
  /**
7
7
  * Shared runtime context available to all authored callbacks that run
8
8
  * inside the ALS-scoped harness step (tools, hooks, channel events).
@@ -22,6 +22,12 @@ export interface SessionContext {
22
22
  readonly parent?: SessionParent;
23
23
  /** Present only for scheduled work; not an application-supplied auth attribute. */
24
24
  readonly schedule?: SessionSchedule;
25
+ /**
26
+ * Present when eve started this session in place of one whose deployment
27
+ * was retired. It names the earlier session, whose recorded stream
28
+ * `sessions.attach(predecessor.sessionId)` from `eve/server` reads.
29
+ */
30
+ readonly predecessor?: SessionPredecessor;
25
31
  };
26
32
  /**
27
33
  * Resolves the session's sandbox. Throws when no sandbox is available
@@ -1,5 +1,5 @@
1
1
  import type { ModelMessage } from "ai";
2
- import type { SessionAuth } from "#context/keys.js";
2
+ import type { SessionAuth, SessionPredecessor } from "#context/keys.js";
3
3
  import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
4
4
  import type { ConversationContext } from "#shared/conversation-context.js";
5
5
  /**
@@ -35,6 +35,12 @@ export interface DynamicResolveContext {
35
35
  readonly id: string;
36
36
  readonly auth: SessionAuth;
37
37
  readonly schedule?: import("#context/session-schedule.js").SessionSchedule;
38
+ /**
39
+ * Present when eve started this session in place of a stranded session,
40
+ * one that another eve version built. It names the earlier session, whose recorded stream
41
+ * `sessions.attach(predecessor.sessionId)` from `eve/server` reads.
42
+ */
43
+ readonly predecessor?: SessionPredecessor;
38
44
  };
39
45
  /** Channel metadata for the request that triggered this resolve. */
40
46
  readonly channel: {
@@ -346,7 +346,8 @@ export interface EveEvalTurn extends EveEvalAssertions, EveEvalOutputAssertions
346
346
  export interface EveEvalJudgeConfig {
347
347
  /** Decision model ID or instance. Defaults to the model used by `eve/ai` decide. */
348
348
  readonly model?: DecisionModel;
349
- readonly modelOptions?: AgentModelOptionsDefinition;
349
+ /** Judge calls carry provider options only; eve places no prompt-cache breakpoints on them. */
350
+ readonly modelOptions?: Pick<AgentModelOptionsDefinition, "providerOptions">;
350
351
  }
351
352
  /** JSON content accepted as decision state, instructions, or rubric descriptions. */
352
353
  export type JudgeInput = string | JsonObject | readonly JsonValue[];
@@ -1 +1 @@
1
- import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{readMatchedStubRules,readStubFailure}from"#execution/tool-stubs/steps.js";import{InvalidToolStubTargetError}from"#tool-stubs/validate-targets.js";import{getRun}from"#internal/workflow/runtime.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{legacyTaskInputRoute}from"#execution/legacy-remote-agent/protocol.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function createdSessionBody(e,t){let n={ok:!0,sessionId:e,status:`accepted`};return t.protocolVersion!==void 0&&(n.protocolVersion=t.protocolVersion),n}function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(legacyTaskInputRoute.path,legacyTaskInputRoute.handler),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=sessionAuthFromResult(i),o=await parseOptionalJsonRequest(n);if(o instanceof Response)return o;if(o.stubs!==void 0&&i.allowToolStubs!==!0)return Response.json({ok:!1,error:`Tool stubbing is not permitted for this caller.`},{status:403});let s=rejectSessionContinuationToken(o);if(s!==null)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:o});if(c instanceof Response)return c;let l=parseCreateBody(o);if(l instanceof Response)return l;l.callback!==void 0&&l.legacyRemoteAgentCaller!==void 0&&log.info(`serving a remote agent protocol 1 caller`,{callerOrigin:new URL(l.callback.url).origin,forwarder:i.principalId});let u=l.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),d;if(typeof u==`object`){if(u.callId!==l.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=c.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(a,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?d=u:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else u===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let f=l.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),p=l.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),f)??f,m=checkUploadPolicy(l,t);if(m!==null)return m;if(l.operationId!==void 0&&c.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let h=l.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:c.auth,operationId:l.operationId});if(h!==void 0){let e=await r.resolveSession(h);if(e!==void 0)return Response.json(createdSessionBody(e.id,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let g=f===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),_=c.accepted&&f!==void 0&&(f.traceFlags&1)==1?typeof g==`object`?g:g===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,v=p;_!==void 0&&p!==void 0&&(v={...p,forwardedTracePolicy:_}),g===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof g==`object`&&(_===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:g.originAudience,ceiling:formatTraceContentCeiling(g.ceiling),forwarder:i.principalId}));let y=l.message===void 0?{auth:c.auth}:await resolveOnMessage({auth:c.auth,config:e,invocation:d===void 0||l.operationId===void 0?void 0:{operationId:l.operationId},message:l.message,request:n});if(y instanceof Response)return y;let b=readRouteSessionCreator(r);if(b===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let x;try{x=await b({audienceAuth:a,toolStubs:l.stubs===void 0?void 0:{rules:l.stubs,token:crypto.randomUUID()},auth:y.auth,capabilities:l.capabilities??{requestInput:!0},callback:l.callback,legacyRemoteAgentCaller:l.legacyRemoteAgentCaller,continuationToken:h,initiatorAuth:c.accepted?c.initiatorAuth:void 0,input:attachClientContext({message:l.message,context:y.context,outputSchema:l.outputSchema},l.context),conversationId:l.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:d,parentTraceContext:v,traceRoot:d===void 0?void 0:{kind:`own`},title:y.title})}catch(e){if(e instanceof InvalidToolStubTargetError)return Response.json({error:e.message,ok:!1},{status:400});let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json(createdSessionBody(x.sessionId,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:x.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:sessionAuthFromResult(a),payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f,p=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.title,p=t.auth}let m;try{let e=r(o),t=attachClientContext({auth:p,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:f},l.context);m=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return m.status===`accepted`?Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`,deliveryId:m.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202}):Response.json({code:m.retryable?`session_not_ready`:`session_not_active`,error:m.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STUBS_ROUTE_PATTERN,async(t,{params:n})=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;if(r.allowToolStubs!==!0)return Response.json({error:`Tool stubbing is not permitted for this caller.`,ok:!1},{status:403});let i=requireSessionId(n);if(i instanceof Response)return i;try{return await getRun(i).exists?Response.json({error:await readStubFailure(i)??null,matchedRuleIds:await readMatchedStubRules(i)},{headers:{"cache-control":`no-store`}}):Response.json({error:`Session not found.`,ok:!1},{status:404})}catch(e){let t=logError(log,`tool-stub verification request failed`,e,{sessionId:i});return Response.json({error:`Failed to verify tool stubs.`,errorId:t,ok:!1},{status:500})}}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteAgentBinding({callId:a,childSessionId:o,childStreamPath:l,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d(u)}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
1
+ import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SESSION_STUBS_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{readMatchedStubRules,readStubFailure}from"#execution/tool-stubs/steps.js";import{InvalidToolStubTargetError}from"#tool-stubs/validate-targets.js";import{getRun}from"#internal/workflow/runtime.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{legacyTaskInputRoute}from"#execution/legacy-remote-agent/protocol.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage,strandedSessionResponse}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function createdSessionBody(e,t){let n={ok:!0,sessionId:e,status:`accepted`};return t.protocolVersion!==void 0&&(n.protocolVersion=t.protocolVersion),n}function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(legacyTaskInputRoute.path,legacyTaskInputRoute.handler),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=sessionAuthFromResult(i),o=await parseOptionalJsonRequest(n);if(o instanceof Response)return o;if(o.stubs!==void 0&&i.allowToolStubs!==!0)return Response.json({ok:!1,error:`Tool stubbing is not permitted for this caller.`},{status:403});let s=rejectSessionContinuationToken(o);if(s!==null)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:o});if(c instanceof Response)return c;let l=parseCreateBody(o);if(l instanceof Response)return l;l.callback!==void 0&&l.legacyRemoteAgentCaller!==void 0&&log.info(`serving a remote agent protocol 1 caller`,{callerOrigin:new URL(l.callback.url).origin,forwarder:i.principalId});let u=l.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),d;if(typeof u==`object`){if(u.callId!==l.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=c.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(a,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?d=u:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else u===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let f=l.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),p=l.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),f)??f,m=checkUploadPolicy(l,t);if(m!==null)return m;if(l.operationId!==void 0&&c.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let h=l.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:c.auth,operationId:l.operationId});if(h!==void 0){let e=await r.resolveSession(h);if(e!==void 0)return Response.json(createdSessionBody(e.id,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let g=f===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),_=c.accepted&&f!==void 0&&(f.traceFlags&1)==1?typeof g==`object`?g:g===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,v=p;_!==void 0&&p!==void 0&&(v={...p,forwardedTracePolicy:_}),g===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof g==`object`&&(_===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:g.originAudience,ceiling:formatTraceContentCeiling(g.ceiling),forwarder:i.principalId}));let y=l.message===void 0?{auth:c.auth}:await resolveOnMessage({auth:c.auth,config:e,invocation:d===void 0||l.operationId===void 0?void 0:{operationId:l.operationId},message:l.message,request:n});if(y instanceof Response)return y;let b=readRouteSessionCreator(r);if(b===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let x;try{x=await b({audienceAuth:a,toolStubs:l.stubs===void 0?void 0:{rules:l.stubs,token:crypto.randomUUID()},auth:y.auth,capabilities:l.capabilities??{requestInput:!0},callback:l.callback,legacyRemoteAgentCaller:l.legacyRemoteAgentCaller,continuationToken:h,initiatorAuth:c.accepted?c.initiatorAuth:void 0,input:attachClientContext({message:l.message,context:y.context,outputSchema:l.outputSchema},l.context),conversationId:l.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:d,parentTraceContext:v,traceRoot:d===void 0?void 0:{kind:`own`},title:y.title})}catch(e){if(e instanceof InvalidToolStubTargetError)return Response.json({error:e.message,ok:!1},{status:400});let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json(createdSessionBody(x.sessionId,l),{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:x.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:sessionAuthFromResult(a),payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f,p=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.title,p=t.auth}let m;try{let e=r(o),t=attachClientContext({auth:p,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:f},l.context);m=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:n,ok:!1},{status:500})}return m.status===`accepted`?Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`,deliveryId:m.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202}):Response.json({code:m.retryable?`session_not_ready`:`session_not_active`,error:m.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:n,ok:!1},{status:500})}return Response.json({ok:!0,...s},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STUBS_ROUTE_PATTERN,async(t,{params:n})=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;if(r.allowToolStubs!==!0)return Response.json({error:`Tool stubbing is not permitted for this caller.`,ok:!1},{status:403});let i=requireSessionId(n);if(i instanceof Response)return i;try{return await getRun(i).exists?Response.json({error:await readStubFailure(i)??null,matchedRuleIds:await readMatchedStubRules(i)},{headers:{"cache-control":`no-store`}}):Response.json({error:`Session not found.`,ok:!1},{status:404})}catch(e){let t=logError(log,`tool-stub verification request failed`,e,{sessionId:i});return Response.json({error:`Failed to verify tool stubs.`,errorId:t,ok:!1},{status:500})}}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteAgentBinding({callId:a,childSessionId:o,childStreamPath:l,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d(u)}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
@@ -1,4 +1,4 @@
1
- import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{parseToolStubs}from"#tool-stubs/rules.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};if(n.stubs!==void 0)try{d.stubs=parseToolStubs(n.stubs)}catch(e){return Response.json({ok:!1,error:e instanceof Error?e.message:`Invalid tool stubs.`},{status:400})}return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e);if(Object.hasOwn(t,`stubs`))return Response.json({ok:!1,error:`Tool stubs are fixed at session creation.`},{status:400});let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseIncludeTailIndex(e);try{let i=t.getEventStream({startIndex:n});i.catch(()=>{});let a;try{a=await t.getStreamTailIndex()}catch(e){throw i.then(e=>e.cancel()).catch(()=>{}),e}let o=await i,s=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,c=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return r&&c.set(EVE_STREAM_TAIL_INDEX_HEADER,String(a)),new Response(serializeAsNdjson(o,e.signal,r?streamEventLimit(n,a):void 0,s!==void 0),{headers:c})}catch(e){let t=isMissingWorkflowRunError(e);return Response.json({error:t?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:t?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
2
- ${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
1
+ import{isInputResponse}from"#shared/input.js";import{hasInternalRefScheme}from"#internal/attachments/url-refs.js";import{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_LEASE_ENDED_CONTROL,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,splitLegacyTaskFields}from"#execution/legacy-remote-agent/protocol.js";import{collectUploadPolicyViolations,formatUploadPolicyViolation}from"#public/channels/upload-policy.js";import{strandedSessionResponse}from"#eve-channel/support.js";import{parseToolStubs}from"#tool-stubs/rules.js";import{parseSessionCallback}from"#channel/session-callback.js";import{isMissingWorkflowRunError}from"#internal/workflow/is-inactive-workflow-run-error.js";import{REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion}from"#protocol/remote-agent-protocol.js";import{parseTurnPolicyField}from"#eve-channel/turn-policy-request.js";import{validateMessageFreeCreate}from"#eve-channel/create-request.js";async function deriveOperationContinuationToken(e){let t=JSON.stringify([`eve:create-session:v1`,e.auth.authenticator,e.auth.issuer??null,e.auth.principalType,e.auth.principalId,e.operationId]),n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return`eve:op:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}`}function parseCreateBody(e){let t=splitLegacyTaskFields(e),{payload:n}=t;if(n.inputResponses!==void 0)return Response.json({error:`'inputResponses' is only accepted for an existing session.`,ok:!1},{status:400});let r=parseMessageField(n.message);if(r instanceof Response)return r;let i=parseClientContextField(n.clientContext);if(i instanceof Response)return i;let a=parseCallbackField(n.callback);if(a instanceof Response)return a;let o=a===void 0?void 0:parseProtocolVersionField(n.protocolVersion);if(o instanceof Response)return o;let s=parseCapabilitiesField(n.capabilities);if(s instanceof Response)return s;let c=parseOutputSchemaField(n.outputSchema);if(c instanceof Response)return c;let l=validateMessageFreeCreate({callback:a,hasClientContext:n.clientContext!==void 0,hasMessageField:`message`in n,message:r,outputSchema:c});if(l!==void 0)return l;let u=n.operationId;if(u!==void 0&&(typeof u!=`string`||!u))return Response.json({error:`Expected 'operationId' to be a non-empty string.`,ok:!1},{status:400});let d={callback:a,capabilities:s,context:i,outputSchema:c};if(n.stubs!==void 0)try{d.stubs=parseToolStubs(n.stubs)}catch(e){return Response.json({ok:!1,error:e instanceof Error?e.message:`Invalid tool stubs.`},{status:400})}return r!==void 0&&(d.message=r),typeof u==`string`&&(d.operationId=u),o!==void 0&&(d.protocolVersion=o),o===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION&&(d.legacyRemoteAgentCaller=t.taskId===void 0?{}:{taskId:t.taskId}),d}function parseSessionMessageBody(e){let{payload:t}=splitLegacyTaskFields(e);if(Object.hasOwn(t,`stubs`))return Response.json({ok:!1,error:`Tool stubs are fixed at session creation.`},{status:400});let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=parseMessageField(t.message);if(r instanceof Response)return r;let i=parseCallbackField(t.callback);if(i instanceof Response)return i;let a=parseInputResponses$1(t.inputResponses);if(a instanceof Response)return a;let o=parseClientContextField(t.clientContext);if(o instanceof Response)return o;let s=parseOutputSchemaField(t.outputSchema);if(s instanceof Response)return s;let c=parseTurnPolicyField(t.turnPolicy);return c instanceof Response?c:r===void 0&&a===void 0?Response.json({error:`Expected a non-empty 'message' or a non-empty 'inputResponses' array.`,ok:!1},{status:400}):r!==void 0&&a!==void 0?Response.json({error:`'message' and 'inputResponses' are mutually exclusive.`,ok:!1},{status:400}):{callback:i,message:r,inputResponses:a,context:o,outputSchema:s,turnPolicy:c}}async function parseCancelTurnBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.turnId;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'turnId' to be a non-empty string.`,ok:!1},{status:400}):typeof r==`string`?{turnId:r}:{}}async function parseJsonRequest(e){let t;try{t=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof t!=`object`||!t||Array.isArray(t)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):t}async function parseResetBody(e){let t=await parseOptionalJsonRequest(e);if(t instanceof Response)return t;let n=rejectSessionContinuationToken(t);if(n!==null)return n;let r=t.reason;return r!==void 0&&(typeof r!=`string`||r.length===0)?Response.json({error:`Expected 'reason' to be a non-empty string.`,ok:!1},{status:400}):r===void 0?{}:{reason:r}}async function parseSessionControlBody(e){let t=await parseOptionalJsonRequest(e);return t instanceof Response?t:rejectSessionContinuationToken(t)??t}async function parseOptionalJsonRequest(e){let t;try{t=await e.text()}catch{return Response.json({error:`Unreadable request body.`,ok:!1},{status:400})}if(t.trim().length===0)return{};let n;try{n=JSON.parse(t)}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}return typeof n!=`object`||!n||Array.isArray(n)?Response.json({error:`Expected a JSON object.`,ok:!1},{status:400}):n}function rejectSessionContinuationToken(e){return`continuationToken`in e?Response.json({error:`Session-ID routes do not accept 'continuationToken'.`,ok:!1},{status:400}):null}function requireSessionId(e){return e.sessionId||Response.json({error:`Missing session id.`,ok:!1},{status:400})}async function createSessionStreamResponse(e,t){let n=parseStartIndex(e);if(n instanceof Response)return n;let r=parseFollow(e),i=!r||parseIncludeTailIndex(e);try{let a=t.getEventStream({follow:r,startIndex:n});a.catch(()=>{});let o;try{o=await t.getStreamTailIndex()}catch(e){throw a.then(e=>e.cancel()).catch(()=>{}),e}let s=await a,c=new URL(e.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY)===EVE_STREAM_CONTROL_VERSION?EVE_STREAM_CONTROL_VERSION:void 0,l=new Headers({"cache-control":`no-store, no-transform`,"content-type":EVE_MESSAGE_STREAM_CONTENT_TYPE,"x-accel-buffering":`no`,[EVE_SESSION_ID_HEADER]:t.id,[EVE_STREAM_FORMAT_HEADER]:EVE_MESSAGE_STREAM_FORMAT,[EVE_STREAM_VERSION_HEADER]:EVE_MESSAGE_STREAM_VERSION});return i&&l.set(EVE_STREAM_TAIL_INDEX_HEADER,String(o)),new Response(serializeAsNdjson(s,e.signal,i?streamEventLimit(n,o):void 0,c!==void 0),{headers:l})}catch(e){let t=strandedSessionResponse(e);if(t!==void 0)return t;let n=isMissingWorkflowRunError(e);return Response.json({error:n?`Session not found.`:`Session stream unavailable.`,ok:!1},{status:n?404:503})}}function parseOutputSchemaField(e){if(e!==void 0)try{return parseJsonObject(e)}catch{return Response.json({error:`Expected 'outputSchema' to be a JSON-serializable object.`,ok:!1},{status:400})}}function parseCallbackField(e){if(e===void 0)return;let t=parseSessionCallback(e);return t.ok?t.callback:Response.json({error:t.message,ok:!1},{status:400})}function parseProtocolVersionField(e){if(e!==void 0&&typeof e!=`number`)return Response.json({error:`Expected 'protocolVersion' to be a number.`,ok:!1},{status:400});let t=readRemoteAgentProtocolVersion(e);return t===REMOTE_AGENT_PROTOCOL_VERSION||t===LEGACY_REMOTE_AGENT_PROTOCOL_VERSION?t:Response.json({code:REMOTE_AGENT_PROTOCOL_MISMATCH,error:`This deployment speaks eve remote agent protocol ${String(REMOTE_AGENT_PROTOCOL_VERSION)}, but the caller speaks protocol ${String(t)}. Upgrade both deployments to the same eve release.`,ok:!1,protocolVersion:REMOTE_AGENT_PROTOCOL_VERSION},{status:409})}function parseCapabilitiesField(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return Response.json({error:`Expected 'capabilities' to be an object.`,ok:!1},{status:400});let t=Object.keys(e),n=Reflect.get(e,`requestInput`);return t.some(e=>e!==`requestInput`)||n!==void 0&&typeof n!=`boolean`?Response.json({error:`Expected 'capabilities.requestInput' to be a boolean when provided.`,ok:!1},{status:400}):n===void 0?{}:{requestInput:n}}function parseMessageField(e){if(e===void 0)return;if(typeof e==`string`)return e.length>0?e:void 0;if(!Array.isArray(e))return Response.json({error:`Expected 'message' to be a string or an array of text/file parts.`,ok:!1},{status:400});if(e.length===0)return;let t=[];for(let n of e){let e=parseMessagePart(n);if(e instanceof Response)return e;t.push(e)}return t}function parseMessagePart(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected each message part to be an object.`,ok:!1},{status:400});let t=e;if(t.type===`text`)return typeof t.text!=`string`||t.text.length===0?Response.json({error:`Text parts require a non-empty 'text' string.`,ok:!1},{status:400}):{type:`text`,text:t.text};if(t.type===`file`){if(typeof t.mediaType!=`string`||t.mediaType.length===0)return Response.json({error:`File parts require a non-empty 'mediaType' string.`,ok:!1},{status:400});if(typeof t.data!=`string`)return Response.json({error:`File parts require a 'data' string (base64, data URL, or URL).`,ok:!1},{status:400});if(hasInternalRefScheme(t.data))return Response.json({error:`File part 'data' must not use a framework-internal ref scheme.`,ok:!1},{status:400});let e={type:`file`,mediaType:t.mediaType,data:t.data};return typeof t.filename==`string`&&t.filename.length>0&&(e.filename=t.filename),e}return Response.json({error:`Unsupported message part type "${String(t.type)}". Use 'text' or 'file'.`,ok:!1},{status:400})}function checkUploadPolicy(e,t){if(!e.message)return null;let n=collectUploadPolicyViolations(e.message,t);if(n.length===0)return null;let[r]=n;if(!r)return null;let i=r.kind===`too-large`?413:415;return Response.json({error:formatUploadPolicyViolation(r),ok:!1,violations:n.map(e=>e.kind===`too-large`?{byteLength:e.byteLength,filename:e.filename,kind:e.kind,limit:e.limit,mediaType:e.mediaType}:{allowedMediaTypes:e.allowedMediaTypes,filename:e.filename,kind:e.kind,mediaType:e.mediaType})},{status:i})}function parseInputResponses$1(e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)return Response.json({error:`Expected 'inputResponses' to be a non-empty array.`,ok:!1},{status:400});let t=e.filter(isInputResponse);return t.length===e.length?t:Response.json({error:`Expected every 'inputResponses' entry to match the HITL response schema.`,ok:!1},{status:400})}function parseClientContextField(e){if(e!==void 0){if(typeof e==`string`)return e.length>0?[toClientContextMessage(e)]:void 0;if(Array.isArray(e))return e.length===0?void 0:e.every(e=>typeof e==`string`&&e.length>0)?e.map(e=>toClientContextMessage(e)):Response.json({error:`Expected 'clientContext' array entries to be non-empty strings.`,ok:!1},{status:400});if(typeof e!=`object`||!e)return Response.json({error:`Expected 'clientContext' to be a string, string array, or JSON object.`,ok:!1},{status:400});try{let t=parseJsonObject(e);return[toClientContextMessage(JSON.stringify(t))]}catch{return Response.json({error:`Expected 'clientContext' to be a JSON-serializable object.`,ok:!1},{status:400})}}}function toClientContextMessage(e){return`Client context:
2
+ ${e}`}function parseIncludeTailIndex(e){let t=new URL(e.url).searchParams.get(`includeTailIndex`);return t===`1`||t===`true`}function parseFollow(e){let t=new URL(e.url).searchParams.get(`follow`);return t!==`0`&&t!==`false`}function parseStartIndex(e){let t=new URL(e.url).searchParams.get(`startIndex`);if(t===null)return;let n=Number(t);return!/^-?\d+$/.test(t)||!Number.isSafeInteger(n)?Response.json({error:`Expected startIndex to be an integer.`,ok:!1},{status:400}):n}function streamEventLimit(e,t){if(t===void 0)return;let n=e===void 0?0:e<0?Math.max(0,t+1+e):e;return Math.max(0,t-n+1)}function serializeAsNdjson(e,t,n,r=!1){let i=new TextEncoder,a=0,o,s,clearTimers=()=>{clearTimeout(o),clearTimeout(s),o=void 0,s=void 0},scheduleHeartbeat=e=>{clearTimeout(o),o=setTimeout(()=>{try{e.enqueue(i.encode(`
3
3
  `)),scheduleHeartbeat(e)}catch{clearTimers()}},1e4)},startLease=e=>{scheduleHeartbeat(e),s=setTimeout(()=>{clearTimers();try{e.enqueue(i.encode(`${JSON.stringify(EVE_STREAM_LEASE_ENDED_CONTROL)}\n`)),e.terminate()}catch{}},6e4)},c=new TransformStream({start(e){e.enqueue(i.encode(`
4
4
  `)),n===0?e.terminate():r&&startLease(e)},transform(e,t){t.enqueue(i.encode(`${JSON.stringify(e)}\n`)),a+=1,a===n?(clearTimers(),t.terminate()):r&&scheduleHeartbeat(t)},flush(){clearTimers()}});return e.pipeTo(c.writable,{signal:t}).catch(()=>{}).finally(clearTimers),c.readable}export{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId};
@@ -4,6 +4,8 @@ import type { MessageStreamEvent } from "#protocol/message.js";
4
4
  import type { ChannelCors } from "#public/definitions/channel.js";
5
5
  import { type EveChannelCors, type EveChannelInput, type EveHandle } from "#eve-channel/types.js";
6
6
  export declare function healthResponse(): Response;
7
+ /** Clients display the error text directly; keep operator details in structured fields. */
8
+ export declare function strandedSessionResponse(error: unknown): Response | undefined;
7
9
  /** Where a remote child the parent session recorded runs, and its credential key. */
8
10
  export interface RemoteAgentBinding {
9
11
  readonly forwardPrincipal?: boolean;
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{defaultEveAuth}from"#eve-channel/types.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`eve.channel`);function healthResponse(){return Response.json({ok:!0,status:`ready`,workflowId:workflowEntryReference.workflowId})}async function findRemoteAgentBinding(e){let t=await e.parent.getStreamTailIndex();if(t<0)return;let n=(await e.parent.getEventStream({startIndex:0})).getReader(),r;try{for(let i=0;i<=t;i+=1){let t=await n.read();if(t.done)break;r=readRemoteAgentBinding(t.value,e)??r}}finally{await n.cancel().catch(()=>{})}return r}function readRemoteAgentBinding(e,t){if(e.type!==`agent.started`)return;let{data:n}=e;if(n.callId===t.callId&&n.sessionId===t.childSessionId&&n.streamPath===t.childStreamPath&&n.remote!==void 0)return{name:n.name,...n.remote}}function normalizeEveCors(e){if(e===void 0||e===!1)return!1;if(e===!0)return!0;let t={};return e.origin!==void 0&&(t.origin=normalizeEveCorsOrigin(e.origin)),e.methods!==void 0&&(t.methods=e.methods),e.allowedHeaders!==void 0&&(t.allowHeaders=e.allowedHeaders),e.exposedHeaders!==void 0&&(t.exposeHeaders=e.exposedHeaders),e.credentials!==void 0&&(t.credentials=e.credentials),e.maxAge!==void 0&&(t.maxAge=e.maxAge),e.preflightStatus!==void 0&&(t.preflight={statusCode:e.preflightStatus}),t}function normalizeEveCorsOrigin(e){return e===`*`||e===`null`?e:typeof e==`string`?[e]:e}async function resolveOnMessage(e){let t=e.config.onMessage??defaultOnMessage,n;try{let r={caller:e.auth,request:e.request};if(n=await t({eve:e.sessionId===void 0?e.invocation===void 0?r:{...r,invocation:e.invocation}:{...r,sessionId:e.sessionId}},e.message),n==null)throw TypeError(`eveChannel onMessage must return an auth result.`)}catch(t){let n=logError(log,`onMessage handler failed`,t,{sessionId:e.sessionId});return Response.json({error:`onMessage handler failed.`,errorId:n,ok:!1},{status:500})}return{auth:n.auth,context:n.context,title:n.title}}function defaultOnMessage(e){return{auth:defaultEveAuth(e)}}export{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage};
1
+ import{createLogger,logError}from"#internal/logging.js";import{defaultEveAuth}from"#eve-channel/types.js";import{SessionStrandedError}from"#channel/session-stranded-error.js";import{workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`eve.channel`);function healthResponse(){return Response.json({ok:!0,status:`ready`,workflowId:workflowEntryReference.workflowId})}function strandedSessionResponse(e){if(!SessionStrandedError.is(e))return;let t={code:`session_stranded`,error:`This session is no longer available.`,ok:!1};return e.owner.eveVersion!==void 0&&(t.eveVersion=e.owner.eveVersion),Response.json(t,{headers:{"cache-control":`no-store`},status:409})}async function findRemoteAgentBinding(e){let t=await e.parent.getStreamTailIndex();if(t<0)return;let n=(await e.parent.getEventStream({startIndex:0})).getReader(),r;try{for(let i=0;i<=t;i+=1){let t=await n.read();if(t.done)break;r=readRemoteAgentBinding(t.value,e)??r}}finally{await n.cancel().catch(()=>{})}return r}function readRemoteAgentBinding(e,t){if(e.type!==`agent.started`)return;let{data:n}=e;if(n.callId===t.callId&&n.sessionId===t.childSessionId&&n.streamPath===t.childStreamPath&&n.remote!==void 0)return{name:n.name,...n.remote}}function normalizeEveCors(e){if(e===void 0||e===!1)return!1;if(e===!0)return!0;let t={};return e.origin!==void 0&&(t.origin=normalizeEveCorsOrigin(e.origin)),e.methods!==void 0&&(t.methods=e.methods),e.allowedHeaders!==void 0&&(t.allowHeaders=e.allowedHeaders),e.exposedHeaders!==void 0&&(t.exposeHeaders=e.exposedHeaders),e.credentials!==void 0&&(t.credentials=e.credentials),e.maxAge!==void 0&&(t.maxAge=e.maxAge),e.preflightStatus!==void 0&&(t.preflight={statusCode:e.preflightStatus}),t}function normalizeEveCorsOrigin(e){return e===`*`||e===`null`?e:typeof e==`string`?[e]:e}async function resolveOnMessage(e){let t=e.config.onMessage??defaultOnMessage,n;try{let r={caller:e.auth,request:e.request};if(n=await t({eve:e.sessionId===void 0?e.invocation===void 0?r:{...r,invocation:e.invocation}:{...r,sessionId:e.sessionId}},e.message),n==null)throw TypeError(`eveChannel onMessage must return an auth result.`)}catch(t){let n=logError(log,`onMessage handler failed`,t,{sessionId:e.sessionId});return Response.json({error:`onMessage handler failed.`,errorId:n,ok:!1},{status:500})}return{auth:n.auth,context:n.context,title:n.title}}function defaultOnMessage(e){return{auth:defaultEveAuth(e)}}export{findRemoteAgentBinding,healthResponse,normalizeEveCors,resolveOnMessage,strandedSessionResponse};