eve 0.37.0 → 0.37.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/src/channel/routes.d.ts +13 -3
- package/dist/src/channel/routes.js +1 -1
- package/dist/src/channel/session-callback.js +1 -1
- package/dist/src/channel/session.d.ts +2 -1
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +41 -0
- package/dist/src/chunks/{use-eve-agent-CnppTEFk.js → use-eve-agent-Bi5fRxcZ.js} +9 -1
- package/dist/src/chunks/{use-eve-agent-COmP-H8R.js → use-eve-agent-DbKUBhl-.js} +9 -1
- package/dist/src/cli/commands/init-git.js +1 -1
- package/dist/src/cli/commands/init-recovery.d.ts +3 -0
- package/dist/src/cli/commands/init-recovery.js +3 -0
- package/dist/src/cli/commands/init-target.d.ts +21 -0
- package/dist/src/cli/commands/init-target.js +1 -0
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +8 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +27 -22
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +16 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
- package/dist/src/client/open-stream.d.ts +2 -0
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@modelcontextprotocol/server/LICENSE +216 -0
- package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +98 -0
- package/dist/src/compiled/@modelcontextprotocol/server/index.js +80 -0
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-subagent.d.ts +1 -1
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/context/serialized-dynamic-model-selection.d.ts +2 -0
- package/dist/src/context/serialized-dynamic-model-selection.js +1 -0
- package/dist/src/execution/agent-handle-dispatch.d.ts +15 -1
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/delegated-parent-notification.d.ts +17 -0
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +155 -0
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +18 -14
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +7 -2
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/effective-output-schema.d.ts +21 -0
- package/dist/src/execution/effective-output-schema.js +1 -0
- package/dist/src/execution/eve-workflow-attributes.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.d.ts +8 -12
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/{route-proxied-deliver-step.d.ts → proxied-deliver-step.d.ts} +7 -4
- package/dist/src/execution/proxied-deliver-step.js +1 -0
- package/dist/src/execution/remote-agent-dispatch.d.ts +32 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/remote-agent-route-url.d.ts +2 -0
- package/dist/src/execution/remote-agent-route-url.js +1 -0
- package/dist/src/execution/route-child-delivery.d.ts +2 -1
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/session-callback-step.d.ts +11 -0
- package/dist/src/execution/session-callback-step.js +1 -1
- package/dist/src/execution/session-command-wire.js +1 -1
- package/dist/src/execution/session-state-cursor.d.ts +25 -0
- package/dist/src/execution/session-state-cursor.js +1 -0
- package/dist/src/execution/settle-cancelled-turn-step.d.ts +2 -0
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.d.ts +15 -0
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +14 -7
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/subagent-start-local.d.ts +29 -0
- package/dist/src/execution/subagent-start-local.js +1 -0
- package/dist/src/execution/subagent-start-remote.d.ts +23 -0
- package/dist/src/execution/subagent-start-remote.js +1 -0
- package/dist/src/execution/task-event-callback.d.ts +13 -0
- package/dist/src/execution/task-event-callback.js +1 -0
- package/dist/src/execution/task-input-capability.d.ts +4 -0
- package/dist/src/execution/task-input-capability.js +1 -0
- package/dist/src/execution/tasks/child/steps.d.ts +46 -0
- package/dist/src/execution/tasks/child/steps.js +1 -0
- package/dist/src/execution/tasks/child/workflow.d.ts +31 -0
- package/dist/src/execution/tasks/child/workflow.js +1 -0
- package/dist/src/execution/tasks/parent/agent-identity.d.ts +13 -0
- package/dist/src/execution/tasks/parent/agent-identity.js +1 -0
- package/dist/src/execution/tasks/parent/agent-views.d.ts +6 -0
- package/dist/src/execution/tasks/parent/agent-views.js +1 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.d.ts +37 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.js +1 -0
- package/dist/src/execution/tasks/parent/control-shared.d.ts +36 -0
- package/dist/src/execution/tasks/parent/control-shared.js +1 -0
- package/dist/src/execution/tasks/parent/delegate.d.ts +70 -0
- package/dist/src/execution/tasks/parent/delegate.js +1 -0
- package/dist/src/execution/tasks/parent/dispatch-task-step.d.ts +19 -0
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -0
- package/dist/src/execution/tasks/parent/dispatch.d.ts +33 -0
- package/dist/src/execution/tasks/parent/dispatch.js +1 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +29 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -0
- package/dist/src/execution/tasks/parent/run-parent.d.ts +72 -0
- package/dist/src/execution/tasks/parent/run-parent.js +1 -0
- package/dist/src/execution/tasks/parent/send.d.ts +25 -0
- package/dist/src/execution/tasks/parent/send.js +1 -0
- package/dist/src/execution/tasks/workflow-target.d.ts +2 -0
- package/dist/src/execution/tasks/workflow-target.js +1 -0
- package/dist/src/execution/terminate-child-sessions-step.d.ts +1 -0
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/turn-control-receiver.d.ts +10 -0
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/turn-dispatch.d.ts +2 -0
- package/dist/src/execution/turn-dispatch.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +2 -8
- package/dist/src/execution/turn-execution-cursor.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-callback-url.d.ts +5 -0
- package/dist/src/execution/workflow-callback-url.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +9 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +7 -21
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +7 -0
- package/dist/src/harness/handles/prompt.d.ts +12 -0
- package/dist/src/harness/handles/prompt.js +2 -1
- package/dist/src/harness/handles/query.js +1 -1
- package/dist/src/harness/handles/store.d.ts +9 -2
- package/dist/src/harness/handles/store.js +1 -1
- package/dist/src/harness/handles/transitions.d.ts +10 -1
- package/dist/src/harness/handles/transitions.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +21 -4
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +2 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/workflow-runtime-action-state.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/invocation/agent-invocation.d.ts +54 -0
- package/dist/src/internal/invocation/agent-invocation.js +1 -0
- package/dist/src/internal/invocation/attributes.d.ts +2 -0
- package/dist/src/internal/invocation/attributes.js +1 -0
- package/dist/src/internal/invocation/metadata.d.ts +9 -0
- package/dist/src/internal/invocation/metadata.js +1 -0
- package/dist/src/internal/invocation/workflow-execution.d.ts +32 -0
- package/dist/src/internal/invocation/workflow-execution.js +1 -0
- package/dist/src/internal/mcp/http-security.d.ts +12 -0
- package/dist/src/internal/mcp/http-security.js +1 -0
- package/dist/src/internal/mcp/protected-resource.d.ts +9 -0
- package/dist/src/internal/mcp/protected-resource.js +1 -0
- package/dist/src/internal/mcp/streamable-http-server.d.ts +51 -0
- package/dist/src/internal/mcp/streamable-http-server.js +1 -0
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-route-context.d.ts +14 -0
- package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
- package/dist/src/internal/nitro/routes/runtime-stack.d.ts +2 -0
- package/dist/src/internal/nitro/routes/runtime-stack.js +1 -1
- package/dist/src/internal/vercel-agent-summary.d.ts +1 -1
- package/dist/src/protocol/message.d.ts +28 -0
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/routes.d.ts +14 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/auth.d.ts +36 -0
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/mcp.d.ts +19 -0
- package/dist/src/public/channels/mcp.js +1 -0
- package/dist/src/public/definitions/channel.d.ts +2 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/actions/types.d.ts +9 -0
- package/dist/src/runtime/actions/types.js +1 -1
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/runtime/connections/authorization-complete-page.js +70 -28
- package/dist/src/runtime/framework-channels/index.js +1 -1
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/framework-tools/tasks.d.ts +95 -0
- package/dist/src/runtime/framework-tools/tasks.js +1 -0
- package/dist/src/runtime/prompt/compose.d.ts +1 -0
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/runtime/task-input-response-route.d.ts +5 -0
- package/dist/src/runtime/task-input-response-route.js +1 -0
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +7 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/json.d.ts +88 -0
- package/dist/src/tasks/json.js +1 -0
- package/dist/src/tasks/session-index.d.ts +48 -0
- package/dist/src/tasks/session-index.js +1 -0
- package/dist/src/tasks/task-id.d.ts +34 -0
- package/dist/src/tasks/task-id.js +1 -0
- package/dist/src/tasks/transitions.d.ts +23 -0
- package/dist/src/tasks/transitions.js +1 -0
- package/dist/src/tasks/types.d.ts +295 -0
- package/dist/src/tasks/types.js +1 -0
- package/dist/src/tasks/wire.d.ts +26 -0
- package/dist/src/tasks/wire.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/eve.mdx +14 -0
- package/docs/guides/client/streaming.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +3 -1
- package/package.json +7 -1
- package/dist/src/execution/route-proxied-deliver-step.js +0 -1
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type RuntimeSession } from "#execution/agent-handle-dispatch.js";
|
|
2
|
+
import { type DelegatedTask } from "#execution/tasks/parent/delegate.js";
|
|
3
|
+
import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
|
|
4
|
+
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
|
|
5
|
+
/**
|
|
6
|
+
* Routes one `task_send`:
|
|
7
|
+
*
|
|
8
|
+
* - `working` tasks are busy — the send surfaces `AGENT_BUSY` instead
|
|
9
|
+
* of queueing (settled decision; queueing is the reversible follow-up);
|
|
10
|
+
* - `input_required` tasks reject model-authored sends; clients answer
|
|
11
|
+
* them through the parent channel's direct HITL route;
|
|
12
|
+
* - terminal tasks accept a `message` follow-up, which starts a new
|
|
13
|
+
* task bound to the same child session and returns its receipt.
|
|
14
|
+
*/
|
|
15
|
+
export declare function executeTaskSend(input: {
|
|
16
|
+
readonly action: RuntimeToolCallActionRequest;
|
|
17
|
+
readonly bundle: CompiledBundle;
|
|
18
|
+
readonly parentStepIndex?: number;
|
|
19
|
+
readonly parentTurnId: string;
|
|
20
|
+
readonly session: RuntimeSession;
|
|
21
|
+
}): Promise<{
|
|
22
|
+
readonly result: RuntimeActionResult;
|
|
23
|
+
readonly session: RuntimeSession;
|
|
24
|
+
readonly pendingTask?: DelegatedTask;
|
|
25
|
+
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AGENT_BUSY,AGENT_UNREACHABLE}from"#harness/agent-handle-errors.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{findSessionTaskEntry}from"#tasks/session-index.js";import{createTaskControlError,createUnknownTasksError,findActiveTaskForAgent,findTaskAgentAddress,readTaskView}from"#execution/tasks/parent/control-shared.js";import{beginDelegatedTask,failDelegatedDispatch,settleDelegatedDispatch}from"#execution/tasks/parent/delegate.js";async function executeTaskSend(t){let{action:n,session:a}=t,o=readTaskSendInput(n.input);if(o.kind===`invalid`)return{result:createTaskControlError(n,o.message),session:a};let c=findSessionTaskEntry(a.state,o.taskId);if(c===void 0)return{result:createUnknownTasksError(n,[o.taskId]),session:a};let l=await readTaskView(c);return l.status===`working`?{result:createTaskControlError(n,`${AGENT_BUSY}: task "${l.taskId}" is still working. Let it finish, or cancel it first.`),session:a}:l.status===`input_required`?{result:createTaskControlError(n,`Task "${l.taskId}" is waiting on input; the human must answer through the parent channel.`),session:a}:followUpTerminalTask({action:n,bundle:t.bundle,message:o.message,parentStepIndex:t.parentStepIndex,parentTurnId:t.parentTurnId,session:a,view:l})}async function followUpTerminalTask(r){let{action:i,view:s}=r,u=await findActiveTaskForAgent(r.session,s.metadata.agentId,r.parentTurnId,r.parentStepIndex);if(u!==void 0)return{result:createTaskControlError(i,`${AGENT_BUSY}: agent "${s.metadata.agentId}" is busy with task "${u.view.taskId}" (${u.view.status}).`),session:r.session};let d=findTaskAgentAddress(r.session,s.metadata.agentId);if(d===void 0)return{result:createTaskControlError(i,`${AGENT_UNREACHABLE}: task "${s.taskId}"'s agent is no longer addressable.`),session:r.session};let f=d.address.kind===`agent/remote`?{callId:i.callId,description:``,input:{message:r.message},kind:`remote-agent-call`,name:d.identity.name,nodeId:d.identity.nodeId,remoteAgentName:d.identity.name}:{callId:i.callId,description:``,input:{message:r.message},kind:`subagent-call`,name:d.identity.name,nodeId:d.identity.nodeId,subagentName:d.identity.name},p=await beginDelegatedTask({agentId:d.identity.id,callId:i.callId,mode:d.address.kind===`agent/remote`?`remote`:`local`,name:d.identity.name,parentSessionId:r.session.sessionId,parentStepIndex:r.parentStepIndex,parentTurnId:r.parentTurnId,session:r.session}),m=await settleDelegatedDispatch({callId:i.callId,session:r.session,subagentName:d.identity.name,task:p}),h=await dispatchToTaskAgentAddress({action:f,agentId:d.identity.id,bundle:r.bundle,currentSession:m.session,parentToken:p.taskInboxToken});return h.kind===`error`?(h.deliveryAmbiguous!==!0&&await failDelegatedDispatch({error:h.result.output,task:p}),{result:{callId:i.callId,isError:!0,kind:`tool-result`,output:{error:h.result.output,taskId:p.taskId},toolName:i.toolName},session:h.session,pendingTask:p}):{result:{callId:i.callId,kind:`tool-result`,output:{agentId:p.metadata.agentId,status:`working`,taskId:p.taskId},toolName:i.toolName},session:h.session,pendingTask:p}}function readTaskSendInput(e){let t=typeof e.taskId==`string`&&e.taskId.trim()!==``?e.taskId:void 0;if(t===void 0)return{kind:`invalid`,message:"Provide the `taskId` from a task receipt."};let n=typeof e.message==`string`&&e.message.trim()!==``?e.message:void 0;return n===void 0?{kind:`invalid`,message:"Provide a non-empty `message`."}:{kind:`send`,message:n,taskId:t}}export{executeTaskSend};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{walkCauseChain}from"#shared/errors.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";function isTaskWorkflowTargetGone(e){for(let t of walkCauseChain(e))if(HookNotFoundError.is(t)||WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}export{isTaskWorkflowTargetGone};
|
|
@@ -11,5 +11,6 @@ import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
|
11
11
|
* remote-termination protocol exists.
|
|
12
12
|
*/
|
|
13
13
|
export declare function terminateChildSessionsStep(input: {
|
|
14
|
+
readonly serializedContext?: Record<string, unknown>;
|
|
14
15
|
readonly sessionState: DurableSessionState;
|
|
15
16
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{readDurableSession}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{cancelRun,getWorld}from"#internal/workflow/runtime.js";import{cancelOwnedTask}from"#execution/tasks/parent/dispatch.js";import{getSessionTaskIndex}from"#tasks/session-index.js";const log=createLogger(`execution.terminate-child-sessions`);async function terminateChildSessionsStep(e){"use step";let s;try{s=await readDurableSession(e.sessionState)}catch(n){logError(log,`failed to read child sessions for termination`,n,{parentSessionId:e.sessionState.sessionId});return}let c=readSessionTaskIndex(s.state,s.sessionId);if(c.length>0){if(e.serializedContext===void 0)throw Error(`Task finalization requires serialized runtime context.`);let r=await deserializeContext(e.serializedContext),i=r.require(BundleKey),a=resolveEffectiveAgentRuntime(i,r),o=hydrateDurableSession({durable:s,turnAgent:a.turnAgent});for(let e of c)try{await cancelOwnedTask({bundle:i,entry:e,session:o})}catch(n){logError(log,`failed to cancel task during parent finalization`,n,{parentSessionId:s.sessionId,taskId:e.taskId})}}let l=(getAgentHandleStore(s.state)?.handles??[]).filter(isLocalChildHandle);if(l.length!==0)for(let e of l){if(e.phase===`starting`){log.debug(`skipping starting child without a session id`,{agentId:e.identity.id,kind:e.target.kind,parentSessionId:s.sessionId});continue}try{await cancelRun(await getWorld(),e.address.sessionId,{cancelReason:`Parent session ended`})}catch(n){logError(log,`failed to terminate child session`,n,{agentId:e.identity.id,childSessionId:e.address.sessionId,kind:e.address.kind,parentSessionId:s.sessionId})}}}function isLocalChildHandle(e){let t=e.phase===`starting`?e.target.kind:e.address.kind;return t===`agent/local`||t===`agent/self`}function readSessionTaskIndex(e,n){try{return getSessionTaskIndex(e)}catch(e){return logError(log,`failed to read the task index during parent finalization`,e,{parentSessionId:n}),[]}}export{terminateChildSessionsStep};
|
|
@@ -9,11 +9,17 @@ export declare class TurnControlReceiver {
|
|
|
9
9
|
private readonly commandInbox;
|
|
10
10
|
private readonly control;
|
|
11
11
|
private readonly controlIterator;
|
|
12
|
+
private readonly expectedTurnId;
|
|
13
|
+
private readonly cancelledTaskIds;
|
|
14
|
+
private readonly seenTaskDeliveries;
|
|
12
15
|
private pendingControl;
|
|
13
16
|
constructor(input: {
|
|
14
17
|
readonly bufferedDeliveries: DeliverHookPayload[];
|
|
15
18
|
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
|
|
19
|
+
readonly cancelledTaskIds?: Set<string>;
|
|
16
20
|
readonly commandInbox: SessionCommandInbox;
|
|
21
|
+
readonly expectedTurnId: string;
|
|
22
|
+
readonly seenTaskDeliveries?: Set<string>;
|
|
17
23
|
readonly token: string;
|
|
18
24
|
});
|
|
19
25
|
/** Token passed to the turn workflow so it can publish control messages. */
|
|
@@ -38,4 +44,8 @@ export declare class TurnControlReceiver {
|
|
|
38
44
|
* accepted by the turn and ahead of deliveries that arrived later.
|
|
39
45
|
*/
|
|
40
46
|
private awaitForwardedDelivery;
|
|
47
|
+
private acceptTaskDelivery;
|
|
48
|
+
private discardTaskDeliveries;
|
|
49
|
+
private originatesFromCancelledTask;
|
|
50
|
+
private shouldDiscard;
|
|
41
51
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{createHook}from"#compiled/@workflow/core/index.js";import{closeHookIterator,disposeHook}from"#execution/hook-ownership.js";import{turnCancellationHookToken}from"#execution/turn-cancellation-token.js";import{forwardTurnCancellationStep}from"#execution/forward-turn-cancellation-step.js";import{forwardTurnDeliveryStep}from"#execution/forward-turn-delivery-step.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";var TurnControlReceiver=class{bufferedDeliveries;bufferedSessionControls;commandInbox;control;controlIterator;pendingControl=null;constructor(e){this.bufferedDeliveries=e.bufferedDeliveries,this.bufferedSessionControls=e.bufferedSessionControls,this.commandInbox=e.commandInbox,this.control=createHook({token:e.token}),this.controlIterator=this.control[Symbol.asyncIterator]()}get token(){return this.control.token}async dispose(){await closeHookIterator(this.controlIterator),await disposeHook(this.control)}async waitForAction(){for(;;){let e=await this.nextControlOrCommand();if(e.kind===`command`){let t=await this.handleSessionCommand(e.command);if(t!==void 0)return t;continue}let t=e.payload,n=this.readTerminalControl(t);if(n!==void 0)return n;if(t.kind===`turn-delivery-request`){let e=await this.serviceDeliveryRequest(t);if(e!==void 0)return e}}}async handleSessionCommand(t){if(t.kind===`deliver`){await this.bufferDelivery(t);return}if(t.kind===`send`){await this.bufferDelivery(sendCommandToDelivery(t));return}if(t.kind===`clear`||t.kind===`compact`){this.bufferedSessionControls.push(t.kind);return}if(t.kind===`session-timeout`){this.bufferedSessionControls.push(`expired`);return}if(t.kind!==`runtime-action-result`){if(t.kind===`cancel`){await forwardTurnCancellationStep({payload:
|
|
1
|
+
import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{createHook}from"#compiled/@workflow/core/index.js";import{closeHookIterator,disposeHook}from"#execution/hook-ownership.js";import{turnCancellationHookToken}from"#execution/turn-cancellation-token.js";import{forwardTurnCancellationStep}from"#execution/forward-turn-cancellation-step.js";import{forwardTurnDeliveryStep}from"#execution/forward-turn-delivery-step.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";var TurnControlReceiver=class{bufferedDeliveries;bufferedSessionControls;commandInbox;control;controlIterator;expectedTurnId;cancelledTaskIds;seenTaskDeliveries;pendingControl=null;constructor(e){this.bufferedDeliveries=e.bufferedDeliveries,this.bufferedSessionControls=e.bufferedSessionControls,this.cancelledTaskIds=e.cancelledTaskIds??new Set,this.commandInbox=e.commandInbox,this.seenTaskDeliveries=e.seenTaskDeliveries??new Set,this.control=createHook({token:e.token}),this.controlIterator=this.control[Symbol.asyncIterator](),this.expectedTurnId=e.expectedTurnId}get token(){return this.control.token}async dispose(){await closeHookIterator(this.controlIterator),await disposeHook(this.control)}async waitForAction(){for(;;){let e=await this.nextControlOrCommand();if(e.kind===`command`){let t=await this.handleSessionCommand(e.command);if(t!==void 0)return t;continue}let t=e.payload,n=this.readTerminalControl(t);if(n!==void 0)return n;if(t.kind===`turn-delivery-request`){let e=await this.serviceDeliveryRequest(t);if(e!==void 0)return e}}}async handleSessionCommand(t){if(t.kind===`deliver`){if(!this.acceptTaskDelivery(t))return;await this.bufferDelivery(t);return}if(t.kind===`send`){if(!this.acceptTaskDelivery(t))return;await this.bufferDelivery(sendCommandToDelivery(t));return}if(t.kind===`clear`||t.kind===`compact`){this.bufferedSessionControls.push(t.kind);return}if(t.kind===`session-timeout`){this.bufferedSessionControls.push(`expired`);return}if(t.kind!==`runtime-action-result`){if(t.kind===`cancel`){t.taskId!==void 0&&this.discardTaskDeliveries(t.taskId);let e=t.taskId!==void 0&&t.turnId!==void 0&&t.turnId!==this.expectedTurnId?void 0:t.turnId;await forwardTurnCancellationStep({payload:e===void 0?{}:{turnId:e},token:turnCancellationHookToken(this.control.token)});return}if(t.kind===`reset`){await forwardTurnCancellationStep({payload:{},token:turnCancellationHookToken(this.control.token)}),this.bufferedSessionControls.push(`reset`);return}return unsupportedSessionCommand(t)}}async bufferDelivery(e){this.bufferedDeliveries.push(e),!(e.turnPolicy!==`steer`||!deliveryHasMessage(e))&&await forwardTurnCancellationStep({payload:{},token:turnCancellationHookToken(this.control.token)})}bufferTurnDeliveries(e){e.bufferedDeliveries!==void 0&&this.bufferedDeliveries.unshift(...e.bufferedDeliveries.filter(e=>!this.shouldDiscard(e)))}consumeControl(){this.pendingControl=null}getControlPromise(){return this.pendingControl??=this.controlIterator.next(),this.pendingControl}async nextControlOrCommand(){let e=await Promise.race([this.getControlPromise().then(e=>({kind:`control`,value:e})),this.commandInbox.next().then(e=>({kind:`command`,value:e}))]);if(e.kind===`command`){if(e.value.done)throw Error(`Session command inbox closed before the active turn settled.`);return this.commandInbox.consumeNext(),{command:e.value.value,kind:`command`}}if(this.consumeControl(),e.value.done)throw Error(`Turn control hook closed before delivering a result.`);let t=e.value.value;if(t.kind===`turn-error`)throw rebuildSerializableError(t.error);return t.kind===`turn-continuation-token`?(await this.commandInbox.rekeyContinuation(t.continuationToken),await this.nextControlOrCommand()):{kind:`control`,payload:t}}readTerminalControl(e){if(e.kind===`turn-error`)throw rebuildSerializableError(e.error);if(e.kind===`turn-result`)return this.bufferTurnDeliveries(e),e.action}async serviceDeliveryRequest(t){await this.commandInbox.rekeyContinuation(t.continuationToken);let n=this.takeInputResponseDelivery();for(;n===void 0;){let r=await Promise.race([this.getControlPromise().then(e=>({kind:`control`,value:e})),this.commandInbox.next().then(e=>({kind:`command`,value:e}))]);if(r.kind===`control`){if(this.consumeControl(),r.value.done)throw Error(`Turn control hook closed during a delivery request.`);if(r.value.value.kind===`turn-continuation-token`){await this.commandInbox.rekeyContinuation(r.value.value.continuationToken);continue}let e=this.readTerminalControl(r.value.value);if(e!==void 0)return e;if(r.value.value.kind===`turn-delivery-cancelled`&&r.value.value.requestId===t.requestId)return;continue}if(r.value.done)throw Error(`Session command inbox closed during a turn delivery request.`);if(this.commandInbox.consumeNext(),r.value.value.kind===`deliver`){if(!this.acceptTaskDelivery(r.value.value))continue;deliveryHasMessage(r.value.value)?await this.bufferDelivery(r.value.value):n=r.value.value;continue}if(r.value.value.kind===`send`){if(!this.acceptTaskDelivery(r.value.value))continue;let t=sendCommandToDelivery(r.value.value);deliveryHasMessage(t)?await this.bufferDelivery(t):n=t;continue}let i=await this.handleSessionCommand(r.value.value);if(i!==void 0)return i}try{await forwardTurnDeliveryStep({inboxToken:t.inboxToken,payload:{delivery:n,kind:`driver-delivery`,requestId:t.requestId}})}catch(e){if(!(e instanceof Error&&e.name===`HookNotFoundError`))throw e}return await this.awaitForwardedDelivery(t.requestId,n)}takeInputResponseDelivery(){let e=this.bufferedDeliveries.findIndex(e=>!deliveryHasMessage(e));if(e!==-1)return this.bufferedDeliveries.splice(e,1)[0]}async awaitForwardedDelivery(e,t){for(;;){let n=await this.nextControlOrCommand();if(n.kind===`command`){let e=await this.handleSessionCommand(n.command);if(e!==void 0)return this.shouldDiscard(t)||this.bufferedDeliveries.unshift(t),e;continue}let r=n.payload;if(r.kind===`turn-delivery-accepted`){if(r.requestId===e)return;continue}if(r.kind===`turn-delivery-cancelled`&&r.requestId===e){this.shouldDiscard(t)||this.bufferedDeliveries.unshift(t);return}r.kind===`turn-result`&&(this.shouldDiscard(t)||this.bufferedDeliveries.unshift(t));let i=this.readTerminalControl(r);if(i!==void 0)return i}}acceptTaskDelivery(e){let t=e.taskDeliveryId??e.caller?.taskId;return t===void 0?!0:this.originatesFromCancelledTask(t)||this.seenTaskDeliveries.has(t)?!1:(this.seenTaskDeliveries.add(t),!0)}discardTaskDeliveries(e){this.cancelledTaskIds.add(e);let t=this.bufferedDeliveries.filter(e=>!this.shouldDiscard(e));this.bufferedDeliveries.splice(0,this.bufferedDeliveries.length,...t)}originatesFromCancelledTask(e){return[...this.cancelledTaskIds].some(t=>deliveryOriginatesFromTask(e,t))}shouldDiscard(e){let t=e.taskDeliveryId??e.caller?.taskId;return t!==void 0&&this.originatesFromCancelledTask(t)}};function deliveryOriginatesFromTask(e,t){return e===t||e.startsWith(`${t}:`)}function deliveryHasMessage(e){return e.payloads.some(e=>e.message!==void 0)}function unsupportedSessionCommand(e){throw Error(`Unsupported session command: ${JSON.stringify(e)}`)}export{TurnControlReceiver};
|
|
@@ -21,11 +21,13 @@ export declare function dispatchAndAwaitTurn(input: {
|
|
|
21
21
|
readonly bufferedDeliveries: DeliverHookPayload[];
|
|
22
22
|
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
|
|
23
23
|
readonly capabilities?: SessionCapabilities;
|
|
24
|
+
readonly cancelledTaskIds?: Set<string>;
|
|
24
25
|
readonly controlToken: string;
|
|
25
26
|
readonly delivery: HookPayload;
|
|
26
27
|
readonly commandInbox: SessionCommandInbox;
|
|
27
28
|
readonly mode: RunMode;
|
|
28
29
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
29
30
|
readonly serializedContext: Record<string, unknown>;
|
|
31
|
+
readonly seenTaskDeliveries?: Set<string>;
|
|
30
32
|
readonly sessionState: DurableSessionState;
|
|
31
33
|
}): Promise<DispatchedTurn>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dispatchTurnStep}from"#execution/dispatch-turn-step.js";import{TurnControlReceiver}from"#execution/turn-control-receiver.js";async function dispatchAndAwaitTurn(t){let n=new TurnControlReceiver({bufferedDeliveries:t.bufferedDeliveries,bufferedSessionControls:t.bufferedSessionControls,commandInbox:t.commandInbox,token:t.controlToken});try{return await dispatchTurnStep({capabilities:t.capabilities,completionToken:n.token,delivery:t.delivery,mode:t.mode,parentWritable:t.parentWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),{action:await n.waitForAction(),dispose:()=>n.dispose()}}catch(e){throw await n.dispose(),e}}export{dispatchAndAwaitTurn};
|
|
1
|
+
import{activeTurnId}from"#harness/active-turn-id.js";import{dispatchTurnStep}from"#execution/dispatch-turn-step.js";import{TurnControlReceiver}from"#execution/turn-control-receiver.js";async function dispatchAndAwaitTurn(t){let n=new TurnControlReceiver({bufferedDeliveries:t.bufferedDeliveries,bufferedSessionControls:t.bufferedSessionControls,cancelledTaskIds:t.cancelledTaskIds,commandInbox:t.commandInbox,expectedTurnId:activeTurnId(t.sessionState.emissionState),seenTaskDeliveries:t.seenTaskDeliveries??new Set,token:t.controlToken});try{return await dispatchTurnStep({capabilities:t.capabilities,completionToken:n.token,delivery:t.delivery,mode:t.mode,parentWritable:t.parentWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),{action:await n.waitForAction(),dispose:()=>n.dispose()}}catch(e){throw await n.dispose(),e}}export{dispatchAndAwaitTurn};
|
|
@@ -2,6 +2,7 @@ import type { DeliverHookPayload } from "#channel/types.js";
|
|
|
2
2
|
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
|
|
3
3
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
4
4
|
import type { TurnStepInput, TurnStepPayload } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
5
|
+
import { SessionStateCursor } from "#execution/session-state-cursor.js";
|
|
5
6
|
import type { SettledTurn } from "#harness/types.js";
|
|
6
7
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
7
8
|
interface TurnTransition {
|
|
@@ -22,11 +23,9 @@ type TurnTerminalAction = {
|
|
|
22
23
|
readonly settled?: SettledTurn;
|
|
23
24
|
};
|
|
24
25
|
/** Owns the mutable durable state cursor for one active turn workflow. */
|
|
25
|
-
export declare class TurnExecutionCursor {
|
|
26
|
+
export declare class TurnExecutionCursor extends SessionStateCursor {
|
|
26
27
|
readonly controlToken: string;
|
|
27
28
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
28
|
-
private currentSerializedContext;
|
|
29
|
-
private currentSessionState;
|
|
30
29
|
private lastReportedContinuationToken;
|
|
31
30
|
constructor(input: {
|
|
32
31
|
readonly controlToken: string;
|
|
@@ -34,10 +33,6 @@ export declare class TurnExecutionCursor {
|
|
|
34
33
|
readonly serializedContext: Record<string, unknown>;
|
|
35
34
|
readonly sessionState: DurableSessionState;
|
|
36
35
|
});
|
|
37
|
-
/** Latest serialized runtime context adopted by the active turn. */
|
|
38
|
-
get serializedContext(): Record<string, unknown>;
|
|
39
|
-
/** Latest durable session state adopted by the active turn. */
|
|
40
|
-
get sessionState(): DurableSessionState;
|
|
41
36
|
/** Adopts a state transition and reports any continuation-token change once. */
|
|
42
37
|
adopt(transition: TurnTransition): Promise<void>;
|
|
43
38
|
/** Builds the next atomic turn-step input from the cursor's current state. */
|
|
@@ -50,6 +45,5 @@ export declare class TurnExecutionCursor {
|
|
|
50
45
|
finish(transition: TurnTransition, action: TurnTerminalAction, bufferedDeliveries: readonly DeliverHookPayload[]): Promise<void>;
|
|
51
46
|
/** Sends one control payload to the session driver. */
|
|
52
47
|
send(payload: TurnControlPayload): Promise<void>;
|
|
53
|
-
private setState;
|
|
54
48
|
}
|
|
55
49
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sendTurnControlStep}from"#execution/turn-control-protocol.js";var TurnExecutionCursor=class{controlToken;parentWritable;
|
|
1
|
+
import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";var TurnExecutionCursor=class extends SessionStateCursor{controlToken;parentWritable;lastReportedContinuationToken;constructor(e){super({serializedContext:e.serializedContext,sessionState:e.sessionState}),this.controlToken=e.controlToken,this.lastReportedContinuationToken=e.sessionState.continuationToken,this.parentWritable=e.parentWritable}async adopt(e){this.adoptState(e);let t=e.sessionState.continuationToken;t===``||t===this.lastReportedContinuationToken||(this.lastReportedContinuationToken=t,await this.send({continuationToken:t,kind:`turn-continuation-token`}))}createStepInput(e,t){return{abortSignal:t,input:e,parentWritable:this.parentWritable,serializedContext:this.serializedContext,sessionState:this.sessionState}}async finish(e,t,n){this.adoptState(e),await this.send({action:{...t,serializedContext:this.serializedContext,sessionState:this.sessionState},bufferedDeliveries:n.length===0?void 0:[...n],kind:`turn-result`})}async send(t){await sendTurnControlStep({controlToken:this.controlToken,payload:t})}};export{TurnExecutionCursor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{
|
|
1
|
+
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{dispatchTaskStep}from"#execution/tasks/parent/dispatch-task-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{turnStep}from"#execution/workflow-steps.js";import{getRuntimeActionResultKey}from"#runtime/actions/keys.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 n=migrateTurnWorkflowInput(e);return n.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(n):runLegacyTurnWorkflow(n)}async function runTurnOwnedWorkflow(t){let i=createHook({token:`${t.completionToken}:inbox`}),a=i[Symbol.asyncIterator](),c=new TurnExecutionCursor({controlToken:t.completionToken,parentWritable:t.stepInput.parentWritable,serializedContext:t.stepInput.serializedContext,sessionState:t.stepInput.sessionState}),m=0,nextDeliveryRequestId=()=>`${i.token}:delivery:${String(m++)}`,h=[],g=t.stepInput.input,_=!1,v;try{try{await claimHookOwnership(i),_=!0}catch(e){if(isHookConflictError(e))return;throw e}for(t.driverCapabilities?.cancelledTurnSettle===!0&&(v=await createTurnCancellationControl({controlToken:t.completionToken,expectedTurnId:activeTurnId(t.stepInput.sessionState.emissionState)}));;){let o=await turnStep(c.createStepInput(g,v?.signal)),l=o.action===`dispatch-workflow-runtime-actions`||o.action===`park`?o.pendingRuntimeActionKeys:void 0;if(o.action===`cancelled`){await c.adopt(o),await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(v?.signal.aborted===!0&&l===void 0){await c.adopt({serializedContext:preserveSerializedSessionDynamicModelSelection(c.serializedContext,o.serializedContext),sessionState:c.sessionState}),await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(o.sleepDurationMs!==void 0&&await waitForTurnSleep(o.sleepDurationMs,v)===`cancel`){await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(o.action===`done`){await v?.dispose(),await c.finish(o,{kind:`done`,output:o.output??``,isError:o.isError,usage:o.usage,usageDelta:o.usageDelta},h);return}if(l!==void 0){await c.adopt(o);let t=o.action===`park`&&o.tasksEnabled,u;u=o.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:t?dispatchTaskStep:dispatchRuntimeActionsStep;let d=await u({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:i.token,parentWritable:c.parentWritable,serializedContext:c.serializedContext,sessionState:c.sessionState}),f=d.results.length===0?void 0:Date.now();await c.adopt(d),await acknowledgeDelegatedTasksStep({tasks:d.pendingTasks});let p=await waitForRuntimeActionResults({bufferedDeliveries:h,cancellation:v,cursor:c,inboxToken:i.token,initialAcceptedAtMs:f,initialResults:d.results,iterator:a,nextDeliveryRequestId,pendingActionKeys:l});if(p===`cancelled`){g=void 0;continue}if(p===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}g={kind:`runtime-action-result`,...p};continue}if(o.action===`park`){if(!(o.hasPendingAuthorization||o.hasPendingInputBatch&&t.capabilities?.requestInput===!0||t.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await v?.dispose(),await c.finish(o,{authorizationAttemptIds:o.authorizationAttemptIds,authorizationNames:o.authorizationNames,kind:`park`,settled:o.settled},h);return}await c.adopt(o),g=void 0}}catch(e){throw await c.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{v!==void 0&&await v.dispose(),_&&await disposeHook(i)}}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],r=new Map;if(e.initialAcceptedAtMs!==void 0)for(let t of e.initialResults)r.set(getRuntimeActionResultKey(t),e.initialAcceptedAtMs);for(;;){let o=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:n});if(o!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(getRuntimeActionResultKey(e))])),results:o};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 s=e.iterator.next();s.catch(()=>{});let c=await(e.cancellation===void 0?s:Promise.race([s,e.cancellation.requested]));if(c===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(c.done)throw Error(`Turn inbox closed before runtime actions completed.`);let l=c.value;if(l.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state,i=l.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e));if(i.length>0){let e=Date.now();n.push(...i);for(let t of i)r.set(getRuntimeActionResultKey(t),e)}continue}if(l.kind===`subagent-input-request`||l.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:l,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(l.kind===`driver-delivery`&&l.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:l.requestId}),t=void 0;let n=await routeDeliverToChildren({delivery:l.delivery,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});if(await e.cursor.adopt({serializedContext:n.serializedContext??e.cursor.serializedContext,sessionState:n.sessionState??e.cursor.sessionState}),n.kind===`cancel-turn`)return n.kind;n.remainder!==void 0&&e.bufferedDeliveries.push(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};
|
|
@@ -28,3 +28,8 @@ export declare function resolveWorkflowCallbackBaseUrl(metadataUrl: string): str
|
|
|
28
28
|
* `new URL(path, base)` would drop for absolute paths.
|
|
29
29
|
*/
|
|
30
30
|
export declare function createWorkflowCallbackUrl(baseUrl: string, callbackPath: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* Builds a callback to a remote task child without disclosing this deployment's
|
|
33
|
+
* protection bypass secret to an authored external origin.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createRemoteTaskInputCallbackUrl(baseUrl: string, callbackPath: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_PUBLIC_ROUTE_PREFIX_ENV,normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function resolveWorkflowCallbackBaseUrl(n){let r=process.env.WORKFLOW_LOCAL_BASE_URL?.trim()||void 0,i=(resolveVercelProductionCallbackBaseUrl()??r??n).replace(/\/$/,``),a=normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]);return a===void 0?i:`${i}${a}`}function createWorkflowCallbackUrl(e,t){let
|
|
1
|
+
import{EVE_PUBLIC_ROUTE_PREFIX_ENV,normalizePublicRoutePrefix}from"#shared/public-route-prefix.js";const VERCEL_PROTECTION_BYPASS_QUERY=`x-vercel-protection-bypass`,VERCEL_CALLBACK_HOST_ENVS=[`VERCEL_URL`,`VERCEL_BRANCH_URL`,`VERCEL_PROJECT_PRODUCTION_URL`];function resolveVercelProductionCallbackBaseUrl(){return process.env.VERCEL_ENV===`production`&&process.env.VERCEL_PROJECT_PRODUCTION_URL?`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`:null}function resolveWorkflowCallbackBaseUrl(n){let r=process.env.WORKFLOW_LOCAL_BASE_URL?.trim()||void 0,i=(resolveVercelProductionCallbackBaseUrl()??r??n).replace(/\/$/,``),a=normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]);return a===void 0?i:`${i}${a}`}function createWorkflowCallbackUrl(e,t){let r=new URL(`${e.replace(/\/$/,``)}${t}`),i=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return i&&r.searchParams.set(VERCEL_PROTECTION_BYPASS_QUERY,i),r.toString()}function createRemoteTaskInputCallbackUrl(e,t){let i=new URL(`${e.replace(/\/$/,``)}${t}`),a=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim(),o=VERCEL_CALLBACK_HOST_ENVS.some(e=>process.env[e]?.trim().toLowerCase()===i.hostname.toLowerCase());return a&&i.protocol===`https:`&&o&&i.searchParams.set(VERCEL_PROTECTION_BYPASS_QUERY,a),i.toString()}export{createRemoteTaskInputCallbackUrl,createWorkflowCallbackUrl,resolveVercelProductionCallbackBaseUrl,resolveWorkflowCallbackBaseUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.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{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:s,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`]=s;let _=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let i=readRootSessionId(e.serializedContext),a=readSerializedSubagentDepth(e.serializedContext),o=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:c}=await createSessionStep({compiledArtifactsSource:g.source,continuationToken:p,dynamicSubagentAgentConfig:o,inheritedLimits:e.limits,nodeId:g.nodeId,outputSchema:e.input.outputSchema,rootSessionId:i,sessionId:s,subagentDepth:a});v.lastSessionState=c,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let l=await runDriverLoop({capabilities:h,driverWritable:_,initialInput:{deliveryMetadata:e.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...e.serializedContext[`eve.channelDelivery`],payloadIndex:0}],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:s,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,s=new Set(e.expectedAttemptIds);for(let e of n.keys())s.has(e)||n.delete(e);for(;;){if(s.size>0&&[...s].every(e=>n.has(e))){let e=[...s].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e,sessionState:r}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:s.size>0,bufferedDeliveries:i,bufferedSessionControls:a,commandInbox:o,deferDeliveries:t.mode===`task`&&s.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`&&s.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=[],a=[],o=createSessionCommandInbox(),c=sessionCommandHookToken(t.sessionState.sessionId);await o.claimStable(c),await o.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:a,capabilities:t.capabilities,commandInbox:o,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 o.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 o.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:{...r.remainder,kind:`deliver`},serializedContext:e.serializedContext,sessionState:e.sessionState}),t.crashCleanupState.lastSessionState=e.sessionState}}finally{await d?.(),await u?.dispose(),await o.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};
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,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{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:o,workflowStartedAt:s}=getWorkflowMetadata(),u=e.serializedContext[`eve.continuationToken`]||``,d=e.serializedContext[`eve.mode`],f=e.serializedContext[`eve.capabilities`],p=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=o;let h=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let i=readRootSessionId(e.serializedContext),a=readSerializedSubagentDepth(e.serializedContext),c=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:l}=await createSessionStep({compiledArtifactsSource:p.source,continuationToken:u,dynamicSubagentAgentConfig:c,inheritedLimits:e.limits,nodeId:p.nodeId,outputSchema:e.input.outputSchema,rootSessionId:i,sessionId:o,subagentDepth:a});v.lastSessionState=l,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let m=await runDriverLoop({capabilities:f,driverWritable:h,initialInput:{deliveryMetadata:e.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...e.serializedContext[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:d,serializedContext:e.serializedContext,sessionState:l,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(s.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return m.kind===`result`?m.result:await finalizeExpiredSession({caller:v.caller,driverWritable:h,mode:d,serializedContext:m.serializedContext,sessionState:m.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:h,serializedContext:e.serializedContext}),d===`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:o,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())r.has(e)||n.delete(e);for(;;){if(r.size>0&&[...r].every(e=>n.has(e))){let e=[...r].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:r.size>0,bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:c,commandInbox:m,deferDeliveries:t.mode===`task`&&r.size>0,driverWritable:t.driverWritable,seenTaskDeliveries:l,stateCursor:v});if(e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&r.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}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],c=new Set,l=new Set,m=createSessionCommandInbox(),g=sessionCommandHookToken(t.sessionState.sessionId);await m.claimStable(g),await m.claimAuthorization(`${t.sessionState.sessionId}:auth`);let _=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:g}),v=new SessionStateCursor({serializedContext:t.serializedContext,sessionState:t.sessionState}),y,runTurn=async e=>{let n=t.crashCleanupState.caller;n?.taskId!==void 0&&(l.add(n.taskId),await notifyTaskTurnStartedStep({caller:n,childSessionId:v.sessionState.sessionId,childTurnId:activeTurnId(v.sessionState.emissionState)}));let r=await bindTurnCallerContextStep({caller:n,serializedContext:v.serializedContext}),o=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:c,capabilities:t.capabilities,commandInbox:m,controlToken:nextTurnControlToken(),delivery:e,mode:t.mode,parentWritable:t.driverWritable,serializedContext:r,seenTaskDeliveries:l,sessionState:v.sessionState});return await y?.(),y=o.dispose,v.adoptState(o.action),t.crashCleanupState.lastSessionState=v.sessionState,o.action};try{if(t.sessionState.continuationToken)try{await m.rekeyContinuation(t.sessionState.continuationToken)}catch(e){if(!isHookConflictError(e))throw e;return{kind:`result`,result:{output:``}}}await _?.start();let e=await runTurn(t.initialInput);for(;;){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 e=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(e);let n={caller:t.crashCleanupState.caller,sessionId:v.sessionState.sessionId};await notifyCancelledTaskCallerStep(e.usage===void 0?n:{...n,usage:e.usage}),t.crashCleanupState.lastSessionState=v.sessionState}v.sessionState.continuationToken&&await m.rekeyContinuation(v.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:v.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[]});if(t.crashCleanupState.lastSessionState=v.sessionState,r.kind===`authorization-resume`){e=await runTurn({kind:`deliver`,payloads:r.payloads});continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:v.serializedContext,sessionState:v.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({kind:r.kind});continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:v.serializedContext,sessionState:v.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(n),e={...e,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=v.sessionState;continue}r.delivery.caller!==void 0&&(t.crashCleanupState.caller=r.delivery.caller),e=await runTurn(r.delivery)}}finally{await y?.(),await _?.dispose(),await m.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({serializedContext:e.serializedContext,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({serializedContext:n,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:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage: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};
|
|
@@ -14,6 +14,9 @@ export declare const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE = "deploymentId 'late
|
|
|
14
14
|
* template) read this single set so they cannot drift.
|
|
15
15
|
*/
|
|
16
16
|
export declare const STABLE_WORKFLOW_NAMES: ReadonlySet<string>;
|
|
17
|
+
interface WorkflowHookRecord {
|
|
18
|
+
readonly runId: string;
|
|
19
|
+
}
|
|
17
20
|
/**
|
|
18
21
|
* Stable workflow reference used by `start()` to locate the workflow
|
|
19
22
|
* entrypoint registered by the Workflow DevKit builder. The id omits
|
|
@@ -37,6 +40,10 @@ export declare const turnWorkflowReference: {
|
|
|
37
40
|
export declare const sessionTimeoutWorkflowReference: {
|
|
38
41
|
workflowId: string;
|
|
39
42
|
};
|
|
43
|
+
/** Stable workflow reference for durable task runs (`experimental.tasks`). */
|
|
44
|
+
export declare const taskRunWorkflowReference: {
|
|
45
|
+
workflowId: string;
|
|
46
|
+
};
|
|
40
47
|
/**
|
|
41
48
|
* Creates a workflow-backed runtime whose long-lived driver owns the
|
|
42
49
|
* event stream and dispatches each turn as a child workflow run.
|
|
@@ -48,8 +55,10 @@ export declare function createWorkflowRuntime(config: {
|
|
|
48
55
|
}): Runtime;
|
|
49
56
|
/** Requests cancellation through a session's stable command inbox. */
|
|
50
57
|
export declare function requestWorkflowTurnCancellation(input: CancelTurnInput): Promise<CancelTurnResult>;
|
|
58
|
+
export declare function waitForCommandHookOwner(token: string): Promise<WorkflowHookRecord>;
|
|
51
59
|
/**
|
|
52
60
|
* Starts a workflow on the latest deployment when latest routing applies,
|
|
53
61
|
* while preserving local/dev worlds that do not implement latest routing.
|
|
54
62
|
*/
|
|
55
63
|
export declare function startWorkflowPreferLatest<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata, args: TArgs, options?: StartOptionsWithoutDeploymentId): Promise<Run<unknown> | Run<TResult>>;
|
|
64
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f=l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,TASK_RUN_WORKFLOW_NAME=`taskRunWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f={...l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),...i.externalInvocation===void 0?{}:buildInvocationAttributes(i.externalInvocation)},p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(i.continuationToken){let e=await waitForCommandHookOwner(i.continuationToken);if(e.runId!==p.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:i.continuationToken,ownerSessionId:e.runId,sessionId:p.runId})}await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId);let m,getEvents=()=>(m??=parseNdjsonStream(()=>getRun(p.runId).getReadable()),m);return{get events(){return getEvents()},sessionId:p.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeHook(e,sessionHookPayload(n)))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function sessionHookPayload(e){return e.kind===`send`?sendCommandToDelivery(e):e}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { SettledTurn } from "#harness/types.js";
|
|
2
2
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
3
|
-
import type { JsonObject } from "#shared/json.js";
|
|
4
|
-
import type { RunMode } from "#shared/run-mode.js";
|
|
5
3
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
6
4
|
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
7
5
|
/**
|
|
@@ -44,6 +42,12 @@ export type DurableStepResult = {
|
|
|
44
42
|
readonly hasPendingAuthorization: boolean;
|
|
45
43
|
readonly hasPendingInputBatch: boolean;
|
|
46
44
|
readonly pendingRuntimeActionKeys?: readonly string[];
|
|
45
|
+
/**
|
|
46
|
+
* Selects the dispatch step for `pendingRuntimeActionKeys`:
|
|
47
|
+
* `dispatchTaskStep` when the agent runs `experimental.tasks`,
|
|
48
|
+
* `dispatchRuntimeActionsStep` otherwise (including when absent).
|
|
49
|
+
*/
|
|
50
|
+
readonly tasksEnabled?: boolean;
|
|
47
51
|
readonly sleepDurationMs?: number;
|
|
48
52
|
readonly serializedContext: Record<string, unknown>;
|
|
49
53
|
readonly sessionState: DurableSessionState;
|
|
@@ -60,21 +64,3 @@ export type { TurnStepInput };
|
|
|
60
64
|
* Runs one atomic harness step inside a durable `"use step"` boundary.
|
|
61
65
|
*/
|
|
62
66
|
export declare function turnStep(rawInput: TurnStepInput): Promise<DurableStepResult>;
|
|
63
|
-
/**
|
|
64
|
-
* Resolves the single output schema in effect for this turn, decoupling schema
|
|
65
|
-
* enforcement from {@link RunMode}: downstream the harness reads
|
|
66
|
-
* `session.outputSchema` unconditionally and never re-derives it from mode.
|
|
67
|
-
*
|
|
68
|
-
* A run-scoped (client-supplied) schema on the turn's {@link StepInput} always
|
|
69
|
-
* wins. With no run-scoped schema, a task run adopts the agent's declared
|
|
70
|
-
* return schema — its function-output contract, which only applies when the
|
|
71
|
-
* agent is invoked as a function (subagent / schedule / job), i.e. task mode.
|
|
72
|
-
* A conversation run with no run-scoped schema enforces nothing. Continuation
|
|
73
|
-
* steps (no new `StepInput`) preserve whatever is already in effect.
|
|
74
|
-
*/
|
|
75
|
-
export declare function resolveEffectiveOutputSchema(input: {
|
|
76
|
-
readonly agentOutputSchema: JsonObject | undefined;
|
|
77
|
-
readonly input: StepInput | undefined;
|
|
78
|
-
readonly mode: RunMode;
|
|
79
|
-
readonly session: HarnessSession;
|
|
80
|
-
}): HarnessSession;
|
|
@@ -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{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{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{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{activeTurnId}from"#harness/active-turn-id.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{getInstrumentationRuntime}from"#harness/instrumentation/runtime.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{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.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{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.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=getInstrumentationRuntime(),g=getHarnessEmissionState(m.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:h?.hooks,rootSessionId:m.rootSessionId??m.sessionId,sequence:g.sequence,sessionId:m.sessionId,turnId:activeTurnId(g)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:h?.hooks,includeTurn:!1,outcome:`failed`})),await h?.forceFlush()},_=buildAdapterContext(l,c),v;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,_):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),v={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{..._.state}}),o.input?.kind===`deliver`&&v===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:h?.hooks,includeTurn:!1,outcome:`completed`})),await h?.forceFlush();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 y=u.hookRegistry,b=u.resolvedAgent.dynamicInstructionsResolvers??[],x=u.resolvedAgent.dynamicSkillResolvers??[],S=u.subagentRegistry.dynamicResolvers??[],C=u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,w=u.resolvedAgent.dynamicToolResolvers??[],T={...u.graph.root,turnAgent:d.turnAgent},E=buildRuntimeIdentity(T);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!g.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:E});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,persistentSessions:C,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:w,event:e,messages:m.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,_);setChannelContext(c,{...l,state:{..._.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:y,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:S,event:n,messages:t??[],persistentSessions:C}),await dispatchDynamicToolEvent({ctx:c,resolvers:w,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:x,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:b,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:v,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:E,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,E,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of p){let r=f?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({authorization:t,candidateId:r,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:T,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,v)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;D.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(o.serializedContext,t),t),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}}export{resolveEffectiveOutputSchema,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{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{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{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.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{getInstrumentationRuntime}from"#harness/instrumentation/runtime.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{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.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=u.resolvedAgent.config?.experimental?.tasks===!0,f=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 p=getPendingAuthorization(s.state),m;if(p&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(p,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))},m=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 h=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),g=getInstrumentationRuntime(),_=getHarnessEmissionState(h.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:g?.hooks,rootSessionId:h.rootSessionId??h.sessionId,sequence:_.sequence,sessionId:h.sessionId,turnId:activeTurnId(_)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:g?.hooks,includeTurn:!1,outcome:`failed`})),await g?.forceFlush()},v=buildAdapterContext(l,c),y;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,v):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}y=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),y={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...v.state}}),o.input?.kind===`deliver`&&y===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:g?.hooks,includeTurn:!1,outcome:`completed`})),await g?.forceFlush();let e=reconcileSessionContinuationToken(c,h),t=serializeContext(c),n=e===h?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let b=u.hookRegistry,x=u.resolvedAgent.dynamicInstructionsResolvers??[],S=u.resolvedAgent.dynamicSkillResolvers??[],C=u.subagentRegistry.dynamicResolvers??[],w=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,T=u.resolvedAgent.dynamicToolResolvers??[],E={...u.graph.root,turnAgent:f.turnAgent},D=buildRuntimeIdentity(E);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!_.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:D});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:C,event:e,messages:h.history,persistentSessions:w,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:h.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let O=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,v);setChannelContext(c,{...l,state:{...v.state}});let r=stampMessageStreamEvent(n);return await O.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{await forwardTaskEventToSessionCallback(c,e);let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:b,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:C,event:n,messages:t??[],persistentSessions:w}),await dispatchDynamicToolEvent({ctx:c,resolvers:T,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:x,event:n,messages:t??[]})},k=c.require(ModeKey),A;try{throwIfTurnAborted(o.abortSignal),A=await runStep(c,h,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:y,mode:k,session:e});if(m){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:D,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,D,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of m){let r=p?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,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:f.thresholdPercent},session:e,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:k,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:E,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,y)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;O.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let j=reconcileSessionContinuationToken(c,A.session),M=serializeContext(c);A={...A,session:j};let N=createDurableSessionState({session:A.session}),P=readTurnSleepDurationMs(c),F=P===void 0?{}:{sleepDurationMs:P};if(A.next!==null&&typeof A.next==`object`&&`done`in A.next){if(k===`task`&&hasPendingInputBatch(A.session.state))throw O.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await O.close();let e=getTurnUsageState(A.session.state)?.session;return{action:`done`,output:A.next.output,isError:A.next.isError,...F,serializedContext:M,sessionState:N,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(A.session).delta}}if(A.next===null){O.releaseLock();let e=getPendingWorkflowInterrupt(A.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...F,serializedContext:M,sessionState:N};let t=derivePendingState(A.session);if(A.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(A.session);return{action:`park`,...t,...F,serializedContext:M,sessionState:createDurableSessionState({session:n}),settled:{output:A.settledTurn.output,isError:A.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...t,...F,serializedContext:M,sessionState:N,tasksEnabled:d}}return O.releaseLock(),{action:`continue`,...F,serializedContext:M,sessionState:N}}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))}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session):filterUnavailableDelegationToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let
|
|
1
|
+
import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{TASK_TOOL_NAMES}from"#runtime/framework-tools/tasks.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session):filterUnavailableDelegationToolMap(e.tools,e.session)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let r=ensureWorkflowContinuationSecurity(e.session),{modelTools:a}=await applyWorkflowTool({continuationSecurity:getWorkflowContinuationSecurity(r),harnessTools:n,lifecycle:e.workflow.lifecycle?.({session:r,tools:n}),maxSubagents:e.workflow.maxSubagents,tools:e.modelTools});return{harnessTools:t,modelTools:a,session:r}}function filterUnavailableDelegationToolDefinitions(e,t){let n=[];for(let r of e)shouldHideDelegationTool(r,t)||n.push(r);return n}function filterUnavailableDelegationToolMap(e,t){let n=new Map;for(let[r,i]of e)shouldHideDelegationTool(i,t)||n.set(r,i);return n}function filterWorkflowHostToolsForRootSession(t,n){let r=new Map,i=resolveSubagentDepth(n);if(n.rootSessionId!==void 0||i.currentDepth>0)return r;for(let[e,n]of t)isDelegatedRuntimeActionTool(n)&&r.set(e,n);return r}function isDelegatedRuntimeActionTool(e){let t=e.runtimeAction;return t?.kind===`subagent-call`||t?.kind===`remote-agent-call`}function shouldHideDelegationTool(t,n){return isRootOnlyFrameworkTool(t)?n.rootSessionId!==void 0||resolveSubagentDepth(n).currentDepth>0:!1}function isRootOnlyFrameworkTool(e){return e.name===AGENT_TOOL_NAME&&e.runtimeAction?.kind===`subagent-call`&&e.runtimeAction.nodeId===ROOT_RUNTIME_AGENT_NODE_ID||TASK_TOOL_NAMES.has(e.name)}function isToolDefinitionList(e){return Array.isArray(e)}export{getAdvertisedTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,candidateId:e.candidateId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),o.length>0&&t.set(PendingAuthorizationResultKey,o),a}function getHookUrl(r,
|
|
1
|
+
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{createUlid}from"#shared/ulid.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({attemptId:e.attemptId,candidateId:e.candidateId,name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],o=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),o.length>0&&t.set(PendingAuthorizationResultKey,o),a}function getHookUrl(r,a){let o=loadContext(),s=o.get(SessionIdKey),c=o.get(CallbackBaseUrlKey);return!s||!c?void 0:createWorkflowCallbackUrl(c,createEveConnectionCallbackRoutePath(r,a,authHookToken(s)))}function createAuthorizationAttempt(e){let t=createUlid(),n=getHookUrl(e,t);return n===void 0?void 0:{attemptId:t,hookUrl:n}}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){let n=getPendingAuthorization(e)?.challenges??[],r=getSupersededAuthorizationChallenges(e,t.challenges);return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:[...n.filter(e=>!r.includes(e)),...t.challenges]}}}function getSupersededAuthorizationChallenges(e,t){return(getPendingAuthorization(e)?.challenges??[]).filter(e=>t.some(t=>e.name===t.name&&samePrincipal(e.principal,t.principal)))}function samePrincipal(e,t){return e===void 0||t===void 0?e===t:e.type===`app`||t.type===`app`?e.type===t.type:e.id===t.id&&e.issuer===t.issuer}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(e.attemptId??e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(!(typeof t!=`object`||!t))return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,createAuthorizationAttempt,getAuthorizationResult,getHookUrl,getPendingAuthorization,getSupersededAuthorizationChallenges,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
|
|
@@ -6,12 +6,19 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
|
6
6
|
*
|
|
7
7
|
* These tools are surfaced to the model without a local `execute` function.
|
|
8
8
|
* The harness records the tool call and the runtime executes it later.
|
|
9
|
+
*
|
|
10
|
+
* `task-control` marks the `experimental.tasks` parent tools
|
|
11
|
+
* (`task_peek`, `task_cancel`): they carry no child
|
|
12
|
+
* address of their own — the dispatch step resolves targets through the
|
|
13
|
+
* session task index by tool name.
|
|
9
14
|
*/
|
|
10
15
|
export type HarnessRuntimeActionDefinition = {
|
|
11
16
|
readonly kind: "remote-agent-call" | "subagent-call";
|
|
12
17
|
readonly nodeId: string;
|
|
13
18
|
readonly remoteAgentName?: string;
|
|
14
19
|
readonly subagentName: string;
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "task-control";
|
|
15
22
|
};
|
|
16
23
|
/**
|
|
17
24
|
* Unified harness-owned tool definition.
|
|
@@ -6,6 +6,15 @@ import type { AgentHandle, AgentHandleStore } from "#harness/handles/store.js";
|
|
|
6
6
|
* than authored user input.
|
|
7
7
|
*/
|
|
8
8
|
export declare const AGENTS_SNIPPET_LABEL = "[Agents]";
|
|
9
|
+
/** Model-safe projection of one persistent task-mode agent. */
|
|
10
|
+
export interface AgentView {
|
|
11
|
+
readonly availability: "available" | "busy";
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly name: string;
|
|
14
|
+
readonly statusLine?: string;
|
|
15
|
+
readonly taskId?: string;
|
|
16
|
+
readonly taskStatus?: "working" | "input_required";
|
|
17
|
+
}
|
|
9
18
|
/** Returns the resumable handles: the only phase the model may continue. */
|
|
10
19
|
export declare function projectParkedAgentHandles(store: AgentHandleStore): readonly Extract<AgentHandle, {
|
|
11
20
|
phase: "parked";
|
|
@@ -16,6 +25,8 @@ export declare function projectParkedAgentHandles(store: AgentHandleStore): read
|
|
|
16
25
|
* delivery coordinates never render.
|
|
17
26
|
*/
|
|
18
27
|
export declare function renderAgentsSnippet(store: AgentHandleStore): string;
|
|
28
|
+
/** Renders task-derived availability without exposing private addresses. */
|
|
29
|
+
export declare function renderAgentViewsSnippet(views: readonly AgentView[]): string;
|
|
19
30
|
/**
|
|
20
31
|
* Returns an append-only announcement when the visible handle listing
|
|
21
32
|
* changed since the last one in history, or `undefined` when it is
|
|
@@ -35,6 +46,7 @@ export declare function renderAgentsSnippet(store: AgentHandleStore): string;
|
|
|
35
46
|
* eve-injected so the model does not attribute it to the user.
|
|
36
47
|
*/
|
|
37
48
|
export declare function resolveAgentsAnnouncement(input: {
|
|
49
|
+
readonly agentViews?: readonly AgentView[];
|
|
38
50
|
readonly messages: readonly ModelMessage[];
|
|
39
51
|
readonly store: AgentHandleStore | undefined;
|
|
40
52
|
}): string | undefined;
|