eve 0.71.2 → 0.71.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 (94) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/src/channel/conversation-context.d.ts +4 -1
  3. package/dist/src/channel/invoke-tool.d.ts +41 -0
  4. package/dist/src/channel/invoke-tool.js +1 -0
  5. package/dist/src/channel/routes.d.ts +3 -0
  6. package/dist/src/compiled/.vendor-stamp.json +1 -1
  7. package/dist/src/compiler/extension-compatibility.d.ts +2 -2
  8. package/dist/src/compiler/extension-compatibility.js +1 -1
  9. package/dist/src/context/caller-scope.d.ts +7 -0
  10. package/dist/src/context/caller-scope.js +1 -0
  11. package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -1
  12. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  13. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  14. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  15. package/dist/src/execution/invoke-tool.d.ts +35 -0
  16. package/dist/src/execution/invoke-tool.js +1 -0
  17. package/dist/src/execution/publish-session-events.d.ts +3 -0
  18. package/dist/src/execution/publish-session-events.js +1 -1
  19. package/dist/src/execution/sandbox/active-handles.d.ts +6 -0
  20. package/dist/src/execution/sandbox/active-handles.js +1 -1
  21. package/dist/src/execution/sandbox/ensure.js +1 -1
  22. package/dist/src/execution/session/active-turn.js +1 -1
  23. package/dist/src/execution/session/answer-caller.d.ts +15 -0
  24. package/dist/src/execution/session/answer-caller.js +1 -0
  25. package/dist/src/execution/session/finalization.js +1 -1
  26. package/dist/src/execution/session/turn-step.js +1 -1
  27. package/dist/src/execution/terminal-session-completion-step.d.ts +3 -0
  28. package/dist/src/execution/terminal-session-completion-step.js +1 -1
  29. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  30. package/dist/src/execution/tools/connection-tools.js +1 -1
  31. package/dist/src/execution/tools/workflow/authorization-completion.js +1 -1
  32. package/dist/src/execution/tools/workflow/step-execution.js +1 -1
  33. package/dist/src/execution/workflow-runtime.js +1 -1
  34. package/dist/src/harness/approval-candidates.d.ts +4 -0
  35. package/dist/src/harness/approval-candidates.js +1 -1
  36. package/dist/src/harness/approved-call-callers.d.ts +11 -0
  37. package/dist/src/harness/approved-call-callers.js +1 -0
  38. package/dist/src/harness/coordination.d.ts +4 -0
  39. package/dist/src/harness/coordination.js +1 -1
  40. package/dist/src/harness/emission-state.d.ts +10 -0
  41. package/dist/src/harness/emission-state.js +1 -1
  42. package/dist/src/harness/emission.js +1 -1
  43. package/dist/src/harness/input-requests.d.ts +6 -0
  44. package/dist/src/harness/input-requests.js +1 -1
  45. package/dist/src/harness/messages.js +1 -1
  46. package/dist/src/harness/provider-tools.d.ts +5 -1
  47. package/dist/src/harness/provider-tools.js +1 -1
  48. package/dist/src/harness/session-limit-continuation.d.ts +3 -1
  49. package/dist/src/harness/session-limit-continuation.js +1 -1
  50. package/dist/src/harness/session-limit-enforcement.js +1 -1
  51. package/dist/src/harness/tool-call-io.d.ts +25 -0
  52. package/dist/src/harness/tool-call-io.js +1 -0
  53. package/dist/src/harness/tool-loop.js +2 -2
  54. package/dist/src/harness/tool-model-output.d.ts +1 -2
  55. package/dist/src/harness/tools.d.ts +1 -0
  56. package/dist/src/harness/tools.js +1 -1
  57. package/dist/src/harness/workflow-dispatch.js +1 -1
  58. package/dist/src/instrumentation/lifecycle.d.ts +4 -0
  59. package/dist/src/instrumentation/native-events.js +1 -1
  60. package/dist/src/internal/application/package.js +1 -1
  61. package/dist/src/internal/gateway.d.ts +2 -0
  62. package/dist/src/internal/gateway.js +1 -1
  63. package/dist/src/internal/nitro/host/instrumentation-entry.js +2 -2
  64. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  65. package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
  66. package/dist/src/internal/nitro/routes/route-invoke-tool.d.ts +24 -0
  67. package/dist/src/internal/nitro/routes/route-invoke-tool.js +1 -0
  68. package/dist/src/public/channels/index.d.ts +1 -1
  69. package/dist/src/public/definitions/channel.d.ts +1 -0
  70. package/dist/src/public/models/openai/chatgpt/model.js +1 -1
  71. package/dist/src/runtime/connections/mcp-client.js +1 -1
  72. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  73. package/dist/src/setup/scaffold/create/project.js +1 -1
  74. package/dist/src/setup/scaffold/create/web-template.d.ts +2 -2
  75. package/dist/src/setup/scaffold/create/web-template.js +25 -8
  76. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  77. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  78. package/dist/src/tracing/agent-action-instrumentation.d.ts +1 -0
  79. package/dist/src/tracing/agent-action-instrumentation.js +1 -1
  80. package/dist/src/tracing/agent-otel-provider.js +1 -1
  81. package/dist/src/tracing/agent-span-contract.d.ts +8 -0
  82. package/dist/src/tracing/agent-span-contract.js +1 -1
  83. package/dist/src/tracing/agent-tool-instrumentation.d.ts +1 -0
  84. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  85. package/dist/src/tracing/agent-trace-context-codec.js +1 -1
  86. package/dist/src/tracing/agent-trace-span-processor.js +1 -1
  87. package/dist/src/tracing/agent-trace-state.d.ts +1 -0
  88. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  89. package/dist/src/tracing/invoke-tool-span.d.ts +61 -0
  90. package/dist/src/tracing/invoke-tool-span.js +1 -0
  91. package/docs/channels/custom.mdx +1 -0
  92. package/docs/reference/cli.md +2 -0
  93. package/docs/tools/human-in-the-loop.md +2 -0
  94. package/package.json +3 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # eve
2
2
 
3
+ ## 0.71.3
4
+
5
+ ### Patch Changes
6
+
7
+ - a8262be: When someone other than the person who asked approves a tool call, only that call now runs as the approver. Before, the approver became the caller for the rest of the turn, so later tool calls and approvals in that turn also ran with the approver's identity and credentials.
8
+ - 8ecfd4f: Show the budget prompt again when someone sends a message after pressing Stop on it. The re-raised prompt reused the earlier prompt's request id, so `eve/client`, the Web Chat template, and the dev TUI treated it as already answered and left it unanswerable.
9
+ - 8df6c83: Typing "approve" on a session budget prompt now resumes the session when you had already sent another message while the prompt was open. Before, eve joined your queued message and the approval into a single message that matched neither option, so the agent stayed blocked. The queued message now runs after the approval.
10
+ - a2453a9: `chatgpt()` now sends `serviceTier: "fast"` to the Codex backend as `priority`, the value the Codex CLI uses for Fast mode, instead of failing with `400 Unsupported service_tier: fast`.
11
+ - dcb995c: Select web search backends using the resolved model provider so dynamic models from non-Gateway providers do not receive AI Gateway tools.
12
+ - 61e20b2: Return a not-found or transient error before opening an unavailable session stream, and close streams after terminal failures.
13
+ - 77c2d3e: Include a new message in the first model step after cancelling a turn that was waiting for tool approval, instead of first replying to the cancelled call alone.
14
+ - 1066932: `eve build` keeps the named exports of the Nitro preset entry. Builds with presets such as `NITRO_PRESET=node-middleware` export `middleware` and `handleUpgrade` again instead of only `default`.
15
+ - 55d4604: Channel route handlers now receive `invokeTool(name, input, { auth })`, which runs one of the agent's tools as the given caller outside any conversation, with a sandbox that lasts for the call. Tools whose approval policy asks a person resolve to `approval-required` without running.
16
+ - 61e20b2: Fix channel `session.completed` handlers throwing when a session expires, resets, or closes between turns. The handler's `ctx.session.turn` reports the session's last turn.
17
+ - dd36ab3: Fix nested connector actions appearing as unrelated model tool calls in traces: they now carry their parent call ID and nest beneath the calling action. Action spans also retain their request start time and cover tool execution when SDK telemetry arrives first.
18
+ - 3d78c3e: The Web Chat template now shows every question a tool call asks at once. Before, when a workflow called `ctx.ask` twice in parallel, the second question replaced the first, so the first question couldn't be answered and the tool stayed blocked.
19
+
3
20
  ## 0.71.2
4
21
 
5
22
  ### Patch Changes
@@ -1,5 +1,8 @@
1
1
  import type { RunInput, SessionAuthContext } from "#channel/types.js";
2
2
  import { type AudienceCaller, type ConversationContext, type ConversationEnvironment } from "#shared/conversation-context.js";
3
- export declare function buildConversationContext(run: RunInput, environment: ConversationEnvironment): ConversationContext;
3
+ /** What a conversation context is built from: a run, or a direct tool call's channel and caller. */
4
+ type ConversationSource = RunInput | (Pick<RunInput, "adapter" | "auth"> & Partial<Pick<RunInput, "audienceAuth" | "channelName" | "inheritedConversation" | "parentTraceContext">>);
5
+ export declare function buildConversationContext(run: ConversationSource, environment: ConversationEnvironment): ConversationContext;
4
6
  /** Projects route auth into the minimal identity audience classifiers need. */
5
7
  export declare function toAudienceCaller(auth: SessionAuthContext | null | undefined): AudienceCaller;
8
+ export {};
@@ -0,0 +1,41 @@
1
+ import type { SessionAuthContext } from "#channel/types.js";
2
+ import type { ToolModelOutput } from "#tools/model-output.js";
3
+ /** Options for one {@link InvokeToolFn} call. */
4
+ export interface InvokeToolOptions {
5
+ /** The caller this request authenticated. Becomes `ctx.session.auth.current`. */
6
+ readonly auth: SessionAuthContext;
7
+ readonly signal?: AbortSignal;
8
+ }
9
+ /** Outcome of one {@link InvokeToolFn} call. */
10
+ export type InvokeToolResult = {
11
+ readonly status: "completed";
12
+ readonly output: unknown;
13
+ readonly modelOutput: ToolModelOutput;
14
+ } | {
15
+ readonly status: "failed";
16
+ readonly message: string;
17
+ readonly errorId?: string;
18
+ } | {
19
+ readonly status: "invalid-input";
20
+ readonly message: string;
21
+ } | {
22
+ readonly status: "denied";
23
+ readonly reason?: string;
24
+ }
25
+ /** The tool's approval policy asks a person. A call has no one to ask, so the tool did not run. */
26
+ | {
27
+ readonly status: "approval-required";
28
+ }
29
+ /** The tool needs a sign-in to these connections first. The tool stopped where it needed them. */
30
+ | {
31
+ readonly status: "authorization-required";
32
+ readonly connections: readonly string[];
33
+ };
34
+ /**
35
+ * Runs one of the agent's tools outside a conversation. No model, turn, or
36
+ * workflow step is involved, and the call never parks. Each call gets its own
37
+ * session: `ctx.session.auth.current` is the caller, authored state starts from
38
+ * its initial value and is not kept, and a sandbox the tool opens is deleted
39
+ * when the call ends.
40
+ */
41
+ export type InvokeToolFn = (name: string, input: unknown, options: InvokeToolOptions) => Promise<InvokeToolResult>;
@@ -0,0 +1 @@
1
+ export{};
@@ -1,6 +1,7 @@
1
1
  import type { UserContent } from "ai";
2
2
  import type { CrossChannelToFn } from "#channel/cross-channel-receive.js";
3
3
  import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
4
+ import type { InvokeToolFn } from "#channel/invoke-tool.js";
4
5
  import type { InputResponse } from "#shared/input.js";
5
6
  import type { Session } from "#channel/session.js";
6
7
  import type { JsonObject } from "#shared/json.js";
@@ -36,6 +37,8 @@ export interface RouteHandlerArgs<TState = undefined> {
36
37
  * inspection detail of `GET /eve/v1/info`.
37
38
  */
38
39
  describe(): Promise<AgentDescription>;
40
+ /** Runs one of the agent's tools as `auth`, outside any conversation. */
41
+ readonly invokeTool: InvokeToolFn;
39
42
  }
40
43
  export interface SendPayload {
41
44
  readonly message?: string | UserContent;
@@ -57,7 +57,7 @@
57
57
  "zod": "4.5.4",
58
58
  "zod-validation-error": "5.0.0"
59
59
  },
60
- "scriptHash": "277be02e8bb80db55cb4e8f8b89fd9dbc1819089604a886604d433558d33d2e8",
60
+ "scriptHash": "635b143e3a7617f1eba75e922597c2ff0b0b034341a16d11b1367e5b119532e2",
61
61
  "toolVersions": {
62
62
  "rolldown": "1.2.9",
63
63
  "typescript": "7.0.2"
@@ -97,8 +97,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
97
97
  };
98
98
  };
99
99
  readonly channel: {
100
- readonly current: 46;
101
- readonly supported: readonly [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];
100
+ readonly current: 47;
101
+ readonly supported: readonly [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];
102
102
  readonly dropped: {
103
103
  readonly 12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
104
104
  readonly 19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.";
@@ -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:73,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,29,30,31,32,34,35,54,55,63,64,65,66,67,68,69,70,71,72,73],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 evaluate from eve/ai`,48:`eve/experimental/evaluate was removed; import evaluate 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.`,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.`}},dynamicTool:{current:70,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],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.`}},channel:{current:46,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],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.`}},schedule:{current:26,supported:[1,2,3,4,6,7,8,9,10,11,12,13,14,15,18,19,20,21,22,23,24,25,26],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:29,supported:[3,4,6,7,8,9,10,11,12,13,14,15,16,19,23,24,25,26,27,28,29],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:38,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],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.`}},hook:{current:37,supported:[20,21,22,23,25,27,31,32,33,34,35,36,37],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.`}},skill:{current:2,supported:[1,2],dropped:{}},dynamicSkill:{current:31,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],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:32,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],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:9,supported:[1,2,3,4,5,7,9],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`}}},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:73,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,29,30,31,32,34,35,54,55,63,64,65,66,67,68,69,70,71,72,73],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 evaluate from eve/ai`,48:`eve/experimental/evaluate was removed; import evaluate 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.`,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.`}},dynamicTool:{current:70,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],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.`}},channel:{current:47,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],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.`}},schedule:{current:26,supported:[1,2,3,4,6,7,8,9,10,11,12,13,14,15,18,19,20,21,22,23,24,25,26],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:29,supported:[3,4,6,7,8,9,10,11,12,13,14,15,16,19,23,24,25,26,27,28,29],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:38,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],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.`}},hook:{current:37,supported:[20,21,22,23,25,27,31,32,33,34,35,36,37],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.`}},skill:{current:2,supported:[1,2],dropped:{}},dynamicSkill:{current:31,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],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:32,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],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:9,supported:[1,2,3,4,5,7,9],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`}}},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};
@@ -0,0 +1,7 @@
1
+ import type { SessionAuthContext } from "#channel/types.js";
2
+ /**
3
+ * Runs `fn` with `caller` as the session's current caller. Writes still reach
4
+ * the outer context; only reads of the caller change, so work running beside
5
+ * `fn` in the same step keeps the outer caller.
6
+ */
7
+ export declare function runAsCaller<T>(caller: SessionAuthContext, fn: () => T): T;
@@ -0,0 +1 @@
1
+ import{contextStorage}from"#context/container.js";import{AuthKey,SessionKey}from"#context/keys.js";function runAsCaller(e,t){let n=contextStorage.getStore();return n===void 0?t():contextStorage.run(new CallerScope(n,e),t)}var CallerScope=class{#e;#t;constructor(e,t){this.#t=e,this.#e=t}get localDevRequest(){return this.#t.localDevRequest}get(e){if(e.name===AuthKey.name)return this.#e;if(e.name===SessionKey.name){let e=this.#t.get(SessionKey);return e===void 0?void 0:{...e,auth:{...e.auth,current:this.#e}}}return this.#t.get(e)}require(e){if(!this.has(e))throw Error(`Context key "${e.name}" is not set.`);return this.get(e)}has(e){return e.name===AuthKey.name||this.#t.has(e)}set(e,t){return this.#t.set(e,t)}ensure(e,t){return this.#t.ensure(e,t)}delete(e){return this.#t.delete(e)}entries(){return this.#t.entries()}setVirtualContext(e,t){this.#t.setVirtualContext(e,t)}};export{runAsCaller};
@@ -1,4 +1,4 @@
1
- /** Shared owner-side dispatch context preparation. */
1
+ import type { SessionAuthContext } from "#channel/types.js";
2
2
  import { type ChannelAdapter, type ChannelAdapterContext } from "#channel/adapter.js";
3
3
  import { type LocalDevRequestProvenance } from "#context/keys.js";
4
4
  import { ContextContainer } from "#context/container.js";
@@ -61,6 +61,7 @@ export declare function prepareCoordinationDispatch(input: {
61
61
  readonly sessionState: DurableSessionState;
62
62
  }): Promise<PreparedCoordinationDispatch | undefined>;
63
63
  interface DispatchBatch {
64
+ readonly approvers?: Readonly<Record<string, SessionAuthContext>>;
64
65
  readonly event: {
65
66
  readonly sequence: number;
66
67
  readonly stepIndex: number;
@@ -1 +1 @@
1
- import{ConversationContextKey}from"#shared/conversation-context.js";import"#channel/adapter.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey,TraceRootKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import"#subagents/tool.js";import{assertUniqueCoordinationCallIds,getPendingCoordinationBatch,setPendingCoordinationBatch}from"#harness/coordination.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";import{readDynamicSubagentSelections}from"#context/dynamic-subagent-lifecycle.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=getPendingCoordinationBatch(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(e.sessionState.emissionState),a=n.event.turnId===i?n.event:{...n.event,turnId:i},o=await deserializeContext(e.serializedContext),s=await prepareActionDispatch({batch:{event:a,requests:r},ctx:o,durableSession:t,plan:()=>r,serializedContext:e.serializedContext});if(a===n.event)return{...s,sessionState:e.sessionState};let c=setPendingCoordinationBatch({...n,event:a,session:s.session});return{...s,session:c,sessionState:createDurableSessionState({session:c})}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx,i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,serializedContext:e.serializedContext,session:o,traceRoot:childTraceRoot(r,o.sessionId),workflowAgents:resolveWorkflowAgentMetadata(r)}}function childTraceRoot(e,t){if(e.get(TraceRootKey)!==void 0)return{kind:`inherited`,sessionId:resolveTraceRootSessionId(e,t)}}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
1
+ import{ConversationContextKey}from"#shared/conversation-context.js";import"#channel/adapter.js";import"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey,LocalDevRequestKey,ParentSessionKey,TraceRootKey}from"#context/keys.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import"#subagents/tool.js";import{assertUniqueCoordinationCallIds,getPendingCoordinationBatch,setPendingCoordinationBatch}from"#harness/coordination.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveTraceRootSessionId}from"#shared/trace-root.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resolveWorkflowAgentMetadata}from"#execution/agent-sessions/metadata.js";import{readDynamicSubagentSelections}from"#context/dynamic-subagent-lifecycle.js";async function prepareCoordinationDispatch(e){let t=readDurableSession(e.sessionState),n=getPendingCoordinationBatch(t.state);if(n===void 0)return;let r=n.tasks;if(r.length===0)return;let i=n.event.turnId||activeTurnId(e.sessionState.emissionState),a=n.event.turnId===i?n.event:{...n.event,turnId:i},o=await deserializeContext(e.serializedContext),s=await prepareActionDispatch({batch:{approvers:n.approvers,event:a,requests:r},ctx:o,durableSession:t,plan:()=>r,serializedContext:e.serializedContext});if(a===n.event)return{...s,sessionState:e.sessionState};let c=setPendingCoordinationBatch({...n,event:a,session:s.session});return{...s,session:c,sessionState:createDurableSessionState({session:c})}}async function prepareActionDispatch(e){let{batch:t,durableSession:n}=e;assertUniqueCoordinationCallIds(t.requests);let r=e.ctx,i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({compactionOverrides:{thresholdPercent:a.thresholdPercent},durable:n,turnAgent:a.turnAgent}),s=r.require(ChannelKey),c=e.plan({bundle:i,ctx:r,requests:t.requests,session:o}),l=resolveActiveSandboxSessionId(s.state,o.sessionId);return{adapter:s,adapterCtx:buildAdapterContext(s,r),auth:r.get(AuthKey)??null,batch:t,bundle:i,capabilities:r.get(CapabilitiesKey),channelMetadata:r.get(ChannelInstrumentationKey),dynamicSubagentSelections:readDynamicSubagentSelections(r),inheritedConversation:r.get(ConversationContextKey),initiatorAuth:r.get(InitiatorAuthKey)??null,localDevRequest:r.get(LocalDevRequestKey),parentSession:r.get(ParentSessionKey),plan:c,sandboxSessionId:l,serializedContext:e.serializedContext,session:o,traceRoot:childTraceRoot(r,o.sessionId),workflowAgents:resolveWorkflowAgentMetadata(r)}}function childTraceRoot(e,t){if(e.get(TraceRootKey)!==void 0)return{kind:`inherited`,sessionId:resolveTraceRootSessionId(e,t)}}function resolveActiveSandboxSessionId(e,t){if(typeof e!=`object`||!e)return t;let n=e.sandboxSessionId;return typeof n==`string`&&n.length>0?n:t}export{prepareActionDispatch,prepareCoordinationDispatch};
@@ -1 +1 @@
1
- import{createDurableSessionState}from"#execution/durable-session-store.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";import{sendToTask,startTaskRun}from"#execution/tasks/start.js";import{captureAgentSessionContext,resolveStepAgentLimits}from"#execution/agent-sessions/context.js";async function dispatchCoordinationStep(e){"use step";return await withSessionStateDelta(e,dispatchCoordination)}async function dispatchCoordination(e){let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],serializedContext:e.serializedContext,sessionState:e.sessionState};let{batch:n,session:r}=t,i=r,a=[],o=[],s=resolveStepAgentLimits(t);for(let r of t.plan){let c=await dispatchWorkflowCall({agentContext:captureAgentSessionContext(t,r.callId,s),auth:{current:t.auth,initiator:t.initiatorAuth},batchEvent:n.event,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r});i=c.session,c.result!==void 0&&a.push(c.result),c.started!==void 0&&o.push(c.started)}return{results:a,...await publishSessionEvents({serializedContext:e.serializedContext,sessionState:i===r?t.sessionState:createDurableSessionState({session:i}),sessionWritable:e.sessionWritable},o)}}async function dispatchWorkflowCall(e){let{entry:t}=e.task;switch(t.entryPoint){case`execute`:return await startWorkflowTask(e);case`task`:case`serve`:return await startTaskRun({...e,entry:t});case`receive`:return await sendToTask({...e,taskId:t.taskId})}}export{dispatchCoordinationStep};
1
+ import{createDurableSessionState}from"#execution/durable-session-store.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{publishSessionEvents}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";import{sendToTask,startTaskRun}from"#execution/tasks/start.js";import{captureAgentSessionContext,resolveStepAgentLimits}from"#execution/agent-sessions/context.js";async function dispatchCoordinationStep(e){"use step";return await withSessionStateDelta(e,dispatchCoordination)}async function dispatchCoordination(e){let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],serializedContext:e.serializedContext,sessionState:e.sessionState};let{batch:n,session:r}=t,i=r,a=[],o=[],s=resolveStepAgentLimits(t);for(let r of t.plan){let c=await dispatchWorkflowCall({agentContext:captureAgentSessionContext(t,r.callId,s),auth:{current:n.approvers?.[r.callId]??t.auth,initiator:t.initiatorAuth},batchEvent:n.event,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r});i=c.session,c.result!==void 0&&a.push(c.result),c.started!==void 0&&o.push(c.started)}return{results:a,...await publishSessionEvents({serializedContext:e.serializedContext,sessionState:i===r?t.sessionState:createDurableSessionState({session:i}),sessionWritable:e.sessionWritable},o)}}async function dispatchWorkflowCall(e){let{entry:t}=e.task;switch(t.entryPoint){case`execute`:return await startWorkflowTask(e);case`task`:case`serve`:return await startTaskRun({...e,entry:t});case`receive`:return await sendToTask({...e,taskId:t.taskId})}}export{dispatchCoordinationStep};
@@ -1 +1 @@
1
- import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.71.2//runWorkflowProgramTask`;export{runWorkflowProgramTask};
1
+ import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@0.71.3//runWorkflowProgramTask`;export{runWorkflowProgramTask};
@@ -0,0 +1,35 @@
1
+ import type { InvokeToolOptions, InvokeToolResult } from "#channel/invoke-tool.js";
2
+ import { type CompiledToolBindings } from "#channel/tool-eligibility.js";
3
+ import type { CompiledToolDefinition } from "#compiler/manifest.js";
4
+ import type { HarnessToolMap } from "#harness/types.js";
5
+ import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
6
+ import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
7
+ import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
8
+ import { type InvokeToolTraceOrigin } from "#tracing/invoke-tool-span.js";
9
+ /** What `invokeTool` needs from the agent: its static tools and sandbox. */
10
+ export interface InvokeToolRuntime {
11
+ /** Present in a deployed agent so framework helpers can reach the compiled graph. */
12
+ readonly bundle?: CompiledRuntimeAgentBundle;
13
+ /** Base URL for framework callbacks, such as the page a sign-in lands on. */
14
+ readonly callbackBaseUrl: string;
15
+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
16
+ /** The root node's compiled tools and source bindings, which decide invocability. */
17
+ readonly manifest: InvokeToolManifest;
18
+ readonly nodeId: string;
19
+ /** The agent's name, for trace policy and `gen_ai.agent.name`. */
20
+ readonly agentName: string;
21
+ /** The channel the call arrived on, for trace policy and span attributes. */
22
+ readonly origin?: InvokeToolTraceOrigin;
23
+ readonly sandboxRegistry: RuntimeSandboxRegistry;
24
+ /** Static tools only: dynamic resolvers never run outside a turn. */
25
+ readonly tools: HarnessToolMap;
26
+ }
27
+ /** The part of a compiled manifest `invokeTool` reads to decide invocability. */
28
+ export interface InvokeToolManifest extends CompiledToolBindings {
29
+ readonly tools: readonly Pick<CompiledToolDefinition, "behavior" | "hasExecute" | "name" | "sourceId">[];
30
+ }
31
+ /**
32
+ * Runs one tool outside a turn; see `InvokeToolFn` for the contract. Each call
33
+ * gets a fresh session id, so nothing it opens is shared with another call.
34
+ */
35
+ export declare function invokeTool(runtime: InvokeToolRuntime, name: string, input: unknown, options: InvokeToolOptions): Promise<InvokeToolResult>;
@@ -0,0 +1 @@
1
+ import{createLogger,logError}from"#internal/logging.js";import{compiledToolOwner,isInvocableCompiledTool}from"#channel/tool-eligibility.js";import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SandboxKey,SessionIdKey,SessionKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{ensureSandboxAccess}from"#execution/sandbox/ensure.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{AuthorizationHookKey,CallbackBaseUrlKey,isAuthorizationSignal,modelFacingAuthorizationOutput}from"#harness/authorization.js";import{checkToolCallInput,toolCallModelOutput}from"#harness/tool-call-io.js";import{normalizeToolJsonOutput}from"#harness/tool-model-output.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createUlid}from"#shared/ulid.js";import{withInvokeToolSpan}from"#tracing/invoke-tool-span.js";const log=createLogger(`invoke-tool`);function ineligibility(e,t){if(!isInvocableCompiledTool(e,t))return compiledToolOwner(e,t).kind===`framework`?`it is a framework tool, which needs a conversation`:t.behavior?.handling===void 0?`it has no server-side execute`:`the harness or the model provider runs it, not its execute`}async function invokeTool(e,t,n,r){let i=e.manifest.tools.find(e=>e.name===t),a=e.tools.get(t);if(i===void 0||a===void 0)return failed(`The agent has no tool named "${t}".`);let o=ineligibility(e.manifest,i)??(a.execute===void 0?`it has no server-side execute`:void 0);if(o!==void 0)return failed(`Tool "${t}" cannot be invoked outside a conversation: ${o}.`);let s=`call_${createUlid()}`,c=`call_session_${createUlid()}`;return await withInvokeToolSpan({agentName:e.agentName,auth:r.auth,callId:s,origin:e.origin,sessionId:c,toolName:t},i=>runInvocation({callId:s,definition:a,input:n,name:t,observer:i,options:r,runtime:e,sessionId:c}))}async function runInvocation(e){let{callId:t,definition:n,name:r,observer:i,options:a,runtime:o,sessionId:s}=e,c=await checkToolCallInput(n,e.input,t);if(c.kind===`threw`)return i.failedWith(c.error),failedFromError(c.error,r,`input validation failed`);if(c.kind===`invalid`)return{message:c.message,status:`invalid-input`};let l=await callSandbox(o,s),u=createCallContext({auth:a.auth,callId:t,callbackBaseUrl:o.callbackBaseUrl,sessionId:s});u.setVirtualContext(SandboxKey,l.access),o.bundle!==void 0&&u.setVirtualContext(BundleKey,o.bundle);try{return await contextStorage.run(u,()=>runCall({callId:t,definition:n,input:c.value,observer:i,signal:a.signal}))}finally{await l.release().catch(e=>{logError(log,`failed to delete a call's sandbox`,e,{sessionId:s,toolName:r})})}}async function callSandbox(e,t){let n=await ensureSandboxAccess({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId,ownsSandbox:!0,registry:e.sandboxRegistry,sessionId:t,state:null}),r;return{access:{...n,get(){let e=n.get();return r=e,e}},async release(){r!==void 0&&await r.catch(()=>null)!==null&&await n.delete?.()}}}function createCallContext(e){let t=new ContextContainer;return t.set(AuthKey,e.auth),t.set(InitiatorAuthKey,e.auth),t.set(SessionIdKey,e.sessionId),t.setVirtualContext(SessionKey,{auth:{current:e.auth,initiator:e.auth},sessionId:e.sessionId,turn:{id:e.callId,sequence:0}}),t.set(CallbackBaseUrlKey,e.callbackBaseUrl.replace(/\/$/,``)),t.setVirtualContext(AuthorizationHookKey,`invoke-tool:${e.callId}`),t}async function runCall(e){let{callId:t,definition:n,observer:r}=e,i=e.signal??new AbortController().signal;if(n.approval!==void 0){let a;try{a=await resolveApprovalPolicy(n.approval)({...buildCallbackContext(),abortSignal:i,approvedTools:new Set,callId:t,toolInput:e.input,toolName:n.name})}catch(e){return r.failedWith(e),failedFromError(e,n.name,`approval policy failed`)}let o=decideApproval(a);if(o.kind===`denied`)return denied(o.reason);if(o.kind===`user-approval`)return{status:`approval-required`}}let a={abortSignal:i,messages:[],toolCallId:t};await r.executing(e.input);let o,s,c=!1,l=performance.now(),elapsed=()=>performance.now()-l,u;try{o=await n.execute(e.input,a),isAsyncIterable(o)&&(o=await lastIterated(o)),c=!0,isAuthorizationSignal(o)||(s=normalizeToolJsonOutput({boundary:`execute`,output:o,toolCallId:t,toolName:n.name})),u=elapsed()}catch(e){return await r.executed({durationMs:elapsed(),error:e,type:`error`}),r.failedWith(e),c?failedFromError(e,n.name,`tool output could not be serialized`):isConnectionAuthorizationFailedError(e)?failed(toErrorMessage(e)):failedFromError(e,n.name,`tool execution failed`)}if(isAuthorizationSignal(o))return await r.executed({durationMs:u,output:modelFacingAuthorizationOutput(o),type:`result`}),{connections:o.challenges.map(e=>e.name),status:`authorization-required`};await r.executed({durationMs:u,output:s,type:`result`});try{return{modelOutput:await toolCallModelOutput(n,s,t),output:s,status:`completed`}}catch(e){return r.failedWith(e),failedFromError(e,n.name,`tool output could not be serialized`)}}function decideApproval(e){if(e===!0||e===`user-approval`)return{kind:`user-approval`};if(e===`denied`)return{kind:`denied`};if(typeof e==`object`&&e){if(e.type===`user-approval`)return{kind:`user-approval`};if(e.type===`denied`)return{kind:`denied`,reason:e.reason}}return{kind:`run`}}async function lastIterated(e){let t;for await(let n of e)t=n;return t}function denied(e){return e===void 0?{status:`denied`}:{reason:e,status:`denied`}}function failed(e){return{message:e,status:`failed`}}function failedFromError(e,t,n){let r=context.with(trace.deleteSpan(context.active()),()=>logError(log,`invokeTool ${n}`,e,{toolName:t}));return{errorId:r,message:`Tool "${t}" failed: ${n}. The error is logged with id ${r}.`,status:`failed`}}export{invokeTool};
@@ -1,6 +1,7 @@
1
1
  import { type ChannelAdapterContext } from "#channel/adapter.js";
2
2
  import { type ContextContainer } from "#context/container.js";
3
3
  import { type DurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
4
+ import type { HarnessTurnRef } from "#harness/emission-state.js";
4
5
  import { type HarnessModelMessage } from "#harness/messages.js";
5
6
  import type { HandleEventFn, HarnessSession, HarnessSessionBase } from "#harness/types.js";
6
7
  import { type MessageStreamEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -145,6 +146,8 @@ export declare function publishTerminalSessionEvent(input: {
145
146
  readonly event: TerminalSessionEvent;
146
147
  readonly serializedContext: Record<string, unknown>;
147
148
  readonly sessionWritable: WritableStream<Uint8Array>;
149
+ /** The session's last turn, for channel handlers' `ctx.session.turn`. */
150
+ readonly turn?: HarnessTurnRef;
148
151
  /** The turn the event ends, for instrumentation. */
149
152
  readonly turnId?: string;
150
153
  }): Promise<void>;
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{ParentSessionKey,TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{forwardSessionInput}from"#execution/forward-session-input.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.publish-session-events`);async function publishSessionEvents(e,t){return await publishEventsFromStep(e,`own`,t)}async function relaySessionEvents(e,t){return await publishEventsFromStep(e,`relayed`,t)}async function publishEventsFromStep(e,t,n){if(n.length===0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let{published:r}=await publishFromSessionStep(await restoreSessionStep(e),{origin:t,async publish(e){for(let t of n)await e(t)}});return r}async function restoreSessionStep(e){return{ctx:await deserializeContext(e.serializedContext),durableSession:readDurableSession(e.sessionState),sessionWritable:e.sessionWritable}}async function publishFromSessionStep(e,t){let{ctx:n}=e,r=await publishInSessionScope(e,t),i=t.updateSession?.(r.session,r.result)??{session:r.session},a=reconcileSessionContinuationToken(n,i.session);return{published:{serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:a}),...`history`in a&&{history:a.history}},result:i.result}}async function publishInSessionScope(e,t){let{ctx:n}=e,r=resolveEffectiveAgentRuntime(n.require(BundleKey),n),i=hydrateDurableSession({compactionOverrides:{thresholdPercent:r.thresholdPercent},durable:e.durableSession,turnAgent:r.turnAgent}),a=e.history===void 0?i:{...i,history:validateHarnessModelMessages(e.history)},o=t.origin===`own`?bindSessionInstrumentation({agentName:r.turnAgent.id,ctx:n,rootSessionId:a.rootSessionId??a.sessionId,sessionId:a.sessionId}):void 0,s=openSessionEventPublisher({ctx:n,inputSource:t.inputSource,origin:t.origin,sessionWritable:e.sessionWritable});try{return await withContextScope(n,a,async n=>{let r=o?.createHandleEvent({handleEvent:s.publish,turnId:activeTurnId(getHarnessEmissionState(e.durableSession.state))})??s.publish;return{result:await t.publish(r,n),session:n}})}finally{await o?.flush(),s.writer.release()}}function openSessionEventPublisher(e){let{ctx:t,origin:n}=e,r=createSessionEventDispatcher(e),i=openSessionEventWriter({deliveryIds:()=>n===`own`?t.get(TurnDeliveryIdsKey):void 0,sessionWritable:e.sessionWritable}),emit=async e=>await i.write(await r.deliver(e));return{dispatcher:r,writer:i,emit,async publish(e){await r.runHooks(await emit(e))}}}function createSessionEventDispatcher(e){let{ctx:t,inputSource:n}=e,r=t.require(ChannelKey),i=buildAdapterContext(r,t);return{adapterCtx:i,async deliver(e){let a=await forwardSessionInput(t,e,n)?e:await callAdapterEventHandler(r,e,n===void 0?i:{...i,inputSource:n});return setChannelContext(t,{...r,state:{...i.state}}),a},async runHooks(e,n){await dispatchStreamEventHooks({cancelTurn:n,ctx:t,event:e,registry:t.require(BundleKey).hookRegistry})}}}function openSessionEventWriter(e){let t=e.sessionWritable.getWriter(),n=!1,release=()=>{n||(n=!0,t.releaseLock())};return{async write(n){let r=stampMessageStreamEvent(n,e.deliveryIds());return await t.write(encodeMessageStreamEvent(r)),r},close:async()=>{await t.close(),release()},release}}async function publishTerminalSessionEvent(e){let t=e.serializedContext[`eve.sessionId`]??``,n={errorId:e.errorId,sessionId:t},{type:r}=e.event,i,a;try{i=await deserializeContext(e.serializedContext),a=openSessionEventPublisher({ctx:i,origin:`own`,sessionWritable:e.sessionWritable})}catch(t){log.error(`failed to restore context for terminal ${r} event`,{...n,error:t}),await writeUnroutedSessionEvent(e.sessionWritable,e.event).catch(e=>log.error(`failed to write terminal ${r} event`,{...n,error:e}));return}let publish=async e=>{await a.emit(e),await a.writer.close()},o;try{o=bindSessionInstrumentation({agentName:i.require(BundleKey).turnAgent.id,ctx:i,rootSessionId:i.get(ParentSessionKey)?.rootSessionId??t,sessionId:t})}catch(e){log.error(`failed to bind instrumentation for terminal ${r} event`,{...n,error:e})}let s=o?.createHandleEvent({handleEvent:publish,turnId:e.turnId})??publish;try{await contextStorage.run(i,()=>s(e.event))}catch(e){log.error(`failed to publish terminal ${r} event`,{...n,error:e})}finally{a.writer.release();try{await o?.flush()}catch(e){log.error(`failed to flush instrumentation after terminal ${r} event`,{...n,error:e})}}}async function writeUnroutedSessionEvent(e,t){let n=openSessionEventWriter({deliveryIds:()=>void 0,sessionWritable:e});try{await n.write(t),await n.close()}finally{n.release()}}export{openSessionEventPublisher,publishFromSessionStep,publishSessionEvents,publishTerminalSessionEvent,relaySessionEvents,restoreSessionStep};
1
+ import{createLogger}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,ParentSessionKey,SessionKey,TurnDeliveryIdsKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{forwardSessionInput}from"#execution/forward-session-input.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";const log=createLogger(`execution.publish-session-events`);async function publishSessionEvents(e,t){return await publishEventsFromStep(e,`own`,t)}async function relaySessionEvents(e,t){return await publishEventsFromStep(e,`relayed`,t)}async function publishEventsFromStep(e,t,n){if(n.length===0)return{serializedContext:e.serializedContext,sessionState:e.sessionState};let{published:r}=await publishFromSessionStep(await restoreSessionStep(e),{origin:t,async publish(e){for(let t of n)await e(t)}});return r}async function restoreSessionStep(e){return{ctx:await deserializeContext(e.serializedContext),durableSession:readDurableSession(e.sessionState),sessionWritable:e.sessionWritable}}async function publishFromSessionStep(e,t){let{ctx:n}=e,r=await publishInSessionScope(e,t),i=t.updateSession?.(r.session,r.result)??{session:r.session},a=reconcileSessionContinuationToken(n,i.session);return{published:{serializedContext:serializeContext(n),sessionState:createDurableSessionState({session:a}),...`history`in a&&{history:a.history}},result:i.result}}async function publishInSessionScope(e,t){let{ctx:n}=e,r=resolveEffectiveAgentRuntime(n.require(BundleKey),n),i=hydrateDurableSession({compactionOverrides:{thresholdPercent:r.thresholdPercent},durable:e.durableSession,turnAgent:r.turnAgent}),a=e.history===void 0?i:{...i,history:validateHarnessModelMessages(e.history)},o=t.origin===`own`?bindSessionInstrumentation({agentName:r.turnAgent.id,ctx:n,rootSessionId:a.rootSessionId??a.sessionId,sessionId:a.sessionId}):void 0,s=openSessionEventPublisher({ctx:n,inputSource:t.inputSource,origin:t.origin,sessionWritable:e.sessionWritable});try{return await withContextScope(n,a,async n=>{let r=o?.createHandleEvent({handleEvent:s.publish,turnId:activeTurnId(getHarnessEmissionState(e.durableSession.state))})??s.publish;return{result:await t.publish(r,n),session:n}})}finally{await o?.flush(),s.writer.release()}}function openSessionEventPublisher(e){let{ctx:t,origin:n}=e,r=createSessionEventDispatcher(e),i=openSessionEventWriter({deliveryIds:()=>n===`own`?t.get(TurnDeliveryIdsKey):void 0,sessionWritable:e.sessionWritable}),emit=async e=>await i.write(await r.deliver(e));return{dispatcher:r,writer:i,emit,async publish(e){await r.runHooks(await emit(e))}}}function createSessionEventDispatcher(e){let{ctx:t,inputSource:n}=e,r=t.require(ChannelKey),i=buildAdapterContext(r,t);return{adapterCtx:i,async deliver(e){let a=await forwardSessionInput(t,e,n)?e:await callAdapterEventHandler(r,e,n===void 0?i:{...i,inputSource:n});return setChannelContext(t,{...r,state:{...i.state}}),a},async runHooks(e,n){await dispatchStreamEventHooks({cancelTurn:n,ctx:t,event:e,registry:t.require(BundleKey).hookRegistry})}}}function openSessionEventWriter(e){let t=e.sessionWritable.getWriter(),n=!1,release=()=>{n||(n=!0,t.releaseLock())};return{async write(n){let r=stampMessageStreamEvent(n,e.deliveryIds());return await t.write(encodeMessageStreamEvent(r)),r},close:async()=>{await t.close(),release()},release}}async function publishTerminalSessionEvent(e){let t=e.serializedContext[`eve.sessionId`]??``,n={errorId:e.errorId,sessionId:t},{type:r}=e.event,i,a;try{i=await deserializeContext(e.serializedContext),a=openSessionEventPublisher({ctx:i,origin:`own`,sessionWritable:e.sessionWritable})}catch(t){log.error(`failed to restore context for terminal ${r} event`,{...n,error:t}),await writeUnroutedSessionEvent(e.sessionWritable,e.event).catch(e=>log.error(`failed to write terminal ${r} event`,{...n,error:e}));return}let o=i.get(AuthKey)??null;i.setVirtualContext(SessionKey,{auth:{current:o,initiator:i.get(InitiatorAuthKey)??o},parent:i.get(ParentSessionKey),sessionId:t,turn:e.turn??{id:`turn_0`,sequence:0}});let publish=async e=>{await a.emit(e),await a.writer.close()},s;try{s=bindSessionInstrumentation({agentName:i.require(BundleKey).turnAgent.id,ctx:i,rootSessionId:i.get(ParentSessionKey)?.rootSessionId??t,sessionId:t})}catch(e){log.error(`failed to bind instrumentation for terminal ${r} event`,{...n,error:e})}let c=s?.createHandleEvent({handleEvent:publish,turnId:e.turnId})??publish;try{await contextStorage.run(i,()=>c(e.event))}catch(e){log.error(`failed to publish terminal ${r} event`,{...n,error:e})}finally{a.writer.release();try{await s?.flush()}catch(e){log.error(`failed to flush instrumentation after terminal ${r} event`,{...n,error:e})}}}async function writeUnroutedSessionEvent(e,t){let n=openSessionEventWriter({deliveryIds:()=>void 0,sessionWritable:e});try{await n.write(t),await n.close()}finally{n.release()}}export{openSessionEventPublisher,publishFromSessionStep,publishSessionEvents,publishTerminalSessionEvent,relaySessionEvents,restoreSessionStep};
@@ -15,6 +15,12 @@ export declare function trackActiveSandboxHandle(input: {
15
15
  readonly handle: ShutdownCapableSandboxHandle;
16
16
  readonly sessionId: string;
17
17
  }): void;
18
+ /** Drops a handle from shutdown tracking, unless a newer handle replaced it. */
19
+ export declare function untrackActiveSandboxHandle(input: {
20
+ readonly providerName: string;
21
+ readonly handle: ShutdownCapableSandboxHandle;
22
+ readonly sessionId: string;
23
+ }): void;
18
24
  /**
19
25
  * Stops every tracked sandbox by invoking its runtime-shutdown hook in
20
26
  * parallel, then clears the registry. Failures are logged and never
@@ -1 +1 @@
1
- import{toErrorMessage}from"#shared/errors.js";const activeSandboxHandles=new Map;function createActiveSandboxHandleKey(e,t){return`${e}\0${t}`}function trackActiveSandboxHandle(e){activeSandboxHandles.set(createActiveSandboxHandleKey(e.providerName,e.sessionId),e.handle)}async function shutdownActiveSandboxHandles(e){let t=[...activeSandboxHandles.entries()];activeSandboxHandles.clear();let n=await Promise.allSettled(t.map(([,e])=>e.onRuntimeShutdown()));for(let[r,i]of n.entries())if(i.status===`rejected`){let n=t[r];e?.log?.(`failed to shut down sandbox "${n?.[0]??`unknown`}": ${toErrorMessage(i.reason)}`)}}export{shutdownActiveSandboxHandles,trackActiveSandboxHandle};
1
+ import{toErrorMessage}from"#shared/errors.js";const activeSandboxHandles=new Map;function createActiveSandboxHandleKey(e,t){return`${e}\0${t}`}function trackActiveSandboxHandle(e){activeSandboxHandles.set(createActiveSandboxHandleKey(e.providerName,e.sessionId),e.handle)}function untrackActiveSandboxHandle(e){let t=createActiveSandboxHandleKey(e.providerName,e.sessionId);activeSandboxHandles.get(t)===e.handle&&activeSandboxHandles.delete(t)}async function shutdownActiveSandboxHandles(e){let t=[...activeSandboxHandles.entries()];activeSandboxHandles.clear();let n=await Promise.allSettled(t.map(([,e])=>e.onRuntimeShutdown()));for(let[r,i]of n.entries())if(i.status===`rejected`){let n=t[r];e?.log?.(`failed to shut down sandbox "${n?.[0]??`unknown`}": ${toErrorMessage(i.reason)}`)}}export{shutdownActiveSandboxHandles,trackActiveSandboxHandle,untrackActiveSandboxHandle};
@@ -1 +1 @@
1
- import{contextStorage}from"#context/container.js";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{getSandboxEnvironmentRuntime,runWithSandboxConstructorRuntime}from"#shared/sandbox-environment.js";import{buildCallbackContext,withRuntimeSandboxLifecycle}from"#context/build-callback-context.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{trackActiveSandboxHandle}from"#execution/sandbox/active-handles.js";import{isSandboxPreparedArtifact}from"#shared/sandbox-provider.js";import{SandboxTemplateNotProvisionedError}from"#shared/sandbox-template-error.js";import{loadSandboxPreparedArtifact}from"#runtime/sandbox/prepared-artifacts.js";import{getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{ensureDevelopmentSandboxesPrepared}from"#execution/sandbox/development-lazy-prewarm.js";import{createSandboxProviderHost}from"#execution/sandbox/provider-host.js";const pendingSandboxStarts=new Map;async function ensureSandboxAccess(e){let t=e.state?.session?.providerName===void 0?null:e.state.session,n,r,i,a=getRuntimeCompiledArtifactsSandboxAppRoot(e.compiledArtifactsSource)??process.cwd(),o=e.registry.sandbox;if(o===null)return{async captureState(){return{session:t}},async get(){return null},async stop(){}};async function open(n,i,s,c){if(r!==void 0)throw Error(`A sandbox definition can open only one sandbox.`);let l=o.inheritance,u=l?.definition??o.definition;if(u.kind!==`independent`)throw Error(`Sandbox "${u.logicalPath}" has no environment.`);if(s!==u.environment)throw Error(`Sandbox "${u.logicalPath}" selected a different environment.`);if(n!==getSandboxEnvironmentRuntime(u.environment))throw Error(`Sandbox "${u.logicalPath}" selected a different provider.`);if(t!==null)throw Error(`Sandbox "${u.logicalPath}" is already initialized.`);let d=l?.nodeId??e.nodeId,f=await loadSandboxPreparedArtifact({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:d,providerName:n.providerName});if(f===void 0)throw new SandboxTemplateNotProvisionedError({providerName:n.providerName,templateKey:d});let p={host:createSandboxProviderHost(a),session:c,storagePath:resolveSandboxCacheDirectory(a)};r=(async()=>{let e=await n.implementation.start(p,i,f);if(!isSandboxPreparedArtifact(e.state))throw Error(`Sandbox provider "${n.providerName}" returned non-serializable session state.`);return t={providerName:n.providerName,state:e.state,stateProtocolVersion:n.stateProtocolVersion},e.handle})().catch(e=>{throw r=void 0,e});let m=await r;return installHandle(n.providerName,m)}function installHandle(e,t){let r=withRuntimeSandboxLifecycle(t.sandbox,e=>t.onSessionDelete(e),()=>t.onSessionStop());return n={handle:t,providerName:e,sandbox:r},r}async function resumePersisted(n,i){if(t===null)throw Error(`Sandbox session state is missing.`);let s=getSandboxEnvironmentRuntime(n.environment);if(t.providerName!==s.providerName)throw Error(`Sandbox session state belongs to provider "${t.providerName}", not "${s.providerName}".`);if(t.stateProtocolVersion!==s.stateProtocolVersion)throw Error(`Sandbox session state protocol ${t.stateProtocolVersion} is incompatible with provider "${s.providerName}" protocol ${s.stateProtocolVersion}.`);let c=o.inheritance?.nodeId??e.nodeId,l=await loadSandboxPreparedArtifact({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:c,providerName:s.providerName});if(l===void 0)throw new SandboxTemplateNotProvisionedError({providerName:s.providerName,templateKey:c});let u={host:createSandboxProviderHost(a),session:i,storagePath:resolveSandboxCacheDirectory(a)};r=s.implementation.resume(u,l,t.state).catch(e=>{throw r=void 0,e});let d=await r;return installHandle(s.providerName,d),trackActiveSandboxHandle({handle:d,providerName:s.providerName,sessionId:e.sessionId}),d}async function resolveHandle(){let n=o.inheritance,r=n?.definition??o.definition;if(r.kind!==`independent`)throw Error(`Sandbox "${r.logicalPath}" has no resolved parent.`);isEveDevEnvironment()&&e.compiledArtifactsSource.kind===`disk`&&await ensureDevelopmentSandboxesPrepared({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:n?.nodeId??e.nodeId,providerName:getSandboxEnvironmentRuntime(r.environment).providerName});let i={...contextStorage.getStore()===void 0?{auth:{current:null,initiator:null},id:e.sessionId,turn:{id:`sandbox-initialization`,sequence:0}}:buildCallbackContext().session,id:e.sessionId};if(t!==null)return await resumePersisted(r,i);let a=`${n?.nodeId??e.nodeId}\0${e.sessionId}`,s=pendingSandboxStarts.get(a);for(;s!==void 0;){if(t=await s,t!==null)return await resumePersisted(r,i);s=pendingSandboxStarts.get(a)}let c=startHandle(r,i),l=c.then(()=>t,()=>null);pendingSandboxStarts.set(a,l);try{return await c}finally{pendingSandboxStarts.get(a)===l&&pendingSandboxStarts.delete(a)}}async function startHandle(i,a){if(o.inheritance!==void 0)await open(getSandboxEnvironmentRuntime(i.environment),void 0,i.environment,a);else try{let e=await runWithSandboxConstructorRuntime({open:({environment:e,options:t,provider:n})=>open(n,t,e,a)},async()=>i.selector({session:a}));if(n===void 0||e!==n.sandbox)throw Error(`Sandbox "${i.logicalPath}" must return the sandbox it opens.`)}catch(e){let a=n?.handle;if(n=void 0,r=void 0,t=null,a!==void 0)try{await a.onSessionDelete()}catch(t){throw AggregateError([e,t],`Sandbox "${i.logicalPath}" initialization and cleanup both failed.`,{cause:e})}throw e}if(n===void 0)throw Error(`Sandbox "${i.logicalPath}" did not open a provider handle.`);return trackActiveSandboxHandle({handle:n.handle,providerName:n.providerName,sessionId:e.sessionId}),n.handle}function requireHandle(){return i===void 0&&(i=resolveHandle().catch(e=>{throw i=void 0,e})),i}let s=o.inheritance?.definition??o.definition;return{environment:s.kind===`independent`?s.environment:void 0,async captureState(){return r!==void 0&&await r,{session:t}},async delete(a){if(e.ownsSandbox===!1)throw Error(`Only the owning session can delete this sandbox.`);await(await requireHandle()).onSessionDelete(a),n=void 0,r=void 0,t=null,i=void 0},async get(){return await requireHandle(),n?.sandbox??null},async stop(){await(await requireHandle()).onSessionStop(),n=void 0,r=void 0,i=void 0}}}export{ensureSandboxAccess};
1
+ import{contextStorage}from"#context/container.js";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{getSandboxEnvironmentRuntime,runWithSandboxConstructorRuntime}from"#shared/sandbox-environment.js";import{buildCallbackContext,withRuntimeSandboxLifecycle}from"#context/build-callback-context.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{trackActiveSandboxHandle,untrackActiveSandboxHandle}from"#execution/sandbox/active-handles.js";import{isSandboxPreparedArtifact}from"#shared/sandbox-provider.js";import{SandboxTemplateNotProvisionedError}from"#shared/sandbox-template-error.js";import{loadSandboxPreparedArtifact}from"#runtime/sandbox/prepared-artifacts.js";import{getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{ensureDevelopmentSandboxesPrepared}from"#execution/sandbox/development-lazy-prewarm.js";import{createSandboxProviderHost}from"#execution/sandbox/provider-host.js";const pendingSandboxStarts=new Map;async function ensureSandboxAccess(e){let t=e.state?.session?.providerName===void 0?null:e.state.session,n,r,i,a=getRuntimeCompiledArtifactsSandboxAppRoot(e.compiledArtifactsSource)??process.cwd(),o=e.registry.sandbox;if(o===null)return{async captureState(){return{session:t}},async get(){return null},async stop(){}};async function open(n,i,s,c){if(r!==void 0)throw Error(`A sandbox definition can open only one sandbox.`);let l=o.inheritance,u=l?.definition??o.definition;if(u.kind!==`independent`)throw Error(`Sandbox "${u.logicalPath}" has no environment.`);if(s!==u.environment)throw Error(`Sandbox "${u.logicalPath}" selected a different environment.`);if(n!==getSandboxEnvironmentRuntime(u.environment))throw Error(`Sandbox "${u.logicalPath}" selected a different provider.`);if(t!==null)throw Error(`Sandbox "${u.logicalPath}" is already initialized.`);let d=l?.nodeId??e.nodeId,f=await loadSandboxPreparedArtifact({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:d,providerName:n.providerName});if(f===void 0)throw new SandboxTemplateNotProvisionedError({providerName:n.providerName,templateKey:d});let p={host:createSandboxProviderHost(a),session:c,storagePath:resolveSandboxCacheDirectory(a)};r=(async()=>{let e=await n.implementation.start(p,i,f);if(!isSandboxPreparedArtifact(e.state))throw Error(`Sandbox provider "${n.providerName}" returned non-serializable session state.`);return t={providerName:n.providerName,state:e.state,stateProtocolVersion:n.stateProtocolVersion},e.handle})().catch(e=>{throw r=void 0,e});let m=await r;return installHandle(n.providerName,m)}function installHandle(e,t){let r=withRuntimeSandboxLifecycle(t.sandbox,e=>t.onSessionDelete(e),()=>t.onSessionStop());return n={handle:t,providerName:e,sandbox:r},r}async function resumePersisted(n,i){if(t===null)throw Error(`Sandbox session state is missing.`);let s=getSandboxEnvironmentRuntime(n.environment);if(t.providerName!==s.providerName)throw Error(`Sandbox session state belongs to provider "${t.providerName}", not "${s.providerName}".`);if(t.stateProtocolVersion!==s.stateProtocolVersion)throw Error(`Sandbox session state protocol ${t.stateProtocolVersion} is incompatible with provider "${s.providerName}" protocol ${s.stateProtocolVersion}.`);let c=o.inheritance?.nodeId??e.nodeId,l=await loadSandboxPreparedArtifact({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:c,providerName:s.providerName});if(l===void 0)throw new SandboxTemplateNotProvisionedError({providerName:s.providerName,templateKey:c});let u={host:createSandboxProviderHost(a),session:i,storagePath:resolveSandboxCacheDirectory(a)};r=s.implementation.resume(u,l,t.state).catch(e=>{throw r=void 0,e});let d=await r;return installHandle(s.providerName,d),trackActiveSandboxHandle({handle:d,providerName:s.providerName,sessionId:e.sessionId}),d}async function resolveHandle(){let n=o.inheritance,r=n?.definition??o.definition;if(r.kind!==`independent`)throw Error(`Sandbox "${r.logicalPath}" has no resolved parent.`);isEveDevEnvironment()&&e.compiledArtifactsSource.kind===`disk`&&await ensureDevelopmentSandboxesPrepared({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:n?.nodeId??e.nodeId,providerName:getSandboxEnvironmentRuntime(r.environment).providerName});let i={...contextStorage.getStore()===void 0?{auth:{current:null,initiator:null},id:e.sessionId,turn:{id:`sandbox-initialization`,sequence:0}}:buildCallbackContext().session,id:e.sessionId};if(t!==null)return await resumePersisted(r,i);let a=`${n?.nodeId??e.nodeId}\0${e.sessionId}`,s=pendingSandboxStarts.get(a);for(;s!==void 0;){if(t=await s,t!==null)return await resumePersisted(r,i);s=pendingSandboxStarts.get(a)}let c=startHandle(r,i),l=c.then(()=>t,()=>null);pendingSandboxStarts.set(a,l);try{return await c}finally{pendingSandboxStarts.get(a)===l&&pendingSandboxStarts.delete(a)}}async function startHandle(i,a){if(o.inheritance!==void 0)await open(getSandboxEnvironmentRuntime(i.environment),void 0,i.environment,a);else try{let e=await runWithSandboxConstructorRuntime({open:({environment:e,options:t,provider:n})=>open(n,t,e,a)},async()=>i.selector({session:a}));if(n===void 0||e!==n.sandbox)throw Error(`Sandbox "${i.logicalPath}" must return the sandbox it opens.`)}catch(e){let a=n?.handle;if(n=void 0,r=void 0,t=null,a!==void 0)try{await a.onSessionDelete()}catch(t){throw AggregateError([e,t],`Sandbox "${i.logicalPath}" initialization and cleanup both failed.`,{cause:e})}throw e}if(n===void 0)throw Error(`Sandbox "${i.logicalPath}" did not open a provider handle.`);return trackActiveSandboxHandle({handle:n.handle,providerName:n.providerName,sessionId:e.sessionId}),n.handle}function requireHandle(){return i===void 0&&(i=resolveHandle().catch(e=>{throw i=void 0,e})),i}let s=o.inheritance?.definition??o.definition;return{environment:s.kind===`independent`?s.environment:void 0,async captureState(){return r!==void 0&&await r,{session:t}},async delete(a){if(e.ownsSandbox===!1)throw Error(`Only the owning session can delete this sandbox.`);let o=await requireHandle(),s=n?.providerName;await o.onSessionDelete(a),s!==void 0&&untrackActiveSandboxHandle({handle:o,providerName:s,sessionId:e.sessionId}),n=void 0,r=void 0,t=null,i=void 0},async get(){return await requireHandle(),n?.sandbox??null},async stop(){await(await requireHandle()).onSessionStop(),n=void 0,r=void 0,i=void 0}}}export{ensureSandboxAccess};
@@ -1 +1 @@
1
- import{coalesceDeliveries}from"#harness/messages.js";import{activeTurnId}from"#harness/active-turn-id.js";import{mapHeldInputResponsesStep}from"#execution/proxied-deliver-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{admitSessionInboxPayload}from"#execution/session/admission.js";import{isSteeringMessage}from"#execution/session/input-queue.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";var ActiveTurn=class{admitted=new Set;routedToChildren=new Set;mappedForHeldRequest=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;identity;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;caller;compacted=!1;constructor(e,t){this.input=e,this.caller=t.caller,this.identity={callerCallId:t.caller?.callId,principal:t.principal},this.expectedTurnId=activeTurnId(e.cursor.sessionState.emissionState),this.unsubscribe=e.inbox.onInterrupt(e=>{this.cancelsThisTurn(e)&&this.abort()}),this.unsubscribeDelivery=e.inbox.onDelivery(this.signalSteering)}signalSteering=e=>{let t;try{t=decodeSessionInboxPayload(e)}catch{return}t.kind===`deliver`&&isSteeringMessage(t,this.identity)&&!this.input.cursor.sessionState.hasProxyInputRequests&&this.steeringController.abort()};get signal(){return this.controller.signal}dispose(){this.unsubscribe(),this.unsubscribeDelivery()}get steeringSignal(){return this.steeringController.signal}resetSteering(){this.steeringController.signal.aborted&&(this.unsubscribeDelivery(),this.steeringController=new AbortController,this.unsubscribeDelivery=this.input.inbox.onDelivery(this.signalSteering))}async admitBoundary(){let e=this.input.inbox.drain();for(let t of e)await this.admit(t)}async takeSteering(e){let t=[];for(;;){let n=this.input.queue.takeSteering(this.admitted,this.identity,e);if(n===void 0)break;for(let e of n.sequences)this.admitted.delete(e);let r=await routeSelectedDelivery(n,this.input.cursor);if(r.kind===`cancel-turn`){this.abort();break}r.kind===`turn`&&t.push(r.delivery)}if(this.resetSteering(),t.length===0)return;let n=t.length===1?t[0]:coalesceDeliveries(t);return n.caller!==void 0&&(this.caller=n.caller),n}takeBoundaryMessages(e){let t=[],n=[];for(let r of this.runtimeResults){let i=asBoundaryMessage(r);i===void 0||e!==void 0&&i.kind!==e?n.push(r):t.push(i)}return this.runtimeResults.splice(0,this.runtimeResults.length,...n),t}async nextRuntimeEvent(e){for(;;){let t=await this.routeAdmittedToChildren();if(this.signal.aborted)return`cancelled`;if(t)return{kind:`steering`};let n=this.runtimeResults.shift();if(n!==void 0)return n;let r=await this.waitForInboxOrTimer(e);if(r!==void 0)return{callId:r,kind:`timeout`};let i=await this.input.inbox.next();if(i===void 0)throw Error(`Session inbox closed before runtime actions completed.`);if(await this.admit(i))return{kind:`input`}}}async takeInputResponses(e){for(let t of this.admitted){let n=this.input.queue.delivery(t);if(n===void 0)continue;let r=n.payloads.flatMap(e=>e.inputResponses??[]);if(r.length!==0){if(!r.some(t=>e.has(t.requestId))){if(this.mappedForHeldRequest.has(t))continue;this.mappedForHeldRequest.add(t);let r=n,i=await this.input.cursor.advance(t=>mapHeldInputResponsesStep({delivery:r,requestIds:[...e],...t}));if(i.delivery===void 0)continue;n=i.delivery}return this.admitted.delete(t),this.input.queue.replaceDelivery(t,void 0),n}}}async waitForInboxOrTimer(e){if(e.length===0||this.input.inbox.hasPending())return;let t=this.input.inbox.whenPending().then(()=>void 0);return await Promise.race([t,...e])}cancelsThisTurn(e){return e.kind===`reset`?!0:e.kind===`cancel`?e.turnId===void 0||e.turnId===this.expectedTurnId:!1}async admit(e){let t=await admitSessionInboxPayload(e,this.input);switch(t.kind){case`delivery`:return this.admitted.add(t.admission.sequence),!0;case`runtime-action-result`:return this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results}),!1;case`workflow`:return this.runtimeResults.push({kind:`workflow`,message:t.message}),!1;case`cancel`:return this.cancelsThisTurn(e)&&this.abort(),!1;case`consumed`:return e.kind===`authorization-callback`}}async routeAdmittedToChildren(){let e=!1;for(let t of this.admitted){if(this.routedToChildren.has(t))continue;let n=this.input.queue.delivery(t);if(n===void 0){this.admitted.delete(t);continue}this.routedToChildren.add(t);let r=await this.input.cursor.advance(e=>routeDeliverToChildren({delivery:n,...e}));if(r.kind===`cancel-turn`)return this.input.queue.replaceDelivery(t,void 0),this.admitted.delete(t),this.abort(),!1;if(this.input.queue.replaceDelivery(t,r.remainder),r.remainder===void 0){this.admitted.delete(t);continue}isSteeringMessage(r.remainder,this.identity)&&(e=!0)}return e}abort(){this.controller.signal.aborted||this.controller.abort(new TurnCancelledError)}};function asBoundaryMessage(e){if(e!==`cancelled`&&e.kind===`workflow`&&(e.message.from.taskId!==void 0||e.message.kind===`agent-started`))return e.message}export{ActiveTurn};
1
+ import{coalesceDeliveries}from"#harness/messages.js";import{activeTurnId}from"#harness/active-turn-id.js";import{mapHeldInputResponsesStep}from"#execution/proxied-deliver-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{admitSessionInboxPayload}from"#execution/session/admission.js";import{isSteeringDelivery,isSteeringMessage}from"#execution/session/input-queue.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";var ActiveTurn=class{admitted=new Set;routedToChildren=new Set;mappedForHeldRequest=new Set;runtimeResults=[];controller=new AbortController;expectedTurnId;input;identity;unsubscribe;unsubscribeDelivery;steeringController=new AbortController;caller;compacted=!1;constructor(e,t){this.input=e,this.caller=t.caller,this.identity={callerCallId:t.caller?.callId,principal:t.principal},this.expectedTurnId=activeTurnId(e.cursor.sessionState.emissionState),this.unsubscribe=e.inbox.onInterrupt(e=>{this.cancelsThisTurn(e)&&this.abort()}),this.unsubscribeDelivery=e.inbox.onDelivery(this.signalSteering)}signalSteering=e=>{let t;try{t=decodeSessionInboxPayload(e)}catch{return}t.kind===`deliver`&&isSteeringMessage(t,this.identity)&&!this.input.cursor.sessionState.hasProxyInputRequests&&this.steeringController.abort()};get signal(){return this.controller.signal}dispose(){this.unsubscribe(),this.unsubscribeDelivery()}get steeringSignal(){return this.steeringController.signal}resetSteering(){this.steeringController.signal.aborted&&(this.unsubscribeDelivery(),this.steeringController=new AbortController,this.unsubscribeDelivery=this.input.inbox.onDelivery(this.signalSteering))}async admitBoundary(){let e=this.input.inbox.drain();for(let t of e)await this.admit(t)}async takeSteering(e){let t=[];for(;;){let n=this.input.queue.takeSteering(this.admitted,this.identity,e);if(n===void 0)break;for(let e of n.sequences)this.admitted.delete(e);let r=await routeSelectedDelivery(n,this.input.cursor);if(r.kind===`cancel-turn`){this.abort();break}r.kind===`turn`&&t.push(r.delivery)}if(this.resetSteering(),t.length===0)return;let n=t.length===1?t[0]:coalesceDeliveries(t);return n.caller!==void 0&&(this.caller=n.caller),n}takeBoundaryMessages(e){let t=[],n=[];for(let r of this.runtimeResults){let i=asBoundaryMessage(r);i===void 0||e!==void 0&&i.kind!==e?n.push(r):t.push(i)}return this.runtimeResults.splice(0,this.runtimeResults.length,...n),t}async nextRuntimeEvent(e){for(;;){let t=await this.routeAdmittedToChildren();if(this.signal.aborted)return`cancelled`;if(t)return{kind:`steering`};let n=this.runtimeResults.shift();if(n!==void 0)return n;let r=await this.waitForInboxOrTimer(e);if(r!==void 0)return{callId:r,kind:`timeout`};let i=await this.input.inbox.next();if(i===void 0)throw Error(`Session inbox closed before runtime actions completed.`);if(await this.admit(i))return{kind:`input`}}}async takeInputResponses(e){for(let t of this.admitted){let n=this.input.queue.delivery(t);if(n===void 0)continue;let r=n.payloads.flatMap(e=>e.inputResponses??[]);if(r.length===0)continue;if(!r.some(t=>e.has(t.requestId))){if(this.mappedForHeldRequest.has(t))continue;this.mappedForHeldRequest.add(t);let r=n,i=await this.input.cursor.advance(t=>mapHeldInputResponsesStep({delivery:r,requestIds:[...e],...t}));if(i.delivery===void 0)continue;n=i.delivery}this.admitted.delete(t);let i=isSteeringDelivery(n,this.identity,{heldOnPerson:!0})?void 0:splitAnswers(n);return this.input.queue.replaceDelivery(t,i?.rest),i?.answers??n}}async waitForInboxOrTimer(e){if(e.length===0||this.input.inbox.hasPending())return;let t=this.input.inbox.whenPending().then(()=>void 0);return await Promise.race([t,...e])}cancelsThisTurn(e){return e.kind===`reset`?!0:e.kind===`cancel`?e.turnId===void 0||e.turnId===this.expectedTurnId:!1}async admit(e){let t=await admitSessionInboxPayload(e,this.input);switch(t.kind){case`delivery`:return this.admitted.add(t.admission.sequence),!0;case`runtime-action-result`:return this.runtimeResults.push({kind:`runtime-action-result`,results:t.payload.results}),!1;case`workflow`:return this.runtimeResults.push({kind:`workflow`,message:t.message}),!1;case`cancel`:return this.cancelsThisTurn(e)&&this.abort(),!1;case`consumed`:return e.kind===`authorization-callback`}}async routeAdmittedToChildren(){let e=!1;for(let t of this.admitted){if(this.routedToChildren.has(t))continue;let n=this.input.queue.delivery(t);if(n===void 0){this.admitted.delete(t);continue}this.routedToChildren.add(t);let r=await this.input.cursor.advance(e=>routeDeliverToChildren({delivery:n,...e}));if(r.kind===`cancel-turn`)return this.input.queue.replaceDelivery(t,void 0),this.admitted.delete(t),this.abort(),!1;if(this.input.queue.replaceDelivery(t,r.remainder),r.remainder===void 0){this.admitted.delete(t);continue}isSteeringMessage(r.remainder,this.identity)&&(e=!0)}return e}abort(){this.controller.signal.aborted||this.controller.abort(new TurnCancelledError)}};function asBoundaryMessage(e){if(e!==`cancelled`&&e.kind===`workflow`&&(e.message.from.taskId!==void 0||e.message.kind===`agent-started`))return e.message}function splitAnswers(e){let t=e.payloads.flatMap(e=>e.inputResponses===void 0?[]:[{inputResponses:e.inputResponses}]),n=e.payloads.flatMap(e=>{let{inputResponses:t,...n}=e;return Object.keys(n).length===0?[]:[n]});return{answers:{...e,payloads:t},rest:n.length===0?void 0:{...e,payloads:n}}}export{ActiveTurn};
@@ -0,0 +1,15 @@
1
+ import type { SessionAuthContext } from "#channel/types.js";
2
+ import type { SessionStateMap, StepInput } from "#harness/types.js";
3
+ /**
4
+ * Answering a request does not make the responder the turn's caller. When
5
+ * `stepInput` only answers pending requests, returns it with each approval
6
+ * answer carrying its responder, so approval policies and the approved call
7
+ * see the responder while the turn keeps its caller. Returns `undefined` when
8
+ * the input carries anything else, such as a message or a stale answer; its
9
+ * sender becomes the caller.
10
+ */
11
+ export declare function attributeAnswers(input: {
12
+ readonly responder: SessionAuthContext | null;
13
+ readonly state: SessionStateMap | undefined;
14
+ readonly stepInput: StepInput | undefined;
15
+ }): StepInput | undefined;
@@ -0,0 +1 @@
1
+ import{getPendingInputBatches}from"#harness/pending-input-batches.js";function attributeAnswers(e){let{stepInput:t}=e,n=t?.inputResponses??[];if(t===void 0||t.message!==void 0||n.length===0)return;let r=new Map(getPendingInputBatches(e.state).flatMap(e=>e.requests.map(e=>[e.requestId,e.kind])));if(!n.every(e=>r.has(e.requestId)))return;let i=n.filter(e=>r.get(e.requestId)===`tool-approval`),a=n.filter(e=>r.get(e.requestId)!==`tool-approval`),{inputResponses:o,...s}=t,c={...s,attributedInputResponses:[...t.attributedInputResponses??[],...i.map(t=>({auth:e.responder,response:t}))]};return a.length===0?c:{...c,inputResponses:a}}export{attributeAnswers};
@@ -1 +1 @@
1
- import{liveTaskRuns,readTaskTable}from"#execution/tasks/table.js";import{getSessionUsage,takeSessionUsageDelta}from"#harness/turn-tag-state.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&liveTaskRuns(readTaskTable(r.snapshot?.session?.state)).length>0&&await terminateChildSessionsStep({sessionState:r});let i=r?.snapshot.session,a=i===void 0?void 0:getSessionUsage(i);e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n,usage:a}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId,usage:a});let o=settledResult(e,t);if(t.caller!==void 0){let e={output:o.output,usage:o.turnUsage};o.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:o.isError,output:o.output,usage:o.sessionUsage,usageDelta:o.turnUsage}}function settledResult(e,t){let n=t.cursor.sessionState?.snapshot.session,r=n===void 0||t.caller===void 0?{}:{sessionUsage:getSessionUsage(n),turnUsage:takeSessionUsageDelta(n).delta};switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return t.caller===void 0?{isError:!1,output:``}:{isError:!0,output:`The session ended before the delegated task completed.`,...r};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error),...r}}}export{finalizeSession};
1
+ import{liveTaskRuns,readTaskTable}from"#execution/tasks/table.js";import{getSessionUsage,takeSessionUsageDelta}from"#harness/turn-tag-state.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{lastHarnessTurn}from"#harness/emission-state.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&liveTaskRuns(readTaskTable(r.snapshot?.session?.state)).length>0&&await terminateChildSessionsStep({sessionState:r});let i=r?.snapshot.session,a=i===void 0?void 0:getSessionUsage(i);e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n,turn:lastHarnessTurn(i?.state),usage:a}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId,usage:a});let o=settledResult(e,t);if(t.caller!==void 0){let e={output:o.output,usage:o.turnUsage};o.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:o.isError,output:o.output,usage:o.sessionUsage,usageDelta:o.turnUsage}}function settledResult(e,t){let n=t.cursor.sessionState?.snapshot.session,r=n===void 0||t.caller===void 0?{}:{sessionUsage:getSessionUsage(n),turnUsage:takeSessionUsageDelta(n).delta};switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return t.caller===void 0?{isError:!1,output:``}:{isError:!0,output:`The session ended before the delegated task completed.`,...r};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error),...r}}}export{finalizeSession};
@@ -1 +1 @@
1
- import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState);for(let e of r?.delegatedUsage??[])i=countRunUsage(i,e);let a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let l=getPendingAuthorization(i.state),u;if(l&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(l,n.payloads);if(n={...n,payloads:t},e.length>0){let r=e.map(e=>e.result.attemptId),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},u=e,t.length===0&&(n=void 0)}}let d=a.get(AuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let f=n===void 0?u?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;f!==void 0&&a.set(AuthKey,f);let p={...hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),history:validateHarnessModelMessages(e.history)},m=createExecutionHistoryView(p),h=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:p.rootSessionId??p.sessionId,sessionId:p.sessionId}),g=getHarnessEmissionState(p.state);if(!g.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>h?.preparePreamble({sequence:g.sequence,sessionStarted:g.sessionStarted})),await contextStorage.run(a,()=>h?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:p.rootSessionId??p.sessionId,sequence:g.sequence,sessionId:p.sessionId,turnId:activeTurnId(g)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>h?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await h?.flush()},_=openSessionEventPublisher({ctx:a,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:v}=_.dispatcher,y=new AbortController,b=e.abortSignal===void 0?y.signal:AbortSignal.any([e.abortSignal,y.signal]);try{let i=bindDynamicConnections(a,s.resolvedAgent),l={...s.graph.root,turnAgent:c.turnAgent},f=!1,x=createTurnEventHandler({abortSignal:b,bundle:s,canCancelTurn:e.input?.control===void 0,hookCancellation:y,ctx:a,dynamicConnections:i,effectiveAgent:c,effectiveNode:l,instrumentation:h,publisher:_}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(f=!0),await x(e,t)},S=n!==void 0&&!isHarnessBetweenTurns(p)?structuredClone(v.state):void 0,C;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,v):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}C=e.length===0?void 0:e.reduce(coalesceTurnInputs)}if(n!==void 0&&C===void 0&&!isHarnessBetweenTurns(p))d===void 0?a.delete(AuthKey):a.set(AuthKey,d),v.state=S;else if(t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,g.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!g.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);if(r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),C={...C,runtimeActionResults:r.results}),t!==void 0){let e={...o,state:{...v.state}};setChannelContext(a,e)}if(n!==void 0&&C===void 0&&isHarnessBetweenTurns(p)){await contextStorage.run(a,()=>h?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await h?.flush();let t=reconcileSessionContinuationToken(a,p),n=serializeContext(a),r=t===p?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t),serializedContext:n,...r}}let w=s.subagentRegistry.dynamicResolvers??[],T=s.resolvedAgent.dynamicToolResolvers??[],E=buildRuntimeIdentity(l);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=g.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:E});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:w,event:e,messages:m.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:T,event:e,messages:m.initial.messages,runtimeRevision:t}))]),isHarnessBetweenTurns(p)||await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:g.sequence,turnId:activeTurnId(g)}),messages:m.initial.messages,resolvers:T})}}catch(e){throw await failChannelDeliveries(e),e}let D=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,O=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:b,capabilities:O,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>i.dispatch(createTurnStartedEvent(e)),historyProjector:m.projector,historyView:m.prepare(r),instrumentation:h,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:l})(r,n)},k,A;try{throwIfTurnAborted(b),A=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:C,initialSession:p,modelCallsPerStep:D,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(a,t,async t=>{a.setVirtualContext(HandleEventKey,handleEvent),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let r=e&&C?.outputSchema!==void 0?{...t,outputSchema:C.outputSchema}:t,o=getHarnessEmissionState(r.state);if(await i.rehydrate(o,E,isHarnessBetweenTurns(r)?void 0:{sequence:o.sequence,turnId:activeTurnId(o)}),e&&u){let e=getHarnessEmissionState(r.state);if(u.some(({challenge:e})=>e.candidateId===void 0)&&isHarnessBetweenTurns(r)){let t=createTurnInputMessages(consumeDeferredStepInput({session:r,input:n}).input);prepareDynamicInstructionPreamble(a,m.messages(r)),prepareMemoryPreamble(a,{history:r.history,input:t,projector:m.projector,state:r.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:h});try{e=await emitTurnPreamble(handleEvent,{},e,m.projector({messages:[...r.history,...t],state:r.state}),E,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);r={...r,history:validateHarnessModelMessages([...r.history,...e?.recalledMessages??[],...i]),state:e?.state??r.state}}r=setHarnessEmissionState(r,e)}for(let{challenge:t}of u)await handleEvent(createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}return runHarnessStep(r,n)});return r.settledTurn===void 0&&throwIfTurnAborted(b),k={result:r,serializedContext:serializeContext(a)},r}})}catch(t){if(!isTurnCancellation(t)&&!b.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:k,ctx:a,initialSession:p,stepInput:C})}let j=reconcileSessionContinuationToken(a,A.session);agentTraceState.pruneAgentTraceState(a,j.sessionId,j.state);let M=serializeContext(a);A={...A,session:j};let N=resolveSessionStepResult(A,M);return N.action===`done`&&await _.writer.close(),f?{...N,compacted:!0}:N}finally{_.writer.release()}}export{turnStep};
1
+ import{defaultDeliverResult}from"#channel/adapter.js";import{contextStorage}from"#context/container.js";import{AuthKey,CapabilitiesKey,ChannelDeliveryKey,HandleEventKey,InitiatorAuthKey,ParentSessionKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,SessionTitleKey,StaticModelReferenceKey,TurnDeliveryIdsKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,createTurnStartedEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{coalesceTurnInputs,createTurnInputMessages,validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{createDurableSessionValues,readDurableSession}from"#execution/durable-session-store.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import*as agentTraceState from"#tracing/agent-trace-context-store.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{openSessionEventPublisher}from"#execution/publish-session-events.js";import{withSessionStateDelta}from"#execution/session/state-delta.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{bindSessionInstrumentation}from"#instrumentation/runtime.js";import{deriveSessionTitle}from"#execution/eve-workflow-attributes.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{consumeDeferredStepInput}from"#harness/pending-input-batches.js";import{bindTurnCallerContext}from"#subagents/parent-notification.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{bindDynamicConnections}from"#execution/dynamic-connections.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{attributeAnswers}from"#execution/session/answer-caller.js";import{resolveSessionStepResult}from"#execution/session/turn-step-result.js";import{createTurnEventHandler}from"#execution/session/turn-event-handler.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{countRunUsage}from"#execution/agent-sessions/usage.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{runModelCallBatch}from"#execution/model-call-batching.js";import{createCancelledModelCallBatchResult}from"#execution/cancelled-model-call-batch.js";function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}async function turnStep(e){"use step";return await withSessionStateDelta(e,e=>runSessionStep({...e,serializedContext:bindTurnCallerContext(e.caller,e.serializedContext)}))}async function runSessionStep(e){let t=e.input?.delivery,n=t,r=e.input?.runtimeResults,i=readDurableSession(e.sessionState);for(let e of r?.delegatedUsage??[])i=countRunUsage(i,e);let a=await deserializeContext(e.serializedContext),o=a.require(ChannelKey),s=a.require(BundleKey),c=resolveEffectiveAgentRuntime(s,a);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&a.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let l=getPendingAuthorization(i.state),u;if(l&&n!==void 0){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(l,n.payloads);if(n={...n,payloads:t},e.length>0){let r=e.map(e=>e.result.attemptId),o=e.map(e=>e.result);a.set(PendingAuthorizationResultKey,o),i={...i,state:clearPendingAuthorization(i.state,r)},u=e,t.length===0&&(n=void 0)}}let d=a.get(AuthKey),f=a.has(InitiatorAuthKey);n?.auth!==void 0&&(a.set(AuthKey,n.auth??null),a.has(InitiatorAuthKey)||a.set(InitiatorAuthKey,n.auth??null));let p=n===void 0?u?.find(({challenge:e})=>e.candidateId===void 0)?.challenge.requester:void 0;p!==void 0&&a.set(AuthKey,p);let m={...hydrateDurableSession({compactionOverrides:{thresholdPercent:c.thresholdPercent},durable:i,turnAgent:c.turnAgent}),history:validateHarnessModelMessages(e.history)},h=createExecutionHistoryView(m),g=bindSessionInstrumentation({agentName:c.turnAgent.id,ctx:a,rootSessionId:m.rootSessionId??m.sessionId,sessionId:m.sessionId}),_=getHarnessEmissionState(m.state);if(!_.sessionStarted&&!a.has(SessionTitleKey)&&!a.has(ParentSessionKey)){let e=t?.payloads.find(e=>e.message!==void 0)?.message,n=deriveSessionTitle(t?.title??e);n!==void 0&&(a.set(SessionTitleKey,n),await setEveAttributes({"$eve.title":n}))}t!==void 0&&(await contextStorage.run(a,()=>g?.preparePreamble({sequence:_.sequence,sessionStarted:_.sessionStarted})),await contextStorage.run(a,()=>g?.instrumentChannelDelivery({agentName:s.turnAgent.id,ctx:a,delivery:t,rootSessionId:m.rootSessionId??m.sessionId,sequence:_.sequence,sessionId:m.sessionId,turnId:activeTurnId(_)})));let failChannelDeliveries=async e=>{await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,error:e,errorCode:channelDeliveryErrorCode(e),includeTurn:!1,outcome:`failed`})),await g?.flush()},v=openSessionEventPublisher({ctx:a,origin:`own`,sessionWritable:e.sessionWritable}),{adapterCtx:y}=v.dispatcher,b=new AbortController,x=e.abortSignal===void 0?b.signal:AbortSignal.any([e.abortSignal,b.signal]);try{let l=bindDynamicConnections(a,s.resolvedAgent),p={...s.graph.root,turnAgent:c.turnAgent},S=!1,C=createTurnEventHandler({abortSignal:x,bundle:s,canCancelTurn:e.input?.control===void 0,hookCancellation:b,ctx:a,dynamicConnections:l,effectiveAgent:c,effectiveNode:p,instrumentation:g,publisher:v}),handleEvent=async(e,t)=>{e.type===`compaction.completed`&&(S=!0),await C(e,t)},w=n!==void 0&&!isHarnessBetweenTurns(m)?structuredClone(y.state):void 0,T;if(n!==void 0){let e=[];try{for(let t of n.payloads){let n=o.deliver?await o.deliver(t,y):defaultDeliverResult(t);n!=null&&e.push(n)}}catch(e){throw await failChannelDeliveries(e),e}T=e.length===0?void 0:e.reduce(coalesceTurnInputs)}let E=n?.auth===void 0?void 0:attributeAnswers({responder:n.auth,state:i.state,stepInput:T});if(E!==void 0&&(T=E,d===void 0?a.delete(AuthKey):a.set(AuthKey,d),f||a.delete(InitiatorAuthKey)),n!==void 0&&T===void 0&&!isHarnessBetweenTurns(m))d===void 0?a.delete(AuthKey):a.set(AuthKey,d),y.state=w;else if(t?.payloads.some(e=>e.message!==void 0)){let e=t.deliveryMetadata?.map(e=>e.deliveryId)??[];a.set(TurnDeliveryIdsKey,_.turnId?[...new Set([...a.get(TurnDeliveryIdsKey)??[],...e])]:e)}else!_.sessionStarted&&a.get(ChannelDeliveryKey)!==void 0&&a.set(TurnDeliveryIdsKey,[a.require(ChannelDeliveryKey).deliveryId]);if(r!==void 0&&(r.acceptedAtMsByCallId!==void 0&&a.set(RuntimeActionSettlementTimesKey,r.acceptedAtMsByCallId),T={...T,runtimeActionResults:r.results}),t!==void 0){let e={...o,state:{...y.state}};setChannelContext(a,e)}if(n!==void 0&&T===void 0&&isHarnessBetweenTurns(m)){await contextStorage.run(a,()=>g?.instrumentChannelDelivery({ctx:a,includeTurn:!1,outcome:`completed`})),await g?.flush();let t=reconcileSessionContinuationToken(a,m),n=serializeContext(a),r=t===m?{history:e.history,sessionState:e.sessionState}:createDurableSessionValues(t);return{action:`park`,...derivePendingState(t),serializedContext:n,...r}}let D=s.subagentRegistry.dynamicResolvers??[],O=s.resolvedAgent.dynamicToolResolvers??[],k=buildRuntimeIdentity(p);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(s.compiledArtifactsSource),n=_.sessionStarted;if(a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null),!n)a.set(SessionDynamicSubagentRuntimeRevisionKey,t),a.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:a,resolvers:D,event:e,messages:h.initial.messages,runtimeRevision:t}),contextStorage.run(a,async()=>await refreshDynamicSessionToolsForRuntimeRevision({ctx:a,resolvers:O,event:e,messages:h.initial.messages,runtimeRevision:t}))]),isHarnessBetweenTurns(m)||await rebindMissingCompiledDynamicToolCallbacks({ctx:a,event:createTurnStartedEvent({sequence:_.sequence,turnId:activeTurnId(_)}),messages:h.initial.messages,resolvers:O})}}catch(e){throw await failChannelDeliveries(e),e}let A=s.resolvedAgent.config?.experimental?.workflow?.modelCallsPerStep??1,j=a.get(CapabilitiesKey),runHarnessStep=async(t,n)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:c.thresholdPercent},session:t,turnAgent:c.turnAgent});return createExecutionNodeStep({steeringSignal:e.steeringSignal,abortSignal:x,capabilities:j,clearOnly:e.input?.control===`clear`,compactOnly:e.input?.control===`compact`,createRuntime:createWorkflowRuntime,handleEvent,prepareApprovalTurn:e=>l.dispatch(createTurnStartedEvent(e)),historyProjector:h.projector,historyView:h.prepare(r),instrumentation:g,modelResolutionScope:{moduleMap:s.moduleMap,nodeId:s.nodeId},node:p})(r,n)},M,N;try{throwIfTurnAborted(x),N=await runModelCallBatch({steeringSignal:e.steeringSignal,initialInput:T,initialSession:m,modelCallsPerStep:A,runStep:async({firstCall:e,session:t,stepInput:n})=>{let r=await runStep(a,t,async t=>{a.setVirtualContext(HandleEventKey,handleEvent),a.setVirtualContext(StaticModelReferenceKey,c.turnAgent.model??null);let r=e&&T?.outputSchema!==void 0?{...t,outputSchema:T.outputSchema}:t,i=getHarnessEmissionState(r.state);if(await l.rehydrate(i,k,isHarnessBetweenTurns(r)?void 0:{sequence:i.sequence,turnId:activeTurnId(i)}),e&&u){let e=getHarnessEmissionState(r.state);if(u.some(({challenge:e})=>e.candidateId===void 0)&&isHarnessBetweenTurns(r)){let t=createTurnInputMessages(consumeDeferredStepInput({session:r,input:n}).input);prepareDynamicInstructionPreamble(a,h.messages(r)),prepareMemoryPreamble(a,{history:r.history,input:t,projector:h.projector,state:r.state});let i=[],o=await prepareWorkflowPreambleTrace({emissionState:e,instrumentation:g});try{e=await emitTurnPreamble(handleEvent,{},e,h.projector({messages:[...r.history,...t],state:r.state}),k,o)}finally{i=drainDynamicInstructionUserMessages(a);let e=drainMemoryCommit(a);r={...r,history:validateHarnessModelMessages([...r.history,...e?.recalledMessages??[],...i]),state:e?.state??r.state}}r=setHarnessEmissionState(r,e)}for(let{challenge:t}of u)await handleEvent(createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}return runHarnessStep(r,n)});return r.settledTurn===void 0&&throwIfTurnAborted(x),M={result:r,serializedContext:serializeContext(a)},r}})}catch(t){if(!isTurnCancellation(t)&&!x.aborted)throw await failChannelDeliveries(t),t;return createCancelledModelCallBatchResult({beforeBatchContext:e.serializedContext,checkpoint:M,ctx:a,initialSession:m,stepInput:T})}let P=reconcileSessionContinuationToken(a,N.session);agentTraceState.pruneAgentTraceState(a,P.sessionId,P.state);let F=serializeContext(a);N={...N,session:P};let I=resolveSessionStepResult(N,F);return I.action===`done`&&await v.writer.close(),S?{...I,compacted:!0}:I}finally{v.writer.release()}}export{turnStep};