eve 0.29.1 → 0.29.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 (182) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/src/channel/types.d.ts +15 -0
  3. package/dist/src/cli/commands/integration-setup.d.ts +3 -7
  4. package/dist/src/cli/commands/integration-setup.js +1 -1
  5. package/dist/src/cli/commands/registry.d.ts +1 -0
  6. package/dist/src/cli/commands/registry.js +1 -1
  7. package/dist/src/cli/commands/trace.d.ts +7 -24
  8. package/dist/src/cli/commands/trace.js +7 -5
  9. package/dist/src/cli/dev/tui/blocks.js +1 -1
  10. package/dist/src/cli/dev/tui/clipboard.d.ts +17 -0
  11. package/dist/src/cli/dev/tui/clipboard.js +1 -0
  12. package/dist/src/cli/dev/tui/command-typeahead.js +1 -1
  13. package/dist/src/cli/dev/tui/prompt-commands.d.ts +3 -0
  14. package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
  15. package/dist/src/cli/dev/tui/remote-auth.js +1 -1
  16. package/dist/src/cli/dev/tui/runner.d.ts +6 -0
  17. package/dist/src/cli/dev/tui/runner.js +1 -1
  18. package/dist/src/cli/dev/tui/stream-format.d.ts +8 -0
  19. package/dist/src/cli/dev/tui/stream-format.js +1 -1
  20. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +3 -0
  21. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  22. package/dist/src/cli/dev/tui/test/mock-terminal.js +3 -3
  23. package/dist/src/cli/dev/tui/traces/trace-content.d.ts +28 -0
  24. package/dist/src/cli/dev/tui/traces/trace-content.js +2 -0
  25. package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +58 -0
  26. package/dist/src/cli/dev/tui/traces/trace-conversation.js +2 -0
  27. package/dist/src/cli/dev/tui/traces/trace-store.d.ts +27 -0
  28. package/dist/src/cli/dev/tui/traces/trace-store.js +1 -0
  29. package/dist/src/cli/dev/tui/traces/trace-view.d.ts +48 -0
  30. package/dist/src/cli/dev/tui/traces/trace-view.js +2 -0
  31. package/dist/src/cli/dev/tui/traces/trace-viewer-session.d.ts +41 -0
  32. package/dist/src/cli/dev/tui/traces/trace-viewer-session.js +1 -0
  33. package/dist/src/cli/dev/tui/traces/trace-viewer-state.d.ts +110 -0
  34. package/dist/src/cli/dev/tui/traces/trace-viewer-state.js +1 -0
  35. package/dist/src/cli/ui/alt-screen.d.ts +42 -0
  36. package/dist/src/cli/ui/alt-screen.js +1 -0
  37. package/dist/src/cli/ui/terminal-text.d.ts +4 -0
  38. package/dist/src/cli/ui/terminal-text.js +1 -1
  39. package/dist/src/compiled/.vendor-stamp.json +2 -1
  40. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/LICENSE +21 -0
  41. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/_spectrum-core.d.ts +3 -0
  42. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/_spectrum-imessage.d.ts +2 -0
  43. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.d.ts +496 -0
  44. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +137 -0
  45. package/dist/src/compiled/@vercel/sandbox/index.js +13 -107
  46. package/dist/src/compiled/_chunks/node/auth-BS3UoyvT.js +2 -0
  47. package/dist/src/compiled/_chunks/node/compat-Dm2n85Mx.js +1 -0
  48. package/dist/src/compiled/_chunks/node/schemas-DtQwuPdM.js +65 -0
  49. package/dist/src/compiled/_chunks/node/undici-DWL_MYmT.js +95 -0
  50. package/dist/src/compiled/_chunks/node/version-Cztrk7z6.js +1 -0
  51. package/dist/src/compiled/shadcn-registry/index.js +461 -893
  52. package/dist/src/context/keys.d.ts +3 -1
  53. package/dist/src/context/keys.js +1 -1
  54. package/dist/src/evals/runner/execute-task.js +1 -1
  55. package/dist/src/evals/runner/run-evals.js +1 -1
  56. package/dist/src/execution/delegated-parent-notification.js +1 -1
  57. package/dist/src/execution/delegated-parent-result.js +1 -1
  58. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  59. package/dist/src/execution/runtime-context.js +1 -1
  60. package/dist/src/execution/sandbox/glob-tool.js +3 -3
  61. package/dist/src/execution/sandbox/grep-tool.js +1 -1
  62. package/dist/src/execution/sandbox/read-file-tool.js +3 -3
  63. package/dist/src/execution/sandbox/require-sandbox.d.ts +3 -3
  64. package/dist/src/execution/sandbox/require-sandbox.js +1 -1
  65. package/dist/src/execution/sandbox/write-file-tool.js +1 -1
  66. package/dist/src/execution/subagent-adapter-state.d.ts +39 -0
  67. package/dist/src/execution/subagent-adapter-state.js +1 -0
  68. package/dist/src/execution/subagent-adapter.d.ts +0 -34
  69. package/dist/src/execution/subagent-adapter.js +1 -1
  70. package/dist/src/execution/subagent-tool.d.ts +2 -1
  71. package/dist/src/execution/subagent-tool.js +1 -1
  72. package/dist/src/execution/workflow-steps.js +1 -1
  73. package/dist/src/harness/emission.js +1 -1
  74. package/dist/src/harness/instrumentation-lifecycle.d.ts +18 -0
  75. package/dist/src/harness/instrumentation-native-events.d.ts +3 -1
  76. package/dist/src/harness/instrumentation-native-events.js +1 -1
  77. package/dist/src/harness/parent-lineage.d.ts +11 -0
  78. package/dist/src/harness/parent-lineage.js +1 -0
  79. package/dist/src/harness/runtime-actions.js +1 -1
  80. package/dist/src/harness/tool-loop.js +2 -2
  81. package/dist/src/internal/application/package.js +1 -1
  82. package/dist/src/internal/nitro/host/local-tracing-runtime-plugin.js +1 -1
  83. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  84. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +7 -0
  85. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
  86. package/dist/src/public/channels/photon/inboundContent.d.ts +4 -0
  87. package/dist/src/public/channels/photon/inboundContent.js +1 -0
  88. package/dist/src/public/channels/photon/index.d.ts +1 -0
  89. package/dist/src/public/channels/photon/index.js +1 -0
  90. package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +54 -0
  91. package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -0
  92. package/dist/src/runtime/channels/registry.js +1 -1
  93. package/dist/src/runtime/framework-tools/glob.js +1 -1
  94. package/dist/src/runtime/framework-tools/grep.js +1 -1
  95. package/dist/src/runtime/framework-tools/read-file.js +1 -1
  96. package/dist/src/runtime/framework-tools/write-file.js +1 -1
  97. package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
  98. package/dist/src/setup/connect-provisioning.d.ts +32 -0
  99. package/dist/src/setup/connect-provisioning.js +1 -0
  100. package/dist/src/setup/flows/login.js +1 -1
  101. package/dist/src/setup/flows/registry.js +1 -1
  102. package/dist/src/setup/integrations/photon/connect.d.ts +40 -0
  103. package/dist/src/setup/integrations/photon/connect.js +1 -0
  104. package/dist/src/setup/integrations/photon/management.d.ts +34 -0
  105. package/dist/src/setup/integrations/photon/management.js +1 -0
  106. package/dist/src/setup/integrations/photon/setup-flow.d.ts +39 -0
  107. package/dist/src/setup/integrations/photon/setup-flow.js +20 -0
  108. package/dist/src/setup/integrations/photon/setup.d.ts +3 -0
  109. package/dist/src/setup/integrations/photon/setup.js +1 -0
  110. package/dist/src/setup/integrations/registry.d.ts +6 -0
  111. package/dist/src/setup/integrations/registry.js +1 -0
  112. package/dist/src/setup/integrations/runner.d.ts +25 -0
  113. package/dist/src/setup/integrations/runner.js +1 -0
  114. package/dist/src/setup/integrations/{channels → shared}/environment.d.ts +3 -3
  115. package/dist/src/setup/integrations/shared/environment.js +1 -0
  116. package/dist/src/setup/integrations/shared/scaffold.d.ts +19 -0
  117. package/dist/src/setup/integrations/shared/scaffold.js +1 -0
  118. package/dist/src/setup/integrations/{channels → shared}/ui.d.ts +3 -3
  119. package/dist/src/setup/integrations/shared/ui.js +2 -0
  120. package/dist/src/setup/integrations/slack/setup.d.ts +16 -0
  121. package/dist/src/setup/integrations/slack/setup.js +1 -0
  122. package/dist/src/setup/integrations/types.d.ts +26 -0
  123. package/dist/src/setup/integrations/web/setup.d.ts +3 -0
  124. package/dist/src/setup/integrations/web/setup.js +1 -0
  125. package/dist/src/setup/primitives/run-vercel.d.ts +2 -7
  126. package/dist/src/setup/primitives/run-vercel.js +1 -1
  127. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  128. package/dist/src/setup/scaffold/create/project.js +2 -2
  129. package/dist/src/setup/scaffold/update/channels.js +1 -1
  130. package/dist/src/setup/scaffold/update/connections.js +1 -1
  131. package/dist/src/setup/slack-connect-lifecycle.d.ts +2 -8
  132. package/dist/src/setup/slack-connect-lifecycle.js +1 -1
  133. package/dist/src/setup/state.d.ts +0 -12
  134. package/dist/src/setup/state.js +1 -1
  135. package/dist/src/shared/skill-paths.d.ts +10 -0
  136. package/dist/src/shared/skill-paths.js +2 -2
  137. package/dist/src/tracing/agent-otel-content.d.ts +32 -0
  138. package/dist/src/tracing/agent-otel-content.js +4 -0
  139. package/dist/src/{harness → tracing}/agent-otel-provider.d.ts +10 -1
  140. package/dist/src/tracing/agent-otel-provider.js +2 -0
  141. package/dist/src/{harness → tracing}/agent-trace-context-store.d.ts +8 -1
  142. package/dist/src/tracing/agent-trace-context-store.js +1 -0
  143. package/dist/src/{harness → tracing}/agent-trace-span-processor.d.ts +5 -1
  144. package/dist/src/tracing/agent-trace-span-processor.js +1 -0
  145. package/dist/src/tracing/local-instrumentation-runtime.js +1 -0
  146. package/dist/src/tracing/local-trace-reader.d.ts +57 -0
  147. package/dist/src/tracing/local-trace-reader.js +1 -0
  148. package/dist/src/{harness → tracing}/local-trace-retention.js +1 -1
  149. package/dist/src/{harness → tracing}/local-trace-span-processor.js +1 -1
  150. package/docs/channels/chat-sdk.mdx +18 -1
  151. package/docs/channels/meta.json +1 -0
  152. package/docs/channels/overview.mdx +1 -1
  153. package/docs/channels/photon.mdx +78 -0
  154. package/docs/concepts/default-harness.md +2 -0
  155. package/docs/guides/dev-tui.md +20 -1
  156. package/docs/guides/instrumentation.md +8 -7
  157. package/docs/reference/cli.md +9 -1
  158. package/docs/sandbox.mdx +1 -1
  159. package/package.json +7 -1
  160. package/dist/src/compiled/_chunks/node/auth-DMsLOrh7.js +0 -2
  161. package/dist/src/compiled/_chunks/node/version-BQBAL95V.js +0 -64
  162. package/dist/src/harness/agent-otel-provider.js +0 -1
  163. package/dist/src/harness/agent-trace-context-store.js +0 -1
  164. package/dist/src/harness/agent-trace-span-processor.js +0 -1
  165. package/dist/src/harness/local-instrumentation-runtime.js +0 -1
  166. package/dist/src/setup/integrations/channels/environment.js +0 -1
  167. package/dist/src/setup/integrations/channels/index.d.ts +0 -7
  168. package/dist/src/setup/integrations/channels/index.js +0 -1
  169. package/dist/src/setup/integrations/channels/runner.d.ts +0 -7
  170. package/dist/src/setup/integrations/channels/runner.js +0 -1
  171. package/dist/src/setup/integrations/channels/setup.d.ts +0 -130
  172. package/dist/src/setup/integrations/channels/setup.js +0 -2
  173. package/dist/src/setup/integrations/channels/slack.d.ts +0 -3
  174. package/dist/src/setup/integrations/channels/slack.js +0 -1
  175. package/dist/src/setup/integrations/channels/types.d.ts +0 -49
  176. package/dist/src/setup/integrations/channels/ui.js +0 -2
  177. package/dist/src/setup/integrations/channels/web.d.ts +0 -3
  178. package/dist/src/setup/integrations/channels/web.js +0 -1
  179. /package/dist/src/setup/integrations/{channels/types.js → types.js} +0 -0
  180. /package/dist/src/{harness → tracing}/local-instrumentation-runtime.d.ts +0 -0
  181. /package/dist/src/{harness → tracing}/local-trace-retention.d.ts +0 -0
  182. /package/dist/src/{harness → tracing}/local-trace-span-processor.d.ts +0 -0
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import type { LanguageModel, SystemModelMessage } from "ai";
7
7
  import type { JsonObject } from "#shared/json.js";
8
- import type { ChannelInstrumentationProjection, SessionAuthContext, SessionCallback, SessionCapabilities, SessionParent, SessionTurn } from "#channel/types.js";
8
+ import type { ChannelInstrumentationProjection, SessionAuthContext, SessionCallback, SessionCapabilities, SessionParent, SessionTraceContext, SessionTurn } from "#channel/types.js";
9
9
  import { ContextKey } from "#context/key.js";
10
10
  import type { SandboxAccess } from "#sandbox/state.js";
11
11
  import type { RunMode } from "#shared/run-mode.js";
@@ -43,6 +43,8 @@ export declare const ChannelRequestIdKey: ContextKey<string>;
43
43
  export declare const ChannelInstrumentationKey: ContextKey<ChannelInstrumentationProjection>;
44
44
  export declare const ModeKey: ContextKey<RunMode>;
45
45
  export declare const ParentSessionKey: ContextKey<SessionParent>;
46
+ /** Separate from {@link ParentSessionKey} so it stays out of what extensions read. */
47
+ export declare const ParentTraceContextKey: ContextKey<SessionTraceContext>;
46
48
  export declare const SubagentDepthKey: ContextKey<number>;
47
49
  /**
48
50
  * Session-level capability flags (see {@link SessionCapabilities}). Set
@@ -1 +1 @@
1
- import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`eve.auth`),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ModeKey=new ContextKey(`eve.mode`),ParentSessionKey=new ContextKey(`eve.parentSession`),SubagentDepthKey=new ContextKey(`eve.subagentDepth`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(`eve.sessionCallback`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),LiveStepToolsKey=new ContextKey(`eve.liveStepTools`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`);export{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,DynamicSkillManifestKey,InitiatorAuthKey,LiveStepDynamicModelSelectionKey,LiveStepToolsKey,ModeKey,ParentSessionKey,SandboxKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionKey,SubagentDepthKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicToolMetadataKey};
1
+ import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`eve.auth`),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ModeKey=new ContextKey(`eve.mode`),ParentSessionKey=new ContextKey(`eve.parentSession`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SubagentDepthKey=new ContextKey(`eve.subagentDepth`),CapabilitiesKey=new ContextKey(`eve.capabilities`),SessionCallbackKey=new ContextKey(`eve.sessionCallback`),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),LiveStepToolsKey=new ContextKey(`eve.liveStepTools`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`);export{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,DynamicSkillManifestKey,InitiatorAuthKey,LiveStepDynamicModelSelectionKey,LiveStepToolsKey,ModeKey,ParentSessionKey,ParentTraceContextKey,SandboxKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionKey,SubagentDepthKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicToolMetadataKey};
@@ -1 +1 @@
1
- import{toErrorMessage}from"#shared/errors.js";import{AssertionCollector}from"#evals/assertions/collector.js";import{scopeEvalTargetHandle}from"#evals/target.js";import{EvalSessionManager}from"#evals/session.js";import{EvalRequirementFailed,EvalSkipped}from"#evals/control-flow.js";import{createEmptyDerivedFacts}from"#evals/runner/derive-run-facts.js";import{createEvalContext}from"#evals/context.js";async function executeTask(a){let{client:o,evaluation:s,target:c,timeoutMs:l}=a,u=l===void 0?neverAbortSignal():AbortSignal.timeout(l),d=new AssertionCollector,f=new EvalSessionManager({client:o,collector:d,signal:u}),p=scopeEvalTargetHandle(c,{sessions:f}),m=[],{context:h}=createEvalContext({collector:d,manager:f,target:p,signal:u,judge:s.judge,log:e=>{m.push(e),a.onLog?.(e)}}),g,_;try{await s.test(h)}catch(t){t instanceof EvalSkipped?_=t.reason:t instanceof EvalRequirementFailed||(g=toErrorMessage(t))}let v=buildTaskResult({logs:m,sessions:f.snapshots(),turn:f.lastTurnSession()?.lastTurn});return{result:v,assertions:await d.finalize(v),error:g,skipReason:_}}function buildTaskResult(e){let t=e.sessions.flatMap(e=>e.events),n=e.turn?.message??null;return{output:e.turn?.data===void 0?n:e.turn.data,finalMessage:n,sessionId:selectPrimarySessionId(e.sessions),status:e.turn?.status??`completed`,events:t,logs:e.logs,derived:combineDerivedFacts(e.sessions),sessions:e.sessions,runtimeIdentity:extractRuntimeIdentity(t)}}function combineDerivedFacts(e){if(e.length===0)return createEmptyDerivedFacts();let t=e.flatMap(e=>e.derived.toolCalls),n=e.flatMap(e=>e.derived.subagentCalls),r=e.flatMap(e=>e.derived.inputRequests),i=e.find(e=>e.derived.failureCode!==void 0)?.derived.failureCode;return{toolCalls:t,toolCallCount:t.length,subagentCalls:n,subagentCallCount:n.length,inputRequests:r,parked:e.some(e=>e.derived.parked),messageCount:sum(e,e=>e.derived.messageCount),reasoningBlockCount:sum(e,e=>e.derived.reasoningBlockCount),failureCode:i}}function selectPrimarySessionId(e){return e.find(e=>e.primary)?.sessionId??e[0]?.sessionId}function extractRuntimeIdentity(e){for(let t of e)if(t.type===`session.started`&&t.data.runtime!==void 0)return t.data.runtime}function sum(e,t){return e.reduce((e,n)=>e+t(n),0)}function neverAbortSignal(){return new AbortController().signal}export{executeTask};
1
+ import{toErrorMessage}from"#shared/errors.js";import{AssertionCollector}from"#evals/assertions/collector.js";import{scopeEvalTargetHandle}from"#evals/target.js";import{EvalSessionManager}from"#evals/session.js";import{EvalRequirementFailed,EvalSkipped}from"#evals/control-flow.js";import{createEmptyDerivedFacts}from"#evals/runner/derive-run-facts.js";import{createEvalContext}from"#evals/context.js";async function executeTask(a){let{client:o,evaluation:s,target:c,timeoutMs:l}=a,u=l===void 0?neverAbortSignal():AbortSignal.timeout(l),d=new AssertionCollector,f=new EvalSessionManager({client:o,collector:d,signal:u}),p=scopeEvalTargetHandle(c,{sessions:f}),m=[],{context:h}=createEvalContext({collector:d,manager:f,target:p,signal:u,judge:s.judge,log:e=>{m.push(e),a.onLog?.(e)}}),g,_;try{await runUntilAborted(s.test(h),u)}catch(t){t instanceof EvalSkipped?_=t.reason:t instanceof EvalRequirementFailed||(g=toErrorMessage(t))}let v=buildTaskResult({logs:m,sessions:f.snapshots(),turn:f.lastTurnSession()?.lastTurn});return{result:v,assertions:await d.finalize(v),error:g,skipReason:_}}function buildTaskResult(e){let t=e.sessions.flatMap(e=>e.events),n=e.turn?.message??null;return{output:e.turn?.data===void 0?n:e.turn.data,finalMessage:n,sessionId:selectPrimarySessionId(e.sessions),status:e.turn?.status??`completed`,events:t,logs:e.logs,derived:combineDerivedFacts(e.sessions),sessions:e.sessions,runtimeIdentity:extractRuntimeIdentity(t)}}function combineDerivedFacts(e){if(e.length===0)return createEmptyDerivedFacts();let t=e.flatMap(e=>e.derived.toolCalls),n=e.flatMap(e=>e.derived.subagentCalls),r=e.flatMap(e=>e.derived.inputRequests),i=e.find(e=>e.derived.failureCode!==void 0)?.derived.failureCode;return{toolCalls:t,toolCallCount:t.length,subagentCalls:n,subagentCallCount:n.length,inputRequests:r,parked:e.some(e=>e.derived.parked),messageCount:sum(e,e=>e.derived.messageCount),reasoningBlockCount:sum(e,e=>e.derived.reasoningBlockCount),failureCode:i}}function selectPrimarySessionId(e){return e.find(e=>e.primary)?.sessionId??e[0]?.sessionId}function extractRuntimeIdentity(e){for(let t of e)if(t.type===`session.started`&&t.data.runtime!==void 0)return t.data.runtime}function sum(e,t){return e.reduce((e,n)=>e+t(n),0)}function neverAbortSignal(){return new AbortController().signal}async function runUntilAborted(e,t){t.throwIfAborted();let onAbort,n=new Promise((e,n)=>{onAbort=()=>n(t.reason),t.addEventListener(`abort`,onAbort,{once:!0})});try{await Promise.race([e,n])}finally{onAbort!==void 0&&t.removeEventListener(`abort`,onAbort)}}export{executeTask};
@@ -1 +1 @@
1
- import{resolveArtifactDirectory,writeArtifacts}from"#evals/runner/artifacts.js";import{executeEval}from"#evals/runner/execute-eval.js";async function runEvals(r){let{config:i,target:a,client:o,appRoot:s}=r,c=r.maxConcurrency??i.maxConcurrency??8;if(!Number.isInteger(c)||c<1)throw Error(`Eval maxConcurrency must be a positive integer; got ${String(r.maxConcurrency??i.maxConcurrency)}.`);let l=r.evaluations.map(e=>applyConfigDefaults(e,i)),u=new Date().toISOString(),d=buildReporterBindings({...r,evaluations:l});for(let e of d)await e.reporter.onRunStart(l.filter(t=>e.evalIds.has(t.id)),a);let f=[],p=[...l],m=new Set,h=Promise.resolve();for(;p.length>0||m.size>0;){for(;p.length>0&&m.size<c;){let e=p.shift();if(e===void 0)break;let t=(async()=>{let t=await executeEval({client:o,evaluation:e,onLog:r.onEvalLog===void 0?void 0:t=>r.onEvalLog?.(e.id,t),target:a,timeoutMs:r.timeoutMs});f.push(t),h=h.then(async()=>{for(let e of d)e.evalIds.has(t.id)&&await e.reporter.onEvalComplete(t)})})().finally(()=>{m.delete(t)});m.add(t)}m.size>0&&await Promise.race(m)}await h;let g=new Map(l.map((e,t)=>[e.id,t]));f.sort((e,t)=>(g.get(e.id)??0)-(g.get(t.id)??0));let _=buildSummary(a,f,u);await writeArtifacts(resolveArtifactDirectory(s),_);for(let e of d)await e.reporter.onRunComplete(scopeSummary(_,e.evalIds));return _}function buildReporterBindings(e){let t=new Set(e.evaluations.map(e=>e.id)),n=new Set(e.reporters);if(e.includeEvalReporters!==!1)for(let t of e.config.reporters??[])n.add(t);let r=[...n].map(e=>({reporter:e,evalIds:t}));if(e.includeEvalReporters===!1)return r;let i=new Map;for(let t of e.evaluations)for(let e of t.reporters??[]){if(n.has(e))continue;let r=i.get(e)??new Set;r.add(t.id),i.set(e,r)}for(let[e,t]of i)r.push({reporter:e,evalIds:t});return r}function applyConfigDefaults(e,t){return e.judge!==void 0||t.judge===void 0?e:{...e,judge:t.judge}}function buildSummary(e,t,n){return{target:e,results:t,startedAt:n,completedAt:new Date().toISOString(),passed:countVerdicts(t,`passed`),failed:countVerdicts(t,`failed`),scored:countVerdicts(t,`scored`),skipped:countVerdicts(t,`skipped`),errored:t.filter(e=>e.error!==void 0).length}}function scopeSummary(e,t){if(e.results.every(e=>t.has(e.id)))return e;let n=e.results.filter(e=>t.has(e.id));return{...e,results:n,passed:countVerdicts(n,`passed`),failed:countVerdicts(n,`failed`),scored:countVerdicts(n,`scored`),skipped:countVerdicts(n,`skipped`),errored:n.filter(e=>e.error!==void 0).length}}function countVerdicts(e,t){return e.filter(e=>e.verdict===t).length}export{runEvals};
1
+ import{resolveArtifactDirectory,writeArtifacts}from"#evals/runner/artifacts.js";import{executeEval}from"#evals/runner/execute-eval.js";async function runEvals(r){let{config:i,target:a,client:o,appRoot:s}=r,c=r.maxConcurrency??i.maxConcurrency??8;if(!Number.isInteger(c)||c<1)throw Error(`Eval maxConcurrency must be a positive integer; got ${String(r.maxConcurrency??i.maxConcurrency)}.`);let l=r.evaluations.map(e=>applyConfigDefaults(e,i)),u=new Date().toISOString(),d=buildReporterBindings({...r,evaluations:l});for(let e of d)await e.reporter.onRunStart(l.filter(t=>e.evalIds.has(t.id)),a);let f=[],p=[...l],m=new Set,h=Promise.resolve();for(;p.length>0||m.size>0;){for(;p.length>0&&m.size<c;){let e=p.shift();if(e===void 0)break;let t=(async()=>{let t=await executeEval({client:o,evaluation:e,onLog:r.onEvalLog===void 0?void 0:t=>r.onEvalLog?.(e.id,t),target:a,timeoutMs:r.timeoutMs});f.push(t),h=h.then(async()=>{for(let e of d)e.evalIds.has(t.id)&&await e.reporter.onEvalComplete(t)})})().finally(()=>{m.delete(t)});m.add(t)}m.size>0&&await Promise.race(m)}await h;let g=new Map(l.map((e,t)=>[e.id,t]));f.sort((e,t)=>(g.get(e.id)??0)-(g.get(t.id)??0));let _=buildSummary(a,f,u);await writeArtifacts(resolveArtifactDirectory(s),_);for(let e of d)await e.reporter.onRunComplete(scopeSummary(_,e.evalIds));return _}function buildReporterBindings(e){let t=new Set(e.evaluations.map(e=>e.id)),n=new Set(e.reporters);if(e.includeEvalReporters!==!1)for(let t of e.config.reporters??[])n.add(t);let r=[...n].map(e=>({reporter:e,evalIds:t}));if(e.includeEvalReporters===!1)return r;let i=new Map;for(let t of e.evaluations)for(let e of t.reporters??[]){if(n.has(e))continue;let r=i.get(e)??new Set;r.add(t.id),i.set(e,r)}for(let[e,t]of i)r.push({reporter:e,evalIds:t});return r}function applyConfigDefaults(e,t){let n=e.judge??t.judge,r=e.timeoutMs??t.timeoutMs;return n===e.judge&&r===e.timeoutMs?e:{...e,judge:n,timeoutMs:r}}function buildSummary(e,t,n){return{target:e,results:t,startedAt:n,completedAt:new Date().toISOString(),passed:countVerdicts(t,`passed`),failed:countVerdicts(t,`failed`),scored:countVerdicts(t,`scored`),skipped:countVerdicts(t,`skipped`),errored:t.filter(e=>e.error!==void 0).length}}function scopeSummary(e,t){if(e.results.every(e=>t.has(e.id)))return e;let n=e.results.filter(e=>t.has(e.id));return{...e,results:n,passed:countVerdicts(n,`passed`),failed:countVerdicts(n,`failed`),scored:countVerdicts(n,`scored`),skipped:countVerdicts(n,`skipped`),errored:n.filter(e=>e.error!==void 0).length}}function countVerdicts(e,t){return e.filter(e=>e.verdict===t).length}export{runEvals};
@@ -1 +1 @@
1
- import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{resumeHook}from"#internal/workflow/runtime.js";async function notifyDelegatedParentStep(e){"use step";if(e.result===void 0)return;let t=(await deserializeContext(e.serializedContext)).get(ChannelKey);if(t?.kind!==SUBAGENT_ADAPTER_KIND)return;let n=String(t.state?.parentContinuationToken??``);n!==``&&await resumeHook(n,{kind:`runtime-action-result`,results:[e.usage===void 0||e.result.isError===!0?e.result:{...e.result,usage:e.usage}]})}export{notifyDelegatedParentStep};
1
+ import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";import{resumeHook}from"#internal/workflow/runtime.js";async function notifyDelegatedParentStep(e){"use step";if(e.result===void 0)return;let t=(await deserializeContext(e.serializedContext)).get(ChannelKey);if(t?.kind!==SUBAGENT_ADAPTER_KIND)return;let n=String(t.state?.parentContinuationToken??``);n!==``&&await resumeHook(n,{kind:`runtime-action-result`,results:[e.usage===void 0||e.result.isError===!0?e.result:{...e.result,usage:e.usage}]})}export{notifyDelegatedParentStep};
@@ -1 +1 @@
1
- import{toErrorMessage}from"#shared/errors.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";function createDelegatedSubagentSuccessResult(e,n){let r=e[`eve.channel`];if(r?.kind===SUBAGENT_ADAPTER_KIND)return{callId:String(r.state?.callId??``),kind:`subagent-result`,output:n,subagentName:String(r.state?.subagentName??``)}}function createDelegatedSubagentErrorResult(t,n){let r=createDelegatedSubagentSuccessResult(t,``);if(r!==void 0)return{...r,isError:!0,output:{code:`SUBAGENT_EXECUTION_FAILED`,message:toErrorMessage(n)}}}export{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult};
1
+ import{toErrorMessage}from"#shared/errors.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";function createDelegatedSubagentSuccessResult(e,n){let r=e[`eve.channel`];if(r?.kind===SUBAGENT_ADAPTER_KIND)return{callId:String(r.state?.callId??``),kind:`subagent-result`,output:n,subagentName:String(r.state?.subagentName??``)}}function createDelegatedSubagentErrorResult(t,n){let r=createDelegatedSubagentSuccessResult(t,``);if(r!==void 0)return{...r,isError:!0,output:{code:`SUBAGENT_EXECUTION_FAILED`,message:toErrorMessage(n)}}}export{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChild}from"#harness/runtime-actions.js";import{hydrateDurableSession}from"#execution/session.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let f=await readDurableSession(e.sessionState),p=getPendingRuntimeActionBatch(f.state);if(p===void 0||p.actions.length===0)return{results:[],sessionState:e.sessionState};let m=await deserializeContext(e.serializedContext),h=m.require(BundleKey),g=hydrateDurableSession({compactionOverrides:{thresholdPercent:h.resolvedAgent.config.compaction?.thresholdPercent},durable:f,turnAgent:h.turnAgent}),_=m.require(ChannelKey),v=m.get(AuthKey)??null,y=m.get(CapabilitiesKey),b=m.get(ChannelInstrumentationKey),x=m.get(InitiatorAuthKey)??null,S=e.parentWritable.getWriter(),C=buildAdapterContext(_,m),w=resolveSubagentDepth(g),T=p.actions.filter(e=>e.kind===`subagent-call`).length,E=g,D=[];try{for(let r of p.actions){if(isRecursiveAgentAction(r,h.subagentRegistry.subagentsByNodeId)&&(g.rootSessionId!==void 0||w.currentDepth>0)){log.warn(`recursive agent call blocked outside the root session`,{callId:r.callId,currentDepth:w.currentDepth,nodeId:r.nodeId,subagentName:r.subagentName}),D.push(createRecursiveAgentRootOnlyResult(r));continue}let i,a,o,u;switch(r.kind){case`subagent-call`:{let n=h.subagentRegistry.subagentsByNodeId.get(r.nodeId),o=n?.definition.kind===`subagent`?{description:n.definition.description,type:`local`}:{type:`runtime`},s=createWorkflowRuntime({compiledArtifactsSource:h.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:c,runInput:l}=buildSubagentRunInput({action:r,auth:v,batchEvent:p.event,capabilities:y,channelMetadata:b,fanoutSize:T,initiatorAuth:x,parentContinuationToken:e.parentContinuationToken,session:g,source:o});try{i=(await s.run(l)).sessionId}catch(e){logError(log,`local subagent start failed`,e,{callId:r.callId,nodeId:r.nodeId,subagentName:r.subagentName}),D.push({callId:r.callId,isError:!0,kind:`subagent-result`,output:{code:`SUBAGENT_START_FAILED`,message:toErrorMessage(e)},subagentName:r.subagentName});continue}E=recordPendingSubagentChild({callId:r.callId,child:{continuationToken:c,kind:`local`,sessionId:i},session:E}),a=r.name,u=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:h.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,auth:v,callbackBaseUrl:e.callbackBaseUrl,callbackToken:e.parentContinuationToken,initiatorAuth:x,remote:n,session:g})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),D.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},u=r.remoteAgentName,E=recordPendingSubagentChild({callId:r.callId,child:{kind:`remote`,sessionId:i},session:E});break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let d=await callAdapterEventHandler(_,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:p.event.sequence,sessionId:g.sessionId,toolName:u,turnId:p.event.turnId,workflowId:workflowEntryReference.workflowId}),C);await S.write(encodeMessageStreamEvent(stampMessageStreamEvent(d)))}}finally{S.releaseLock()}return{results:D,sessionState:E===g?e.sessionState:createDurableSessionState({session:E})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}function createRecursiveAgentRootOnlyResult(e){return{callId:e.callId,isError:!0,kind:`subagent-result`,output:{code:`RECURSIVE_AGENT_ROOT_ONLY`,message:`The built-in "agent" tool is only available to the root session.`},subagentName:e.subagentName}}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}export{dispatchRuntimeActionsStep};
1
+ import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChild}from"#harness/runtime-actions.js";import{hydrateDurableSession}from"#execution/session.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{readSessionTraceContext}from"#tracing/agent-trace-context-store.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let f=await readDurableSession(e.sessionState),p=getPendingRuntimeActionBatch(f.state);if(p===void 0||p.actions.length===0)return{results:[],sessionState:e.sessionState};let m=await deserializeContext(e.serializedContext),h=m.require(BundleKey),g=hydrateDurableSession({compactionOverrides:{thresholdPercent:h.resolvedAgent.config.compaction?.thresholdPercent},durable:f,turnAgent:h.turnAgent}),_=m.require(ChannelKey),v=m.get(AuthKey)??null,y=m.get(CapabilitiesKey),b=m.get(ChannelInstrumentationKey),x=m.get(InitiatorAuthKey)??null,S=e.parentWritable.getWriter(),C=buildAdapterContext(_,m),w=resolveSubagentDepth(g),T=readSessionTraceContext(e.serializedContext,g.sessionId),E=p.actions.filter(e=>e.kind===`subagent-call`).length,D=g,O=[];try{for(let r of p.actions){if(isRecursiveAgentAction(r,h.subagentRegistry.subagentsByNodeId)&&(g.rootSessionId!==void 0||w.currentDepth>0)){log.warn(`recursive agent call blocked outside the root session`,{callId:r.callId,currentDepth:w.currentDepth,nodeId:r.nodeId,subagentName:r.subagentName}),O.push(createRecursiveAgentRootOnlyResult(r));continue}let i,a,o,u;switch(r.kind){case`subagent-call`:{let n=h.subagentRegistry.subagentsByNodeId.get(r.nodeId),o=n?.definition.kind===`subagent`?{description:n.definition.description,type:`local`}:{type:`runtime`},s=createWorkflowRuntime({compiledArtifactsSource:h.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:c,runInput:l}=buildSubagentRunInput({action:r,auth:v,batchEvent:p.event,capabilities:y,channelMetadata:b,fanoutSize:E,initiatorAuth:x,parentContinuationToken:e.parentContinuationToken,parentTraceContext:T,session:g,source:o});try{i=(await s.run(l)).sessionId}catch(e){logError(log,`local subagent start failed`,e,{callId:r.callId,nodeId:r.nodeId,subagentName:r.subagentName}),O.push({callId:r.callId,isError:!0,kind:`subagent-result`,output:{code:`SUBAGENT_START_FAILED`,message:toErrorMessage(e)},subagentName:r.subagentName});continue}D=recordPendingSubagentChild({callId:r.callId,child:{continuationToken:c,kind:`local`,sessionId:i},session:D}),a=r.name,u=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:h.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,auth:v,callbackBaseUrl:e.callbackBaseUrl,callbackToken:e.parentContinuationToken,initiatorAuth:x,remote:n,session:g})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),O.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},u=r.remoteAgentName,D=recordPendingSubagentChild({callId:r.callId,child:{kind:`remote`,sessionId:i},session:D});break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let d=await callAdapterEventHandler(_,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:p.event.sequence,sessionId:g.sessionId,toolName:u,turnId:p.event.turnId,workflowId:workflowEntryReference.workflowId}),C);await S.write(encodeMessageStreamEvent(stampMessageStreamEvent(d)))}}finally{S.releaseLock()}return{results:O,sessionState:D===g?e.sessionState:createDurableSessionState({session:D})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}function createRecursiveAgentRootOnlyResult(e){return{callId:e.callId,isError:!0,kind:`subagent-result`,output:{code:`RECURSIVE_AGENT_ROOT_ONLY`,message:`The built-in "agent" tool is only available to the root session.`},subagentName:e.subagentName}}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}export{dispatchRuntimeActionsStep};
@@ -1 +1 @@
1
- import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SessionCallbackKey,SubagentDepthKey}from"#context/keys.js";import{ContextContainer}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{setChannelContext}from"#execution/channel-context.js";function buildRunContext(t){let{bundle:n,run:r}=t,i=new ContextContainer,a=r.auth;if(i.set(BundleKey,n),setChannelContext(i,r.adapter,{channelName:r.channelName}),r.channelMetadata!==void 0){let e=i.get(ChannelInstrumentationKey);i.set(ChannelInstrumentationKey,{kind:e?.kind??r.channelMetadata.kind,metadata:r.channelMetadata.metadata})}return i.set(ContinuationTokenKey,r.continuationToken??``),i.set(ModeKey,r.mode),i.set(AuthKey,a),i.set(InitiatorAuthKey,r.initiatorAuth??a),r.capabilities!==void 0&&i.set(CapabilitiesKey,r.capabilities),r.requestId!==void 0&&i.set(ChannelRequestIdKey,r.requestId),r.callback!==void 0&&i.set(SessionCallbackKey,r.callback),r.parent!==void 0&&i.set(ParentSessionKey,r.parent),r.subagentDepth!==void 0&&i.set(SubagentDepthKey,r.subagentDepth),i}export{buildRunContext};
1
+ import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,InitiatorAuthKey,ModeKey,ParentSessionKey,ParentTraceContextKey,SessionCallbackKey,SubagentDepthKey}from"#context/keys.js";import{ContextContainer}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{setChannelContext}from"#execution/channel-context.js";function buildRunContext(t){let{bundle:n,run:r}=t,i=new ContextContainer,a=r.auth;if(i.set(BundleKey,n),setChannelContext(i,r.adapter,{channelName:r.channelName}),r.channelMetadata!==void 0){let e=i.get(ChannelInstrumentationKey);i.set(ChannelInstrumentationKey,{kind:e?.kind??r.channelMetadata.kind,metadata:r.channelMetadata.metadata})}return i.set(ContinuationTokenKey,r.continuationToken??``),i.set(ModeKey,r.mode),i.set(AuthKey,a),i.set(InitiatorAuthKey,r.initiatorAuth??a),r.capabilities!==void 0&&i.set(CapabilitiesKey,r.capabilities),r.requestId!==void 0&&i.set(ChannelRequestIdKey,r.requestId),r.callback!==void 0&&i.set(SessionCallbackKey,r.callback),r.parent!==void 0&&i.set(ParentSessionKey,r.parent),r.parentTraceContext!==void 0&&i.set(ParentTraceContextKey,r.parentTraceContext),r.subagentDepth!==void 0&&i.set(SubagentDepthKey,r.subagentDepth),i}export{buildRunContext};
@@ -1,3 +1,3 @@
1
- import{normalizeModelPath}from"#runtime/framework-tools/file-state.js";import{MAX_OUTPUT_BYTES}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{validateAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGlobOnSandbox(n,a){let o=a.path??`/workspace`;validateAbsoluteFilePath(o);let s=normalizeModelPath(o),c=Math.min(Math.max(1,a.limit??100),1e3),l=await ripgrepIsAvailable(n)?buildRipgrepCommand({normalizedPath:s,pattern:a.pattern}):buildPosixFindCommand({normalizedPath:s,pattern:a.pattern}),u=await n.run({command:l});if(u.exitCode!==0&&u.exitCode!==1)throw buildGlobExecutionError(l,u.exitCode,u.stderr);let d=u.stdout.split(`
2
- `).filter(e=>e.length>0),f=d.length>c,p=f?d.slice(0,c):d,m=[],h=0,g=!1;for(let n of p){let r=normalizeModelPath(n),i=Buffer.byteLength(r,`utf8`)+1;if(h+i>MAX_OUTPUT_BYTES&&m.length>0){g=!0;break}m.push(r),h+=i}if(m.length===0)return{content:`No files found`,count:0,path:s,truncated:!1};let _=f||g,v=[...m];return _&&(v.push(``),v.push(`(Results truncated: showing first ${m.length} results out of more. Use a more specific path or pattern to narrow results.)`)),{content:v.join(`
3
- `),count:m.length,path:s,truncated:_}}function buildRipgrepCommand(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${shellQuote(e.pattern)}`,`-- ${shellQuote(e.normalizedPath)}`].join(` `)}function buildPosixFindCommand(e){let t=translateGlobToFindPattern(e.pattern),r=t.includes(`/`)?`-path ${shellQuote(`*/${t}`)}`:`-name ${shellQuote(t)}`;return[`find ${shellQuote(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,r].join(` `)}function translateGlobToFindPattern(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function buildGlobExecutionError(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`glob failed (exit ${t}): ${i}\nCommand: ${e}`)}export{executeGlobOnSandbox};
1
+ import{normalizeModelPath}from"#runtime/framework-tools/file-state.js";import{MAX_OUTPUT_BYTES}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGlobOnSandbox(n,a){let o=normalizeModelPath(await resolveAbsoluteFilePath(n,a.path??`/workspace`)),s=Math.min(Math.max(1,a.limit??100),1e3),c=await ripgrepIsAvailable(n)?buildRipgrepCommand({normalizedPath:o,pattern:a.pattern}):buildPosixFindCommand({normalizedPath:o,pattern:a.pattern}),l=await n.run({command:c});if(l.exitCode!==0&&l.exitCode!==1)throw buildGlobExecutionError(c,l.exitCode,l.stderr);let u=l.stdout.split(`
2
+ `).filter(e=>e.length>0),d=u.length>s,f=d?u.slice(0,s):u,p=[],m=0,h=!1;for(let n of f){let r=normalizeModelPath(n),i=Buffer.byteLength(r,`utf8`)+1;if(m+i>MAX_OUTPUT_BYTES&&p.length>0){h=!0;break}p.push(r),m+=i}if(p.length===0)return{content:`No files found`,count:0,path:o,truncated:!1};let g=d||h,_=[...p];return g&&(_.push(``),_.push(`(Results truncated: showing first ${p.length} results out of more. Use a more specific path or pattern to narrow results.)`)),{content:_.join(`
3
+ `),count:p.length,path:o,truncated:g}}function buildRipgrepCommand(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${shellQuote(e.pattern)}`,`-- ${shellQuote(e.normalizedPath)}`].join(` `)}function buildPosixFindCommand(e){let t=translateGlobToFindPattern(e.pattern),r=t.includes(`/`)?`-path ${shellQuote(`*/${t}`)}`:`-name ${shellQuote(t)}`;return[`find ${shellQuote(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,r].join(` `)}function translateGlobToFindPattern(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function buildGlobExecutionError(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`glob failed (exit ${t}): ${i}\nCommand: ${e}`)}export{executeGlobOnSandbox};
@@ -1,3 +1,3 @@
1
- import{normalizeModelPath}from"#runtime/framework-tools/file-state.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{validateAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGrepOnSandbox(t,n){let r=n.path??`/workspace`;validateAbsoluteFilePath(r);let o=normalizeModelPath(r),s=Math.min(Math.max(1,n.limit??100),1e3),c=n.context!==void 0&&n.context>0?n.context:0,l=await ripgrepIsAvailable(t)?buildRipgrepCommand({contextLines:c,effectiveLimit:s,glob:n.glob,ignoreCase:n.ignoreCase??!1,literal:n.literal??!1,normalizedPath:o,pattern:n.pattern}):buildPosixGrepCommand({contextLines:c,effectiveLimit:s,glob:n.glob,ignoreCase:n.ignoreCase??!1,literal:n.literal??!1,normalizedPath:o,pattern:n.pattern}),u=await t.run({command:l});if(u.exitCode!==0&&u.exitCode!==1)throw buildGrepExecutionError(l,u.exitCode,u.stderr);let d=u.stdout;return d.trim().length===0?{content:`No matches found`,matchCount:0,path:o,truncated:!1}:processOutput({effectiveLimit:s,normalizedPath:o,stdout:d})}function buildRipgrepCommand(e){let t=[`rg`,`--line-number`,`--color=never`,`--hidden`,`--glob '!.git/*'`];return e.ignoreCase&&t.push(`--ignore-case`),e.literal&&t.push(`--fixed-strings`),e.glob!==void 0&&t.push(`--glob ${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(shellQuote(e.pattern)),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function buildPosixGrepCommand(e){let t=[`grep`,`-r`,`-n`,`--color=never`,`--exclude-dir=.git`];return e.ignoreCase&&t.push(`-i`),e.literal?t.push(`-F`):t.push(`-E`),e.glob!==void 0&&t.push(`--include=${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`--`),t.push(shellQuote(e.pattern)),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function processOutput(e){let r=e.stdout.split(`
1
+ import{normalizeModelPath}from"#runtime/framework-tools/file-state.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGrepOnSandbox(t,n){let r=normalizeModelPath(await resolveAbsoluteFilePath(t,n.path??`/workspace`)),o=Math.min(Math.max(1,n.limit??100),1e3),s=n.context!==void 0&&n.context>0?n.context:0,c=await ripgrepIsAvailable(t)?buildRipgrepCommand({contextLines:s,effectiveLimit:o,glob:n.glob,ignoreCase:n.ignoreCase??!1,literal:n.literal??!1,normalizedPath:r,pattern:n.pattern}):buildPosixGrepCommand({contextLines:s,effectiveLimit:o,glob:n.glob,ignoreCase:n.ignoreCase??!1,literal:n.literal??!1,normalizedPath:r,pattern:n.pattern}),l=await t.run({command:c});if(l.exitCode!==0&&l.exitCode!==1)throw buildGrepExecutionError(c,l.exitCode,l.stderr);let u=l.stdout;return u.trim().length===0?{content:`No matches found`,matchCount:0,path:r,truncated:!1}:processOutput({effectiveLimit:o,normalizedPath:r,stdout:u})}function buildRipgrepCommand(e){let t=[`rg`,`--line-number`,`--color=never`,`--hidden`,`--glob '!.git/*'`];return e.ignoreCase&&t.push(`--ignore-case`),e.literal&&t.push(`--fixed-strings`),e.glob!==void 0&&t.push(`--glob ${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(shellQuote(e.pattern)),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function buildPosixGrepCommand(e){let t=[`grep`,`-r`,`-n`,`--color=never`,`--exclude-dir=.git`];return e.ignoreCase&&t.push(`-i`),e.literal?t.push(`-F`):t.push(`-E`),e.glob!==void 0&&t.push(`--include=${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`--`),t.push(shellQuote(e.pattern)),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function processOutput(e){let r=e.stdout.split(`
2
2
  `),i=[],a=0,o=0,s=!1;for(let e=0;e<r.length;e+=1){let c=r[e]??``;if(c.length===0&&e===r.length-1)continue;c!==`--`&&c.length>0&&/^.+:\d+:/.test(c)&&o++;let l=capLineLength(c),u=Buffer.byteLength(l,`utf8`)+1;if(a+u>MAX_OUTPUT_BYTES&&i.length>0){s=!0;break}i.push(l),a+=u}let c=s||o>=e.effectiveLimit,l=i.join(`
3
3
  `);if(c){let t=[];o>=e.effectiveLimit&&t.push(`Match limit reached (${e.effectiveLimit}). Use a larger limit or more specific pattern.`),s&&t.push(`Output truncated due to size. Use a more specific path or pattern.`),l+=`\n\n[${t.join(` `)}]`}return{content:l,matchCount:o,path:e.normalizedPath,truncated:c}}function buildGrepExecutionError(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`grep failed (exit ${t}): ${i}\nCommand: ${e}`)}export{executeGrepOnSandbox};
@@ -1,3 +1,3 @@
1
- import{loadContext}from"#context/container.js";import{buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp}from"#runtime/framework-tools/file-state.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{validateAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";async function executeReadFileOnSandbox(r,i){let{filePath:a,offset:o,limit:s}=i;validateAbsoluteFilePath(a);let c=normalizeModelPath(a),l=o??1,u=s??2e3;if(l<1)throw Error(`offset must be >= 1. Received: ${l}.`);let d=await r.readTextFile({path:a});if(d===null)throw Error(`File not found: ${a}. Verify the path exists and is accessible in the sandbox.`);if(d.includes(`\0`))throw Error(`File "${a}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let f=d.split(`
2
- `),p=f.length>0&&f[f.length-1]===``?f.length-1:f.length;if(p===0){if(l>1)throw Error(`offset ${l} is past the end of the file (0 lines). Use the default offset to read an empty file.`)}else if(l>p)throw Error(`offset ${l} is past the end of the file (${p} lines).`);let m=createReadFileStamp({content:d,filePath:c}),h=buildReadFileTargetKey(c);if(setReadFileStamp(loadContext(),h,m),p===0)return{content:``,path:c,totalLines:0,truncated:!1};let g=l-1,_=Math.min(g+u,p),v=f.slice(g,_),y=[],b=0,x=!1;for(let e=0;e<v.length;e++){let t=`${l+e}: ${capLineLength(v[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(b+n>MAX_OUTPUT_BYTES&&y.length>0){x=!0;break}y.push(t),b+=n}let S=y.join(`
3
- `),C=l+y.length-1;return C<p||x?{content:S,nextOffset:C+1,path:c,totalLines:p,truncated:!0}:{content:S,path:c,totalLines:p,truncated:!1}}export{executeReadFileOnSandbox};
1
+ import{loadContext}from"#context/container.js";import{buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp}from"#runtime/framework-tools/file-state.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";async function executeReadFileOnSandbox(r,i){let{filePath:a,offset:o,limit:s}=i,c=await resolveAbsoluteFilePath(r,a),l=normalizeModelPath(c),u=o??1,d=s??2e3;if(u<1)throw Error(`offset must be >= 1. Received: ${u}.`);let f=await r.readTextFile({path:c});if(f===null)throw Error(`File not found: ${a}. Verify the path exists and is accessible in the sandbox.`);if(f.includes(`\0`))throw Error(`File "${a}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let p=f.split(`
2
+ `),m=p.length>0&&p[p.length-1]===``?p.length-1:p.length;if(m===0){if(u>1)throw Error(`offset ${u} is past the end of the file (0 lines). Use the default offset to read an empty file.`)}else if(u>m)throw Error(`offset ${u} is past the end of the file (${m} lines).`);let h=createReadFileStamp({content:f,filePath:l}),g=buildReadFileTargetKey(l);if(setReadFileStamp(loadContext(),g,h),m===0)return{content:``,path:l,totalLines:0,truncated:!1};let _=u-1,v=Math.min(_+d,m),y=p.slice(_,v),b=[],x=0,S=!1;for(let e=0;e<y.length;e++){let t=`${u+e}: ${capLineLength(y[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(x+n>MAX_OUTPUT_BYTES&&b.length>0){S=!0;break}b.push(t),x+=n}let C=b.join(`
3
+ `),w=u+b.length-1;return w<m||S?{content:C,nextOffset:w+1,path:l,totalLines:m,truncated:!0}:{content:C,path:l,totalLines:m,truncated:!1}}export{executeReadFileOnSandbox};
@@ -11,7 +11,7 @@ import type { SandboxSession } from "#public/definitions/sandbox.js";
11
11
  */
12
12
  export declare function requireSandboxSession(abortSignal?: AbortSignal): Promise<SandboxSession>;
13
13
  /**
14
- * Validates that a model-supplied file path is absolute. Throws a
15
- * descriptive error when the path does not start with `/`.
14
+ * Resolves a model-supplied `$HOME` prefix and validates that the resulting
15
+ * sandbox file path is absolute.
16
16
  */
17
- export declare function validateAbsoluteFilePath(filePath: string): void;
17
+ export declare function resolveAbsoluteFilePath(sandbox: SandboxSession, filePath: string): Promise<string>;
@@ -1 +1 @@
1
- import{SandboxKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{bindSandboxAbortSignal}from"#execution/sandbox/abort-bound-session.js";async function requireSandboxSession(t){let n=loadContext().get(SandboxKey);if(n===void 0)throw Error(`This tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let r=await n.get();if(r===null)throw Error(`The sandbox is not available in the current runtime context.`);return t===void 0?r:bindSandboxAbortSignal(r,t)}function validateAbsoluteFilePath(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}export{requireSandboxSession,validateAbsoluteFilePath};
1
+ import{SandboxKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{bindSandboxAbortSignal}from"#execution/sandbox/abort-bound-session.js";import{resolveSandboxModelPath}from"#shared/skill-paths.js";async function requireSandboxSession(r){let i=loadContext().get(SandboxKey);if(i===void 0)throw Error(`This tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let a=await i.get();if(a===null)throw Error(`The sandbox is not available in the current runtime context.`);return r===void 0?a:bindSandboxAbortSignal(a,r)}async function resolveAbsoluteFilePath(e,t){let n=await resolveSandboxModelPath({path:t,sandbox:e});if(!n.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${t}". Use an absolute path such as /workspace/foo.ts or a path beginning with \$HOME/.`);return n}export{requireSandboxSession,resolveAbsoluteFilePath};
@@ -1 +1 @@
1
- import{loadContext}from"#context/container.js";import{ReadFileStateKey,buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp}from"#runtime/framework-tools/file-state.js";import{validateAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";async function executeWriteFileOnSandbox(e,t){let{filePath:n,content:r}=t;validateAbsoluteFilePath(n);let i=loadContext(),a=normalizeModelPath(n),o=buildReadFileTargetKey(a),s=await e.readTextFile({path:n});if(s===null)return await e.writeTextFile({content:r,path:n}),setReadFileStamp(i,o,createReadFileStamp({content:r,filePath:a})),{existed:!1,path:a};let c=i.ensure(ReadFileStateKey,()=>({byTarget:{}})).byTarget[o];if(c===void 0)throw Error(`You must read file ${n} before overwriting it. Use the read_file tool first.`);let l=createReadFileStamp({content:s,filePath:a});if(l.contentHash!==c.contentHash||l.byteLength!==c.byteLength)throw Error(`File ${n} has been modified since it was last read. Please read the file again before modifying it.`);return await e.writeTextFile({content:r,path:n}),setReadFileStamp(i,o,createReadFileStamp({content:r,filePath:a})),{existed:!0,path:a}}export{executeWriteFileOnSandbox};
1
+ import{loadContext}from"#context/container.js";import{ReadFileStateKey,buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp}from"#runtime/framework-tools/file-state.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";async function executeWriteFileOnSandbox(e,t){let{filePath:n,content:r}=t,i=await resolveAbsoluteFilePath(e,n),a=loadContext(),o=normalizeModelPath(i),s=buildReadFileTargetKey(o),c=await e.readTextFile({path:i});if(c===null)return await e.writeTextFile({content:r,path:i}),setReadFileStamp(a,s,createReadFileStamp({content:r,filePath:o})),{existed:!1,path:o};let l=a.ensure(ReadFileStateKey,()=>({byTarget:{}})).byTarget[s];if(l===void 0)throw Error(`You must read file ${n} before overwriting it. Use the read_file tool first.`);let u=createReadFileStamp({content:c,filePath:o});if(u.contentHash!==l.contentHash||u.byteLength!==l.byteLength)throw Error(`File ${n} has been modified since it was last read. Please read the file again before modifying it.`);return await e.writeTextFile({content:r,path:i}),setReadFileStamp(a,s,createReadFileStamp({content:r,filePath:o})),{existed:!0,path:o}}export{executeWriteFileOnSandbox};
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Durable state for the subagent adapter, split from the adapter itself so
3
+ * harness code can identify a delegated child run without reaching the
4
+ * adapter's workflow-coupled behavior (`runtime-boundary.test.ts`).
5
+ */
6
+ /**
7
+ * Durable adapter kind used for delegated subagent child runs.
8
+ *
9
+ * Framework-owned — authored channel code never constructs a subagent
10
+ * adapter directly. Emitted by `buildSubagentRunInput`
11
+ * (`execution/subagent-tool.ts`) when a parent dispatches a child
12
+ * subagent.
13
+ */
14
+ export declare const SUBAGENT_ADAPTER_KIND = "subagent";
15
+ /**
16
+ * Durable state carried on a subagent adapter instance.
17
+ *
18
+ * Populated by `buildSubagentRunInput` at dispatch time so the child
19
+ * run retains the parent lineage metadata required to resume its parent
20
+ * when the child finishes and to forward HITL requests up the chain.
21
+ *
22
+ * The parent's turn identifier is not duplicated here — it lives on
23
+ * `RunInput.parent.turn.id` which is the single source of truth for the
24
+ * child's parent-turn lineage.
25
+ */
26
+ export interface SubagentAdapterState extends Record<string, unknown> {
27
+ readonly callId: string;
28
+ readonly parentContinuationToken: string;
29
+ readonly parentSessionId: string;
30
+ readonly subagentName: string;
31
+ }
32
+ /**
33
+ * Narrow runtime guard for {@link SubagentAdapterState}.
34
+ *
35
+ * Framework adapters live through a JSON round-trip at every workflow
36
+ * step boundary, so consumers that want to treat the adapter state as
37
+ * a structured record must validate the shape explicitly.
38
+ */
39
+ export declare function isSubagentAdapterState(value: unknown): value is SubagentAdapterState;
@@ -0,0 +1 @@
1
+ const SUBAGENT_ADAPTER_KIND=`subagent`;function isSubagentAdapterState(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.callId==`string`&&t.callId.length>0&&typeof t.parentContinuationToken==`string`&&t.parentContinuationToken.length>0&&typeof t.parentSessionId==`string`&&typeof t.subagentName==`string`&&t.subagentName.length>0}export{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState};
@@ -1,38 +1,4 @@
1
1
  import type { ChannelAdapter } from "#channel/adapter.js";
2
- /**
3
- * Durable adapter kind used for delegated subagent child runs.
4
- *
5
- * Framework-owned — authored channel code never constructs a subagent
6
- * adapter directly. Emitted by `buildSubagentRunInput`
7
- * (`execution/subagent-tool.ts`) when a parent dispatches a child
8
- * subagent.
9
- */
10
- export declare const SUBAGENT_ADAPTER_KIND = "subagent";
11
- /**
12
- * Durable state carried on a subagent adapter instance.
13
- *
14
- * Populated by `buildSubagentRunInput` at dispatch time so the child
15
- * run retains the parent lineage metadata required to resume its parent
16
- * when the child finishes and to forward HITL requests up the chain.
17
- *
18
- * The parent's turn identifier is not duplicated here — it lives on
19
- * `RunInput.parent.turn.id` which is the single source of truth for the
20
- * child's parent-turn lineage.
21
- */
22
- export interface SubagentAdapterState extends Record<string, unknown> {
23
- readonly callId: string;
24
- readonly parentContinuationToken: string;
25
- readonly parentSessionId: string;
26
- readonly subagentName: string;
27
- }
28
- /**
29
- * Narrow runtime guard for {@link SubagentAdapterState}.
30
- *
31
- * Framework adapters live through a JSON round-trip at every workflow
32
- * step boundary, so consumers that want to treat the adapter state as
33
- * a structured record must validate the shape explicitly.
34
- */
35
- export declare function isSubagentAdapterState(value: unknown): value is SubagentAdapterState;
36
2
  /**
37
3
  * Framework adapter that bridges a child subagent session to its
38
4
  * parent.
@@ -1 +1 @@
1
- import{createErrorId,createLogger}from"#internal/logging.js";import{ContinuationTokenKey,SessionIdKey}from"#context/keys.js";import{resumeHook}from"#internal/workflow/runtime.js";const log=createLogger(`execution.subagent-adapter`),SUBAGENT_ADAPTER_KIND=`subagent`;function isSubagentAdapterState(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.callId==`string`&&t.callId.length>0&&typeof t.parentContinuationToken==`string`&&t.parentContinuationToken.length>0&&typeof t.parentSessionId==`string`&&typeof t.subagentName==`string`&&t.subagentName.length>0}const SUBAGENT_ADAPTER={kind:SUBAGENT_ADAPTER_KIND,async"authorization.required"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.required`},t)},async"authorization.completed"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.completed`},t)},async"input.requested"(e,t){let i=t.state;isSubagentAdapterState(i)&&await forwardSubagentInputRequestStep({hookPayload:{callId:i.callId,childContinuationToken:t.ctx.require(ContinuationTokenKey),childSessionId:t.ctx.require(SessionIdKey),event:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},kind:`subagent-input-request`,subagentName:i.subagentName},parentContinuationToken:i.parentContinuationToken})}};async function forwardSubagentAuthorizationEvent(e,t){let n=t.state;isSubagentAdapterState(n)&&await forwardSubagentAuthorizationEventStep({hookPayload:{callId:n.callId,childSessionId:t.ctx.require(SessionIdKey),event:e,kind:`subagent-authorization-event`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}async function forwardSubagentAuthorizationEventStep(t){"use step";try{await resumeHook(t.parentContinuationToken,t.hookPayload)}catch(n){let r=createErrorId();throw log.warn(`failed to forward subagent authorization event to parent`,{callId:t.hookPayload.callId,childSessionId:t.hookPayload.childSessionId,errorId:r,eventType:t.hookPayload.event.type,parentContinuationToken:t.parentContinuationToken,subagentName:t.hookPayload.subagentName,error:n}),n}}async function forwardSubagentInputRequestStep(t){"use step";try{await resumeHook(t.parentContinuationToken,t.hookPayload)}catch(n){let r=createErrorId();throw log.warn(`failed to forward proxied HITL batch to parent`,{callId:t.hookPayload.callId,childContinuationToken:t.hookPayload.childContinuationToken,childSessionId:t.hookPayload.childSessionId,errorId:r,parentContinuationToken:t.parentContinuationToken,subagentName:t.hookPayload.subagentName,error:n}),n}}export{SUBAGENT_ADAPTER,SUBAGENT_ADAPTER_KIND,isSubagentAdapterState};
1
+ import{createErrorId,createLogger}from"#internal/logging.js";import{ContinuationTokenKey,SessionIdKey}from"#context/keys.js";import{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState}from"#execution/subagent-adapter-state.js";import{resumeHook}from"#internal/workflow/runtime.js";const log=createLogger(`execution.subagent-adapter`),SUBAGENT_ADAPTER={kind:SUBAGENT_ADAPTER_KIND,async"authorization.required"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.required`},t)},async"authorization.completed"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.completed`},t)},async"input.requested"(e,t){let i=t.state;isSubagentAdapterState(i)&&await forwardSubagentInputRequestStep({hookPayload:{callId:i.callId,childContinuationToken:t.ctx.require(ContinuationTokenKey),childSessionId:t.ctx.require(SessionIdKey),event:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},kind:`subagent-input-request`,subagentName:i.subagentName},parentContinuationToken:i.parentContinuationToken})}};async function forwardSubagentAuthorizationEvent(e,t){let n=t.state;isSubagentAdapterState(n)&&await forwardSubagentAuthorizationEventStep({hookPayload:{callId:n.callId,childSessionId:t.ctx.require(SessionIdKey),event:e,kind:`subagent-authorization-event`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}async function forwardSubagentAuthorizationEventStep(t){"use step";try{await resumeHook(t.parentContinuationToken,t.hookPayload)}catch(n){let r=createErrorId();throw log.warn(`failed to forward subagent authorization event to parent`,{callId:t.hookPayload.callId,childSessionId:t.hookPayload.childSessionId,errorId:r,eventType:t.hookPayload.event.type,parentContinuationToken:t.parentContinuationToken,subagentName:t.hookPayload.subagentName,error:n}),n}}async function forwardSubagentInputRequestStep(t){"use step";try{await resumeHook(t.parentContinuationToken,t.hookPayload)}catch(n){let r=createErrorId();throw log.warn(`failed to forward proxied HITL batch to parent`,{callId:t.hookPayload.callId,childContinuationToken:t.hookPayload.childContinuationToken,childSessionId:t.hookPayload.childSessionId,errorId:r,parentContinuationToken:t.parentContinuationToken,subagentName:t.hookPayload.subagentName,error:n}),n}}export{SUBAGENT_ADAPTER};
@@ -1,4 +1,4 @@
1
- import type { ChannelInstrumentationProjection, RunInput, SessionAuthContext, SessionCapabilities } from "#channel/types.js";
1
+ import type { ChannelInstrumentationProjection, RunInput, SessionAuthContext, SessionCapabilities, SessionTraceContext } from "#channel/types.js";
2
2
  import type { HarnessSession } from "#harness/types.js";
3
3
  import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";
4
4
  /**
@@ -49,6 +49,7 @@ export declare function buildSubagentRunInput(input: {
49
49
  readonly initiatorAuth: SessionAuthContext | null;
50
50
  /** Hook token owned by the workflow currently waiting for this child. */
51
51
  readonly parentContinuationToken?: string;
52
+ readonly parentTraceContext?: SessionTraceContext;
52
53
  readonly session: HarnessSession;
53
54
  readonly source: SubagentInputSource;
54
55
  }): SubagentRunInputBuild;
@@ -1 +1 @@
1
- import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{resolveRemainingSessionTokenLimits}from"#harness/subagent-token-budget.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l,source:u}=n,d=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),f=l.rootSessionId??l.sessionId,p=resolveSubagentDepth(l),m=resolveRemainingSessionTokenLimits(l,n.fanoutSize),h=normalizeRequestedOutputSchema(r.input.outputSchema);return{childContinuationToken:d,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:d,initiatorAuth:c,input:{message:formatSubagentCallInputMessage({action:r,source:u}),outputSchema:h},limits:m,mode:`task`,parent:{callId:r.callId,rootSessionId:f,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}},subagentDepth:p.nextChildDepth}}}function formatSubagentCallInputMessage(e){let{message:t}=e.action.input;switch(e.source.type){case`local`:return formatSubagentInput({description:e.source.description,message:t,name:e.action.subagentName,type:`local`}).message;case`runtime`:return formatSubagentInput({message:t,name:e.action.subagentName,type:`runtime`}).message;default:return e.source}}export{buildSubagentRunInput};
1
+ import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{resolveRemainingSessionTokenLimits}from"#harness/subagent-token-budget.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l,source:u}=n,d=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),f=l.rootSessionId??l.sessionId,p=resolveSubagentDepth(l),m=resolveRemainingSessionTokenLimits(l,n.fanoutSize),h=normalizeRequestedOutputSchema(r.input.outputSchema);return{childContinuationToken:d,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:d,initiatorAuth:c,input:{message:formatSubagentCallInputMessage({action:r,source:u}),outputSchema:h},limits:m,mode:`task`,parent:{callId:r.callId,rootSessionId:f,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}},parentTraceContext:n.parentTraceContext,subagentDepth:p.nextChildDepth}}}function formatSubagentCallInputMessage(e){let{message:t}=e.action.input;switch(e.source.type){case`local`:return formatSubagentInput({description:e.source.description,message:t,name:e.action.subagentName,type:`local`}).message;case`runtime`:return formatSubagentInput({message:t,name:e.action.subagentName,type:`runtime`}).message;default:return e.source}}export{buildSubagentRunInput};
@@ -1 +1 @@
1
- import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{preserveSerializedAgentTraceState}from"#harness/agent-trace-context-store.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let d=getPendingAuthorization(s.state),f;if(d&&o.input?.kind===`deliver`){let e=[],t=[],n=[];for(let r of o.input.payloads){let i=r.authorizationCallback;if(i){let n=d.challenges.find(e=>e.name===i.connectionName);n&&(e.push({name:n.name,resume:n.resume,callback:i.callback,hookUrl:n.hookUrl}),t.push({name:n.name,authorization:n.challenge}))}else n.push(r)}e.length>0&&(c.set(PendingAuthorizationResultKey,e),s={...s,state:clearPendingAuthorization(s.state,e.map(e=>e.name))},f=t,o=n.length>0?{...o,input:{...o.input,payloads:n}}:{...o,input:void 0})}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let p=hydrateDurableSession({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:u.turnAgent}),m=buildAdapterContext(l,c),h;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,m):defaultDeliverResult(n);r!=null&&e.push(r)}h=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),h={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...m.state}}),o.input?.kind===`deliver`&&h===void 0){let e=reconcileSessionContinuationToken(c,p),t=serializeContext(c),n=e===p?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let g=u.hookRegistry,_=u.resolvedAgent.dynamicInstructionsResolvers??[],v=u.resolvedAgent.dynamicSkillResolvers??[],y=u.resolvedAgent.dynamicToolResolvers??[],b=buildRuntimeIdentity(u.graph.root),x=process.env.VERCEL_DEPLOYMENT_ID?.trim(),S=x?`deployment:${x}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);getHarnessEmissionState(p.state).sessionStarted?await refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:y,event:createSessionStartedEvent({runtime:b}),messages:p.history,runtimeRevision:S}):c.set(SessionDynamicToolRuntimeRevisionKey,S);let C=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,m);setChannelContext(c,{...l,state:{...m.state}});let r=stampMessageStreamEvent(n);return await C.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:g,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:u.turnAgent.dynamicModel,event:n,fallback:u.turnAgent.model,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicToolEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:v,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:_,event:n,messages:t??[]})},w=c.require(ModeKey),T;try{throwIfTurnAborted(o.abortSignal),T=await runStep(c,p,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:u.turnAgent.outputSchema,input:h,mode:w,session:e});if(f){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of f)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:u.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:u.graph.root,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,h)})}catch(e){if(!isTurnCancellation(e))throw e;return C.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let E=reconcileSessionContinuationToken(c,T.session),D=serializeContext(c);T={...T,session:E};let O=createDurableSessionState({session:T.session}),k=readTurnSleepDurationMs(c),A=k===void 0?{}:{sleepDurationMs:k};if(T.next!==null&&typeof T.next==`object`&&`done`in T.next){await C.close();let e=getTurnUsageState(T.session.state)?.session;return{action:`done`,output:T.next.output,isError:T.next.isError,...A,serializedContext:D,sessionState:O,usage:e===void 0?void 0:toUsage(e)}}if(T.next===null){C.releaseLock();let e=getPendingWorkflowInterrupt(T.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...A,serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),...A,serializedContext:D,sessionState:O}}return C.releaseLock(),{action:`continue`,...A,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return n.parentAction??{kind:`continue`,remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
1
+ import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let d=getPendingAuthorization(s.state),f;if(d&&o.input?.kind===`deliver`){let e=[],t=[],n=[];for(let r of o.input.payloads){let i=r.authorizationCallback;if(i){let n=d.challenges.find(e=>e.name===i.connectionName);n&&(e.push({name:n.name,resume:n.resume,callback:i.callback,hookUrl:n.hookUrl}),t.push({name:n.name,authorization:n.challenge}))}else n.push(r)}e.length>0&&(c.set(PendingAuthorizationResultKey,e),s={...s,state:clearPendingAuthorization(s.state,e.map(e=>e.name))},f=t,o=n.length>0?{...o,input:{...o.input,payloads:n}}:{...o,input:void 0})}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let p=hydrateDurableSession({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:u.turnAgent}),m=buildAdapterContext(l,c),h;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,m):defaultDeliverResult(n);r!=null&&e.push(r)}h=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),h={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...m.state}}),o.input?.kind===`deliver`&&h===void 0){let e=reconcileSessionContinuationToken(c,p),t=serializeContext(c),n=e===p?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let g=u.hookRegistry,_=u.resolvedAgent.dynamicInstructionsResolvers??[],v=u.resolvedAgent.dynamicSkillResolvers??[],y=u.resolvedAgent.dynamicToolResolvers??[],b=buildRuntimeIdentity(u.graph.root),x=process.env.VERCEL_DEPLOYMENT_ID?.trim(),S=x?`deployment:${x}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);getHarnessEmissionState(p.state).sessionStarted?await refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:y,event:createSessionStartedEvent({runtime:b}),messages:p.history,runtimeRevision:S}):c.set(SessionDynamicToolRuntimeRevisionKey,S);let C=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,m);setChannelContext(c,{...l,state:{...m.state}});let r=stampMessageStreamEvent(n);return await C.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:g,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:u.turnAgent.dynamicModel,event:n,fallback:u.turnAgent.model,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicToolEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:v,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:_,event:n,messages:t??[]})},w=c.require(ModeKey),T;try{throwIfTurnAborted(o.abortSignal),T=await runStep(c,p,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:u.turnAgent.outputSchema,input:h,mode:w,session:e});if(f){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of f)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:u.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:u.graph.root,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,h)})}catch(e){if(!isTurnCancellation(e))throw e;return C.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let E=reconcileSessionContinuationToken(c,T.session),D=serializeContext(c);T={...T,session:E};let O=createDurableSessionState({session:T.session}),k=readTurnSleepDurationMs(c),A=k===void 0?{}:{sleepDurationMs:k};if(T.next!==null&&typeof T.next==`object`&&`done`in T.next){await C.close();let e=getTurnUsageState(T.session.state)?.session;return{action:`done`,output:T.next.output,isError:T.next.isError,...A,serializedContext:D,sessionState:O,usage:e===void 0?void 0:toUsage(e)}}if(T.next===null){C.releaseLock();let e=getPendingWorkflowInterrupt(T.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...A,serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),...A,serializedContext:D,sessionState:O}}return C.releaseLock(),{action:`continue`,...A,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return n.parentAction??{kind:`continue`,remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
@@ -1 +1 @@
1
- import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let a=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:a})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:a})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:a}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent(n.continuationToken)),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n,r){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent(r)):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(i,o,s,c,l){let u=``,d=``,f=`stop`,p,m=new Set,h=new Set,g=new Set,_=new Set,v=new Set,y=new Set,b=[],x=[],flushCurrentMessage=async()=>{d.length!==0&&(await i(createMessageCompletedEvent({finishReason:`tool-calls`,message:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d=``)},emitActionRequest=async e=>{h.has(e.callId)||(d.trim().length>0&&await flushCurrentMessage(),h.add(e.callId),await i(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{if(_.has(e.toolCallId)||(_.add(e.toolCallId),h.has(e.toolCallId)))return;h.add(e.toolCallId),d.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e);if(t.toolError!==void 0){y.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),v.add(e.toolCallId);return}c.observe(t.request)},emitActionResult=async t=>{g.has(t.callId)||(g.add(t.callId),await i(createActionResultEvent({result:t,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(isInvalidToolCall(e)){y.add(e.toolCallId);return}if(!(l===void 0||l.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:l.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});y.add(e.toolCallId),d.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),v.add(e.toolCallId),x.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let e of s)if(p===void 0)switch(e.type){case`reasoning-delta`:await c.flush(),u+=e.text,await i(createReasoningAppendedEvent({reasoningDelta:e.text,reasoningSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await c.flush(),u.trim().length>0&&(await i(createReasoningCompletedEvent({reasoning:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``),d+=e.text,await i(createMessageAppendedEvent({messageDelta:e.text,messageSoFar:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let t=e;m.add(t.toolCallId),t.providerExecuted===!0?await collectProviderToolCall(t):(await c.flush(),await emitToolCall(t));break}case`tool-result`:{let t=e;if(t.preliminary===!0)break;if(t.providerExecuted===!0){await collectProviderToolCall({input:`input`in t?t.input:void 0,toolCallId:t.toolCallId,toolName:t.toolName}),await c.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(t));break}if(m.has(e.toolCallId)){if(isInlineAuthorizationToolResult(t))break;h.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(t)),v.add(e.toolCallId));break}if(await c.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(t)){v.add(e.toolCallId),b.push(t);break}await emitActionResult(createRuntimeToolResultFromStepResult(t)),v.add(e.toolCallId);break}case`tool-error`:{let t=e;t.providerExecuted===!0?(await collectProviderToolCall(t),await c.flush(),await emitActionResult(createRuntimeToolResultFromToolError(t))):h.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(t)),v.add(t.toolCallId),x.push(createToolResultMessagePartFromToolError(t)));break}case`finish-step`:f=normalizeAssistantStepFinishReason(e.finishReason),await c.flush();break;case`error`:p=normalizeModelStreamError(e.error);break;case`abort`:throw new DOMException(e.reason??`The model stream was aborted.`,`AbortError`);default:break}if(await c.flush(),p!==void 0)throw p;return u.trim().length>0&&await i(createReasoningCompletedEvent({reasoning:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),f!==`tool-calls`&&hasEmptyDeliverySentinel(d)?await i(createMessageCompletedEvent({finishReason:f,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):d.trim().length>0&&await i(createMessageCompletedEvent({finishReason:f,message:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:h,handledInlineToolResultCallIds:v,invalidInputToolCallIds:y,inlineAuthorizationResults:b,trailingInlineToolResultParts:x}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
1
+ import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let a=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:a})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:a})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:a}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent(n.continuationToken)),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n,r){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent(r)):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(i,o,s,c,l){let u=``,d=``,f=`stop`,p,m=new Set,h=new Set,g=new Set,_=new Set,v=new Set,y=new Set,b=[],x=[],flushCurrentMessage=async()=>{d.length!==0&&(await i(createMessageCompletedEvent({finishReason:`tool-calls`,message:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d=``)},emitActionRequest=async e=>{h.has(e.callId)||(d.trim().length>0&&await flushCurrentMessage(),h.add(e.callId),await i(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{if(_.has(e.toolCallId)||(_.add(e.toolCallId),h.has(e.toolCallId)))return;h.add(e.toolCallId),d.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e);if(t.toolError!==void 0){y.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),v.add(e.toolCallId),x.push(createToolResultMessagePartFromToolError(t.toolError));return}c.observe(t.request)},emitActionResult=async t=>{g.has(t.callId)||(g.add(t.callId),await i(createActionResultEvent({result:t,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(isInvalidToolCall(e)){y.add(e.toolCallId);return}if(!(l===void 0||l.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:l.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});y.add(e.toolCallId),d.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),v.add(e.toolCallId),x.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let e of s)if(p===void 0)switch(e.type){case`reasoning-delta`:await c.flush(),u+=e.text,await i(createReasoningAppendedEvent({reasoningDelta:e.text,reasoningSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await c.flush(),u.trim().length>0&&(await i(createReasoningCompletedEvent({reasoning:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``),d+=e.text,await i(createMessageAppendedEvent({messageDelta:e.text,messageSoFar:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let t=e;m.add(t.toolCallId),t.providerExecuted===!0?await collectProviderToolCall(t):(await c.flush(),await emitToolCall(t));break}case`tool-result`:{let t=e;if(t.preliminary===!0)break;if(t.providerExecuted===!0){await collectProviderToolCall({input:`input`in t?t.input:void 0,toolCallId:t.toolCallId,toolName:t.toolName}),await c.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(t));break}if(m.has(e.toolCallId)){if(isInlineAuthorizationToolResult(t))break;h.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(t)),v.add(e.toolCallId));break}if(await c.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(t)){v.add(e.toolCallId),b.push(t);break}await emitActionResult(createRuntimeToolResultFromStepResult(t)),v.add(e.toolCallId);break}case`tool-error`:{let t=e;t.providerExecuted===!0?(await collectProviderToolCall(t),await c.flush(),await emitActionResult(createRuntimeToolResultFromToolError(t))):h.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(t)),v.add(t.toolCallId),x.push(createToolResultMessagePartFromToolError(t)));break}case`finish-step`:f=normalizeAssistantStepFinishReason(e.finishReason),await c.flush();break;case`error`:p=normalizeModelStreamError(e.error);break;case`abort`:throw new DOMException(e.reason??`The model stream was aborted.`,`AbortError`);default:break}if(await c.flush(),p!==void 0)throw p;return u.trim().length>0&&await i(createReasoningCompletedEvent({reasoning:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),f!==`tool-calls`&&hasEmptyDeliverySentinel(d)?await i(createMessageCompletedEvent({finishReason:f,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):d.trim().length>0&&await i(createMessageCompletedEvent({finishReason:f,message:d,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:h,handledInlineToolResultCallIds:v,invalidInputToolCallIds:y,inlineAuthorizationResults:b,trailingInlineToolResultParts:x}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
@@ -20,9 +20,25 @@ export interface InstrumentationSessionStartedEvent {
20
20
  readonly type: "session.started";
21
21
  readonly agentName?: string;
22
22
  readonly channelKind?: string;
23
+ readonly parentTraceContext?: InstrumentationTraceContext;
23
24
  readonly rootSessionId: string;
24
25
  readonly sessionId: string;
25
26
  }
27
+ export interface InstrumentationTraceContext {
28
+ readonly spanId: string;
29
+ readonly traceFlags: number;
30
+ readonly traceId: string;
31
+ }
32
+ /**
33
+ * Which tool call dispatched a subagent child. The trace structure alone
34
+ * cannot say: one turn's children all parent to the same window.
35
+ */
36
+ export interface InstrumentationParentLineage {
37
+ readonly callId: string;
38
+ readonly sessionId: string;
39
+ readonly subagentName?: string;
40
+ readonly turnId: string;
41
+ }
26
42
  export interface InstrumentationSessionTransitionEvent {
27
43
  readonly type: "session.completed" | "session.failed" | "session.waiting";
28
44
  readonly error?: unknown;
@@ -31,6 +47,8 @@ export interface InstrumentationSessionTransitionEvent {
31
47
  }
32
48
  export interface InstrumentationTurnStartedEvent {
33
49
  readonly type: "turn.started";
50
+ readonly parentLineage?: InstrumentationParentLineage;
51
+ readonly parentTraceContext?: InstrumentationTraceContext;
34
52
  readonly rootSessionId: string;
35
53
  readonly sequence: number;
36
54
  readonly sessionId: string;
@@ -1,9 +1,11 @@
1
- import type { InstrumentationHooks } from "#harness/instrumentation-lifecycle.js";
1
+ import type { InstrumentationHooks, InstrumentationParentLineage, InstrumentationTraceContext } from "#harness/instrumentation-lifecycle.js";
2
2
  import type { HandleEventFn } from "#harness/types.js";
3
3
  export interface CreateInstrumentationHandleEventInput {
4
4
  readonly agentName?: string;
5
5
  readonly handleEvent?: HandleEventFn;
6
6
  readonly hooks?: InstrumentationHooks;
7
+ readonly parentLineage?: InstrumentationParentLineage;
8
+ readonly parentTraceContext?: InstrumentationTraceContext;
7
9
  readonly rootSessionId?: string;
8
10
  readonly sessionId: string;
9
11
  readonly turnId?: string;
@@ -1 +1 @@
1
- function createInstrumentationHandleEvent(e){if(e.hooks===void 0)return e.handleEvent;if(e.handleEvent===void 0)return;let t=e.handleEvent,n=e.hooks,r=e.turnId;return async(i,a)=>{await t(i,a);let o=toLifecycleEvent(i,e,r);i.type===`turn.started`&&(r=i.data.turnId),o!==void 0&&await n.publish(o)}}function toLifecycleEvent(e,t,n){switch(e.type){case`session.started`:return{agentName:t.agentName,rootSessionId:t.rootSessionId??t.sessionId,sessionId:t.sessionId,type:`session.started`};case`session.completed`:case`session.waiting`:return{sessionId:t.sessionId,turnId:n,type:e.type};case`session.failed`:return{error:Error(e.data.message),sessionId:t.sessionId,turnId:n,type:`session.failed`};case`turn.started`:return{rootSessionId:t.rootSessionId??t.sessionId,sequence:e.data.sequence,sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.started`};case`turn.completed`:case`turn.cancelled`:return{sessionId:t.sessionId,turnId:e.data.turnId,type:e.type};case`turn.failed`:return{error:Error(e.data.message),sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.failed`};default:return}}export{createInstrumentationHandleEvent};
1
+ function createInstrumentationHandleEvent(e){if(e.hooks===void 0)return e.handleEvent;if(e.handleEvent===void 0)return;let t=e.handleEvent,n=e.hooks,r=e.turnId;return async(i,a)=>{await t(i,a);let o=toLifecycleEvent(i,e,r);i.type===`turn.started`&&(r=i.data.turnId),o!==void 0&&await n.publish(o)}}function toLifecycleEvent(e,t,n){switch(e.type){case`session.started`:return{agentName:t.agentName,parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId??t.sessionId,sessionId:t.sessionId,type:`session.started`};case`session.completed`:case`session.waiting`:return{sessionId:t.sessionId,turnId:n,type:e.type};case`session.failed`:return{error:Error(e.data.message),sessionId:t.sessionId,turnId:n,type:`session.failed`};case`turn.started`:return{parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId??t.sessionId,sequence:e.data.sequence,sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.started`};case`turn.completed`:case`turn.cancelled`:return{sessionId:t.sessionId,turnId:e.data.turnId,type:e.type};case`turn.failed`:return{error:Error(e.data.message),sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.failed`};default:return}}export{createInstrumentationHandleEvent};
@@ -0,0 +1,11 @@
1
+ import type { SessionParent } from "#channel/types.js";
2
+ import type { InstrumentationParentLineage } from "#harness/instrumentation-lifecycle.js";
3
+ /**
4
+ * Resolves the dispatch that created the running session, if any. Dispatch
5
+ * splits the lineage across two owners — the identifiers onto
6
+ * {@link SessionParent}, the subagent name onto the adapter state — so both
7
+ * are read here rather than either being duplicated onto the other.
8
+ */
9
+ export declare function resolveParentLineage(parent: SessionParent | undefined, adapter: {
10
+ readonly state?: unknown;
11
+ } | undefined): InstrumentationParentLineage | undefined;
@@ -0,0 +1 @@
1
+ import{isSubagentAdapterState}from"#execution/subagent-adapter-state.js";function resolveParentLineage(e,t){if(e===void 0)return;let n=t?.state;return{callId:e.callId,sessionId:e.sessionId,subagentName:isSubagentAdapterState(n)?n.subagentName:void 0,turnId:e.turn.id}}export{resolveParentLineage};
@@ -1 +1 @@
1
- import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey,getRuntimeActionResultKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function recordPendingSubagentChild(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t===void 0)return e.session;let n={...e.session.state};return n[PENDING_RUNTIME_ACTION_BATCH_KEY]={...t,...e.child.kind===`local`?{childContinuationTokens:{...t.childContinuationTokens,[e.callId]:e.child.continuationToken}}:{},childSessionIds:{...t.childSessionIds,[e.callId]:e.child.sessionId}},{...e.session,state:n}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results})}function resolveRuntimeActionResultsForKeys(e){let t=new Set(e.pendingKeys),n=new Map;for(let r of e.results){let e=getRuntimeActionResultKey(r);t.has(e)&&n.set(e,r)}let r=[];for(let t of e.pendingKeys){let e=n.get(t);if(e===void 0)return;r.push(e)}return r}async function resolvePendingRuntimeActions(t){let i=getPendingRuntimeActionBatch(t.session.state);if(i===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let a=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(a===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of a)n.kind===`subagent-result`&&n.isError!==!0&&await t.emit({data:{callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName},type:`subagent.completed`}),await t.emit(createActionResultEvent({result:n,sequence:i.event.sequence,stepIndex:i.event.stepIndex,turnId:i.event.turnId}));let o={...t.session.state};delete o[PENDING_RUNTIME_ACTION_BATCH_KEY];let s={...t.session,state:Object.keys(o).length>0?o:void 0},c=i.childContinuationTokens;if(c!==void 0)for(let e of a){if(e.kind!==`subagent-result`)continue;let t=c[e.callId];t!==void 0&&(s=clearProxyInputRequestsForChild(s,t))}for(let e of a)e.kind!==`subagent-result`||e.usage===void 0||(s=setTurnUsageState(s,accumulateSessionUsage({previous:getTurnUsageState(s.state),usage:e.usage})));let l=a.map(e=>{switch(e.kind){case`load-skill-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`};case`subagent-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`};case`tool-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`}}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}),u=[...s.history,...i.responseMessages];return l.length>0&&u.push({content:l,role:`tool`}),{messages:u,outcome:`resolved`,session:s}}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);return t?.runtimeAction?.kind===`subagent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`subagent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,subagentName:t.runtimeAction.subagentName}:t?.runtimeAction?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`remote-agent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,remoteAgentName:t.runtimeAction.remoteAgentName??t.name}:{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e,n){if(e==null||typeof e==`string`&&e.trim()===``)return{};try{return parseJsonObject(typeof e==`string`?parseJsonStringInput(e):e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function parseJsonStringInput(e){try{return JSON.parse(e)}catch{return e}}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{clearPendingRuntimeActionBatch,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,recordPendingSubagentChild,resolvePendingRuntimeActions,resolveRuntimeActionResultsForKeys,resolveToolCallInputObject,setPendingRuntimeActionBatch};
1
+ import{createActionResultEvent}from"#protocol/message.js";import{parseJsonObject}from"#shared/json.js";import{clearProxyInputRequestsForChild}from"#harness/proxy-input-requests.js";import{accumulateSessionUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey,getRuntimeActionResultKey}from"#runtime/actions/keys.js";const PENDING_RUNTIME_ACTION_BATCH_KEY=`eve.runtime.pendingActionBatch`;function getPendingRuntimeActionBatch(e){let t=e?.[PENDING_RUNTIME_ACTION_BATCH_KEY];if(typeof t!=`object`||!t)return;let n=t;if(!(!Array.isArray(n.actions)||!Array.isArray(n.responseMessages)||typeof n.event!=`object`||n.event===null))return n}function hasPendingRuntimeActionBatch(e){return getPendingRuntimeActionBatch(e)!==void 0}function clearPendingRuntimeActionBatch(e){if(e.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY]===void 0)return e;let t={...e.state};return delete t[PENDING_RUNTIME_ACTION_BATCH_KEY],{...e,state:Object.keys(t).length>0?t:void 0}}function setPendingRuntimeActionBatch(e){let t={...e.session.state};return t[PENDING_RUNTIME_ACTION_BATCH_KEY]={actions:[...e.actions],event:e.event,responseMessages:[...e.responseMessages]},{...e.session,state:t}}function recordPendingSubagentChild(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t===void 0)return e.session;let n={...e.session.state};return n[PENDING_RUNTIME_ACTION_BATCH_KEY]={...t,...e.child.kind===`local`?{childContinuationTokens:{...t.childContinuationTokens,[e.callId]:e.child.continuationToken}}:{},childSessionIds:{...t.childSessionIds,[e.callId]:e.child.sessionId}},{...e.session,state:n}}function resolveReadyRuntimeActionResults(e){let t=getPendingRuntimeActionBatch(e.session.state);if(t!==void 0)return resolveRuntimeActionResultsForBatch({batch:t,results:e.results})}function resolveRuntimeActionResultsForBatch(e){return resolveRuntimeActionResultsForKeys({pendingKeys:e.batch.actions.map(e=>getRuntimeActionRequestKey(e)),results:e.results})}function resolveRuntimeActionResultsForKeys(e){let t=new Set(e.pendingKeys),n=new Map;for(let r of e.results){let e=getRuntimeActionResultKey(r);t.has(e)&&n.set(e,r)}let r=[];for(let t of e.pendingKeys){let e=n.get(t);if(e===void 0)return;r.push(e)}return r}async function resolvePendingRuntimeActions(t){let i=getPendingRuntimeActionBatch(t.session.state);if(i===void 0)return{messages:[...t.session.history],outcome:`continue`,session:t.session};let a=resolveReadyRuntimeActionResults({results:t.stepInput?.runtimeActionResults??[],session:t.session});if(a===void 0)return{messages:[...t.session.history],outcome:`unresolved`,session:t.session};if(t.emit!==void 0)for(let n of a)n.kind===`subagent-result`&&n.isError!==!0&&await t.emit({data:{callId:n.callId,output:typeof n.output==`string`?n.output:JSON.stringify(n.output),subagentName:n.subagentName},type:`subagent.completed`}),await t.emit(createActionResultEvent({result:n,sequence:i.event.sequence,stepIndex:i.event.stepIndex,turnId:i.event.turnId}));let o={...t.session.state};delete o[PENDING_RUNTIME_ACTION_BATCH_KEY];let s={...t.session,state:Object.keys(o).length>0?o:void 0},c=i.childContinuationTokens;if(c!==void 0)for(let e of a){if(e.kind!==`subagent-result`)continue;let t=c[e.callId];t!==void 0&&(s=clearProxyInputRequestsForChild(s,t))}for(let e of a)e.kind!==`subagent-result`||e.usage===void 0||(s=setTurnUsageState(s,accumulateSessionUsage({previous:getTurnUsageState(s.state),usage:e.usage})));let l=a.map(e=>{switch(e.kind){case`load-skill-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:`load_skill`,type:`tool-result`};case`subagent-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.subagentName,type:`tool-result`};case`tool-result`:return{output:toToolResultOutput(e),toolCallId:e.callId,toolName:e.toolName,type:`tool-result`}}throw Error(`Unsupported runtime action result kind "${String(e)}".`)}),u=[...s.history,...i.responseMessages];return l.length>0&&u.push({content:l,role:`tool`}),{messages:u,outcome:`resolved`,session:s}}function createRuntimeActionRequestFromToolCall(e){let t=e.tools.get(e.toolCall.toolName);return t?.runtimeAction?.kind===`subagent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`subagent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,subagentName:t.runtimeAction.subagentName}:t?.runtimeAction?.kind===`remote-agent-call`?{callId:e.toolCall.toolCallId,description:t.description,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`remote-agent-call`,name:t.name,nodeId:t.runtimeAction.nodeId,remoteAgentName:t.runtimeAction.remoteAgentName??t.name}:{callId:e.toolCall.toolCallId,input:resolveToolCallInputObject(e.toolCall.input,{callId:e.toolCall.toolCallId,toolName:e.toolCall.toolName}),kind:`tool-call`,toolName:e.toolCall.toolName}}function resolveToolCallInputObject(e,n){if(e==null||typeof e==`string`&&e.trim()===``)return{};try{return parseJsonObject(typeof e==`string`?parseJsonStringInput(e):e)}catch(e){let t=e instanceof Error?e.message:String(e);throw TypeError(`Failed to parse tool-call arguments for "${n.toolName}" (${n.callId}): ${t}`,{cause:e})}}function parseJsonStringInput(e){return JSON.parse(e)}function toToolResultOutput(e){return typeof e.output==`string`?e.isError===!0?{type:`error-text`,value:e.output}:{type:`text`,value:e.output}:e.isError===!0?{type:`error-json`,value:toMutableJsonValue(e.output)}:{type:`json`,value:toMutableJsonValue(e.output)}}function toMutableJsonValue(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(e=>toMutableJsonValue(e));let t={};for(let[n,r]of Object.entries(e))t[n]=toMutableJsonValue(r);return t}export{clearPendingRuntimeActionBatch,createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,hasPendingRuntimeActionBatch,recordPendingSubagentChild,resolvePendingRuntimeActions,resolveRuntimeActionResultsForKeys,resolveToolCallInputObject,setPendingRuntimeActionBatch};