eve 0.37.0 → 0.37.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/src/channel/routes.d.ts +13 -3
- package/dist/src/channel/routes.js +1 -1
- package/dist/src/channel/session-callback.js +1 -1
- package/dist/src/channel/session.d.ts +2 -1
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +41 -0
- package/dist/src/chunks/{use-eve-agent-CnppTEFk.js → use-eve-agent-Bi5fRxcZ.js} +9 -1
- package/dist/src/chunks/{use-eve-agent-COmP-H8R.js → use-eve-agent-DbKUBhl-.js} +9 -1
- package/dist/src/cli/commands/init-git.js +1 -1
- package/dist/src/cli/commands/init-recovery.d.ts +3 -0
- package/dist/src/cli/commands/init-recovery.js +3 -0
- package/dist/src/cli/commands/init-target.d.ts +21 -0
- package/dist/src/cli/commands/init-target.js +1 -0
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +8 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +27 -22
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +16 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
- package/dist/src/client/open-stream.d.ts +2 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@modelcontextprotocol/server/LICENSE +216 -0
- package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +98 -0
- package/dist/src/compiled/@modelcontextprotocol/server/index.js +80 -0
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-subagent.d.ts +1 -1
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/context/serialized-dynamic-model-selection.d.ts +2 -0
- package/dist/src/context/serialized-dynamic-model-selection.js +1 -0
- package/dist/src/execution/agent-handle-dispatch.d.ts +15 -1
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/delegated-parent-notification.d.ts +17 -0
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +155 -0
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +18 -14
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +7 -2
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/effective-output-schema.d.ts +21 -0
- package/dist/src/execution/effective-output-schema.js +1 -0
- package/dist/src/execution/eve-workflow-attributes.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.d.ts +8 -12
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/{route-proxied-deliver-step.d.ts → proxied-deliver-step.d.ts} +7 -4
- package/dist/src/execution/proxied-deliver-step.js +1 -0
- package/dist/src/execution/remote-agent-dispatch.d.ts +32 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/remote-agent-route-url.d.ts +2 -0
- package/dist/src/execution/remote-agent-route-url.js +1 -0
- package/dist/src/execution/route-child-delivery.d.ts +2 -1
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/session-callback-step.d.ts +11 -0
- package/dist/src/execution/session-callback-step.js +1 -1
- package/dist/src/execution/session-command-wire.js +1 -1
- package/dist/src/execution/session-state-cursor.d.ts +25 -0
- package/dist/src/execution/session-state-cursor.js +1 -0
- package/dist/src/execution/settle-cancelled-turn-step.d.ts +2 -0
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.d.ts +15 -0
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +14 -7
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/subagent-start-local.d.ts +29 -0
- package/dist/src/execution/subagent-start-local.js +1 -0
- package/dist/src/execution/subagent-start-remote.d.ts +23 -0
- package/dist/src/execution/subagent-start-remote.js +1 -0
- package/dist/src/execution/task-event-callback.d.ts +13 -0
- package/dist/src/execution/task-event-callback.js +1 -0
- package/dist/src/execution/task-input-capability.d.ts +4 -0
- package/dist/src/execution/task-input-capability.js +1 -0
- package/dist/src/execution/tasks/child/steps.d.ts +46 -0
- package/dist/src/execution/tasks/child/steps.js +1 -0
- package/dist/src/execution/tasks/child/workflow.d.ts +31 -0
- package/dist/src/execution/tasks/child/workflow.js +1 -0
- package/dist/src/execution/tasks/parent/agent-identity.d.ts +13 -0
- package/dist/src/execution/tasks/parent/agent-identity.js +1 -0
- package/dist/src/execution/tasks/parent/agent-views.d.ts +6 -0
- package/dist/src/execution/tasks/parent/agent-views.js +1 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.d.ts +37 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.js +1 -0
- package/dist/src/execution/tasks/parent/control-shared.d.ts +36 -0
- package/dist/src/execution/tasks/parent/control-shared.js +1 -0
- package/dist/src/execution/tasks/parent/delegate.d.ts +70 -0
- package/dist/src/execution/tasks/parent/delegate.js +1 -0
- package/dist/src/execution/tasks/parent/dispatch-task-step.d.ts +19 -0
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -0
- package/dist/src/execution/tasks/parent/dispatch.d.ts +33 -0
- package/dist/src/execution/tasks/parent/dispatch.js +1 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +29 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -0
- package/dist/src/execution/tasks/parent/run-parent.d.ts +72 -0
- package/dist/src/execution/tasks/parent/run-parent.js +1 -0
- package/dist/src/execution/tasks/parent/send.d.ts +25 -0
- package/dist/src/execution/tasks/parent/send.js +1 -0
- package/dist/src/execution/tasks/workflow-target.d.ts +2 -0
- package/dist/src/execution/tasks/workflow-target.js +1 -0
- package/dist/src/execution/terminate-child-sessions-step.d.ts +1 -0
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/turn-control-receiver.d.ts +10 -0
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.d.ts +2 -0
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +2 -8
- package/dist/src/execution/turn-execution-cursor.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +5 -0
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +9 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +7 -21
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +7 -0
- package/dist/src/harness/handles/prompt.d.ts +12 -0
- package/dist/src/harness/handles/prompt.js +2 -1
- package/dist/src/harness/handles/query.js +1 -1
- package/dist/src/harness/handles/store.d.ts +9 -2
- package/dist/src/harness/handles/store.js +1 -1
- package/dist/src/harness/handles/transitions.d.ts +10 -1
- package/dist/src/harness/handles/transitions.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +21 -4
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +2 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/workflow-runtime-action-state.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/invocation/agent-invocation.d.ts +54 -0
- package/dist/src/internal/invocation/agent-invocation.js +1 -0
- package/dist/src/internal/invocation/attributes.d.ts +2 -0
- package/dist/src/internal/invocation/attributes.js +1 -0
- package/dist/src/internal/invocation/metadata.d.ts +9 -0
- package/dist/src/internal/invocation/metadata.js +1 -0
- package/dist/src/internal/invocation/workflow-execution.d.ts +32 -0
- package/dist/src/internal/invocation/workflow-execution.js +1 -0
- package/dist/src/internal/mcp/http-security.d.ts +12 -0
- package/dist/src/internal/mcp/http-security.js +1 -0
- package/dist/src/internal/mcp/protected-resource.d.ts +9 -0
- package/dist/src/internal/mcp/protected-resource.js +1 -0
- package/dist/src/internal/mcp/streamable-http-server.d.ts +51 -0
- package/dist/src/internal/mcp/streamable-http-server.js +1 -0
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-route-context.d.ts +14 -0
- package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
- package/dist/src/internal/nitro/routes/runtime-stack.d.ts +2 -0
- package/dist/src/internal/nitro/routes/runtime-stack.js +1 -1
- package/dist/src/internal/vercel-agent-summary.d.ts +1 -1
- package/dist/src/protocol/message.d.ts +28 -0
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/routes.d.ts +14 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/auth.d.ts +36 -0
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/mcp.d.ts +19 -0
- package/dist/src/public/channels/mcp.js +1 -0
- package/dist/src/public/definitions/channel.d.ts +2 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/actions/types.d.ts +9 -0
- package/dist/src/runtime/actions/types.js +1 -1
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/runtime/connections/authorization-complete-page.js +70 -28
- package/dist/src/runtime/framework-channels/index.js +1 -1
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/framework-tools/tasks.d.ts +95 -0
- package/dist/src/runtime/framework-tools/tasks.js +1 -0
- package/dist/src/runtime/prompt/compose.d.ts +1 -0
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/runtime/task-input-response-route.d.ts +5 -0
- package/dist/src/runtime/task-input-response-route.js +1 -0
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +7 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/json.d.ts +88 -0
- package/dist/src/tasks/json.js +1 -0
- package/dist/src/tasks/session-index.d.ts +48 -0
- package/dist/src/tasks/session-index.js +1 -0
- package/dist/src/tasks/task-id.d.ts +34 -0
- package/dist/src/tasks/task-id.js +1 -0
- package/dist/src/tasks/transitions.d.ts +23 -0
- package/dist/src/tasks/transitions.js +1 -0
- package/dist/src/tasks/types.d.ts +295 -0
- package/dist/src/tasks/types.js +1 -0
- package/dist/src/tasks/wire.d.ts +26 -0
- package/dist/src/tasks/wire.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/eve.mdx +14 -0
- package/docs/guides/client/streaming.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +3 -1
- package/package.json +7 -1
- package/dist/src/execution/route-proxied-deliver-step.js +0 -1
|
@@ -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{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{SUBAGENT_START_FAILED}from"#harness/agent-handle-errors.js";import{confirmAgentStarted,prepareAgentStart,rejectAgentEffect}from"#harness/handles/transitions.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{dispatchToAgentHandle,isAgentHandleAction}from"#execution/agent-handle-dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{getPendingRuntimeActionBatch,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createRecursiveAgentRootOnlyResult,createRemoteAgentStartFailureResult,createUnavailableDynamicSubagentResult,getSubagentName}from"#execution/dispatch-action-failures.js";import{mintStartOperation}from"#execution/dispatch-start-operation.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import*as traceState from"#tracing/agent-trace-context-store.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{activeTurnId}from"#harness/active-turn-id.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),p=getPendingRuntimeActionBatch(s.state);if(p===void 0||p.actions.length===0)return{results:[],sessionState:e.sessionState};let m=p.event.turnId||activeTurnId(e.sessionState.emissionState),h={...p.event,turnId:m},g=await deserializeContext(e.serializedContext),_=g.require(BundleKey),v=resolveEffectiveAgentRuntime(_,g),y=setPendingRuntimeActionBatch({...p,event:h,session:hydrateDurableSession({compactionOverrides:{thresholdPercent:v.thresholdPercent},durable:s,turnAgent:v.turnAgent})}),b=g.require(ChannelKey),x=g.get(AuthKey)??null,S=g.get(CapabilitiesKey),C=g.get(ChannelInstrumentationKey),w=g.get(InitiatorAuthKey)??null,T=buildAdapterContext(b,g),E=traceState.readSessionTraceContext(e.serializedContext,y.sessionId),D=_.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0;getAgentHandleStore(s.state);let O=planDispatch({actions:p.actions,bundle:_,ctx:g,session:y}),k=e.parentWritable.getWriter(),A=O.filter(e=>e.kind===`start`&&e.target.kind===`local`).length,j=y,M=[];try{for(let r of O){if(r.kind===`reject`){M.push(r.result);continue}let i;switch(r.kind){case`resume`:i=await dispatchToAgentHandle({action:r.action,agentId:r.agentId,bundle:createAgentContinuationBundle({action:r.action,bundle:_,dynamicRemoteAgent:r.dynamicRemoteAgent}),currentSession:j,parentToken:e.parentContinuationToken??y.continuationToken,parentTurnId:m});break;case`start`:i=await startSubagent({auth:x,batchEvent:h,bundle:_,callbackBaseUrl:e.callbackBaseUrl,capabilities:S,channelMetadata:C,currentSession:j,fanoutSize:A,initiatorAuth:w,parentContinuationToken:e.parentContinuationToken,parentTraceContext:traceState.readActionTraceContext(e.serializedContext,y.sessionId,p.event.turnId,r.target.action.callId)??E,persistentSessions:D,session:y,target:r.target});break}if(j=i.session,i.kind===`error`){M.push(i.result);continue}try{let e=await callAdapterEventHandler(b,createSubagentCalledEvent({callId:i.callId,childSessionId:i.address.sessionId,name:i.name,remote:i.address.kind===`agent/remote`?{url:i.address.url}:void 0,sequence:h.sequence,sessionId:y.sessionId,toolName:i.toolName,turnId:m,workflowId:workflowEntryReference.workflowId}),T);await k.write(encodeMessageStreamEvent(stampMessageStreamEvent(e)))}catch(e){logError(log,`subagent.called emission failed`,e,{callId:i.callId,childSessionId:i.address.sessionId,toolName:i.toolName})}}}finally{k.releaseLock()}return{results:M,sessionState:j===y&&p.event.turnId===m?e.sessionState:createDurableSessionState({session:j})}}function planDispatch(e){let t=getAgentHandleStore(e.session.state)?.handles??[];return e.actions.map(n=>{let r=n.input.agentId,i=typeof r==`string`&&r.trim()!==``?r:void 0;if(i!==void 0&&isAgentHandleAction(n)){if(t.some(e=>e.identity.id===i)){let t=e.bundle.subagentRegistry.dynamicNodeIds?.has(n.nodeId)===!0?getDynamicSubagentSelection(e.ctx,n.nodeId):void 0;return{action:n,agentId:i,dynamicRemoteAgent:n.kind===`remote-agent-call`&&t?.kind===`remote`?t.remoteAgent:void 0,kind:`resume`}}log.warn(`unknown agentId on subagent call; starting a new agent`,{agentId:i,callId:n.callId})}return classifyFreshStart({action:n,bundle:e.bundle,ctx:e.ctx,session:e.session})})}function classifyFreshStart(e){let{action:t}=e,n=e.bundle.subagentRegistry.subagentsByNodeId,r=resolveSubagentDepth(e.session),i=e.session.rootSessionId!==void 0||r.currentDepth>0,a=(t.kind===`subagent-call`||t.kind===`remote-agent-call`)&&e.bundle.subagentRegistry.dynamicNodeIds?.has(t.nodeId)===!0,o=a?getDynamicSubagentSelection(e.ctx,t.nodeId):void 0;if(a&&(o===void 0||t.kind===`subagent-call`&&o.kind!==`subagent`||t.kind===`remote-agent-call`&&o.kind!==`remote`)){let e=getSubagentName(t);return log.warn(`dynamic subagent call blocked after availability changed`,{callId:t.callId,nodeId:t.nodeId,subagentName:e}),{kind:`reject`,result:createUnavailableDynamicSubagentResult(t)}}if(isRecursiveAgentAction(t,n)&&i)return log.warn(`recursive agent call blocked outside the root session`,{callId:t.callId,currentDepth:r.currentDepth,nodeId:t.nodeId,subagentName:t.subagentName}),{kind:`reject`,result:createRecursiveAgentRootOnlyResult(t)};switch(t.kind){case`subagent-call`:{let e=o?.kind===`subagent`?o.agentConfig:void 0,r=n.get(t.nodeId),i=e?.description??(r?.definition.kind===`subagent`?r.definition.description:void 0);return{kind:`start`,target:{action:t,dynamicSubagentAgentConfig:e,kind:`local`,source:i===void 0?{type:`runtime`}:{description:i,type:`local`}}}}case`remote-agent-call`:return{kind:`start`,target:{action:t,dynamicRemoteAgent:o?.kind===`remote`?o.remoteAgent:void 0,kind:`remote`}};default:throw Error(`Unsupported runtime action kind "${t.kind}" in workflow runtime.`)}}async function startSubagent(e){switch(e.target.kind){case`local`:return startLocalSubagent({action:e.target.action,auth:e.auth,batchEvent:e.batchEvent,bundle:e.bundle,capabilities:e.capabilities,channelMetadata:e.channelMetadata,currentSession:e.currentSession,dynamicSubagentAgentConfig:e.target.dynamicSubagentAgentConfig,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,persistentSessions:e.persistentSessions,session:e.session,source:e.target.source});case`remote`:return startRemoteSubagent({action:e.target.action,auth:e.auth,batchEvent:e.batchEvent,bundle:e.bundle,callbackBaseUrl:e.callbackBaseUrl,currentSession:e.currentSession,dynamicRemoteAgent:e.target.dynamicRemoteAgent,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,persistentSessions:e.persistentSessions,session:e.session});default:return e.target}}async function startLocalSubagent(e){let{action:n,source:r}=e,i=createWorkflowRuntime({compiledArtifactsSource:e.bundle.compiledArtifactsSource,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,nodeId:n.nodeId}),{childContinuationToken:a,runInput:o}=buildSubagentRunInput({action:n,auth:e.auth,batchEvent:e.batchEvent,capabilities:e.capabilities,channelMetadata:e.channelMetadata,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,persistentSessions:e.persistentSessions,session:e.session,source:r}),c=r.type===`runtime`?`agent/self`:`agent/local`,{identity:l,operation:u}=mintStartOperation({callId:n.callId,name:n.subagentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),d=prepareAgentStart(e.currentSession,{identity:l,operation:u,target:{continuationToken:a,kind:c}}),f;try{f=(await i.createSession(o)).sessionId}catch(e){return logError(log,`local subagent start failed`,e,{callId:n.callId,nodeId:n.nodeId,subagentName:n.subagentName}),{kind:`error`,result:{callId:n.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:SUBAGENT_START_FAILED,message:toErrorMessage(e)},subagentName:n.subagentName},session:rejectAgentEffect(d,{disposition:`dead`,operationId:u.id})}}let p={continuationToken:a,kind:c,sessionId:f};return{address:p,callId:n.callId,kind:`called`,name:n.name,session:confirmAgentStarted(d,{address:p,operationId:u.id}),toolName:n.subagentName}}async function startRemoteSubagent(e){let{action:n}=e,r,i;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);r=e.callbackBaseUrl,i=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:n.nodeId,remoteAgentName:n.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(r){return logError(log,`remote agent start failed`,r,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:n,error:r}),session:e.currentSession}}let{identity:a,operation:o}=mintStartOperation({callId:n.callId,name:n.remoteAgentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),s=prepareAgentStart(e.currentSession,{identity:a,operation:o,target:{callbackBaseUrl:r,kind:`agent/remote`,url:i.url}});try{let t=await startRemoteAgentSession({action:n,auth:e.auth,callbackBaseUrl:r,callbackToken:e.parentContinuationToken,initiatorAuth:e.initiatorAuth,parentTraceContext:e.parentTraceContext,persistentSessions:e.persistentSessions,remote:i,session:e.session}),a={callbackBaseUrl:r,kind:`agent/remote`,sessionId:t.sessionId,url:i.url};return{address:a,callId:n.callId,kind:`called`,name:n.name,session:confirmAgentStarted(s,{address:a,operationId:o.id}),toolName:n.remoteAgentName}}catch(e){return logError(log,`remote agent start failed`,e,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:n,error:e}),session:rejectAgentEffect(s,{disposition:`dead`,operationId:o.id})}}}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}export{dispatchRuntimeActionsStep};
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{dispatchToAgentHandle}from"#execution/agent-handle-dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{emitSubagentCalled,prepareRuntimeActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";async function dispatchRuntimeActionsStep(n){"use step";let r=await prepareRuntimeActionDispatch({serializedContext:n.serializedContext,sessionState:n.sessionState,taskControls:!1});if(r===void 0)return{results:[],sessionState:n.sessionState,pendingTasks:[]};let{batch:i,bundle:a,session:o}=r,s=a.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,c=n.parentWritable.getWriter(),l=o,u=[];try{for(let e of r.plan){if(e.kind===`reject`){u.push(e.result);continue}if(e.kind===`task-control`)throw Error(`Task-control actions require the task dispatch step.`);let t;switch(e.kind){case`resume`:t=await dispatchToAgentHandle({action:e.action,agentId:e.agentId,bundle:createAgentContinuationBundle({action:e.action,bundle:a,dynamicRemoteAgent:e.dynamicRemoteAgent}),currentSession:l,parentToken:n.parentContinuationToken??o.continuationToken,parentTurnId:i.event.turnId});break;case`start`:t=await startSubagent({auth:r.auth,batchEvent:i.event,bundle:a,callbackBaseUrl:n.callbackBaseUrl,capabilities:r.capabilities,channelMetadata:r.channelMetadata,currentSession:l,fanoutSize:r.fanoutSize,initiatorAuth:r.initiatorAuth,parentContinuationToken:n.parentContinuationToken,parentTraceContext:r.parentTraceContext,persistentSessions:s,serializedContext:r.serializedContext,session:o,taskOwned:!1,target:e.target});break}if(l=t.session,t.kind===`error`){u.push(t.result);continue}await emitSubagentCalled({adapter:r.adapter,adapterCtx:r.adapterCtx,batchEvent:i.event,entry:e,outcome:t,sessionId:o.sessionId,writer:c})}}finally{c.releaseLock()}return{results:u,sessionState:l===o?n.sessionState:createDurableSessionState({session:l}),pendingTasks:[]}}export{dispatchRuntimeActionsStep};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { RuntimeActionResult } from "#runtime/actions/types.js";
|
|
3
3
|
/** Dispatches the child-agent action currently blocking a dynamic workflow. */
|
|
4
4
|
export declare function dispatchWorkflowRuntimeActionsStep(input: {
|
|
5
5
|
readonly callbackBaseUrl?: string;
|
|
@@ -8,6 +8,11 @@ export declare function dispatchWorkflowRuntimeActionsStep(input: {
|
|
|
8
8
|
readonly serializedContext: Record<string, unknown>;
|
|
9
9
|
readonly sessionState: DurableSessionState;
|
|
10
10
|
}): Promise<{
|
|
11
|
-
readonly results: readonly
|
|
11
|
+
readonly results: readonly RuntimeActionResult[];
|
|
12
12
|
readonly sessionState: DurableSessionState;
|
|
13
|
+
readonly pendingTasks: readonly {
|
|
14
|
+
readonly taskInboxToken: string;
|
|
15
|
+
readonly taskId: string;
|
|
16
|
+
readonly taskRunId: string;
|
|
17
|
+
}[];
|
|
13
18
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getSubagentDelegationName,isSubagentDelegationAction}from"#harness/subagent-depth.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{buildRuntimeActionsFromWorkflowInterrupt}from"#harness/workflow-runtime-action-state.js";import{planWorkflowSubagentDispatch}from"#harness/workflow-subagent-limit.js";const log=createLogger(`execution.dispatch-workflow-runtime-actions`);async function dispatchWorkflowRuntimeActionsStep(e){"use step";let n=await readDurableSession(e.sessionState),r=getPendingWorkflowInterrupt(n.state);if(r===void 0)return{results:[],sessionState:e.sessionState};let i=buildRuntimeActionsFromWorkflowInterrupt(r.interrupt);if(i.length===0)return{results:[],sessionState:e.sessionState};let a=await deserializeContext(e.serializedContext),o=
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getSubagentDelegationName,isSubagentDelegationAction}from"#harness/subagent-depth.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{dispatchTaskStep}from"#execution/tasks/parent/dispatch-task-step.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{buildRuntimeActionsFromWorkflowInterrupt}from"#harness/workflow-runtime-action-state.js";import{planWorkflowSubagentDispatch}from"#harness/workflow-subagent-limit.js";const log=createLogger(`execution.dispatch-workflow-runtime-actions`);async function dispatchWorkflowRuntimeActionsStep(e){"use step";let n=await readDurableSession(e.sessionState),r=getPendingWorkflowInterrupt(n.state);if(r===void 0)return{results:[],sessionState:e.sessionState,pendingTasks:[]};let i=buildRuntimeActionsFromWorkflowInterrupt(r.interrupt);if(i.length===0)return{results:[],sessionState:e.sessionState,pendingTasks:[]};let a=await deserializeContext(e.serializedContext),o=a.require(BundleKey),s=resolveEffectiveAgentRuntime(o,a),c=planWorkflowSubagentDispatch({actions:i,interrupt:r.interrupt,maxSubagents:n.workflowMaxSubagents}),l=c.blocked.map(e=>(log.warn(`workflow subagent limit reached; blocking delegated call`,{callId:e.callId,maxSubagents:c.maxSubagents,subagentName:isSubagentDelegationAction(e)?getSubagentDelegationName(e):e.kind,usedCalls:c.usedCalls}),createWorkflowSubagentLimitResult({action:e,plan:c})));if(c.allowed.length===0)return{results:l,sessionState:e.sessionState,pendingTasks:[]};let u=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.thresholdPercent},durable:n,turnAgent:s.turnAgent}),d=setPendingRuntimeActionBatch({actions:c.allowed,event:{sequence:0,stepIndex:0,turnId:`workflow-dispatch`},responseMessages:[],session:u}),f=await(o.resolvedAgent.config?.experimental?.tasks===!0?dispatchTaskStep:dispatchRuntimeActionsStep)({callbackBaseUrl:e.callbackBaseUrl,parentContinuationToken:e.parentContinuationToken,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:createDurableSessionState({session:d})});return l.length===0?f:{results:[...f.results,...l],sessionState:f.sessionState,pendingTasks:f.pendingTasks}}function createWorkflowSubagentLimitResult(e){let t=isSubagentDelegationAction(e.action)?getSubagentDelegationName(e.action):e.action.kind;return{callId:e.action.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`WORKFLOW_SUBAGENT_LIMIT_REACHED`,maxSubagents:e.plan.maxSubagents,message:`Workflow subagent limit reached (${String(e.plan.maxSubagents)}); "${t}" was not called.`},subagentName:t}}export{dispatchWorkflowRuntimeActionsStep};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { HarnessSession, StepInput } from "#harness/types.js";
|
|
2
|
+
import type { JsonObject } from "#shared/json.js";
|
|
3
|
+
import type { RunMode } from "#shared/run-mode.js";
|
|
4
|
+
/**
|
|
5
|
+
* Resolves the single output schema in effect for this turn, decoupling schema
|
|
6
|
+
* enforcement from {@link RunMode}: downstream the harness reads
|
|
7
|
+
* `session.outputSchema` unconditionally and never re-derives it from mode.
|
|
8
|
+
*
|
|
9
|
+
* A run-scoped (client-supplied) schema on the turn's {@link StepInput} always
|
|
10
|
+
* wins. With no run-scoped schema, a task run adopts the agent's declared
|
|
11
|
+
* return schema — its function-output contract, which only applies when the
|
|
12
|
+
* agent is invoked as a function (subagent / schedule / job), i.e. task mode.
|
|
13
|
+
* A conversation run with no run-scoped schema enforces nothing. Continuation
|
|
14
|
+
* steps (no new `StepInput`) preserve whatever is already in effect.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveEffectiveOutputSchema(input: {
|
|
17
|
+
readonly agentOutputSchema: JsonObject | undefined;
|
|
18
|
+
readonly input: StepInput | undefined;
|
|
19
|
+
readonly mode: RunMode;
|
|
20
|
+
readonly session: HarnessSession;
|
|
21
|
+
}): HarnessSession;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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}}export{resolveEffectiveOutputSchema};
|
|
@@ -23,6 +23,8 @@
|
|
|
23
23
|
* - `$eve.trigger` — channel adapter kind (session/subagent rows)
|
|
24
24
|
* - `$eve.title` — truncated session title from the first user message
|
|
25
25
|
* - `$eve.channel_request_id` — inbound channel request id
|
|
26
|
+
* - `$eve.invocation_token` — channel-local continuation token for an external invocation
|
|
27
|
+
* - `$eve.invocation_owner` — SHA-256 fingerprint of the invocation's initiating principal
|
|
26
28
|
*/
|
|
27
29
|
import type { EveAttributeValue } from "#runtime/attributes/normalize.js";
|
|
28
30
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME,isImplicitAgentToolAvailable}from"#runtime/framework-tools/agent.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node}),i=getInstrumentationRuntime(),a=createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,webSearchProvider:e.node.agent.webSearchProvider,handleEvent:e.handleEvent,instrumentation:i,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,persistentSubagentSessions:e.node.agent.config?.experimental?.subagentPersistentSessions===!0,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?a:async(e,t)=>{try{return await a(e,t)}finally{await i.forceFlush()}}}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t){return n=>dispatchDynamicModelEvent({ctx:n.ctx,dynamicModel:t,event:n.event,messages:n.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME,isImplicitAgentToolAvailable}from"#runtime/framework-tools/agent.js";import{createTaskToolHarnessDefinitions,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node}),i=getInstrumentationRuntime(),a=createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,webSearchProvider:e.node.agent.webSearchProvider,handleEvent:e.handleEvent,instrumentation:i,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,persistentSubagentSessions:e.node.agent.config?.experimental?.tasks===!0||e.node.agent.config?.experimental?.subagentPersistentSessions===!0,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?a:async(e,t)=>{try{return await a(e,t)}finally{await i.forceFlush()}}}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t){return n=>dispatchDynamicModelEvent({ctx:n.ctx,dynamicModel:t,event:n.event,messages:n.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}isImplicitAgentToolAvailable({disabledFrameworkTools:e.node.agent.disabledFrameworkTools,hasAuthoredAgentTool:t.has(AGENT_TOOL_NAME),nodeId:e.node.nodeId})&&t.set(AGENT_TOOL_NAME,{description:AGENT_TOOL_DESCRIPTION,inputSchema:e.node.agent.config?.experimental?.tasks===!0||e.node.agent.config?.experimental?.subagentPersistentSessions===!0?PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA:SUBAGENT_TOOL_INPUT_SCHEMA,name:AGENT_TOOL_NAME,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:AGENT_TOOL_NAME}});let n=e.node.agent.config?.experimental?.tasks===!0;for(let r of createTaskToolHarnessDefinitions())isTaskToolAvailable({disabledFrameworkTools:e.node.agent.disabledFrameworkTools,hasAuthoredTool:t.has(r.name),tasksEnabled:n,toolName:r.name})&&t.set(r.name,r);return t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`||e.tool.kind===`remote`)return createHarnessDelegationToolDefinition(e.tool);let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=t.definition,i=r.sourceId.startsWith(`eve:`),o=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:o,scope:r.name}),frameworkAction:i&&r.name===LOAD_SKILL_TOOL_NAME?`load-skill`:void 0,inputSchema:r.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:r.name,approval:r.approval,outputSchema:r.outputSchema,toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{isFrameworkTool:t,rawExecute:n,scope:i}=e;return n===void 0?void 0:t?n:createToolExecuteWithAuth({execute:n,scope:i})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -1,38 +1,29 @@
|
|
|
1
1
|
import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
|
|
2
|
-
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
2
|
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
|
|
3
|
+
import type { SessionStateCursor } from "#execution/session-state-cursor.js";
|
|
4
4
|
/** One authorization-callback read surfaced during a parked wait. */
|
|
5
5
|
export interface AuthorizationCallbackInstruction {
|
|
6
6
|
readonly kind: "authorization";
|
|
7
7
|
/** True when the authorization hook closed; no further callbacks can arrive. */
|
|
8
8
|
readonly closed: boolean;
|
|
9
9
|
readonly payloads: readonly DeliverPayload[];
|
|
10
|
-
readonly sessionState: DurableSessionState;
|
|
11
10
|
}
|
|
12
11
|
/** What the parked driver should do with the next session activity. */
|
|
13
12
|
export type NextTurnInstruction = {
|
|
14
13
|
readonly kind: "clear";
|
|
15
|
-
readonly sessionState: DurableSessionState;
|
|
16
14
|
} | {
|
|
17
15
|
readonly kind: "compact";
|
|
18
|
-
readonly sessionState: DurableSessionState;
|
|
19
16
|
} | {
|
|
20
17
|
readonly kind: "expired";
|
|
21
|
-
readonly sessionState: DurableSessionState;
|
|
22
18
|
} | {
|
|
23
19
|
readonly kind: "reset";
|
|
24
|
-
readonly sessionState: DurableSessionState;
|
|
25
20
|
} | {
|
|
26
21
|
readonly kind: "closed";
|
|
27
|
-
readonly sessionState: DurableSessionState;
|
|
28
22
|
} | {
|
|
29
23
|
readonly kind: "cancel-turn";
|
|
30
|
-
readonly sessionState: DurableSessionState;
|
|
31
24
|
} | AuthorizationCallbackInstruction | {
|
|
32
25
|
readonly kind: "turn";
|
|
33
|
-
readonly
|
|
34
|
-
readonly remainder: DeliverHookPayload;
|
|
35
|
-
readonly sessionState: DurableSessionState;
|
|
26
|
+
readonly delivery: DeliverHookPayload;
|
|
36
27
|
};
|
|
37
28
|
/**
|
|
38
29
|
* Awaits the next delivery that requires driver action while the session
|
|
@@ -46,13 +37,18 @@ export type NextTurnInstruction = {
|
|
|
46
37
|
* without producing a parent turn (no-op cancels, fully-routed descendant
|
|
47
38
|
* deliveries) — so an open challenge's callback surfaces as an
|
|
48
39
|
* `"authorization"` instruction no matter when it arrives.
|
|
40
|
+
*
|
|
41
|
+
* Routing steps mutate durable state; each transition is adopted into the
|
|
42
|
+
* caller-owned `stateCursor`, so returns carry only the instruction kind.
|
|
49
43
|
*/
|
|
50
44
|
export declare function nextTurnDelivery(input: {
|
|
51
45
|
readonly awaitAuthorizationCallbacks?: boolean;
|
|
52
46
|
readonly bufferedDeliveries: DeliverHookPayload[];
|
|
53
47
|
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
|
|
48
|
+
readonly cancelledTaskIds?: Set<string>;
|
|
54
49
|
readonly commandInbox: SessionCommandInbox;
|
|
55
50
|
readonly deferDeliveries?: boolean;
|
|
56
51
|
readonly driverWritable: WritableStream<Uint8Array>;
|
|
57
|
-
readonly
|
|
52
|
+
readonly seenTaskDeliveries?: Set<string>;
|
|
53
|
+
readonly stateCursor: SessionStateCursor;
|
|
58
54
|
}): Promise<NextTurnInstruction>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{coalesceDeliveries}from"#harness/messages.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";async function nextTurnDelivery(e){if(e.awaitAuthorizationCallbacks!==!0)return await awaitNextTurnDelivery(e);e.commandInbox.setAuthorizationWindow(!0);try{return await awaitNextTurnDelivery(e)}finally{e.commandInbox.setAuthorizationWindow(!1)}}async function awaitNextTurnDelivery(e){let n=e.
|
|
1
|
+
import{coalesceDeliveries}from"#harness/messages.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";async function nextTurnDelivery(e){if(e.awaitAuthorizationCallbacks!==!0)return await awaitNextTurnDelivery(e);e.commandInbox.setAuthorizationWindow(!0);try{return await awaitNextTurnDelivery(e)}finally{e.commandInbox.setAuthorizationWindow(!1)}}async function awaitNextTurnDelivery(e){let n=e.cancelledTaskIds??new Set,r=e.seenTaskDeliveries??new Set;for(;;){let i=await waitForNextSessionAction({bufferedDeliveries:e.bufferedDeliveries,bufferedSessionControls:e.bufferedSessionControls,cancelledTaskIds:n,commandInbox:e.commandInbox,deferDeliveries:e.deferDeliveries,seenTaskDeliveries:r});if(i.kind===`authorization`)return i;if(i.kind!==`delivery`)return{kind:i.kind};let a=i.delivery;if(a===null)return{kind:`closed`};let o=await routeDeliverToChildren({delivery:a,parentWritable:e.driverWritable,serializedContext:e.stateCursor.serializedContext,sessionState:e.stateCursor.sessionState});if(e.stateCursor.adoptState(o),o.kind===`cancel-turn`)return{kind:`cancel-turn`};if(o.remainder!==void 0)return{delivery:o.remainder,kind:`turn`}}}async function waitForNextSessionAction(e){let t=e.bufferedSessionControls.shift();if(t!==void 0)return{kind:t};for(;e.bufferedDeliveries[0]!==void 0&&isCancelledTaskDelivery(e.bufferedDeliveries[0],e.cancelledTaskIds);)e.bufferedDeliveries.shift();if(e.deferDeliveries!==!0&&!e.commandInbox.hasReadyAuthorization()&&e.bufferedDeliveries.length>0)return{delivery:takeBufferedTurnDelivery(e.bufferedDeliveries),kind:`delivery`};for(;;){let{result:t,source:r}=await e.commandInbox.nextWithSource();if(e.commandInbox.consumeNext(),r===`authorization`)return t.done?{closed:!0,kind:`authorization`,payloads:[]}:{closed:!1,kind:`authorization`,payloads:t.value.kind===`deliver`?t.value.payloads:[]};if(t.done)return{delivery:null,kind:`delivery`};if(t.value.kind===`session-timeout`)return{kind:`expired`};if(t.value.kind===`clear`||t.value.kind===`compact`||t.value.kind===`reset`)return{kind:t.value.kind};if(t.value.kind===`cancel`){if(t.value.taskId!==void 0){e.cancelledTaskIds.add(t.value.taskId);let n=e.bufferedDeliveries.filter(t=>!isCancelledTaskDelivery(t,e.cancelledTaskIds));e.bufferedDeliveries.splice(0,e.bufferedDeliveries.length,...n)}continue}if(t.value.kind===`runtime-action-result`)continue;let i=t.value.taskDeliveryId??t.value.caller?.taskId;if(i!==void 0&&isCancelledTaskDeliveryId(i,e.cancelledTaskIds))continue;if(i!==void 0){if(e.seenTaskDeliveries.has(i))continue;e.seenTaskDeliveries.add(i)}if(t.value.kind===`deliver`){if(e.deferDeliveries===!0){e.bufferedDeliveries.push(t.value);continue}return{delivery:t.value,kind:`delivery`}}let a=sendCommandToDelivery(t.value);if(e.deferDeliveries===!0){e.bufferedDeliveries.push(a);continue}return{delivery:a,kind:`delivery`}}}function isCancelledTaskDelivery(e,t){let n=e.taskDeliveryId??e.caller?.taskId;return n!==void 0&&isCancelledTaskDeliveryId(n,t)}function isCancelledTaskDeliveryId(e,t){return[...t].some(t=>e===t||e.startsWith(`${t}:`))}function takeBufferedTurnDelivery(t){let n=t.shift();if(n===void 0)throw Error(`Cannot take a turn delivery from an empty buffer.`);let r=[n],i=n.caller;for(;t.length>0;){let e=t[0];if(e===void 0||n.taskDeliveryId!==void 0||e.taskDeliveryId!==void 0||i!==void 0&&e.caller!==void 0)break;let a=t.shift();if(a===void 0)throw Error(`Buffered turn delivery disappeared while partitioning.`);r.push(a),i??=a.caller}return coalesceDeliveries(r)}export{nextTurnDelivery};
|
|
@@ -2,33 +2,36 @@ import type { DeliverHookPayload, DeliverPayload, SessionAuthContext } from "#ch
|
|
|
2
2
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
3
|
export type RoutedDeliverResult = {
|
|
4
4
|
readonly kind: "cancel-turn";
|
|
5
|
+
readonly serializedContext: Record<string, unknown>;
|
|
5
6
|
readonly sessionState: DurableSessionState;
|
|
6
7
|
} | {
|
|
7
8
|
readonly kind: "continue";
|
|
8
9
|
readonly remainder: DeliverHookPayload | undefined;
|
|
10
|
+
readonly serializedContext: Record<string, unknown>;
|
|
9
11
|
readonly sessionState: DurableSessionState;
|
|
10
12
|
};
|
|
11
13
|
type LegacyRoutedDeliverResult = {
|
|
12
14
|
readonly kind: "cancel-turn";
|
|
15
|
+
readonly serializedContext: Record<string, unknown>;
|
|
13
16
|
readonly sessionState: DurableSessionState;
|
|
14
17
|
} | {
|
|
15
18
|
readonly kind: "continue";
|
|
16
19
|
readonly remainder: DeliverPayload | undefined;
|
|
20
|
+
readonly serializedContext: Record<string, unknown>;
|
|
17
21
|
readonly sessionState: DurableSessionState;
|
|
18
22
|
};
|
|
19
|
-
/**
|
|
20
|
-
* Splits an inbound deliver payload into parent-local and proxied-child buckets.
|
|
21
|
-
* Successfully forwarded request IDs are retired from the returned snapshot.
|
|
22
|
-
*/
|
|
23
|
+
/** Splits an envelope and validates task routes before forwarding descendant input. */
|
|
23
24
|
export declare function routeProxiedDeliverStep(input: {
|
|
24
25
|
readonly delivery: DeliverHookPayload;
|
|
25
26
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
27
|
+
readonly serializedContext?: Record<string, unknown>;
|
|
26
28
|
readonly sessionState: DurableSessionState;
|
|
27
29
|
}): Promise<RoutedDeliverResult>;
|
|
28
30
|
export declare function routeProxiedDeliverStep(input: {
|
|
29
31
|
readonly auth?: SessionAuthContext | null;
|
|
30
32
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
31
33
|
readonly payload: DeliverPayload;
|
|
34
|
+
readonly serializedContext?: Record<string, unknown>;
|
|
32
35
|
readonly sessionState: DurableSessionState;
|
|
33
36
|
}): Promise<LegacyRoutedDeliverResult>;
|
|
34
37
|
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{resumeHook}from"#internal/workflow/runtime.js";import{createTaskInputRequestId,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{findSessionTaskEntry}from"#tasks/session-index.js";async function routeProxiedDeliverStep(r){"use step";let l=await readDurableSession(r.sessionState),u=!(`delivery`in r),d=`delivery`in r?r.delivery:{auth:r.auth,kind:`deliver`,payloads:[r.payload]},f=new Map,p=new Map,m;for(let[e,t]of d.payloads.entries()){let n=routeDeliverPayload({allowRoute:(e,t)=>t.taskId===void 0||findSessionTaskEntry(l.state,t.taskId)!==void 0,payload:t,state:l.state});m??=n.parentAction,n.forSelf!==void 0&&f.set(e,n.forSelf);for(let[t,r]of n.forChildren.entries()){let i=r.taskId===void 0?r.childContinuationToken:[r.childContinuationToken,r.childResponseUrl??``,r.taskId].join(`\0`),a=p.get(i)??{childContinuationToken:r.childContinuationToken,childResponseUrl:r.childResponseUrl,metadata:[],payloads:[],retireRequestIds:[],sourcePayloadIndexes:[],taskId:r.taskId},o=a.payloads.length;if(a.payloads.push(r.payload),a.retireRequestIds.push(...r.retireRequestIds),a.sourcePayloadIndexes.push(e),n.forSelf===void 0&&t===0)for(let t of d.deliveryMetadata??[])t.payloadIndex===e&&a.metadata.push({...t,payloadIndex:o});p.set(i,a)}}let h=!1;for(let e of p.values()){let t=e.taskId;if(t!==void 0){let n=findSessionTaskEntry(l.state,t);if(n===void 0){mergeStrandedResponses(f,e,t);continue}if(await sendTaskInboundPayload({taskInboxToken:n.taskInboxToken,payload:{auth:d.auth,childContinuationToken:e.childContinuationToken,childResponseUrl:e.childResponseUrl,inputResponses:coalesceDeliverPayloads(e.payloads).inputResponses??[],kind:`input-response`,taskId:t}})===`unreachable`){mergeStrandedResponses(f,e,t);continue}l=retireProxyInputRequests(l,e.retireRequestIds),h=!0;continue}let r={...d,deliveryMetadata:e.metadata.length===0?void 0:e.metadata,payloads:e.payloads};await resumeHook(e.childContinuationToken,{...r,payload:coalesceDeliverPayloads(e.payloads)}),l=retireProxyInputRequests(l,e.retireRequestIds),h=!0}let g={serializedContext:r.serializedContext??{},sessionState:h?replaceDurableSessionSnapshot({session:l,state:r.sessionState}):r.sessionState};if(m!==void 0)return{...g,...m};let _=[...f].sort(([e],[t])=>e-t),v=_.flatMap(([e],t)=>(d.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),y=_.length===0?void 0:u?coalesceDeliverPayloads(_.map(([,e])=>e)):{...d,deliveryMetadata:v.length===0?void 0:v,payloads:_.map(([,e])=>e)};return{...g,kind:`continue`,remainder:y}}function mergeStrandedResponses(e,t,n){for(let[i,a]of t.payloads.entries()){let o=t.sourcePayloadIndexes[i];if(o===void 0)continue;let s=(a.inputResponses??[]).map(e=>({...e,requestId:createTaskInputRequestId(n,e.requestId)}));if(s.length===0)continue;let c=e.get(o);e.set(o,{...c,inputResponses:[...c?.inputResponses??[],...s]})}}export{routeProxiedDeliverStep};
|
|
@@ -3,6 +3,7 @@ import type { HarnessSession } from "#harness/types.js";
|
|
|
3
3
|
import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
|
|
4
4
|
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
|
|
5
5
|
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
|
|
6
|
+
import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
|
|
6
7
|
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
|
|
7
8
|
import type { JsonObject } from "#shared/json.js";
|
|
8
9
|
type RemoteAgentSessionCoordinates = {
|
|
@@ -16,6 +17,12 @@ export declare function startRemoteAgentSession(input: {
|
|
|
16
17
|
readonly callbackToken?: string;
|
|
17
18
|
/** The root initiator's principal, forwarded alongside {@link auth}. */
|
|
18
19
|
readonly initiatorAuth?: SessionAuthContext | null;
|
|
20
|
+
/**
|
|
21
|
+
* Replay-stable identity of this create attempt. A retried dispatch step
|
|
22
|
+
* re-sends the same value, letting the receiver return the child it already
|
|
23
|
+
* created instead of starting a second one.
|
|
24
|
+
*/
|
|
25
|
+
readonly operationId?: string;
|
|
19
26
|
/**
|
|
20
27
|
* Whether the dispatching agent opted into
|
|
21
28
|
* `experimental.subagentPersistentSessions`. Persistent remote children run
|
|
@@ -31,6 +38,7 @@ export declare function continueRemoteAgentSession(input: {
|
|
|
31
38
|
readonly callback: {
|
|
32
39
|
readonly callId: string;
|
|
33
40
|
readonly subagentName: string;
|
|
41
|
+
readonly taskId?: string;
|
|
34
42
|
readonly token: string;
|
|
35
43
|
readonly url: string;
|
|
36
44
|
};
|
|
@@ -45,8 +53,10 @@ export declare function continueRemoteAgentSession(input: {
|
|
|
45
53
|
* with real instances instead of re-encoding the classification.
|
|
46
54
|
*/
|
|
47
55
|
export declare class RemoteAgentContinueRequestError extends Error {
|
|
56
|
+
readonly deliveryAmbiguous: boolean;
|
|
48
57
|
readonly retryable: boolean;
|
|
49
58
|
constructor(message: string, options: {
|
|
59
|
+
readonly deliveryAmbiguous: boolean;
|
|
50
60
|
readonly retryable: boolean;
|
|
51
61
|
});
|
|
52
62
|
}
|
|
@@ -60,9 +70,13 @@ export declare class RemoteAgentContinueRequestError extends Error {
|
|
|
60
70
|
* whose response was lost).
|
|
61
71
|
*/
|
|
62
72
|
export declare function isRetryableRemoteAgentContinueError(error: unknown): boolean;
|
|
73
|
+
/** Whether the callee may have accepted the continuation before delivery failed. */
|
|
74
|
+
export declare function isAmbiguousRemoteAgentContinueError(error: unknown): boolean;
|
|
63
75
|
export declare function cancelRemoteAgentTurn(input: {
|
|
64
76
|
readonly remote: ResolvedRuntimeRemoteAgentNode;
|
|
65
77
|
readonly sessionId: string;
|
|
78
|
+
readonly taskId?: string;
|
|
79
|
+
readonly turnId?: string;
|
|
66
80
|
}): Promise<CancelTurnResult>;
|
|
67
81
|
export declare function isRetryableRemoteAgentCancelError(error: unknown): boolean;
|
|
68
82
|
export declare function resolveRemoteAgentForAction(input: {
|
|
@@ -71,4 +85,22 @@ export declare function resolveRemoteAgentForAction(input: {
|
|
|
71
85
|
readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
|
|
72
86
|
readonly remoteAgentName: string;
|
|
73
87
|
}): ResolvedRuntimeRemoteAgentNode;
|
|
88
|
+
/**
|
|
89
|
+
* Resolves authored outbound headers for a server-authored remote child event.
|
|
90
|
+
*
|
|
91
|
+
* `resolverId` is the key persisted on the `subagent.called` event (see
|
|
92
|
+
* `SubagentCalledStreamEvent`): it identifies the authored credential
|
|
93
|
+
* functions, never their resolved values. Lookup order mirrors how dispatch
|
|
94
|
+
* chose the key — first as a subagent node id (static remote definition),
|
|
95
|
+
* then as a `credentialsStepId` in the step registry (dynamic remote
|
|
96
|
+
* definition). The matched static definition must still agree with the
|
|
97
|
+
* event's `name`/`url`, so a stale or mismatched key fails closed rather
|
|
98
|
+
* than minting headers for the wrong upstream.
|
|
99
|
+
*/
|
|
100
|
+
export declare function resolveRemoteAgentStreamHeaders(input: {
|
|
101
|
+
readonly bundle: CompiledRuntimeAgentBundle;
|
|
102
|
+
readonly name: string;
|
|
103
|
+
readonly resolverId?: string;
|
|
104
|
+
readonly url: string;
|
|
105
|
+
}): Promise<Record<string, string>>;
|
|
74
106
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{createEveCallbackRoutePath,createEveSessionCancelRoutePath,createEveSessionRoutePath}from"#protocol/routes.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{AgentHandleError}from"#protocol/agent-handle-error.js";import{formatTraceparent}from"#protocol/traceparent.js";const CreateSessionResponseSchema=z.object({ok:z.literal(!0),sessionId:z.string().min(1),status:z.literal(`accepted`)});var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.callbackToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let n=buildForwardedPrincipalField(e),i={capabilities:{},callback:{callId:e.action.callId,subagentName:e.action.remoteAgentName,token:t,url:createWorkflowCallbackUrl(e.callbackBaseUrl,createEveCallbackRoutePath(t))},message:formatRemoteAgentCallInputMessage({action:e.action,persistentSession:e.persistentSessions,remote:e.remote}),mode:e.persistentSessions===!0?`conversation`:`task`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};n!==void 0&&(i.forwardedPrincipal=n);let a=await resolveRemoteAgentRequestHeaders(e.remote),o=formatTraceparent(e.parentTraceContext);if(o!==void 0){for(let e of Object.keys(a))e.toLowerCase()===`traceparent`&&delete a[e];a.traceparent=o}let s=await fetch(createRemoteAgentSessionUrl(e.remote),{body:JSON.stringify(i),headers:{"content-type":`application/json`,...a},method:`POST`});if(!s.ok)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session request failed with HTTP ${s.status}.`);let c;try{c=await s.json()}catch{throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was not valid JSON.`)}let l=CreateSessionResponseSchema.safeParse(c);if(!l.success)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was invalid.`);return{sessionId:l.data.sessionId}}async function continueRemoteAgentSession(e){let t=await fetch(createRemoteAgentContinueUrl(e.remote,e.sessionId),{body:JSON.stringify({callback:e.callback,message:e.message,outputSchema:e.outputSchema}),headers:{"content-type":`application/json`,...await resolveRemoteAgentRequestHeaders(e.remote)},method:`POST`});if(!t.ok){let n=await readRemoteAgentErrorCode(t),r=t.status===404||n===AgentHandleError.SessionNotResumable.code;throw new RemoteAgentContinueRequestError(`Remote agent "${e.remote.name}" continue-session request failed${r?` permanently`:``} with HTTP ${t.status}.`,{retryable:!r})}}var RemoteAgentContinueRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentContinueRequestError`,this.retryable=t.retryable}};function isRetryableRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.retryable}async function readRemoteAgentErrorCode(e){let t;try{t=await e.json()}catch{return}if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`code`);return typeof n==`string`?n:void 0}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.status===`accepted`&&i.data.sessionId!==e.sessionId)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was invalid.`,{retryable:!1});return i.data.status===`accepted`?{sessionId:i.data.sessionId,status:`accepted`}:{status:`no_active_turn`}}function isRetryableRemoteAgentCancelError(e){return!(e instanceof RemoteAgentCancelRequestError)||e.retryable}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(e.dynamicRemoteAgent!==void 0){if(t===void 0)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);let n=resolveDynamicRemoteAgentCredentials(e.dynamicRemoteAgent),r=e.dynamicRemoteAgent,i={description:r.description,kind:`remote`,logicalPath:t.logicalPath,name:e.remoteAgentName,nodeId:e.nodeId,outputSchema:r.outputSchema,path:r.path,sourceId:t.sourceId,sourceKind:`module`,url:r.url};return r.forwardPrincipal!==void 0&&(i.forwardPrincipal=r.forwardPrincipal),n.auth!==void 0&&(i.auth=n.auth),n.headers!==void 0&&(i.headers=n.headers),i}if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}function resolveDynamicRemoteAgentCredentials(e){if(e.credentialsStepId===void 0)return{};let r=getStepRegistry().get(e.credentialsStepId);if(r===void 0)throw Error(`Dynamic remote subagent credentials function "${e.credentialsStepId}" is not registered.`);let i=expectObjectRecord(r(),`Dynamic remote subagent credentials are invalid.`),a={};return i.auth!==void 0&&(a.auth=expectFunction(i.auth,`Dynamic remote subagent auth is invalid.`)),i.headers!==void 0&&(a.headers=resolveDynamicRemoteAgentHeaders(i.headers)),a}function resolveDynamicRemoteAgentHeaders(e){if(typeof e==`function`)return e;let t=expectObjectRecord(e,`Dynamic remote subagent headers are invalid.`);for(let e of Object.values(t))if(typeof e!=`string`)throw Error(`Dynamic remote subagent headers are invalid.`);return t}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function createRemoteAgentSessionUrl(e){return createRemoteAgentRouteUrl(e.url,e.path)}function createRemoteAgentCancelTurnUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionCancelRoutePath(t))}function createRemoteAgentContinueUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionRoutePath(t))}function
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{createEveCallbackRoutePath,createEveSessionCancelRoutePath,createEveSessionRoutePath}from"#protocol/routes.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{readTaskIdFromInboxToken}from"#tasks/task-id.js";import{AgentHandleError}from"#protocol/agent-handle-error.js";import{createRemoteAgentRouteUrl}from"#execution/remote-agent-route-url.js";import{formatTraceparent}from"#protocol/traceparent.js";const CreateSessionResponseSchema=z.object({ok:z.literal(!0),sessionId:z.string().min(1),status:z.literal(`accepted`)});var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.callbackToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let n=buildForwardedPrincipalField(e),i={capabilities:{},callback:{callId:e.action.callId,subagentName:e.action.remoteAgentName,taskId:readTaskIdFromInboxToken(t),token:t,url:createWorkflowCallbackUrl(e.callbackBaseUrl,createEveCallbackRoutePath(t))},message:formatRemoteAgentCallInputMessage({action:e.action,persistentSession:e.persistentSessions,remote:e.remote}),mode:e.persistentSessions===!0?`conversation`:`task`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};n!==void 0&&(i.forwardedPrincipal=n),e.operationId!==void 0&&(i.operationId=e.operationId);let a=await resolveRemoteAgentRequestHeaders(e.remote),o=formatTraceparent(e.parentTraceContext);if(o!==void 0){for(let e of Object.keys(a))e.toLowerCase()===`traceparent`&&delete a[e];a.traceparent=o}let s=await fetch(createRemoteAgentSessionUrl(e.remote),{body:JSON.stringify(i),headers:{"content-type":`application/json`,...a},method:`POST`});if(!s.ok)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session request failed with HTTP ${s.status}.`);let c;try{c=await s.json()}catch{throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was not valid JSON.`)}let l=CreateSessionResponseSchema.safeParse(c);if(!l.success)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was invalid.`);return{sessionId:l.data.sessionId}}async function continueRemoteAgentSession(e){let t=await fetch(createRemoteAgentContinueUrl(e.remote,e.sessionId),{body:JSON.stringify({callback:e.callback,message:e.message,outputSchema:e.outputSchema}),headers:{"content-type":`application/json`,...await resolveRemoteAgentRequestHeaders(e.remote)},method:`POST`});if(!t.ok){let n=await readRemoteAgentErrorCode(t),r=t.status===404||n===AgentHandleError.SessionNotResumable.code;throw new RemoteAgentContinueRequestError(`Remote agent "${e.remote.name}" continue-session request failed${r?` permanently`:``} with HTTP ${t.status}.`,{deliveryAmbiguous:isAmbiguousRemoteContinueStatus(t.status),retryable:!r})}}var RemoteAgentContinueRequestError=class extends Error{deliveryAmbiguous;retryable;constructor(e,t){super(e),this.name=`RemoteAgentContinueRequestError`,this.deliveryAmbiguous=t.deliveryAmbiguous,this.retryable=t.retryable}};function isRetryableRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.retryable}function isAmbiguousRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.deliveryAmbiguous}function isAmbiguousRemoteContinueStatus(e){return e===408||e===425||e>=500}async function readRemoteAgentErrorCode(e){let t;try{t=await e.json()}catch{return}if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`code`);return typeof n==`string`?n:void 0}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{body:e.turnId===void 0&&e.taskId===void 0?void 0:JSON.stringify({taskId:e.taskId,turnId:e.turnId}),headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.status===`accepted`&&i.data.sessionId!==e.sessionId)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was invalid.`,{retryable:!1});return i.data.status===`accepted`?{sessionId:i.data.sessionId,status:`accepted`}:{status:`no_active_turn`}}function isRetryableRemoteAgentCancelError(e){return!(e instanceof RemoteAgentCancelRequestError)||e.retryable}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(e.dynamicRemoteAgent!==void 0){if(t===void 0)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);let n=resolveDynamicRemoteAgentCredentials(e.dynamicRemoteAgent),r=e.dynamicRemoteAgent,i={description:r.description,kind:`remote`,logicalPath:t.logicalPath,name:e.remoteAgentName,nodeId:e.nodeId,outputSchema:r.outputSchema,path:r.path,sourceId:t.sourceId,sourceKind:`module`,url:r.url};return r.forwardPrincipal!==void 0&&(i.forwardPrincipal=r.forwardPrincipal),n.auth!==void 0&&(i.auth=n.auth),n.headers!==void 0&&(i.headers=n.headers),i}if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}async function resolveRemoteAgentStreamHeaders(e){if(e.resolverId===void 0)return{};let t=new Set([e.bundle.graph.root,...e.bundle.graph.nodesByNodeId.values()]);for(let n of t){let t=n.subagentRegistry.subagentsByNodeId.get(e.resolverId)?.definition;if(t!==void 0){if(t.kind!==`remote`||t.name!==e.name||t.url!==e.url)throw Error(`Remote child stream resolver does not match the authored remote agent.`);return await resolveRemoteAgentRequestHeaders(t)}}return await resolveRemoteAgentRequestHeaders(resolveDynamicRemoteAgentCredentials({credentialsStepId:e.resolverId,description:``,path:``,url:e.url}))}function resolveDynamicRemoteAgentCredentials(e){if(e.credentialsStepId===void 0)return{};let r=getStepRegistry().get(e.credentialsStepId);if(r===void 0)throw Error(`Dynamic remote subagent credentials function "${e.credentialsStepId}" is not registered.`);let i=expectObjectRecord(r(),`Dynamic remote subagent credentials are invalid.`),a={};return i.auth!==void 0&&(a.auth=expectFunction(i.auth,`Dynamic remote subagent auth is invalid.`)),i.headers!==void 0&&(a.headers=resolveDynamicRemoteAgentHeaders(i.headers)),a}function resolveDynamicRemoteAgentHeaders(e){if(typeof e==`function`)return e;let t=expectObjectRecord(e,`Dynamic remote subagent headers are invalid.`);for(let e of Object.values(t))if(typeof e!=`string`)throw Error(`Dynamic remote subagent headers are invalid.`);return t}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function createRemoteAgentSessionUrl(e){return createRemoteAgentRouteUrl(e.url,e.path)}function createRemoteAgentCancelTurnUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionCancelRoutePath(t))}function createRemoteAgentContinueUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionRoutePath(t))}function isRetryableRemoteCancelStatus(e){return e===408||e===425||e===429||e>=500}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,persistentSession:e.persistentSession,type:`remote`}).message}export{RemoteAgentContinueRequestError,cancelRemoteAgentTurn,continueRemoteAgentSession,isAmbiguousRemoteAgentContinueError,isRetryableRemoteAgentCancelError,isRetryableRemoteAgentContinueError,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders,startRemoteAgentSession};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function createRemoteAgentRouteUrl(e,t){return new URL(t.replace(/^\/+/,``),`${trimTrailingSlash(e)}/`).toString()}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{createRemoteAgentRouteUrl};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { DeliverHookPayload } from "#channel/types.js";
|
|
2
2
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
|
-
import { type RoutedDeliverResult } from "#execution/
|
|
3
|
+
import { type RoutedDeliverResult } from "#execution/proxied-deliver-step.js";
|
|
4
4
|
/**
|
|
5
5
|
* Coalesces inbound deliver payloads and routes any descendant-bound input
|
|
6
6
|
* responses down to the owning child. A descendant session-limit Stop is
|
|
@@ -15,4 +15,5 @@ export declare function routeDeliverToChildren(input: {
|
|
|
15
15
|
readonly delivery: DeliverHookPayload;
|
|
16
16
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
17
17
|
readonly sessionState: DurableSessionState;
|
|
18
|
+
readonly serializedContext: Record<string, unknown>;
|
|
18
19
|
}): Promise<RoutedDeliverResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{routeProxiedDeliverStep}from"#execution/
|
|
1
|
+
import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeProxiedDeliverStep}from"#execution/proxied-deliver-step.js";import{emitRecordedTaskAuthorizationEventStep,emitRecordedTaskInputRequestStep}from"#execution/subagent-event-proxy-step.js";import{acceptTaskAuthorizationEventStep,recordTaskInputRequestStep,recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";async function routeDeliverToChildren(i){let a=coalesceDeliverPayloads(i.delivery.payloads),o=i.serializedContext,s=i.sessionState;(a.task?.views?.length??0)>0&&(s=await recordTerminalTaskViewsStep({sessionState:s,views:a.task?.views??[]}));for(let e of a.task?.inputRequests??[]){let t=await recordTaskInputRequestStep({hookPayload:e.hookPayload,serializedContext:o,sessionState:s,taskId:e.taskId});if(s=t.sessionState,!t.accepted)continue;let n=await emitRecordedTaskInputRequestStep({hookPayload:t.hookPayload,parentWritable:i.parentWritable,serializedContext:o,sessionState:s});o=n.serializedContext,s=n.sessionState}for(let e of a.task?.authorizationEvents??[]){if(!await acceptTaskAuthorizationEventStep({hookPayload:e.hookPayload,sessionState:s,taskId:e.taskId}))continue;let t=await emitRecordedTaskAuthorizationEventStep({hookPayload:e.hookPayload,parentWritable:i.parentWritable,serializedContext:o,sessionState:s});o=t.serializedContext,s=t.sessionState}let c=[],l=[];for(let[e,t]of i.delivery.payloads.entries()){let n={...t};if(delete n.task,Object.keys(n).length===0)continue;let r=c.length;c.push(n);for(let t of i.delivery.deliveryMetadata??[])t.payloadIndex===e&&l.push({...t,payloadIndex:r})}let u=c.length===0?void 0:{...i.delivery,deliveryMetadata:l.length===0?void 0:l,payloads:c};return u===void 0?{kind:`continue`,remainder:void 0,serializedContext:o,sessionState:s}:s.hasProxyInputRequests?await routeProxiedDeliverStep({delivery:u,parentWritable:i.parentWritable,serializedContext:o,sessionState:s}):{kind:`continue`,remainder:u,serializedContext:o,sessionState:s}}export{routeDeliverToChildren};
|
|
@@ -1,4 +1,15 @@
|
|
|
1
|
+
import type { SubagentAuthorizationEvent } from "#channel/types.js";
|
|
1
2
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
3
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
4
|
+
/** Sends task-owned remote HITL and authorization events to the parent callback capability. */
|
|
5
|
+
export declare function fireTaskEventCallbackStep(input: {
|
|
6
|
+
readonly callback: unknown;
|
|
7
|
+
readonly childContinuationToken: string;
|
|
8
|
+
readonly childSessionId: string;
|
|
9
|
+
readonly event: SubagentAuthorizationEvent | Extract<UnstampedMessageStreamEvent, {
|
|
10
|
+
type: "input.requested";
|
|
11
|
+
}>;
|
|
12
|
+
}): Promise<void>;
|
|
2
13
|
/**
|
|
3
14
|
* Sends the configured session terminal callback.
|
|
4
15
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{SESSION_FAILED}from"#harness/agent-handle-errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{SESSION_FAILED}from"#harness/agent-handle-errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function fireTaskEventCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=e.event.type===`input.requested`,r=n?`task.input-requested`:`task.authorization`,i=await postSessionCallbackRequest({body:{callId:t.callId,childContinuationToken:e.childContinuationToken,childSessionId:e.childSessionId,event:n?e.event.data:e.event,kind:r,subagentName:t.subagentName,taskId:t.taskId},url:t.url});if(!i.ok)throw Error(`Task event callback failed with HTTP ${i.status}.`)}async function fireSessionCallbackStep(e){"use step";let i=e.serializedContext[`eve.sessionId`]??``,o=e.serializedContext[SessionCallbackKey.name];if(o!==void 0)try{let t=parseSerializedSessionCallback(o),a=await postSessionCallbackRequest({body:e.status===`completed`?buildCompletedCallbackBody({callback:t,output:e.output,sessionId:i,usage:e.usage}):{callId:t.callId,error:{code:SESSION_FAILED,message:toErrorMessage(e.error)},kind:`session.failed`,sessionId:i,subagentName:t.subagentName,usage:e.usage},url:t.url});if(!a.ok)throw Error(`Session callback failed with HTTP ${a.status}.`)}catch(e){throw log.error(`failed to post session callback`,{error:e,sessionId:i}),e}}function buildCompletedCallbackBody(e){let t={callId:e.callback.callId,kind:`session.completed`,output:e.output??``,sessionId:e.sessionId,subagentName:e.callback.subagentName};return e.usage===void 0?t:{...t,usage:e.usage}}function parseSerializedSessionCallback(e){let t=parseSessionCallback(e);if(!t.ok)throw Error(`Serialized session callback is invalid.`,{cause:t.cause});return t.callback}export{fireSessionCallbackStep,fireTaskEventCallbackStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function sendCommandToDelivery(e){return{auth:e.auth,caller:e.caller,deliveryMetadata:e.delivery===void 0?void 0:[{...e.delivery,payloadIndex:0}],kind:`deliver`,payload:e.payload,payloads:[e.payload],requestId:e.requestId,turnPolicy:e.turnPolicy}}export{sendCommandToDelivery};
|
|
1
|
+
function sendCommandToDelivery(e){return{auth:e.auth,caller:e.caller,deliveryMetadata:e.delivery===void 0?void 0:[{...e.delivery,payloadIndex:0}],kind:`deliver`,payload:e.payload,payloads:[e.payload],requestId:e.requestId,taskDeliveryId:e.taskDeliveryId,turnPolicy:e.turnPolicy}}export{sendCommandToDelivery};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
+
/** A durable-state transition; absent fields keep the cursor's current value. */
|
|
3
|
+
export interface SessionStateTransition {
|
|
4
|
+
readonly serializedContext?: Record<string, unknown>;
|
|
5
|
+
readonly sessionState?: DurableSessionState;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Owns the mutable serialized-context / session-state pair that durable
|
|
9
|
+
* steps thread through a run. Holders adopt each step's transition instead
|
|
10
|
+
* of rebinding both values by hand at every callsite.
|
|
11
|
+
*/
|
|
12
|
+
export declare class SessionStateCursor {
|
|
13
|
+
private currentSerializedContext;
|
|
14
|
+
private currentSessionState;
|
|
15
|
+
constructor(input: {
|
|
16
|
+
readonly serializedContext: Record<string, unknown>;
|
|
17
|
+
readonly sessionState: DurableSessionState;
|
|
18
|
+
});
|
|
19
|
+
/** Latest adopted serialized runtime context. */
|
|
20
|
+
get serializedContext(): Record<string, unknown>;
|
|
21
|
+
/** Latest adopted durable session state. */
|
|
22
|
+
get sessionState(): DurableSessionState;
|
|
23
|
+
/** Adopts a state transition; fields a step did not change carry forward. */
|
|
24
|
+
adoptState(transition: SessionStateTransition): void;
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var SessionStateCursor=class{currentSerializedContext;currentSessionState;constructor(e){this.currentSerializedContext=e.serializedContext,this.currentSessionState=e.sessionState}get serializedContext(){return this.currentSerializedContext}get sessionState(){return this.currentSessionState}adoptState(e){this.currentSerializedContext=e.serializedContext??this.currentSerializedContext,this.currentSessionState=e.sessionState??this.currentSessionState}};export{SessionStateCursor};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
+
import type { TokenUsage } from "#shared/token-usage.js";
|
|
2
3
|
export interface CancelledTurnSettleResult {
|
|
3
4
|
readonly serializedContext: Record<string, unknown>;
|
|
4
5
|
readonly sessionState: DurableSessionState;
|
|
6
|
+
readonly usage?: TokenUsage;
|
|
5
7
|
}
|
|
6
8
|
/**
|
|
7
9
|
* Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler}from"#channel/adapter.js";import{ChannelInstrumentationKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{abandonRunningAgentTurns}from"#harness/handles/transitions.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{
|
|
1
|
+
import{callAdapterEventHandler}from"#channel/adapter.js";import{ChannelInstrumentationKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{abandonRunningAgentTurns}from"#harness/handles/transitions.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation/native-events.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";async function settleCancelledTurnStep(a){"use step";let o=await readDurableSession(a.sessionState),s=await deserializeContext(a.serializedContext),c=s.require(ChannelKey),l=buildAdapterContext(c,s),u=s.require(BundleKey),d=resolveEffectiveAgentRuntime(u,s),f=getInstrumentationRuntime(),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:o,turnAgent:d.turnAgent}),m=getHarnessEmissionState(o.state),h=[...getProxyInputRequests(o.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(p)&&hasProxyInputRequests(o.state)&&!h)){let n=a.parentWritable.getWriter();try{let r=await withContextScope(s,p,async r=>{let baseEmit=async t=>{let r=await callAdapterEventHandler(c,t,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await n.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.turnAgent.id,channelKind:s.get(ChannelInstrumentationKey)?.kind,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m),session:r}});m=r.result,p=r.session}finally{await f?.forceFlush(),n.releaseLock()}}let g=reconcileSessionContinuationToken(s,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(abandonRunningAgentTurns(p))))),m)),_=getTurnUsageState(p.state)?.session,v={serializedContext:serializeContext(s),sessionState:createDurableSessionState({session:g})};return _===void 0?v:{...v,usage:toUsage(_)}}export{settleCancelledTurnStep};
|
|
@@ -13,11 +13,26 @@ export declare function runProxySubagentEventStep(input: {
|
|
|
13
13
|
readonly serializedContext: Record<string, unknown>;
|
|
14
14
|
readonly sessionState: DurableSessionState;
|
|
15
15
|
}): Promise<ProxySubagentEventResult>;
|
|
16
|
+
/** Emits a task request whose proxy routes were committed by a prior step. */
|
|
17
|
+
export declare function emitRecordedTaskInputRequestStep(input: {
|
|
18
|
+
readonly hookPayload: SubagentInputRequestHookPayload;
|
|
19
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
20
|
+
readonly serializedContext: Record<string, unknown>;
|
|
21
|
+
readonly sessionState: DurableSessionState;
|
|
22
|
+
}): Promise<ProxySubagentEventResult>;
|
|
23
|
+
/** Emits a task authorization event after its ownership was validated. */
|
|
24
|
+
export declare function emitRecordedTaskAuthorizationEventStep(input: {
|
|
25
|
+
readonly hookPayload: SubagentAuthorizationEventHookPayload;
|
|
26
|
+
readonly parentWritable: WritableStream<Uint8Array>;
|
|
27
|
+
readonly serializedContext: Record<string, unknown>;
|
|
28
|
+
readonly sessionState: DurableSessionState;
|
|
29
|
+
}): Promise<ProxySubagentEventResult>;
|
|
16
30
|
/** Applies one proxied child event to an already-hydrated parent context. */
|
|
17
31
|
export declare function emitProxiedSubagentEvent(input: {
|
|
18
32
|
readonly ctx: ContextContainer;
|
|
19
33
|
readonly durableSession: DurableSession;
|
|
20
34
|
readonly hookPayload: SubagentEventHookPayload;
|
|
21
35
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
36
|
+
readonly recordProxyInputRequests?: boolean;
|
|
22
37
|
}): Promise<ProxySubagentEventResult>;
|
|
23
38
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler}from"#channel/adapter.js";import{ModeKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{emitProxiedInputRequest}from"#execution/subagent-hitl-proxy.js";import{setChannelContext}from"#execution/channel-context.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";async function runProxySubagentEventStep(e){"use step";let t=await readDurableSession(e.sessionState);return emitProxiedSubagentEvent({ctx:await deserializeContext(e.serializedContext),durableSession:t,hookPayload:e.hookPayload,parentWritable:e.parentWritable})}async function emitProxiedSubagentEvent(i){let{ctx:a}=i,o=a.require(ChannelKey),s=resolveEffectiveAgentRuntime(a.require(BundleKey),a),c=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.thresholdPercent},durable:i.durableSession,turnAgent:s.turnAgent}),l=buildAdapterContext(o,a),u=i.parentWritable.getWriter(),d,f;try{let emit=async t=>{let r=await callAdapterEventHandler(o,t,l);await u.write(encodeMessageStreamEvent(stampMessageStreamEvent(r)))},r=await withContextScope(a,c,async e=>{if(i.hookPayload.kind===`subagent-authorization-event`)return await emit(i.hookPayload.event),{result:void 0,session:e};let n=await emitProxiedInputRequest({emit,hookPayload:i.hookPayload,mode:a.require(ModeKey),session:e});return{result:n.entries,session:n.session}});d=r.result,f=r.session}finally{u.releaseLock()}setChannelContext(a,{...o,state:{...l.state}}),d!==void 0&&i.hookPayload.kind===`subagent-input-request`&&(f=upsertProxyInputRequests({entries:d,forChildContinuationToken:i.hookPayload.childContinuationToken,session:f}));let p=reconcileSessionContinuationToken(a,f);return{serializedContext:serializeContext(a),sessionState:createDurableSessionState({session:p})}}export{emitProxiedSubagentEvent,runProxySubagentEventStep};
|
|
1
|
+
import{callAdapterEventHandler}from"#channel/adapter.js";import{ModeKey}from"#context/keys.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{emitProxiedInputRequest}from"#execution/subagent-hitl-proxy.js";import{setChannelContext}from"#execution/channel-context.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";async function runProxySubagentEventStep(e){"use step";let t=await readDurableSession(e.sessionState);return emitProxiedSubagentEvent({ctx:await deserializeContext(e.serializedContext),durableSession:t,hookPayload:e.hookPayload,parentWritable:e.parentWritable})}async function emitRecordedTaskInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState);return emitProxiedSubagentEvent({ctx:await deserializeContext(e.serializedContext),durableSession:t,hookPayload:e.hookPayload,parentWritable:e.parentWritable,recordProxyInputRequests:!1})}async function emitRecordedTaskAuthorizationEventStep(e){"use step";let t=await readDurableSession(e.sessionState);return emitProxiedSubagentEvent({ctx:await deserializeContext(e.serializedContext),durableSession:t,hookPayload:e.hookPayload,parentWritable:e.parentWritable,recordProxyInputRequests:!1})}async function emitProxiedSubagentEvent(i){let{ctx:a}=i,o=a.require(ChannelKey),s=resolveEffectiveAgentRuntime(a.require(BundleKey),a),c=hydrateDurableSession({compactionOverrides:{thresholdPercent:s.thresholdPercent},durable:i.durableSession,turnAgent:s.turnAgent}),l=buildAdapterContext(o,a),u=i.parentWritable.getWriter(),d,f;try{let emit=async t=>{let r=await callAdapterEventHandler(o,t,l);await u.write(encodeMessageStreamEvent(stampMessageStreamEvent(r)))},r=await withContextScope(a,c,async e=>{if(i.hookPayload.kind===`subagent-authorization-event`)return await emit(i.hookPayload.event),{result:void 0,session:e};let n=await emitProxiedInputRequest({emit,hookPayload:i.hookPayload,mode:a.require(ModeKey),session:e});return{result:n.entries,session:n.session}});d=r.result,f=r.session}finally{u.releaseLock()}setChannelContext(a,{...o,state:{...l.state}}),i.recordProxyInputRequests!==!1&&d!==void 0&&i.hookPayload.kind===`subagent-input-request`&&(f=upsertProxyInputRequests({entries:d,forChildContinuationToken:i.hookPayload.childContinuationToken,session:f}));let p=reconcileSessionContinuationToken(a,f);return{serializedContext:serializeContext(a),sessionState:createDurableSessionState({session:p})}}export{emitProxiedSubagentEvent,emitRecordedTaskAuthorizationEventStep,emitRecordedTaskInputRequestStep,runProxySubagentEventStep};
|
|
@@ -17,19 +17,25 @@ export declare function emitProxiedInputRequest(input: {
|
|
|
17
17
|
readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
|
|
18
18
|
readonly session: HarnessSession;
|
|
19
19
|
}>;
|
|
20
|
+
/** One proxied-child bucket of a routed deliver payload. */
|
|
21
|
+
export interface RoutedChildDelivery {
|
|
22
|
+
readonly childContinuationToken: string;
|
|
23
|
+
readonly childResponseUrl?: string;
|
|
24
|
+
readonly payload: {
|
|
25
|
+
readonly inputResponses: readonly InputResponse[];
|
|
26
|
+
};
|
|
27
|
+
/** Parent-visible request IDs safe to retire once this bucket is forwarded. */
|
|
28
|
+
readonly retireRequestIds: readonly string[];
|
|
29
|
+
/** Present when the child is owned by a task run, which delivers on the parent's behalf. */
|
|
30
|
+
readonly taskId?: string;
|
|
31
|
+
}
|
|
20
32
|
/**
|
|
21
33
|
* Outcome of splitting one deliver payload by the session's proxy map.
|
|
22
34
|
* `forSelf` is the parent-local remainder (or `undefined` when fully
|
|
23
35
|
* routed); `forChildren` carries one entry per descendant token.
|
|
24
36
|
*/
|
|
25
37
|
export interface RoutedDeliverPayload {
|
|
26
|
-
readonly forChildren: readonly
|
|
27
|
-
readonly childContinuationToken: string;
|
|
28
|
-
readonly payload: {
|
|
29
|
-
readonly inputResponses: readonly InputResponse[];
|
|
30
|
-
};
|
|
31
|
-
readonly retireRequestIds: readonly string[];
|
|
32
|
-
}[];
|
|
38
|
+
readonly forChildren: readonly RoutedChildDelivery[];
|
|
33
39
|
readonly forSelf: DeliverPayload | undefined;
|
|
34
40
|
readonly parentAction: {
|
|
35
41
|
readonly kind: "cancel-turn";
|
|
@@ -37,6 +43,7 @@ export interface RoutedDeliverPayload {
|
|
|
37
43
|
}
|
|
38
44
|
/** Splits a deliver payload into parent-local and proxied-child buckets. */
|
|
39
45
|
export declare function routeDeliverPayload(input: {
|
|
46
|
+
readonly allowRoute?: (requestId: string, route: ProxyInputRequest) => boolean;
|
|
40
47
|
readonly payload: DeliverPayload;
|
|
41
48
|
readonly state: SessionStateMap | undefined;
|
|
42
49
|
}): RoutedDeliverPayload;
|