eve 0.33.0 → 0.33.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 +10 -0
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +3 -9
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +5 -0
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/parked-delivery-wait.d.ts +8 -0
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +1 -0
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +4 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/hitl/approval-input-requests.d.ts +13 -0
- package/dist/src/harness/hitl/approval-input-requests.js +1 -0
- package/dist/src/harness/hitl/pending-input-resolution.d.ts +51 -0
- package/dist/src/harness/hitl/pending-input-resolution.js +1 -0
- package/dist/src/harness/hitl/question-input-requests.d.ts +15 -0
- package/dist/src/harness/hitl/question-input-requests.js +1 -0
- package/dist/src/harness/hitl/session-limit-input-requests.d.ts +10 -0
- package/dist/src/harness/hitl/session-limit-input-requests.js +1 -0
- package/dist/src/harness/input-requests.d.ts +17 -105
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/pending-input-batches.d.ts +77 -0
- package/dist/src/harness/pending-input-batches.js +1 -0
- package/dist/src/harness/proxy-input-requests.d.ts +13 -3
- package/dist/src/harness/proxy-input-requests.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/internal/application/package.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +9 -0
- package/dist/src/setup/scaffold/create/web-template.js +291 -1
- package/dist/src/setup/scaffold/index.d.ts +1 -1
- package/dist/src/setup/scaffold/update/channels.d.ts +4 -13
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/web-options.d.ts +15 -0
- package/dist/src/setup/scaffold/update/web-options.js +1 -0
- package/dist/src/setup/vercel-project.js +0 -0
- package/docs/concepts/sessions-runs-and-streaming.md +4 -4
- package/docs/guides/frontend/overview.mdx +31 -10
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +37 -15
- package/docs/guides/frontend/use-eve-agent-vue.mdx +38 -15
- package/docs/tools/human-in-the-loop.md +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.33.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 7dd64d3: Messages no longer wait behind pending tool approvals: a follow-up message now runs as an ordinary turn while the approval stays open and answerable, and a later structured answer still resolves the original tool call. Pending HITL batches are stored as an ordered collection, so a turn that runs while an approval is open can raise its own requests without overwriting it; multiple approval answers delivered together resume safely in order. Sessions wedged by the old deferral release the held message on their next delivery.
|
|
8
|
+
- b1ce580: Add an opt-in Sign in with Vercel authentication variant for programmatically scaffolded Web Chat apps.
|
|
9
|
+
- 7dd64d3: Keep task runs parked when unrelated messages arrive while tool approvals remain open, and resolve later text approval responses before replaying deferred messages. Invalid persisted input request kinds now fail closed.
|
|
10
|
+
- e402672: Keep follow-up subagent dispatches in the active parent turn when a resumed runtime-action batch has lost its turn ID, preventing the session from failing while persisting the child handle.
|
|
11
|
+
- 8d6afc3: Scope Vercel CLI authentication checks to an existing linked team project, preventing an unrelated default CLI scope from blocking integration setup.
|
|
12
|
+
|
|
3
13
|
## 0.33.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
|
@@ -1,13 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* The batch is classified into a dispatch plan first (reject / resume /
|
|
6
|
-
* start), then each entry dispatches and emits one
|
|
7
|
-
* parent `subagent.called` control-plane event through a single tail.
|
|
8
|
-
* Every start commits an agent handle (`starting`) before its side effect
|
|
9
|
-
* and confirms it (`running`) once the child reports coordinates, so the
|
|
10
|
-
* returned snapshot-bearing state owns every child it may have created.
|
|
2
|
+
* Dispatches every pending runtime action for a parked parent session.
|
|
3
|
+
* Starts commit ownership before their side effect, so the returned state
|
|
4
|
+
* owns every child it may have created.
|
|
11
5
|
*/
|
|
12
6
|
import type { RuntimeSubagentResult } from "#runtime/actions/types.js";
|
|
13
7
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
@@ -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}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{readSessionTraceContext}from"#tracing/agent-trace-context-store.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),p=getPendingRuntimeActionBatch(s.state);if(p===void 0||p.actions.length===0)return{results:[],sessionState:e.sessionState};let m=await deserializeContext(e.serializedContext),h=m.require(BundleKey),g=resolveEffectiveAgentRuntime(h,m),_=hydrateDurableSession({compactionOverrides:{thresholdPercent:g.thresholdPercent},durable:s,turnAgent:g.turnAgent}),v=m.require(ChannelKey),y=m.get(AuthKey)??null,b=m.get(CapabilitiesKey),x=m.get(ChannelInstrumentationKey),S=m.get(InitiatorAuthKey)??null,C=buildAdapterContext(v,m),w=readSessionTraceContext(e.serializedContext,_.sessionId),T=h.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0;getAgentHandleStore(s.state);let E=planDispatch({actions:p.actions,bundle:h,ctx:m,session:_}),D=e.parentWritable.getWriter(),O=E.filter(e=>e.kind===`start`&&e.target.kind===`local`).length,k=_,A=[];try{for(let r of E){if(r.kind===`reject`){A.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:h,dynamicRemoteAgent:r.dynamicRemoteAgent}),currentSession:k,parentToken:e.parentContinuationToken??_.continuationToken,parentTurnId:p.event.turnId});break;case`start`:i=await startSubagent({auth:y,batchEvent:p.event,bundle:h,callbackBaseUrl:e.callbackBaseUrl,capabilities:b,channelMetadata:x,currentSession:k,fanoutSize:O,initiatorAuth:S,parentContinuationToken:e.parentContinuationToken,parentTraceContext:w,persistentSessions:T,session:_,target:r.target});break}if(k=i.session,i.kind===`error`){A.push(i.result);continue}try{let e=await callAdapterEventHandler(v,createSubagentCalledEvent({callId:i.callId,childSessionId:i.address.sessionId,name:i.name,remote:i.address.kind===`agent/remote`?{url:i.address.url}:void 0,sequence:p.event.sequence,sessionId:_.sessionId,toolName:i.toolName,turnId:p.event.turnId,workflowId:workflowEntryReference.workflowId}),C);await D.write(encodeMessageStreamEvent(stampMessageStreamEvent(e)))}catch(e){logError(log,`subagent.called emission failed`,e,{callId:i.callId,childSessionId:i.address.sessionId,toolName:i.toolName})}}}finally{D.releaseLock()}return{results:A,sessionState:k===_?e.sessionState:createDurableSessionState({session:k})}}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,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,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{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{readSessionTraceContext}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=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: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,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,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};
|
|
@@ -115,3 +115,8 @@ export declare function readDurableSession(state: DurableSessionState): Promise<
|
|
|
115
115
|
export declare function createDurableSessionState(input: {
|
|
116
116
|
readonly session: HarnessSession;
|
|
117
117
|
}): DurableSessionState;
|
|
118
|
+
/** Replaces the embedded session while preserving additive snapshot fields. */
|
|
119
|
+
export declare function replaceDurableSessionSnapshot(input: {
|
|
120
|
+
readonly session: DurableSession;
|
|
121
|
+
readonly state: DurableSessionState;
|
|
122
|
+
}): DurableSessionState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getHarnessEmissionState}from"#harness/emission.js";import{projectToDurableSession}from"#execution/session.js";import{getRun}from"#internal/workflow/runtime.js";import{hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{migrateDurableSessionSnapshot}from"#execution/durable-session-migrations/snapshot.js";const EVE_SESSION_STREAM_NAMESPACE=`eve.session`,DURABLE_SESSION_VERSION=1,DURABLE_SESSION_READ_TIMEOUT_MS=1e4;function projectSessionState(t){return{continuationToken:t.session.continuationToken,emissionState:getHarnessEmissionState(t.session.state),hasProxyInputRequests:hasProxyInputRequests(t.session.state),sessionId:t.session.sessionId,version:1}}async function readDurableSession(e){if(e.snapshot!==void 0)return migrateDurableSessionSnapshot(e.snapshot).session;let t=getRun(e.sessionId).getReadable({namespace:EVE_SESSION_STREAM_NAMESPACE,startIndex:-1}).getReader(),r=`eve durable session tail read failed`,i;try{let n=await Promise.race([t.read().then(e=>({kind:`read`,read:e})),new Promise(e=>{i=setTimeout(()=>e({kind:`timeout`}),DURABLE_SESSION_READ_TIMEOUT_MS)})]);if(n.kind===`timeout`)throw r=`eve durable session tail read timed out after ${DURABLE_SESSION_READ_TIMEOUT_MS}ms`,new DurableSessionReadTimeoutError(e);if(n.read.done||n.read.value===void 0)throw r=`eve durable session tail read returned no snapshot`,Error(`No durable session snapshot found in stream "${EVE_SESSION_STREAM_NAMESPACE}" for run ${e.sessionId}.`);return r=`eve durable session tail read complete`,migrateDurableSessionSnapshot(n.read.value).session}finally{i!==void 0&&clearTimeout(i),await t.cancel(r).catch(()=>{}),t.releaseLock()}}var DurableSessionReadTimeoutError=class extends Error{constructor(e){super(`Timed out reading durable session snapshot from stream "${EVE_SESSION_STREAM_NAMESPACE}" for run ${e.sessionId} after ${DURABLE_SESSION_READ_TIMEOUT_MS}ms.`),this.name=`DurableSessionReadTimeoutError`}};function createDurableSessionState(e){let n={session:projectToDurableSession(e.session),version:1};return{...projectSessionState({session:e.session}),snapshot:n}}export{DURABLE_SESSION_VERSION,createDurableSessionState,projectSessionState,readDurableSession};
|
|
1
|
+
import{getHarnessEmissionState}from"#harness/emission.js";import{projectToDurableSession}from"#execution/session.js";import{getRun}from"#internal/workflow/runtime.js";import{hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{migrateDurableSessionSnapshot}from"#execution/durable-session-migrations/snapshot.js";const EVE_SESSION_STREAM_NAMESPACE=`eve.session`,DURABLE_SESSION_VERSION=1,DURABLE_SESSION_READ_TIMEOUT_MS=1e4;function projectSessionState(t){return{continuationToken:t.session.continuationToken,emissionState:getHarnessEmissionState(t.session.state),hasProxyInputRequests:hasProxyInputRequests(t.session.state),sessionId:t.session.sessionId,version:1}}async function readDurableSession(e){if(e.snapshot!==void 0)return migrateDurableSessionSnapshot(e.snapshot).session;let t=getRun(e.sessionId).getReadable({namespace:EVE_SESSION_STREAM_NAMESPACE,startIndex:-1}).getReader(),r=`eve durable session tail read failed`,i;try{let n=await Promise.race([t.read().then(e=>({kind:`read`,read:e})),new Promise(e=>{i=setTimeout(()=>e({kind:`timeout`}),DURABLE_SESSION_READ_TIMEOUT_MS)})]);if(n.kind===`timeout`)throw r=`eve durable session tail read timed out after ${DURABLE_SESSION_READ_TIMEOUT_MS}ms`,new DurableSessionReadTimeoutError(e);if(n.read.done||n.read.value===void 0)throw r=`eve durable session tail read returned no snapshot`,Error(`No durable session snapshot found in stream "${EVE_SESSION_STREAM_NAMESPACE}" for run ${e.sessionId}.`);return r=`eve durable session tail read complete`,migrateDurableSessionSnapshot(n.read.value).session}finally{i!==void 0&&clearTimeout(i),await t.cancel(r).catch(()=>{}),t.releaseLock()}}var DurableSessionReadTimeoutError=class extends Error{constructor(e){super(`Timed out reading durable session snapshot from stream "${EVE_SESSION_STREAM_NAMESPACE}" for run ${e.sessionId} after ${DURABLE_SESSION_READ_TIMEOUT_MS}ms.`),this.name=`DurableSessionReadTimeoutError`}};function createDurableSessionState(e){let n={session:projectToDurableSession(e.session),version:1};return{...projectSessionState({session:e.session}),snapshot:n}}function replaceDurableSessionSnapshot(t){return{...t.state,continuationToken:t.session.continuationToken,emissionState:getHarnessEmissionState(t.session.state),hasProxyInputRequests:hasProxyInputRequests(t.session.state),sessionId:t.session.sessionId,version:1,snapshot:{...t.state.snapshot,session:t.session,version:1}}}export{DURABLE_SESSION_VERSION,createDurableSessionState,projectSessionState,readDurableSession,replaceDurableSessionSnapshot};
|
|
@@ -7,24 +7,32 @@ export interface AuthorizationCallbackInstruction {
|
|
|
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;
|
|
10
11
|
}
|
|
11
12
|
/** What the parked driver should do with the next session activity. */
|
|
12
13
|
export type NextTurnInstruction = {
|
|
13
14
|
readonly kind: "clear";
|
|
15
|
+
readonly sessionState: DurableSessionState;
|
|
14
16
|
} | {
|
|
15
17
|
readonly kind: "compact";
|
|
18
|
+
readonly sessionState: DurableSessionState;
|
|
16
19
|
} | {
|
|
17
20
|
readonly kind: "expired";
|
|
21
|
+
readonly sessionState: DurableSessionState;
|
|
18
22
|
} | {
|
|
19
23
|
readonly kind: "reset";
|
|
24
|
+
readonly sessionState: DurableSessionState;
|
|
20
25
|
} | {
|
|
21
26
|
readonly kind: "closed";
|
|
27
|
+
readonly sessionState: DurableSessionState;
|
|
22
28
|
} | {
|
|
23
29
|
readonly kind: "cancel-turn";
|
|
30
|
+
readonly sessionState: DurableSessionState;
|
|
24
31
|
} | AuthorizationCallbackInstruction | {
|
|
25
32
|
readonly kind: "turn";
|
|
26
33
|
readonly deliver: DeliverHookPayload;
|
|
27
34
|
readonly remainder: DeliverPayload;
|
|
35
|
+
readonly sessionState: DurableSessionState;
|
|
28
36
|
};
|
|
29
37
|
/**
|
|
30
38
|
* Awaits the next delivery that requires driver action while the session
|
|
@@ -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){for(;;){let
|
|
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.sessionState;for(;;){let r=await waitForNextSessionAction({bufferedDeliveries:e.bufferedDeliveries,bufferedSessionControls:e.bufferedSessionControls,commandInbox:e.commandInbox,deferDeliveries:e.deferDeliveries});if(r.kind===`authorization`)return{...r,sessionState:n};if(r.kind!==`delivery`)return{kind:r.kind,sessionState:n};let i=r.delivery;if(i===null)return{kind:`closed`,sessionState:n};let a=await routeDeliverToChildren({auth:i.auth,parentWritable:e.driverWritable,payloads:i.payloads,sessionState:n});if(n=a.sessionState,a.kind===`cancel-turn`)return{kind:`cancel-turn`,sessionState:n};if(a.remainder!==void 0)return{deliver:i,kind:`turn`,remainder:a.remainder,sessionState:n}}}async function waitForNextSessionAction(e){let t=e.bufferedSessionControls.shift();if(t!==void 0)return{kind:t};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`)continue;if(t.value.kind===`deliver`){if(e.deferDeliveries===!0){e.bufferedDeliveries.push(t.value);continue}return{delivery:t.value,kind:`delivery`}}let i=sendCommandToDelivery(t.value);if(e.deferDeliveries===!0){e.bufferedDeliveries.push(i);continue}return{delivery:i,kind:`delivery`}}}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||i!==void 0&&e.caller!==void 0)break;let n=t.shift();if(n===void 0)throw Error(`Buffered turn delivery disappeared while partitioning.`);r.push(n),i??=n.caller}return coalesceDeliveries(r)}export{nextTurnDelivery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeProxiedDeliverStep}from"#execution/workflow-steps.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.payloads);return e.sessionState.hasProxyInputRequests?await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState}):{kind:`continue`,remainder:t}}export{routeDeliverToChildren};
|
|
1
|
+
import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeProxiedDeliverStep}from"#execution/workflow-steps.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.payloads);return e.sessionState.hasProxyInputRequests?await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState}):{kind:`continue`,remainder:t,sessionState:e.sessionState}}export{routeDeliverToChildren};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler}from"#channel/adapter.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{
|
|
1
|
+
import{callAdapterEventHandler}from"#channel/adapter.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{activeTurnId}from"#harness/active-turn-id.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{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation-native-events.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 t=a.parentWritable.getWriter();try{let n=await withContextScope(s,p,async n=>{let baseEmit=async n=>{let r=await callAdapterEventHandler(c,n,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await t.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.turnAgent.id,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m),session:n}});m=n.result,p=n.session}finally{await f?.forceFlush(),t.releaseLock()}}let g=reconcileSessionContinuationToken(s,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(abandonRunningAgentTurns(p))))),m));return{serializedContext:serializeContext(s),sessionState:createDurableSessionState({session:g})}}export{settleCancelledTurnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/session-limit-continuation.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[],s;for(let e of n){let n=t.get(e.requestId);if(n===void 0){a.push(e);continue}n.kind===`session-limit`&&e.optionId===SESSION_LIMIT_STOP_OPTION_ID&&(s={kind:`cancel-turn`});let i=r.get(n.childContinuationToken);i===void 0?r.set(n.childContinuationToken,[e]):i.push(e)}let c=[...r.entries()].map(([e,
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitTurnEpilogue,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{getProxyInputRequests,toProxyInputRequestEntries}from"#harness/proxy-input-requests.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/session-limit-continuation.js";async function emitProxiedInputRequest(i){await i.emit(createInputRequestedEvent({requests:i.hookPayload.event.requests,sequence:i.hookPayload.event.sequence,stepIndex:i.hookPayload.event.stepIndex,turnId:i.hookPayload.event.turnId}));let o=i.session;if(i.mode===`conversation`){let e=getHarnessEmissionState(i.session.state),a=await emitTurnEpilogue(i.emit,e,i.mode);o=setHarnessEmissionState(i.session,a)}return{entries:toProxyInputRequestEntries(i.hookPayload),session:o}}function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),n=e.payload.inputResponses??[],r=new Map,a=[],s;for(let e of n){let n=t.get(e.requestId);if(n===void 0){a.push(e);continue}n.kind===`session-limit`&&e.optionId===SESSION_LIMIT_STOP_OPTION_ID&&(s={kind:`cancel-turn`});let i=r.get(n.childContinuationToken);i===void 0?r.set(n.childContinuationToken,{responses:[e],routes:[n]}):(i.responses.push(e),i.routes.push(n))}let c=[...r.entries()].map(([e,n])=>{let r=new Set(n.responses.map(e=>e.requestId)),i=new Set(r);for(let a of n.routes)if(a.batch!==void 0&&batchResolves({batch:a.batch,childContinuationToken:e,entries:t,responseIds:r}))for(let e of a.batch.requestIds)i.add(e);return{childContinuationToken:e,payload:{inputResponses:n.responses},retireRequestIds:[...i]}}),l={};for(let[t,n]of Object.entries(e.payload))t===`inputResponses`||n===void 0||(l[t]=n);return a.length>0&&(l.inputResponses=a),{forChildren:c,forSelf:Object.keys(l).length>0?l:void 0,parentAction:s}}function batchResolves(e){return e.batch.approvalRequestIds.length===0||e.batch.approvalRequestIds.every(t=>{let n=e.entries.get(t);return n===void 0||!sameBatch(n,e)||e.responseIds.has(t)})}function sameBatch(e,t){return e.childContinuationToken===t.childContinuationToken&&e.batch?.requestIds.length===t.batch.requestIds.length&&e.batch.requestIds.every((e,n)=>e===t.batch.requestIds[n])}export{emitProxiedInputRequest,routeDeliverPayload};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{turnStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{
|
|
1
|
+
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{activeTurnId}from"#harness/active-turn-id.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{turnStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let t=migrateTurnWorkflowInput(e);return t.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(t):runLegacyTurnWorkflow(t)}async function runTurnOwnedWorkflow(r){let s=createHook({token:`${r.completionToken}:inbox`}),c=s[Symbol.asyncIterator](),l=new TurnExecutionCursor({controlToken:r.completionToken,parentWritable:r.stepInput.parentWritable,serializedContext:r.stepInput.serializedContext,sessionState:r.stepInput.sessionState}),u=0,nextDeliveryRequestId=()=>`${s.token}:delivery:${String(u++)}`,d=[],f=r.stepInput.input,p=!1,m;try{try{await claimHookOwnership(s),p=!0}catch(e){if(isHookConflictError(e))return;throw e}for(r.driverCapabilities?.cancelledTurnSettle===!0&&(m=await createTurnCancellationControl({controlToken:r.completionToken,expectedTurnId:activeTurnId(r.stepInput.sessionState.emissionState)}));;){let t=await turnStep(l.createStepInput(f,m?.signal)),a=t.action===`dispatch-workflow-runtime-actions`||t.action===`park`?t.pendingRuntimeActionKeys:void 0;if(t.action===`cancelled`||m?.signal.aborted===!0&&a===void 0){await finishCancelledTurn({bufferedDeliveries:d,cancellation:m,cursor:l});return}if(t.sleepDurationMs!==void 0&&await waitForTurnSleep(t.sleepDurationMs,m)===`cancel`){await finishCancelledTurn({bufferedDeliveries:d,cancellation:m,cursor:l});return}if(t.action===`done`){await m?.dispose(),await l.finish(t,{kind:`done`,output:t.output??``,isError:t.isError,usage:t.usage,usageDelta:t.usageDelta},d);return}if(a!==void 0){await l.adopt(t);let r=await(t.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:s.token,parentWritable:l.parentWritable,serializedContext:l.serializedContext,sessionState:l.sessionState});await l.adopt(r);let i=await waitForRuntimeActionResults({bufferedDeliveries:d,cancellation:m,cursor:l,inboxToken:s.token,initialResults:r.results,iterator:c,nextDeliveryRequestId,pendingActionKeys:a});if(i===`cancelled`){f=void 0;continue}if(i===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:d,cancellation:m,cursor:l});return}f={kind:`runtime-action-result`,results:i};continue}if(t.action===`park`){if(!(t.hasPendingAuthorization||t.hasPendingInputBatch&&r.capabilities?.requestInput===!0||r.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await m?.dispose(),await l.finish(t,{authorizationAttemptIds:t.authorizationAttemptIds,authorizationNames:t.authorizationNames,kind:`park`,settled:t.settled},d);return}await l.adopt(t),f=void 0}}catch(e){throw await l.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{m!==void 0&&await m.dispose(),p&&await disposeHook(s)}}async function finishCancelledTurn(e){await cancelDescendantTurnsStep({serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}),await e.cancellation?.dispose(),await e.cursor.finish({sessionState:e.cursor.sessionState},{cancelled:!0,kind:`park`},e.bufferedDeliveries)}async function waitForTurnSleep(e,t){if(t?.signal.aborted===!0)return`cancel`;let n=sleep(e).then(()=>`slept`);return t===void 0?n:Promise.race([n,t.requested])}async function waitForRuntimeActionResults(e){let t,n=[...e.initialResults];for(;;){let i=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:n});if(i!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),i;e.cursor.sessionState.hasProxyInputRequests&&t===void 0&&(t=e.nextDeliveryRequestId(),await e.cursor.send({continuationToken:e.cursor.sessionState.continuationToken,inboxToken:e.inboxToken,kind:`turn-delivery-request`,requestId:t}));let a=e.iterator.next();a.catch(()=>{});let o=await(e.cancellation===void 0?a:Promise.race([a,e.cancellation.requested]));if(o===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(o.done)throw Error(`Turn inbox closed before runtime actions completed.`);let s=o.value;if(s.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state;n.push(...s.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e)));continue}if(s.kind===`subagent-input-request`||s.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:s,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(s.kind===`driver-delivery`&&s.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:s.requestId}),t=void 0;let n=await routeDeliverToChildren({auth:s.delivery.auth,parentWritable:e.cursor.parentWritable,payloads:s.delivery.payloads,sessionState:e.cursor.sessionState});if(await e.cursor.adopt(n),n.kind===`cancel-turn`)return n.kind;n.remainder!==void 0&&e.bufferedDeliveries.push({...s.delivery,payloads:[n.remainder]})}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action!==`cancelled`&&n.sleepDurationMs!==void 0&&await sleep(n.sleepDurationMs),n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState,usage:n.usage,usageDelta:n.usageDelta},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationAttemptIds:n.authorizationAttemptIds,authorizationNames:n.authorizationNames,settled:n.settled}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:a,workflowStartedAt:f}=getWorkflowMetadata(),p=e.serializedContext[`eve.continuationToken`]||``,m=e.serializedContext[`eve.mode`],h=e.serializedContext[`eve.capabilities`],g=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=a;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let n=readRootSessionId(e.serializedContext),r=readSerializedSubagentDepth(e.serializedContext),i=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:c}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:p,dynamicSubagentAgentConfig:i,inheritedLimits:e.limits,nodeId:g.nodeId,outputSchema:e.input.outputSchema,rootSessionId:n,sessionId:a,subagentDepth:r});v.lastSessionState=c,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let l=await runDriverLoop({capabilities:h,driverWritable:_,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:m,serializedContext:e.serializedContext,sessionState:c,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(f.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return l.kind===`result`?l.result:await finalizeExpiredSession({caller:v.caller,driverWritable:_,mode:m,serializedContext:l.serializedContext,sessionState:l.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:_,serializedContext:e.serializedContext}),m===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(v,e.serializedContext),lifecycle:`terminal`,sessionId:a,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let n=new Map,nextParkedActivity=async e=>{let r=new Set(e.expectedAttemptIds);for(let e of n.keys())
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:a,workflowStartedAt:f}=getWorkflowMetadata(),p=e.serializedContext[`eve.continuationToken`]||``,m=e.serializedContext[`eve.mode`],h=e.serializedContext[`eve.capabilities`],g=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=a;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let n=readRootSessionId(e.serializedContext),r=readSerializedSubagentDepth(e.serializedContext),i=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:c}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:p,dynamicSubagentAgentConfig:i,inheritedLimits:e.limits,nodeId:g.nodeId,outputSchema:e.input.outputSchema,rootSessionId:n,sessionId:a,subagentDepth:r});v.lastSessionState=c,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let l=await runDriverLoop({capabilities:h,driverWritable:_,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:m,serializedContext:e.serializedContext,sessionState:c,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(f.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return l.kind===`result`?l.result:await finalizeExpiredSession({caller:v.caller,driverWritable:_,mode:m,serializedContext:l.serializedContext,sessionState:l.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:_,serializedContext:e.serializedContext}),m===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(v,e.serializedContext),lifecycle:`terminal`,sessionId:a,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let n=new Map,nextParkedActivity=async e=>{let r=e.sessionState,a=new Set(e.expectedAttemptIds);for(let e of n.keys())a.has(e)||n.delete(e);for(;;){if(a.size>0&&[...a].every(e=>n.has(e))){let e=[...a].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:a.size>0,bufferedDeliveries:i,bufferedSessionControls:o,commandInbox:s,deferDeliveries:t.mode===`task`&&a.size>0,driverWritable:t.driverWritable,sessionState:r});if(r=e.sessionState,e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&a.has(e.attemptId)&&!n.has(e.attemptId)&&n.set(e.attemptId,t)}if(e.closed){let e=[...n.values()];return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],o=[],s=createSessionCommandInbox(),c=sessionCommandHookToken(t.sessionState.sessionId);await s.claimStable(c),await s.claimAuthorization(`${t.sessionState.sessionId}:auth`);let u=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:c}),d,runTurn=async e=>{let n=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:o,capabilities:t.capabilities,commandInbox:s,controlToken:nextTurnControlToken(),delivery:e.delivery,mode:t.mode,parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});return await d?.(),d=n.dispose,n.action};try{t.sessionState.continuationToken&&await s.rekeyContinuation(t.sessionState.continuationToken),await u?.start();let e=await runTurn({delivery:t.initialInput,serializedContext:t.serializedContext,sessionState:t.sessionState});for(t.crashCleanupState.lastSessionState=e.sessionState;;){if(e.kind===`done`)return{kind:`result`,result:await finalizeDone({action:e,caller:t.crashCleanupState.caller,mode:t.mode})};if(e.kind!==`park`)throw Error(`Driver received unexpected turn action "${e.kind}".`);if(e.cancelled===!0){let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState},t.crashCleanupState.lastSessionState=e.sessionState}e.sessionState.continuationToken&&await s.rekeyContinuation(e.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:e.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[],sessionState:e.sessionState});if(e={...e,sessionState:r.sessionState},t.crashCleanupState.lastSessionState=e.sessionState,r.kind===`authorization-resume`){e=await runTurn({delivery:{kind:`deliver`,payloads:r.payloads},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:e.serializedContext,sessionState:e.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({sessionState:e.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({delivery:{kind:r.kind},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState;continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:e.serializedContext,sessionState:e.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});e={...e,serializedContext:n.serializedContext,sessionState:n.sessionState,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=e.sessionState;continue}r.deliver.caller!==void 0&&(t.crashCleanupState.caller=r.deliver.caller),e=await runTurn({delivery:{auth:r.deliver.auth,kind:`deliver`,payloads:[r.remainder],requestId:r.deliver.requestId},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState}}finally{await d?.(),await u?.dispose(),await s.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({sessionState:e.sessionState}),await emitTerminalSessionCompletionStep({parentWritable:e.driverWritable,serializedContext:e.serializedContext}),e.mode===`task`?(await fireSessionCallbackStep({output:``,serializedContext:e.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.serializedContext,``),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.sessionState.sessionId,settled:{output:``}}),{output:``}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;if(await terminateChildSessionsStep({sessionState:e.action.sessionState}),e.mode===`task`)await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:r?void 0:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:r?void 0:e.action.usage});else{let n={output:t,usage:e.action.usageDelta};r&&(n.isError=!0),await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.action.sessionState.sessionId,settled:n})}return{output:t}}export{workflowEntry};
|
|
@@ -81,15 +81,18 @@ export declare function resolveEffectiveOutputSchema(input: {
|
|
|
81
81
|
}): HarnessSession;
|
|
82
82
|
export type RoutedDeliverResult = {
|
|
83
83
|
readonly kind: "cancel-turn";
|
|
84
|
+
readonly sessionState: DurableSessionState;
|
|
84
85
|
} | {
|
|
85
86
|
readonly kind: "continue";
|
|
86
87
|
/** `undefined` when the entire payload was routed to descendants. */
|
|
87
88
|
readonly remainder: DeliverPayload | undefined;
|
|
89
|
+
readonly sessionState: DurableSessionState;
|
|
88
90
|
};
|
|
89
91
|
/**
|
|
90
92
|
* Splits an inbound deliver payload into parent-local and
|
|
91
93
|
* proxied-child buckets and forwards the child buckets via
|
|
92
|
-
* `resumeHook`.
|
|
94
|
+
* `resumeHook`. Successfully forwarded request IDs are retired in the
|
|
95
|
+
* returned snapshot so later deliveries cannot route through stale entries.
|
|
93
96
|
*/
|
|
94
97
|
export declare function routeProxiedDeliverStep(input: {
|
|
95
98
|
readonly auth?: SessionAuthContext | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(f,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},p=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=buildAdapterContext(l,c),g;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,h):defaultDeliverResult(n);r!=null&&e.push(r)}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),g={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...h.state}}),o.input?.kind===`deliver`&&g===void 0){let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let _=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.subagentRegistry.dynamicResolvers??[],x=u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,S=u.resolvedAgent.dynamicToolResolvers??[],C={...u.graph.root,turnAgent:d.turnAgent},w=buildRuntimeIdentity(C),T=process.env.VERCEL_DEPLOYMENT_ID?.trim(),E=T?`deployment:${T}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!getHarnessEmissionState(m.state).sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,E),c.set(SessionDynamicToolRuntimeRevisionKey,E);else{let e=createSessionStartedEvent({runtime:w});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:b,event:e,messages:m.history,persistentSessions:x,runtimeRevision:E}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,runtimeRevision:E})])}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,h);setChannelContext(c,{...l,state:{...h.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:b,event:n,messages:t??[],persistentSessions:x}),await dispatchDynamicToolEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:g,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);isHarnessBetweenTurns(t)&&(e=await emitTurnPreamble(handleEvent,{},e,w),t=setHarnessEmissionState(t,e));for(let{authorization:t,result:n}of p)await handleEvent(createAuthorizationCompletedEvent({authorization:t,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:C,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,g)})}catch(e){if(!isTurnCancellation(e))throw e;return D.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(!t.hasPendingAuthorization&&!t.hasPendingInputBatch&&(t.pendingRuntimeActionKeys?.length??0)===0&&k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,sendCommandToDelivery({auth:e.auth,kind:`send`,payload:t.payload}));return n.parentAction??{kind:`continue`,remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(f,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},p=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=buildAdapterContext(l,c),g;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,h):defaultDeliverResult(n);r!=null&&e.push(r)}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),g={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...h.state}}),o.input?.kind===`deliver`&&g===void 0){let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let _=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.subagentRegistry.dynamicResolvers??[],x=u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,S=u.resolvedAgent.dynamicToolResolvers??[],C={...u.graph.root,turnAgent:d.turnAgent},w=buildRuntimeIdentity(C),T=process.env.VERCEL_DEPLOYMENT_ID?.trim(),E=T?`deployment:${T}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!getHarnessEmissionState(m.state).sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,E),c.set(SessionDynamicToolRuntimeRevisionKey,E);else{let e=createSessionStartedEvent({runtime:w});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:b,event:e,messages:m.history,persistentSessions:x,runtimeRevision:E}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,runtimeRevision:E})])}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,h);setChannelContext(c,{...l,state:{...h.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:b,event:n,messages:t??[],persistentSessions:x}),await dispatchDynamicToolEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:g,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);isHarnessBetweenTurns(t)&&(e=await emitTurnPreamble(handleEvent,{},e,w),t=setHarnessEmissionState(t,e));for(let{authorization:t,result:n}of p)await handleEvent(createAuthorizationCompletedEvent({authorization:t,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:C,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,g)})}catch(e){if(!isTurnCancellation(e))throw e;return D.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){if(O===`task`&&hasPendingInputBatch(k.session.state))throw D.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let r of n.forChildren)await resumeHook(r.childContinuationToken,sendCommandToDelivery({auth:e.auth,kind:`send`,payload:r.payload})),t=retireProxyInputRequests(t,r.retireRequestIds);let r=n.forChildren.length===0?e.sessionState:replaceDurableSessionSnapshot({session:t,state:e.sessionState});return n.parentAction===void 0?{kind:`continue`,remainder:n.forSelf,sessionState:r}:{...n.parentAction,sessionState:r}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
|
|
2
|
+
import type { PendingInputBatch } from "#harness/pending-input-batches.js";
|
|
3
|
+
import type { InputDomainResolverInput, ResolvedInputActionBatch, ResolvePendingInputResult } from "#harness/hitl/pending-input-resolution.js";
|
|
4
|
+
import type { HarnessSession } from "#harness/types.js";
|
|
5
|
+
export type RejectedActionBatch = ResolvedInputActionBatch;
|
|
6
|
+
export declare function hasAnsweredApprovalBatch(batches: readonly PendingInputBatch[], responses: readonly InputResponse[]): boolean;
|
|
7
|
+
export declare function resolveApprovalInputBatches(input: InputDomainResolverInput & {
|
|
8
|
+
readonly approvalBatches: readonly PendingInputBatch[];
|
|
9
|
+
readonly questionBatches: readonly PendingInputBatch[];
|
|
10
|
+
readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;
|
|
11
|
+
}): ResolvePendingInputResult;
|
|
12
|
+
/** Returns tool approval keys recorded during this session. */
|
|
13
|
+
export declare function getApprovedTools(session: HarnessSession): ReadonlySet<string>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isApprovalRequest}from"#harness/input-request-class.js";import{queueDeferredStepInput,removePendingInputBatches}from"#harness/pending-input-batches.js";import{appendResolvedBatchTranscript,compactStepInput,finishResolvedInput,responsesForBatches}from"#harness/hitl/pending-input-resolution.js";import{buildQuestionToolResponsePart,findAnsweredQuestionBatches,resolveQuestionBatches}from"#harness/hitl/question-input-requests.js";const APPROVED_TOOLS_KEY=`eve.runtime.hitl.approvedTools`,TOOL_EXECUTION_DENIED_MESSAGE=`Tool execution was denied.`;function hasAnsweredApprovalBatch(t,n){let r=new Set(n.map(e=>e.requestId));return t.some(t=>t.requests.every(t=>!isApprovalRequest(t)||r.has(t.requestId)))}function resolveApprovalInputBatches(r){let s=new Set(r.responses.map(e=>e.requestId)),c=new Set(r.approvalBatches.filter(t=>t.requests.every(t=>!isApprovalRequest(t)||s.has(t.requestId)))),l=new Set(findAnsweredQuestionBatches(r.questionBatches,r.responses)),u=r.batches.filter(e=>c.has(e)||l.has(e)),d=u.findIndex(t=>t.requests.some(t=>isApprovalRequest(t)));d>=0&&(u=u.slice(0,d+1));let f=r.batches.filter(e=>!u.includes(e)),p=responsesForBatches(r.responses,f);if(u.length===0){if(r.resolvedStepInput?.message===void 0)return{outcome:`unresolved`,messages:[...r.baseHistory],session:queueDeferredStepInput(r.session,compactStepInput(r.resolvedStepInput))};let e=p.length===0?r.session:queueDeferredStepInput(r.session,{inputResponses:p});return{consumedMessage:r.resolvedStepInput.messageConsumed,outcome:`continue`,messages:[...r.baseHistory],session:e}}let m=u.find(t=>t.requests.some(t=>isApprovalRequest(t))),h=resolveQuestionBatches({batches:u.filter(e=>e!==m),messages:[...r.baseHistory],responses:r.responses}),g=m===void 0?{messages:h,session:r.session}:resolveApprovalBatch({batch:m,messages:h,resolveApprovalKey:r.resolveApprovalKey,responses:r.responses,session:r.session});return finishResolvedInput({deferTurnInput:m!==void 0||r.deferTurnInput,leftoverResponses:p,messages:g.messages,rejectedActions:g.rejectedActions,resolvedStepInput:r.resolvedStepInput,session:removePendingInputBatches(g.session,u)})}function getApprovedTools(e){let t=e.state?.[APPROVED_TOOLS_KEY];return Array.isArray(t)?new Set(t):new Set}function resolveApprovalBatch(e){let t=recordApprovedTools({pendingBatch:e.batch,resolveApprovalKey:e.resolveApprovalKey,responses:e.responses,session:e.session}),n=buildApprovalBatchToolResponseParts(e.batch,e.responses);appendResolvedBatchTranscript(e.messages,e.batch,n);let i=buildRejectedActionBatch(e.batch,e.responses);return{messages:e.messages,rejectedActions:i===void 0?void 0:[i],session:t}}function recordApprovedTools(t){let n=new Set(t.responses.filter(e=>e.optionId===`approve`).map(e=>e.requestId)),r=t.pendingBatch.requests.filter(t=>isApprovalRequest(t)&&n.has(t.requestId)).map(e=>t.resolveApprovalKey?.(e)??e.action.toolName);if(r.length===0)return t.session;let i={...t.session.state};return i[APPROVED_TOOLS_KEY]=[...new Set([...getApprovedTools(t.session),...r])],{...t.session,state:i}}function resolveApprovalOutcome(e){return e===void 0?{approved:!1,reason:`Ignored because the user continued without responding.`,status:`ignored`}:e.optionId===`approve`?{approved:!0,reason:void 0,status:`approved`}:e.optionId===`cancel`?{approved:!1,reason:TOOL_EXECUTION_DENIED_MESSAGE,status:`denied`}:{approved:!1,reason:`Invalid approval response.`,status:`invalid`}}function buildRejectedActionBatch(t,n){if(t.event===void 0)return;let r=new Map(n.map(e=>[e.requestId,e])),i=[];for(let n of t.requests){if(!isApprovalRequest(n))continue;let{approved:t,reason:a,status:o}=resolveApprovalOutcome(r.get(n.requestId));t||i.push({callId:n.action.callId,isError:!0,kind:`tool-result`,output:{approval:{requestId:n.requestId,status:o},code:`TOOL_EXECUTION_DENIED`,message:a??TOOL_EXECUTION_DENIED_MESSAGE,tool:{result:`not_run`}},toolName:n.action.toolName})}return i.length>0?{event:t.event,results:i}:void 0}function buildApprovalBatchToolResponseParts(e,t){let n=new Map(t.map(e=>[e.requestId,e])),r=[];for(let t of e.requests){let e=n.get(t.requestId);switch(t.kind){case`tool-approval`:r.push(...buildApprovalToolResponseParts(t,e));break;case`question`:r.push(buildQuestionToolResponsePart(t,e));break;case`session-limit`:throw TypeError(`Session-limit pending input batches must contain only session-limit requests.`);default:{let e=t.kind;throw TypeError(`Unhandled pending input request kind: ${String(e)}`)}}}return r}function buildApprovalToolResponseParts(e,t){let{approved:n,reason:r}=resolveApprovalOutcome(t),i=[{approvalId:e.requestId,approved:n,reason:r,type:`tool-approval-response`}];return n||i.push({output:{type:`execution-denied`,reason:r},toolCallId:e.action.callId,toolName:e.action.toolName,type:`tool-result`}),i}export{getApprovedTools,hasAnsweredApprovalBatch,resolveApprovalInputBatches};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { ModelMessage } from "ai";
|
|
2
|
+
import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";
|
|
3
|
+
import type { InputResponse } from "#runtime/input/types.js";
|
|
4
|
+
import type { PendingInputBatch, PendingInputBatchEvent } from "#harness/pending-input-batches.js";
|
|
5
|
+
import type { HarnessSession, StepInput } from "#harness/types.js";
|
|
6
|
+
export type ToolResponsePart = Extract<ModelMessage, {
|
|
7
|
+
role: "tool";
|
|
8
|
+
}>["content"][number];
|
|
9
|
+
/** Action results from one resolved batch, attributed to their originating turn. */
|
|
10
|
+
export interface ResolvedInputActionBatch {
|
|
11
|
+
readonly event: PendingInputBatchEvent;
|
|
12
|
+
readonly results: readonly RuntimeToolResultActionResult[];
|
|
13
|
+
}
|
|
14
|
+
export type ResolvedStepInput = StepInput & {
|
|
15
|
+
readonly messageConsumed?: boolean;
|
|
16
|
+
};
|
|
17
|
+
export type InputDomainResolverInput = {
|
|
18
|
+
readonly baseHistory: ModelMessage[];
|
|
19
|
+
readonly batches: readonly PendingInputBatch[];
|
|
20
|
+
readonly deferTurnInput: boolean;
|
|
21
|
+
readonly resolvedStepInput: ResolvedStepInput | undefined;
|
|
22
|
+
readonly responses: readonly InputResponse[];
|
|
23
|
+
readonly session: HarnessSession;
|
|
24
|
+
};
|
|
25
|
+
export type ResolvePendingInputResult = {
|
|
26
|
+
readonly consumedMessage?: boolean;
|
|
27
|
+
readonly deferredContext?: boolean;
|
|
28
|
+
readonly deferredMessage?: boolean;
|
|
29
|
+
/** Present when a session-limit continuation prompt was resolved. */
|
|
30
|
+
readonly limitContinuation?: {
|
|
31
|
+
readonly granted: boolean;
|
|
32
|
+
};
|
|
33
|
+
readonly outcome: "resolved" | "continue" | "unresolved";
|
|
34
|
+
readonly messages: ModelMessage[];
|
|
35
|
+
readonly rejectedActions?: readonly ResolvedInputActionBatch[];
|
|
36
|
+
readonly session: HarnessSession;
|
|
37
|
+
};
|
|
38
|
+
export declare function responsesForBatches(responses: readonly InputResponse[], batches: readonly PendingInputBatch[]): readonly InputResponse[];
|
|
39
|
+
export declare function appendResolvedBatchTranscript(messages: ModelMessage[], batch: PendingInputBatch, toolParts: readonly ToolResponsePart[]): void;
|
|
40
|
+
export declare function finishResolvedInput(input: {
|
|
41
|
+
readonly deferTurnInput: boolean;
|
|
42
|
+
readonly leftoverResponses: readonly InputResponse[];
|
|
43
|
+
readonly limitContinuation?: {
|
|
44
|
+
readonly granted: boolean;
|
|
45
|
+
};
|
|
46
|
+
readonly messages: ModelMessage[];
|
|
47
|
+
readonly rejectedActions?: readonly ResolvedInputActionBatch[];
|
|
48
|
+
readonly resolvedStepInput: ResolvedStepInput | undefined;
|
|
49
|
+
readonly session: HarnessSession;
|
|
50
|
+
}): ResolvePendingInputResult;
|
|
51
|
+
export declare function compactStepInput(input: ResolvedStepInput | undefined): ResolvedStepInput;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{queueDeferredStepInput}from"#harness/pending-input-batches.js";function responsesForBatches(e,t){return e.filter(e=>t.some(t=>t.requests.some(t=>t.requestId===e.requestId)))}function appendResolvedBatchTranscript(e,t,n){e.push(...t.responseMessages),n.length>0&&e.push({content:[...n],role:`tool`})}function finishResolvedInput(t){let n={};return t.leftoverResponses.length>0&&(n.inputResponses=t.leftoverResponses),t.deferTurnInput&&((t.resolvedStepInput?.context?.length??0)>0&&(n.context=t.resolvedStepInput?.context),t.resolvedStepInput?.message!==void 0&&(n.message=t.resolvedStepInput.message)),Object.keys(n).length>0?{consumedMessage:t.resolvedStepInput?.messageConsumed,deferredContext:n.context!==void 0||void 0,deferredMessage:n.message!==void 0||void 0,limitContinuation:t.limitContinuation,outcome:`resolved`,messages:t.messages,rejectedActions:t.rejectedActions,session:queueDeferredStepInput(t.session,n)}:{consumedMessage:t.resolvedStepInput?.messageConsumed,limitContinuation:t.limitContinuation,outcome:`resolved`,messages:t.messages,rejectedActions:t.rejectedActions,session:t.session}}function compactStepInput(e){if(e===void 0)return{};let t={};return(e.context?.length??0)>0&&(t.context=e.context),(e.inputResponses?.length??0)>0&&(t.inputResponses=e.inputResponses),e.message!==void 0&&(t.message=e.message),e.messageConsumed===!0&&(t.messageConsumed=!0),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),t}export{appendResolvedBatchTranscript,compactStepInput,finishResolvedInput,responsesForBatches};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ModelMessage } from "ai";
|
|
2
|
+
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
|
|
3
|
+
import type { PendingInputBatch } from "#harness/pending-input-batches.js";
|
|
4
|
+
import type { InputDomainResolverInput, ResolvePendingInputResult, ToolResponsePart } from "#harness/hitl/pending-input-resolution.js";
|
|
5
|
+
export type QuestionInputRequest = InputRequest & {
|
|
6
|
+
readonly kind: "question";
|
|
7
|
+
};
|
|
8
|
+
export declare function resolveQuestionOnlyInputBatches(input: InputDomainResolverInput): ResolvePendingInputResult;
|
|
9
|
+
export declare function findAnsweredQuestionBatches(batches: readonly PendingInputBatch[], responses: readonly InputResponse[]): PendingInputBatch[];
|
|
10
|
+
export declare function resolveQuestionBatches(input: {
|
|
11
|
+
readonly batches: readonly PendingInputBatch[];
|
|
12
|
+
readonly messages: ModelMessage[];
|
|
13
|
+
readonly responses: readonly InputResponse[];
|
|
14
|
+
}): ModelMessage[];
|
|
15
|
+
export declare function buildQuestionToolResponsePart(request: QuestionInputRequest, response: InputResponse | undefined): ToolResponsePart;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{queueDeferredStepInput,removePendingInputBatches}from"#harness/pending-input-batches.js";import{appendResolvedBatchTranscript,compactStepInput,finishResolvedInput,responsesForBatches}from"#harness/hitl/pending-input-resolution.js";function resolveQuestionOnlyInputBatches(n){let o=findAnsweredQuestionBatches(n.batches,n.responses),s=n.batches.filter(e=>!o.includes(e)),c=responsesForBatches(n.responses,s);if(o.length===0){if(n.resolvedStepInput?.message===void 0)return{outcome:`unresolved`,messages:[...n.baseHistory],session:queueDeferredStepInput(n.session,compactStepInput(n.resolvedStepInput))};let i=n.batches.length===1?n.batches[0]:void 0;if(i===void 0){let t=c.length===0?n.session:queueDeferredStepInput(n.session,{inputResponses:c});return{consumedMessage:n.resolvedStepInput.messageConsumed,outcome:`continue`,messages:[...n.baseHistory],session:t}}let a=resolveQuestionBatches({batches:[i],messages:[...n.baseHistory],responses:[]});return{consumedMessage:n.resolvedStepInput.messageConsumed,outcome:`resolved`,messages:a,session:removePendingInputBatches(n.session,[i])}}let l=resolveQuestionBatches({batches:o,messages:[...n.baseHistory],responses:n.responses});return finishResolvedInput({deferTurnInput:n.deferTurnInput,leftoverResponses:c,messages:l,resolvedStepInput:n.resolvedStepInput,session:removePendingInputBatches(n.session,o)})}function findAnsweredQuestionBatches(e,t){let n=new Set(t.map(e=>e.requestId));return e.filter(e=>e.requests.some(e=>n.has(e.requestId)))}function resolveQuestionBatches(e){let t=new Map(e.responses.map(e=>[e.requestId,e]));for(let r of e.batches){let i=r.requests.map(e=>buildQuestionToolResponsePart(e,t.get(e.requestId)));appendResolvedBatchTranscript(e.messages,r,i)}return e.messages}function buildQuestionToolResponsePart(e,t){return{output:{type:`json`,value:t===void 0?{status:`ignored`}:{optionId:t.optionId,text:t.text,status:`answered`}},toolCallId:e.action.callId,toolName:e.action.toolName,type:`tool-result`}}export{buildQuestionToolResponsePart,findAnsweredQuestionBatches,resolveQuestionBatches,resolveQuestionOnlyInputBatches};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PendingInputBatch } from "#harness/pending-input-batches.js";
|
|
2
|
+
import type { InputDomainResolverInput, ResolvePendingInputResult } from "#harness/hitl/pending-input-resolution.js";
|
|
3
|
+
import type { HarnessSession } from "#harness/types.js";
|
|
4
|
+
/** Returns whether this is a valid session-limit batch and rejects mixed ownership. */
|
|
5
|
+
export declare function isSessionLimitInputBatch(batch: PendingInputBatch): boolean;
|
|
6
|
+
export declare function resolveSessionLimitInput(input: InputDomainResolverInput & {
|
|
7
|
+
readonly pendingBatch: PendingInputBatch;
|
|
8
|
+
}): ResolvePendingInputResult;
|
|
9
|
+
/** Drops only harness-authored session-limit prompts from a parked session. */
|
|
10
|
+
export declare function clearPendingSessionLimitPrompt(session: HarnessSession): HarnessSession;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isSessionLimitContinuationRequest,resolveSessionLimitContinuation}from"#harness/session-limit-continuation.js";import{getPendingInputBatches,queueDeferredStepInput,removePendingInputBatches}from"#harness/pending-input-batches.js";import{appendResolvedBatchTranscript,compactStepInput,finishResolvedInput,responsesForBatches}from"#harness/hitl/pending-input-resolution.js";function isSessionLimitInputBatch(e){let t=e.requests.some(e=>e.kind===`session-limit`);if(t&&e.requests.some(e=>e.kind!==`session-limit`))throw TypeError(`Session-limit pending input batches must contain only session-limit requests.`);return t}function resolveSessionLimitInput(n){let i=new Set(n.responses.map(e=>e.requestId));if(!(n.pendingBatch.requests.some(e=>i.has(e.requestId))&&n.pendingBatch.requests.every(e=>i.has(e.requestId))))return{deferredMessage:!0,outcome:`unresolved`,messages:[...n.baseHistory],session:queueDeferredStepInput(n.session,compactStepInput(n.resolvedStepInput))};let a=n.batches.filter(e=>e!==n.pendingBatch),o=responsesForBatches(n.responses,a),s=a.some(t=>t.requests.some(t=>isSessionLimitContinuationRequest(t))),c=[...n.baseHistory];appendResolvedBatchTranscript(c,n.pendingBatch,[]);let l=removePendingInputBatches(n.session,[n.pendingBatch]),u=resolveSessionLimitContinuation({requests:n.pendingBatch.requests,responses:n.responses});return finishResolvedInput({deferTurnInput:n.deferTurnInput||s,leftoverResponses:o,limitContinuation:u,messages:c,resolvedStepInput:n.resolvedStepInput,session:l})}function clearPendingSessionLimitPrompt(t){let r=getPendingInputBatches(t.state).filter(t=>t.requests.length>0&&t.requests.every(t=>isSessionLimitContinuationRequest(t)));return r.length===0?t:removePendingInputBatches(t,r)}export{clearPendingSessionLimitPrompt,isSessionLimitInputBatch,resolveSessionLimitInput};
|