eve 0.30.0 → 0.30.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 +6 -0
- package/dist/src/channel/routes.d.ts +11 -4
- package/dist/src/channel/send.js +1 -1
- package/dist/src/channel/types.d.ts +6 -3
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/execution/agent-handle-dispatch.d.ts +32 -0
- package/dist/src/execution/agent-handle-dispatch.js +1 -0
- package/dist/src/execution/cancel-descendant-turns-step.d.ts +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/delegated-parent-notification.d.ts +2 -2
- package/dist/src/execution/delegated-parent-result.d.ts +4 -4
- package/dist/src/execution/delegated-parent-result.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +8 -6
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +2 -2
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +10 -2
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +7 -2
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/session-callback-step.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +3 -3
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/agent-handle-errors.d.ts +25 -0
- package/dist/src/harness/agent-handle-errors.js +1 -0
- package/dist/src/harness/handles/operation-id.d.ts +15 -0
- package/dist/src/harness/handles/operation-id.js +1 -0
- package/dist/src/harness/handles/prompt.d.ts +21 -0
- package/dist/src/harness/handles/prompt.js +2 -0
- package/dist/src/harness/handles/query.d.ts +41 -0
- package/dist/src/harness/handles/query.js +1 -0
- package/dist/src/harness/handles/state-key.d.ts +8 -0
- package/dist/src/harness/handles/state-key.js +1 -0
- package/dist/src/harness/handles/store.d.ts +132 -0
- package/dist/src/harness/handles/store.js +1 -0
- package/dist/src/harness/handles/transitions.d.ts +107 -0
- package/dist/src/harness/handles/transitions.js +1 -0
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +4 -25
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/tool-loop.d.ts +22 -0
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/types.d.ts +6 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/protocol/agent-handle-error.d.ts +13 -0
- package/dist/src/protocol/agent-handle-error.js +1 -0
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/runtime/actions/results.d.ts +6 -0
- package/dist/src/runtime/actions/results.js +1 -0
- package/dist/src/runtime/actions/types.d.ts +40 -7
- package/dist/src/runtime/actions/types.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/package.json +1 -1
- package/dist/src/harness/agent-handles.d.ts +0 -238
- package/dist/src/harness/agent-handles.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.30.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- dae6f73: Upload Vercel sandbox workspace seed files in one compressed SDK request instead of one request per file, substantially reducing fresh template build times for large workspaces.
|
|
8
|
+
|
|
3
9
|
## 0.30.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { UserContent } from "ai";
|
|
2
2
|
import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";
|
|
3
|
-
import type { CancelTurnResult, ClearSessionResult, CompactSessionResult, SessionAuthContext, SessionCallback } from "#channel/types.js";
|
|
3
|
+
import type { CancelTurnResult, ClearSessionResult, CompactSessionResult, SessionAuthContext, SessionCallback, SessionCapabilities, TurnCaller } from "#channel/types.js";
|
|
4
4
|
import type { InputResponse } from "#runtime/input/types.js";
|
|
5
5
|
import type { Session } from "#channel/session.js";
|
|
6
6
|
import type { RunMode } from "#shared/run-mode.js";
|
|
@@ -60,9 +60,8 @@ export interface SendPayload {
|
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
62
|
* Starts or continues a session on this channel. Accepts a plain string,
|
|
63
|
-
* `UserContent`, or a {@link SendPayload}, plus {@link SendOptions}
|
|
64
|
-
*
|
|
65
|
-
* channels). Resolves to the resulting {@link Session}.
|
|
63
|
+
* `UserContent`, or a {@link SendPayload}, plus {@link SendOptions}. Resolves
|
|
64
|
+
* to the resulting {@link Session}.
|
|
66
65
|
*/
|
|
67
66
|
export type SendFn<TState = undefined> = (input: string | UserContent | SendPayload, options: SendOptions<TState>) => Promise<Session>;
|
|
68
67
|
/** Resolves the active owner of a channel-local continuation token. */
|
|
@@ -74,7 +73,15 @@ export type ResolveActiveSessionFn = (options: {
|
|
|
74
73
|
type BaseSendOptions = {
|
|
75
74
|
auth: SessionAuthContext | null;
|
|
76
75
|
callback?: SessionCallback;
|
|
76
|
+
/** Framework-internal delegated caller waiting on this turn's settled result. */
|
|
77
|
+
caller?: TurnCaller;
|
|
78
|
+
capabilities?: SessionCapabilities;
|
|
77
79
|
continuationToken: string;
|
|
80
|
+
/**
|
|
81
|
+
* `"resume"` requires an active session and propagates a typed no-active-session
|
|
82
|
+
* error. `"resume-or-start"` preserves the default channel behavior.
|
|
83
|
+
*/
|
|
84
|
+
intent?: "resume" | "resume-or-start";
|
|
78
85
|
/**
|
|
79
86
|
* The original (top-level) caller's auth for a newly started session,
|
|
80
87
|
* becoming `session.auth.initiator`. Defaults to {@link auth} when omitted
|
package/dist/src/channel/send.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSession}from"#channel/session.js";import{isRuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{serializeUrlFilePart}from"#internal/attachments/url-refs.js";function createSendFn(n,r,i,a={}){return async(o,s)=>{let c=s
|
|
1
|
+
import{createSession}from"#channel/session.js";import{isRuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{serializeUrlFilePart}from"#internal/attachments/url-refs.js";function createSendFn(n,r,i,a={}){return async(o,s)=>{let c=s,{auth:l,callback:u,caller:d,capabilities:f,initiatorAuth:p,state:m,title:h}=c,g=c.intent??`resume-or-start`,_=c.mode??`conversation`,v=c.continuationToken,y=`${i}:${v}`,{message:b,inputResponses:x,context:S,outputSchema:C}=normalizeSendInput(o),w=serializeUrlFilePartsInMessage(b);try{let t={auth:l,caller:d,continuationToken:y,requestId:a.requestId,payload:{inputResponses:x,message:w,context:S,outputSchema:C}},{sessionId:r}=await n.deliver(t);return createSession(r,v,n)}catch(e){if(!isRuntimeNoActiveSessionError(e)||g===`resume`)throw e}if(x&&x.length>0)throw Error(`Cannot deliver inputResponses — the target session was not found via continuation token.`);let T={adapter:m?{...r,state:{...r.state,...m}}:r,auth:l,capabilities:f??(_===`conversation`?{requestInput:!0}:void 0),channelName:i,callback:u,continuationToken:y,input:{message:w??``,context:S,outputSchema:C},mode:_,requestId:a.requestId,title:h};return p!==void 0&&(T.initiatorAuth=p),createSession((await n.run(T)).sessionId,v,n)}}function serializeUrlFilePartsInMessage(e){if(e===void 0||typeof e==`string`)return e;let t=!1,r=e.map(e=>e.type===`file`&&e.data instanceof URL&&e.data.protocol!==`data:`?(t=!0,{...e,data:serializeUrlFilePart(e.data)}):e);return t?r:e}function normalizeSendInput(e){return typeof e==`string`||Array.isArray(e)?{message:e}:e}export{createSendFn};
|
|
@@ -2,7 +2,7 @@ import type { UserContent } from "ai";
|
|
|
2
2
|
import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";
|
|
3
3
|
import type { CancelTurnStatus } from "#protocol/cancel-turn.js";
|
|
4
4
|
import type { RunMode } from "#shared/run-mode.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
|
|
6
6
|
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
|
|
7
7
|
import type { ChannelAdapter } from "#channel/adapter.js";
|
|
8
8
|
import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
|
|
@@ -181,11 +181,14 @@ export interface ClearSessionHookPayload {
|
|
|
181
181
|
readonly kind: "clear";
|
|
182
182
|
}
|
|
183
183
|
/**
|
|
184
|
-
*
|
|
184
|
+
* Child-produced subagent results resumed back into a parked parent workflow.
|
|
185
|
+
*
|
|
186
|
+
* The `runtime-action-result` discriminator predates this subagent-only inbox
|
|
187
|
+
* lane. Parent-produced dispatch results never travel through this hook.
|
|
185
188
|
*/
|
|
186
189
|
export interface RuntimeActionResultHookPayload {
|
|
187
190
|
readonly kind: "runtime-action-result";
|
|
188
|
-
readonly results: readonly
|
|
191
|
+
readonly results: readonly RuntimeSubagentChildResult[];
|
|
189
192
|
}
|
|
190
193
|
/**
|
|
191
194
|
* Event coordinates attached to a proxied `input.requested` batch.
|
|
@@ -11,13 +11,13 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
11
11
|
readonly dropped: {};
|
|
12
12
|
};
|
|
13
13
|
readonly tool: {
|
|
14
|
-
readonly current:
|
|
15
|
-
readonly supported: readonly [1, 2, 3];
|
|
14
|
+
readonly current: 4;
|
|
15
|
+
readonly supported: readonly [1, 2, 3, 4];
|
|
16
16
|
readonly dropped: {};
|
|
17
17
|
};
|
|
18
18
|
readonly dynamicTool: {
|
|
19
|
-
readonly current:
|
|
20
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
|
|
19
|
+
readonly current: 8;
|
|
20
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
|
|
21
21
|
readonly dropped: {};
|
|
22
22
|
};
|
|
23
23
|
readonly connection: {
|
|
@@ -26,8 +26,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
26
26
|
readonly dropped: {};
|
|
27
27
|
};
|
|
28
28
|
readonly hook: {
|
|
29
|
-
readonly current:
|
|
30
|
-
readonly supported: readonly [1, 2, 3, 4, 5];
|
|
29
|
+
readonly current: 6;
|
|
30
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6];
|
|
31
31
|
readonly dropped: {};
|
|
32
32
|
};
|
|
33
33
|
readonly skill: {
|
|
@@ -36,8 +36,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
36
36
|
readonly dropped: {};
|
|
37
37
|
};
|
|
38
38
|
readonly dynamicSkill: {
|
|
39
|
-
readonly current:
|
|
40
|
-
readonly supported: readonly [1, 2, 3, 4];
|
|
39
|
+
readonly current: 5;
|
|
40
|
+
readonly supported: readonly [1, 2, 3, 4, 5];
|
|
41
41
|
readonly dropped: {};
|
|
42
42
|
};
|
|
43
43
|
readonly instructions: {
|
|
@@ -46,8 +46,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
46
46
|
readonly dropped: {};
|
|
47
47
|
};
|
|
48
48
|
readonly dynamicInstructions: {
|
|
49
|
-
readonly current:
|
|
50
|
-
readonly supported: readonly [1, 2, 3, 4];
|
|
49
|
+
readonly current: 5;
|
|
50
|
+
readonly supported: readonly [1, 2, 3, 4, 5];
|
|
51
51
|
readonly dropped: {};
|
|
52
52
|
};
|
|
53
53
|
readonly config: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:
|
|
1
|
+
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:4,supported:[1,2,3,4],dropped:{}},dynamicTool:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:6,supported:[1,2,3,4,5,6],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:5,supported:[1,2,3,4,5],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:5,supported:[1,2,3,4,5],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared shapes for the runtime-action dispatch step: the hydrated parent
|
|
3
|
+
* session snapshot threaded through dispatch, and the per-action outcome
|
|
4
|
+
* every dispatch helper resolves to.
|
|
5
|
+
*/
|
|
6
|
+
import type { AgentAddress } from "#harness/handles/store.js";
|
|
7
|
+
import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
|
|
8
|
+
import type { hydrateDurableSession } from "#execution/session.js";
|
|
9
|
+
/** Hydrated parent session snapshot threaded through dispatch. */
|
|
10
|
+
export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;
|
|
11
|
+
/**
|
|
12
|
+
* Outcome of dispatching one planned runtime action: an adopted child ready
|
|
13
|
+
* for the `subagent.called` emission tail, or a per-action error result.
|
|
14
|
+
* Either way the (possibly updated) session snapshot rides along.
|
|
15
|
+
*
|
|
16
|
+
* `address` is the same confirmed {@link AgentAddress} recorded on the
|
|
17
|
+
* child's running handle; consumers project it into wire shapes (e.g. the
|
|
18
|
+
* flat `childSessionId` / `remote` fields of `subagent.called`) at the
|
|
19
|
+
* emission site instead of this type re-encoding them.
|
|
20
|
+
*/
|
|
21
|
+
export type DispatchOutcome = {
|
|
22
|
+
readonly address: AgentAddress;
|
|
23
|
+
readonly callId: string;
|
|
24
|
+
readonly kind: "called";
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly session: RuntimeSession;
|
|
27
|
+
readonly toolName: string;
|
|
28
|
+
} | {
|
|
29
|
+
readonly kind: "error";
|
|
30
|
+
readonly result: RuntimeSubagentDispatchFailure;
|
|
31
|
+
readonly session: RuntimeSession;
|
|
32
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
-
/** Cancels every
|
|
2
|
+
/** Cancels every running delegated child recorded in the agent handle store. */
|
|
3
3
|
export declare function cancelDescendantTurnsStep(input: {
|
|
4
4
|
readonly serializedContext: Record<string, unknown>;
|
|
5
5
|
readonly sessionState: DurableSessionState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";const log=createLogger(`execution.cancel-descendant-turns`);async function cancelDescendantTurnsStep(e){"use step";let a;try{a=(getAgentHandleStore((await readDurableSession(e.sessionState)).state)?.handles??[]).filter(e=>e.phase===`running`)}catch(n){logError(log,`failed to read pending descendants during cancellation`,n,{sessionId:e.sessionState.sessionId});return}if(a.length===0){log.warn(`no running agent handles found while cancelling descendants; nothing to cancel`,{sessionId:e.sessionState.sessionId});return}let o,getRemoteContext=()=>o??=deserializeContext(e.serializedContext).then(e=>({ctx:e,registry:e.require(BundleKey).subagentRegistry.subagentsByNodeId}));await Promise.all(a.map(e=>e.address.kind===`agent/remote`?cancelRemoteDescendant({handle:e,remoteContext:getRemoteContext()}):cancelLocalDescendant({handle:e})))}async function cancelLocalDescendant(e){let{handle:n}=e;try{let e=await requestCancellationWithRetry({request:()=>requestWorkflowTurnCancellation({sessionId:n.address.sessionId}),shouldRetryError:()=>!1});e.status!==`accepted`&&log.warn(`descendant cancel was never accepted; the child may run to completion`,{callId:n.operation.callId,childSessionId:n.address.sessionId,finalStatus:e.status,reason:e.reason,subagentName:n.identity.name})}catch(e){logError(log,`failed to cancel local descendant turn`,e,{callId:n.operation.callId,childSessionId:n.address.sessionId,subagentName:n.identity.name})}}async function cancelRemoteDescendant(e){let{handle:n}=e;if(n.address.kind!==`agent/remote`)return;let r=n.address.url;try{let{ctx:t,registry:i}=await e.remoteContext,s=getDynamicSubagentSelection(t,n.identity.nodeId),c={...await resolveRemoteAgentForAction({dynamicRemoteAgent:s?.kind===`remote`?s.remoteAgent:void 0,nodeId:n.identity.nodeId,remoteAgentName:n.identity.name,registry:i}),url:r},l=await requestCancellationWithRetry({request:()=>cancelRemoteAgentTurn({remote:c,sessionId:n.address.sessionId}),shouldRetryError:isRetryableRemoteAgentCancelError});l.status!==`accepted`&&log.warn(`remote descendant cancel was never accepted; the child may run to completion`,{callId:n.operation.callId,childSessionId:n.address.sessionId,finalStatus:l.status,reason:l.reason,remoteAgentName:n.identity.name})}catch(e){logError(log,`failed to cancel remote descendant turn`,e,{callId:n.operation.callId,childSessionId:n.address.sessionId,remoteAgentName:n.identity.name})}}async function requestCancellationWithRetry(e){let t=250,n={status:`no_active_turn`};for(let r=1;r<=8;r+=1){try{if(n=await e.request(),n.status===`accepted`||r===8)return n}catch(t){if(!e.shouldRetryError(t)||r===8)throw t}await new Promise(e=>setTimeout(e,t)),t=Math.min(t*2,1500)}return n}export{cancelDescendantTurnsStep};
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* in `delegated-parent-result.ts` so the workflow step-proxy transform
|
|
5
5
|
* doesn't strip them from this file.
|
|
6
6
|
*/
|
|
7
|
-
import type {
|
|
7
|
+
import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
|
|
8
8
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
9
9
|
/**
|
|
10
10
|
* Resumes the parent driver's hook with a delegated subagent result.
|
|
@@ -15,7 +15,7 @@ import type { TokenUsage } from "#shared/token-usage.js";
|
|
|
15
15
|
* subagent's tokens. Error results never carry usage.
|
|
16
16
|
*/
|
|
17
17
|
export declare function notifyDelegatedParentStep(input: {
|
|
18
|
-
readonly result:
|
|
18
|
+
readonly result: RuntimeSubagentChildResult | undefined;
|
|
19
19
|
readonly serializedContext: Record<string, unknown>;
|
|
20
20
|
readonly usage?: TokenUsage;
|
|
21
21
|
}): Promise<void>;
|
|
@@ -4,11 +4,11 @@
|
|
|
4
4
|
* Lives in its own (non-directive) file to escape the workflow
|
|
5
5
|
* step-proxy transform.
|
|
6
6
|
*/
|
|
7
|
-
import type {
|
|
7
|
+
import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
|
|
8
8
|
/**
|
|
9
|
-
* Builds the success-shaped {@link
|
|
9
|
+
* Builds the success-shaped {@link RuntimeSubagentChildResult}.
|
|
10
10
|
* Returns `undefined` for root sessions (no parent to notify).
|
|
11
11
|
*/
|
|
12
|
-
export declare function createDelegatedSubagentSuccessResult(serializedContext: Record<string, unknown>, output: unknown):
|
|
12
|
+
export declare function createDelegatedSubagentSuccessResult(serializedContext: Record<string, unknown>, output: unknown): RuntimeSubagentChildResult | undefined;
|
|
13
13
|
/** Failure-path mirror of {@link createDelegatedSubagentSuccessResult}. */
|
|
14
|
-
export declare function createDelegatedSubagentErrorResult(serializedContext: Record<string, unknown>, error: unknown):
|
|
14
|
+
export declare function createDelegatedSubagentErrorResult(serializedContext: Record<string, unknown>, error: unknown): RuntimeSubagentChildResult | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorMessage}from"#shared/errors.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";function createDelegatedSubagentSuccessResult(e,n){let r=e[`eve.channel`];if(r?.kind===SUBAGENT_ADAPTER_KIND)return{callId:String(r.state?.callId??``),kind:`subagent-result`,output:n,subagentName:String(r.state?.subagentName??``)}}function createDelegatedSubagentErrorResult(t,
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";import{SUBAGENT_EXECUTION_FAILED}from"#harness/agent-handle-errors.js";function createDelegatedSubagentSuccessResult(e,n){let r=e[`eve.channel`];if(r?.kind===SUBAGENT_ADAPTER_KIND)return{callId:String(r.state?.callId??``),kind:`subagent-result`,origin:`child`,output:n,subagentName:String(r.state?.subagentName??``)}}function createDelegatedSubagentErrorResult(t,r){let i=createDelegatedSubagentSuccessResult(t,``);if(i!==void 0)return{...i,isError:!0,output:{code:SUBAGENT_EXECUTION_FAILED,message:toErrorMessage(r)}}}export{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult};
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Starts every pending runtime action for the parked parent session.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* The batch is classified into a dispatch plan first (reject / start), then
|
|
5
|
+
* each entry dispatches and emits one parent `subagent.called` control-plane
|
|
6
|
+
* event through a single tail. Every start commits an agent handle
|
|
7
|
+
* (`starting`) before its side effect and confirms it (`running`) once the
|
|
8
|
+
* child reports coordinates, so the returned snapshot-bearing state owns
|
|
9
|
+
* every child it may have created.
|
|
8
10
|
*/
|
|
9
|
-
import type {
|
|
11
|
+
import type { RuntimeSubagentResult } from "#runtime/actions/types.js";
|
|
10
12
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
11
13
|
export declare function dispatchRuntimeActionsStep(input: {
|
|
12
14
|
readonly callbackBaseUrl?: string;
|
|
@@ -16,6 +18,6 @@ export declare function dispatchRuntimeActionsStep(input: {
|
|
|
16
18
|
readonly serializedContext: Record<string, unknown>;
|
|
17
19
|
readonly sessionState: DurableSessionState;
|
|
18
20
|
}): Promise<{
|
|
19
|
-
readonly results: readonly
|
|
21
|
+
readonly results: readonly RuntimeSubagentResult[];
|
|
20
22
|
readonly sessionState: DurableSessionState;
|
|
21
23
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChild}from"#harness/runtime-actions.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{readSessionTraceContext}from"#tracing/agent-trace-context-store.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let m=await readDurableSession(e.sessionState),h=getPendingRuntimeActionBatch(m.state);if(h===void 0||h.actions.length===0)return{results:[],sessionState:e.sessionState};let g=await deserializeContext(e.serializedContext),_=g.require(BundleKey),v=resolveEffectiveAgentRuntime(_,g),y=hydrateDurableSession({compactionOverrides:{thresholdPercent:v.thresholdPercent},durable:m,turnAgent:v.turnAgent}),b=g.require(ChannelKey),x=g.get(AuthKey)??null,S=g.get(CapabilitiesKey),C=g.get(ChannelInstrumentationKey),w=g.get(InitiatorAuthKey)??null,T=e.parentWritable.getWriter(),E=buildAdapterContext(b,g),D=resolveSubagentDepth(y),O=readSessionTraceContext(e.serializedContext,y.sessionId),k=h.actions.filter(e=>e.kind===`subagent-call`).length,A=y,j=[];try{for(let r of h.actions){let i=(r.kind===`subagent-call`||r.kind===`remote-agent-call`)&&_.subagentRegistry.dynamicNodeIds?.has(r.nodeId)===!0,a=i?getDynamicSubagentSelection(g,r.nodeId):void 0;if(isRecursiveAgentAction(r,_.subagentRegistry.subagentsByNodeId)&&(y.rootSessionId!==void 0||D.currentDepth>0)){log.warn(`recursive agent call blocked outside the root session`,{callId:r.callId,currentDepth:D.currentDepth,nodeId:r.nodeId,subagentName:r.subagentName}),j.push(createRecursiveAgentRootOnlyResult(r));continue}if(i&&(a===void 0||r.kind===`subagent-call`&&a.kind!==`subagent`||r.kind===`remote-agent-call`&&a.kind!==`remote`)){let e=getSubagentName(r);log.warn(`dynamic subagent call blocked after availability changed`,{callId:r.callId,nodeId:r.nodeId,subagentName:e}),j.push(createUnavailableDynamicSubagentResult(r));continue}let o,u,d,f;switch(r.kind){case`subagent-call`:{let n=a?.kind===`subagent`?a.agentConfig:void 0,i=_.subagentRegistry.subagentsByNodeId.get(r.nodeId),s=n?.description??(i?.definition.kind===`subagent`?i.definition.description:void 0),c=s===void 0?{type:`runtime`}:{description:s,type:`local`},l=createWorkflowRuntime({compiledArtifactsSource:_.compiledArtifactsSource,dynamicSubagentAgentConfig:n,nodeId:r.nodeId}),{childContinuationToken:d,runInput:p}=buildSubagentRunInput({action:r,auth:x,batchEvent:h.event,capabilities:S,channelMetadata:C,fanoutSize:k,initiatorAuth:w,parentContinuationToken:e.parentContinuationToken,parentTraceContext:O,session:y,source:c});try{o=(await l.run(p)).sessionId}catch(e){logError(log,`local subagent start failed`,e,{callId:r.callId,nodeId:r.nodeId,subagentName:r.subagentName}),j.push({callId:r.callId,isError:!0,kind:`subagent-result`,output:{code:`SUBAGENT_START_FAILED`,message:toErrorMessage(e)},subagentName:r.subagentName});continue}A=recordPendingSubagentChild({callId:r.callId,child:{continuationToken:d,kind:`local`,sessionId:o},session:A}),u=r.name,f=r.subagentName;break}case`remote-agent-call`:{let n;try{n=await resolveRemoteAgentForAction({dynamicRemoteAgent:a?.kind===`remote`?a.remoteAgent:void 0,nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:_.subagentRegistry.subagentsByNodeId}),o=await startRemoteAgentSession({action:r,auth:x,callbackBaseUrl:e.callbackBaseUrl,callbackToken:e.parentContinuationToken,initiatorAuth:w,remote:n,session:y})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),j.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}u=r.name,d={url:n.url},f=r.remoteAgentName,A=recordPendingSubagentChild({callId:r.callId,child:{kind:`remote`,sessionId:o},session:A});break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let p=await callAdapterEventHandler(b,createSubagentCalledEvent({callId:r.callId,childSessionId:o,name:u,remote:d,sequence:h.event.sequence,sessionId:y.sessionId,toolName:f,turnId:h.event.turnId,workflowId:workflowEntryReference.workflowId}),E);await T.write(encodeMessageStreamEvent(stampMessageStreamEvent(p)))}}finally{T.releaseLock()}return{results:j,sessionState:A===y?e.sessionState:createDurableSessionState({session:A})}}function createUnavailableDynamicSubagentResult(e){let t=getSubagentName(e);return{callId:e.callId,isError:!0,kind:`subagent-result`,output:{code:`SUBAGENT_UNAVAILABLE`,message:`Subagent "${t}" is not available in the current session context.`},subagentName:t}}function getSubagentName(e){return e.kind===`remote-agent-call`?e.remoteAgentName:e.subagentName}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}function createRecursiveAgentRootOnlyResult(e){return{callId:e.callId,isError:!0,kind:`subagent-result`,output:{code:`RECURSIVE_AGENT_ROOT_ONLY`,message:`The built-in "agent" tool is only available to the root session.`},subagentName:e.subagentName}}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}export{dispatchRuntimeActionsStep};
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";import{deriveAgentId,getAgentHandleStore}from"#harness/handles/store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{REMOTE_AGENT_START_FAILED,SUBAGENT_START_FAILED}from"#harness/agent-handle-errors.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{deriveAgentOperationId}from"#harness/handles/operation-id.js";import{confirmAgentStarted,prepareAgentStart,rejectAgentEffect}from"#harness/handles/transitions.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{readSessionTraceContext}from"#tracing/agent-trace-context-store.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),m=getPendingRuntimeActionBatch(s.state);if(m===void 0||m.actions.length===0)return{results:[],sessionState:e.sessionState};let h=await deserializeContext(e.serializedContext),g=h.require(BundleKey),_=resolveEffectiveAgentRuntime(g,h),v=hydrateDurableSession({compactionOverrides:{thresholdPercent:_.thresholdPercent},durable:s,turnAgent:_.turnAgent}),y=h.require(ChannelKey),b=h.get(AuthKey)??null,x=h.get(CapabilitiesKey),S=h.get(ChannelInstrumentationKey),C=h.get(InitiatorAuthKey)??null,w=buildAdapterContext(y,h),T=readSessionTraceContext(e.serializedContext,v.sessionId);getAgentHandleStore(s.state);let E=planDispatch({actions:m.actions,bundle:g,ctx:h,session:v}),D=e.parentWritable.getWriter(),O=E.filter(e=>e.kind===`start`&&e.target.kind===`local`).length,k=v,A=[];try{for(let r of E){if(r.kind===`reject`){A.push(r.result);continue}let i=await startSubagent({auth:b,batchEvent:m.event,bundle:g,callbackBaseUrl:e.callbackBaseUrl,capabilities:x,channelMetadata:S,currentSession:k,fanoutSize:O,initiatorAuth:C,parentContinuationToken:e.parentContinuationToken,parentTraceContext:T,session:v,target:r.target});if(k=i.session,i.kind===`error`){A.push(i.result);continue}try{let e=await callAdapterEventHandler(y,createSubagentCalledEvent({callId:i.callId,childSessionId:i.address.sessionId,name:i.name,remote:i.address.kind===`agent/remote`?{url:i.address.url}:void 0,sequence:m.event.sequence,sessionId:v.sessionId,toolName:i.toolName,turnId:m.event.turnId,workflowId:workflowEntryReference.workflowId}),w);await D.write(encodeMessageStreamEvent(stampMessageStreamEvent(e)))}catch(e){logError(log,`subagent.called emission failed`,e,{callId:i.callId,childSessionId:i.address.sessionId,toolName:i.toolName})}}}finally{D.releaseLock()}return{results:A,sessionState:k===v?e.sessionState:createDurableSessionState({session:k})}}function planDispatch(e){let t=e.bundle.subagentRegistry.subagentsByNodeId,n=resolveSubagentDepth(e.session),r=e.session.rootSessionId!==void 0||n.currentDepth>0;return e.actions.map(i=>{let a=(i.kind===`subagent-call`||i.kind===`remote-agent-call`)&&e.bundle.subagentRegistry.dynamicNodeIds?.has(i.nodeId)===!0,o=a?getDynamicSubagentSelection(e.ctx,i.nodeId):void 0;if(a&&(o===void 0||i.kind===`subagent-call`&&o.kind!==`subagent`||i.kind===`remote-agent-call`&&o.kind!==`remote`)){let e=getSubagentName(i);return log.warn(`dynamic subagent call blocked after availability changed`,{callId:i.callId,nodeId:i.nodeId,subagentName:e}),{kind:`reject`,result:createUnavailableDynamicSubagentResult(i)}}if(isRecursiveAgentAction(i,t)&&r)return log.warn(`recursive agent call blocked outside the root session`,{callId:i.callId,currentDepth:n.currentDepth,nodeId:i.nodeId,subagentName:i.subagentName}),{kind:`reject`,result:createRecursiveAgentRootOnlyResult(i)};switch(i.kind){case`subagent-call`:{let e=o?.kind===`subagent`?o.agentConfig:void 0,n=t.get(i.nodeId),r=e?.description??(n?.definition.kind===`subagent`?n.definition.description:void 0);return{kind:`start`,target:{action:i,dynamicSubagentAgentConfig:e,kind:`local`,source:r===void 0?{type:`runtime`}:{description:r,type:`local`}}}}case`remote-agent-call`:return{kind:`start`,target:{action:i,dynamicRemoteAgent:o?.kind===`remote`?o.remoteAgent:void 0,kind:`remote`}};default:throw Error(`Unsupported runtime action kind "${i.kind}" in workflow runtime.`)}})}async function startSubagent(e){switch(e.target.kind){case`local`:return startLocalSubagent({action:e.target.action,auth:e.auth,batchEvent:e.batchEvent,bundle:e.bundle,capabilities:e.capabilities,channelMetadata:e.channelMetadata,currentSession:e.currentSession,dynamicSubagentAgentConfig:e.target.dynamicSubagentAgentConfig,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,session:e.session,source:e.target.source});case`remote`:return startRemoteSubagent({action:e.target.action,auth:e.auth,batchEvent:e.batchEvent,bundle:e.bundle,callbackBaseUrl:e.callbackBaseUrl,currentSession:e.currentSession,dynamicRemoteAgent:e.target.dynamicRemoteAgent,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,session:e.session});default:return e.target}}function mintStartOperation(e){let t=deriveAgentOperationId({callId:e.callId,parentSessionId:e.parentSessionId,parentTurnId:e.parentTurnId});return{identity:{id:deriveAgentId(e.name,t),name:e.name,nodeId:e.nodeId},operation:{callId:e.callId,id:t,kind:`start`,parentTurnId:e.parentTurnId}}}async function startLocalSubagent(e){let{action:n,source:r}=e,i=createWorkflowRuntime({compiledArtifactsSource:e.bundle.compiledArtifactsSource,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,nodeId:n.nodeId}),{childContinuationToken:a,runInput:o}=buildSubagentRunInput({action:n,auth:e.auth,batchEvent:e.batchEvent,capabilities:e.capabilities,channelMetadata:e.channelMetadata,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,session:e.session,source:r}),c=r.type===`runtime`?`agent/self`:`agent/local`,{identity:l,operation:u}=mintStartOperation({callId:n.callId,name:n.subagentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),d=prepareAgentStart(e.currentSession,{identity:l,operation:u,target:{continuationToken:a,kind:c}}),f;try{f=(await i.run(o)).sessionId}catch(e){return logError(log,`local subagent start failed`,e,{callId:n.callId,nodeId:n.nodeId,subagentName:n.subagentName}),{kind:`error`,result:{callId:n.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:SUBAGENT_START_FAILED,message:toErrorMessage(e)},subagentName:n.subagentName},session:rejectAgentEffect(d,{disposition:`dead`,operationId:u.id})}}let p={continuationToken:a,kind:c,sessionId:f};return{address:p,callId:n.callId,kind:`called`,name:n.name,session:confirmAgentStarted(d,{address:p,operationId:u.id}),toolName:n.subagentName}}async function startRemoteSubagent(e){let{action:n}=e,r,i;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);r=e.callbackBaseUrl,i=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:n.nodeId,remoteAgentName:n.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(r){return logError(log,`remote agent start failed`,r,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:n,error:r}),session:e.currentSession}}let{identity:a,operation:o}=mintStartOperation({callId:n.callId,name:n.remoteAgentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),s=prepareAgentStart(e.currentSession,{identity:a,operation:o,target:{callbackBaseUrl:r,kind:`agent/remote`,url:i.url}});try{let t=await startRemoteAgentSession({action:n,auth:e.auth,callbackBaseUrl:r,callbackToken:e.parentContinuationToken,initiatorAuth:e.initiatorAuth,remote:i,session:e.session}),a={callbackBaseUrl:r,kind:`agent/remote`,sessionId:t.sessionId,url:i.url,...t.continuationToken===void 0?{}:{continuationToken:t.continuationToken}};return{address:a,callId:n.callId,kind:`called`,name:n.name,session:confirmAgentStarted(s,{address:a,operationId:o.id}),toolName:n.remoteAgentName}}catch(e){return logError(log,`remote agent start failed`,e,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:n,error:e}),session:rejectAgentEffect(s,{disposition:`dead`,operationId:o.id})}}}function createUnavailableDynamicSubagentResult(e){let t=getSubagentName(e);return{callId:e.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`SUBAGENT_UNAVAILABLE`,message:`Subagent "${t}" is not available in the current session context.`},subagentName:t}}function getSubagentName(e){return e.kind===`remote-agent-call`?e.remoteAgentName:e.subagentName}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:REMOTE_AGENT_START_FAILED,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}function createRecursiveAgentRootOnlyResult(e){return{callId:e.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`RECURSIVE_AGENT_ROOT_ONLY`,message:`The built-in "agent" tool is only available to the root session.`},subagentName:e.subagentName}}function isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}export{dispatchRuntimeActionsStep};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { RuntimeSubagentResult } from "#runtime/actions/types.js";
|
|
3
3
|
/** Dispatches the child-agent action currently blocking a dynamic workflow. */
|
|
4
4
|
export declare function dispatchWorkflowRuntimeActionsStep(input: {
|
|
5
5
|
readonly callbackBaseUrl?: string;
|
|
@@ -8,6 +8,6 @@ export declare function dispatchWorkflowRuntimeActionsStep(input: {
|
|
|
8
8
|
readonly serializedContext: Record<string, unknown>;
|
|
9
9
|
readonly sessionState: DurableSessionState;
|
|
10
10
|
}): Promise<{
|
|
11
|
-
readonly results: readonly
|
|
11
|
+
readonly results: readonly RuntimeSubagentResult[];
|
|
12
12
|
readonly sessionState: DurableSessionState;
|
|
13
13
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getSubagentDelegationName,isSubagentDelegationAction}from"#harness/subagent-depth.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{buildRuntimeActionsFromWorkflowInterrupt}from"#harness/workflow-runtime-action-state.js";import{planWorkflowSubagentDispatch}from"#harness/workflow-subagent-limit.js";const log=createLogger(`execution.dispatch-workflow-runtime-actions`);async function dispatchWorkflowRuntimeActionsStep(e){"use step";let n=await readDurableSession(e.sessionState),r=getPendingWorkflowInterrupt(n.state);if(r===void 0)return{results:[],sessionState:e.sessionState};let i=buildRuntimeActionsFromWorkflowInterrupt(r.interrupt);if(i.length===0)return{results:[],sessionState:e.sessionState};let a=await deserializeContext(e.serializedContext),o=resolveEffectiveAgentRuntime(a.require(BundleKey),a),s=planWorkflowSubagentDispatch({actions:i,interrupt:r.interrupt,maxSubagents:n.workflowMaxSubagents}),c=s.blocked.map(e=>(log.warn(`workflow subagent limit reached; blocking delegated call`,{callId:e.callId,maxSubagents:s.maxSubagents,subagentName:isSubagentDelegationAction(e)?getSubagentDelegationName(e):e.kind,usedCalls:s.usedCalls}),createWorkflowSubagentLimitResult({action:e,plan:s})));if(s.allowed.length===0)return{results:c,sessionState:e.sessionState};let l=hydrateDurableSession({compactionOverrides:{thresholdPercent:o.thresholdPercent},durable:n,turnAgent:o.turnAgent}),u=setPendingRuntimeActionBatch({actions:s.allowed,event:{sequence:0,stepIndex:0,turnId:`workflow-dispatch`},responseMessages:[],session:l}),d=await dispatchRuntimeActionsStep({callbackBaseUrl:e.callbackBaseUrl,parentContinuationToken:e.parentContinuationToken,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:createDurableSessionState({session:u})});return c.length===0?d:{results:[...d.results,...c],sessionState:d.sessionState}}function createWorkflowSubagentLimitResult(e){let t=isSubagentDelegationAction(e.action)?getSubagentDelegationName(e.action):e.action.kind;return{callId:e.action.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`WORKFLOW_SUBAGENT_LIMIT_REACHED`,maxSubagents:e.plan.maxSubagents,message:`Workflow subagent limit reached (${String(e.plan.maxSubagents)}); "${t}" was not called.`},subagentName:t}}export{dispatchWorkflowRuntimeActionsStep};
|
|
@@ -10,14 +10,21 @@
|
|
|
10
10
|
* deployment still runs after a rollout. Future shape changes bump
|
|
11
11
|
* {@link TURN_WORKFLOW_INPUT_VERSION} and append a v{N} → v{N+1} migration.
|
|
12
12
|
*/
|
|
13
|
-
import type { HookPayload, SessionCapabilities } from "#channel/types.js";
|
|
13
|
+
import type { HookPayload, RuntimeActionResultHookPayload, SessionCapabilities } from "#channel/types.js";
|
|
14
14
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
15
|
+
import type { RuntimeActionResult } from "#runtime/actions/types.js";
|
|
15
16
|
import type { RunMode } from "#shared/run-mode.js";
|
|
16
17
|
export declare const TURN_WORKFLOW_INPUT_VERSION = 1;
|
|
18
|
+
/** Trusted runtime-action results collected by the parent turn driver. */
|
|
19
|
+
interface RuntimeActionResultStepInput {
|
|
20
|
+
readonly kind: "runtime-action-result";
|
|
21
|
+
readonly results: readonly RuntimeActionResult[];
|
|
22
|
+
}
|
|
23
|
+
export type TurnStepPayload = Exclude<HookPayload, RuntimeActionResultHookPayload> | RuntimeActionResultStepInput;
|
|
17
24
|
export interface TurnStepInput {
|
|
18
25
|
/** Cancellation signal forwarded into the turn step. */
|
|
19
26
|
readonly abortSignal?: AbortSignal;
|
|
20
|
-
readonly input:
|
|
27
|
+
readonly input: TurnStepPayload | undefined;
|
|
21
28
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
22
29
|
readonly serializedContext: Record<string, unknown>;
|
|
23
30
|
readonly sessionState: DurableSessionState;
|
|
@@ -48,3 +55,4 @@ export interface TurnWorkflowDispatchInput {
|
|
|
48
55
|
}
|
|
49
56
|
export declare function createTurnWorkflowInput(input: TurnWorkflowDispatchInput): TurnWorkflowInput;
|
|
50
57
|
export declare function migrateTurnWorkflowInput(value: unknown): TurnWorkflowInput;
|
|
58
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation-runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node}),i=getInstrumentationRuntime(),a=createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,handleEvent:e.handleEvent,instrumentation:i,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?a:async(e,t)=>{try{return await a(e,t)}finally{await i.forceFlush()}}}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version,modelId:e.turnAgent.dynamicModel===void 0?e.turnAgent.model.id:`dynamic:${e.turnAgent.model.id}`},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t){return n=>dispatchDynamicModelEvent({ctx:n.ctx,dynamicModel:t,event:n.event,fallback:n.fallback,messages:n.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return e.node.nodeId===ROOT_RUNTIME_AGENT_NODE_ID&&!e.node.agent.disabledFrameworkTools.includes(AGENT_TOOL_NAME)&&!t.has(AGENT_TOOL_NAME)&&t.set(AGENT_TOOL_NAME,{description:AGENT_TOOL_DESCRIPTION,inputSchema:SUBAGENT_TOOL_INPUT_SCHEMA,name:AGENT_TOOL_NAME,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:AGENT_TOOL_NAME}}),t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`||e.tool.kind===`remote`)return createHarnessDelegationToolDefinition(e.tool);let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=t.definition,i=r.sourceId.startsWith(`eve:`),o=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:o,scope:r.name}),inputSchema:r.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:r.name,approval:r.approval,outputSchema:r.outputSchema,toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{isFrameworkTool:t,rawExecute:n,scope:i}=e;return n===void 0?void 0:t?n:createToolExecuteWithAuth({execute:n,scope:i})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation-runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node}),i=getInstrumentationRuntime(),a=createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,handleEvent:e.handleEvent,instrumentation:i,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,persistentSubagentSessions:e.node.agent.config?.experimental?.subagentPersistentSessions===!0,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?a:async(e,t)=>{try{return await a(e,t)}finally{await i.forceFlush()}}}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version,modelId:e.turnAgent.dynamicModel===void 0?e.turnAgent.model.id:`dynamic:${e.turnAgent.model.id}`},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t){return n=>dispatchDynamicModelEvent({ctx:n.ctx,dynamicModel:t,event:n.event,fallback:n.fallback,messages:n.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return e.node.nodeId===ROOT_RUNTIME_AGENT_NODE_ID&&!e.node.agent.disabledFrameworkTools.includes(AGENT_TOOL_NAME)&&!t.has(AGENT_TOOL_NAME)&&t.set(AGENT_TOOL_NAME,{description:AGENT_TOOL_DESCRIPTION,inputSchema:SUBAGENT_TOOL_INPUT_SCHEMA,name:AGENT_TOOL_NAME,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:AGENT_TOOL_NAME}}),t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`||e.tool.kind===`remote`)return createHarnessDelegationToolDefinition(e.tool);let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=t.definition,i=r.sourceId.startsWith(`eve:`),o=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:o,scope:r.name}),inputSchema:r.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:r.name,approval:r.approval,outputSchema:r.outputSchema,toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{isFrameworkTool:t,rawExecute:n,scope:i}=e;return n===void 0?void 0:t?n:createToolExecuteWithAuth({execute:n,scope:i})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -4,6 +4,10 @@ import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types
|
|
|
4
4
|
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
|
|
5
5
|
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
|
|
6
6
|
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
|
|
7
|
+
type RemoteAgentSessionCoordinates = {
|
|
8
|
+
readonly continuationToken?: string;
|
|
9
|
+
readonly sessionId: string;
|
|
10
|
+
};
|
|
7
11
|
export declare function startRemoteAgentSession(input: {
|
|
8
12
|
readonly action: RuntimeRemoteAgentCallActionRequest;
|
|
9
13
|
/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
|
|
@@ -14,7 +18,7 @@ export declare function startRemoteAgentSession(input: {
|
|
|
14
18
|
readonly initiatorAuth?: SessionAuthContext | null;
|
|
15
19
|
readonly remote: ResolvedRuntimeRemoteAgentNode;
|
|
16
20
|
readonly session: HarnessSession;
|
|
17
|
-
}): Promise<
|
|
21
|
+
}): Promise<RemoteAgentSessionCoordinates>;
|
|
18
22
|
export declare function cancelRemoteAgentTurn(input: {
|
|
19
23
|
readonly remote: ResolvedRuntimeRemoteAgentNode;
|
|
20
24
|
readonly sessionId: string;
|
|
@@ -25,4 +29,5 @@ export declare function resolveRemoteAgentForAction(input: {
|
|
|
25
29
|
readonly nodeId: string;
|
|
26
30
|
readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
|
|
27
31
|
readonly remoteAgentName: string;
|
|
28
|
-
}):
|
|
32
|
+
}): ResolvedRuntimeRemoteAgentNode;
|
|
33
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{createEveCallbackRoutePath,createEveCancelTurnRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/message.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.callbackToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{createEveCallbackRoutePath,createEveCancelTurnRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER}from"#protocol/message.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";const CreateSessionResponseSchema=z.object({continuationToken:z.string().min(1).optional(),sessionId:z.string().min(1).optional()});var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.callbackToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let n=buildForwardedPrincipalField(e),i={capabilities:{},callback:{callId:e.action.callId,subagentName:e.action.remoteAgentName,token:t,url:createWorkflowCallbackUrl(e.callbackBaseUrl,createEveCallbackRoutePath(t))},message:formatRemoteAgentCallInputMessage({action:e.action,remote:e.remote}),mode:`task`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};n!==void 0&&(i.forwardedPrincipal=n);let o=await resolveRemoteAgentRequestHeaders(e.remote),s=await fetch(createRemoteAgentSessionUrl(e.remote),{body:JSON.stringify(i),headers:{"content-type":`application/json`,...o},method:`POST`});if(!s.ok)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session request failed with HTTP ${s.status}.`);let c;try{c=await s.json()}catch{throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was not valid JSON.`)}let l=CreateSessionResponseSchema.safeParse(c),u=s.headers.get(EVE_SESSION_ID_HEADER),d=u!==null&&u.length>0?u:l.success?l.data.sessionId:void 0;if(!l.success||d===void 0)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response did not include a sessionId.`);return l.data.continuationToken===void 0?{sessionId:d}:{continuationToken:l.data.continuationToken,sessionId:d}}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.sessionId!==e.sessionId)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was invalid.`,{retryable:!1});return{status:i.data.status}}function isRetryableRemoteAgentCancelError(e){return!(e instanceof RemoteAgentCancelRequestError)||e.retryable}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(e.dynamicRemoteAgent!==void 0){if(t===void 0)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);let n=resolveDynamicRemoteAgentCredentials(e.dynamicRemoteAgent),r=e.dynamicRemoteAgent,i={description:r.description,kind:`remote`,logicalPath:t.logicalPath,name:e.remoteAgentName,nodeId:e.nodeId,outputSchema:r.outputSchema,path:r.path,sourceId:t.sourceId,sourceKind:`module`,url:r.url};return r.forwardPrincipal!==void 0&&(i.forwardPrincipal=r.forwardPrincipal),n.auth!==void 0&&(i.auth=n.auth),n.headers!==void 0&&(i.headers=n.headers),i}if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}function resolveDynamicRemoteAgentCredentials(e){if(e.credentialsStepId===void 0)return{};let r=getStepRegistry().get(e.credentialsStepId);if(r===void 0)throw Error(`Dynamic remote subagent credentials function "${e.credentialsStepId}" is not registered.`);let i=expectObjectRecord(r(),`Dynamic remote subagent credentials are invalid.`),a={};return i.auth!==void 0&&(a.auth=expectFunction(i.auth,`Dynamic remote subagent auth is invalid.`)),i.headers!==void 0&&(a.headers=resolveDynamicRemoteAgentHeaders(i.headers)),a}function resolveDynamicRemoteAgentHeaders(e){if(typeof e==`function`)return e;let t=expectObjectRecord(e,`Dynamic remote subagent headers are invalid.`);for(let e of Object.values(t))if(typeof e!=`string`)throw Error(`Dynamic remote subagent headers are invalid.`);return t}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function createRemoteAgentSessionUrl(e){return createRemoteAgentRouteUrl(e.url,e.path)}function createRemoteAgentCancelTurnUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveCancelTurnRoutePath(t))}function createRemoteAgentRouteUrl(e,t){return new URL(t.replace(/^\/+/,``),`${trimTrailingSlash(e)}/`).toString()}function isRetryableRemoteCancelStatus(e){return e===408||e===425||e===429||e>=500}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,type:`remote`}).message}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction,startRemoteAgentSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resolveSandboxModelPath}from"#shared/skill-paths.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{streamToBuffer}from"#execution/sandbox/stream-utils.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{adaptMultiplexedCommandToSandboxProcess}from"#execution/sandbox/multiplexed-command.js";import{applyInitialVercelNetworkPolicy,ensureVercelSandboxBaseRuntime}from"#execution/sandbox/bindings/vercel-base-runtime.js";import{createVercelEveImageSandbox}from"#execution/sandbox/bindings/vercel-create-sdk.js";import{isVercelSandboxMissingError,isVercelSnapshotUnavailableError}from"#execution/sandbox/bindings/vercel-errors.js";import{getNamedVercelSandbox}from"#execution/sandbox/bindings/vercel-lookup.js";import{normalizeVercelReadStream}from"#execution/sandbox/bindings/vercel-read-stream.js";function createVercelSandbox(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:DEFAULT_SANDBOX_TIMEOUT_MS,...e.createOptions},r=e.createSandbox??createVercelEveImageSandbox,i=new Map;return{name:`vercel`,async create(e){let o=resolveVercelSandboxTags(n.tags,e.tags),s=e.templateKey===null?null:await readTemplateForCreate({createOptions:n,loadSandboxModule:t,prewarmedTemplates:i,templateKey:e.templateKey}),l=await t(),u;try{u=await ensureSession({createOptions:n,createSandbox:r,existingMetadata:e.existingMetadata,sandboxModule:l,sessionKey:e.sessionKey,snapshotId:s?.snapshotId,tags:o})}catch(t){throw s!==null&&(isVercelSnapshotUnavailableError(t)||isVercelSandboxMissingError(t))?(i.delete(s.templateKey),await(await getNamedVercelSandbox({createOptions:n,sandboxModule:l,sandboxName:s.sandboxName}))?.delete(),new SandboxTemplateNotProvisionedError({backendName:`vercel`,templateKey:s.templateKey})):Error(`Failed to create sandbox session "${e.sessionKey}": ${errorMessage(t)}`,{cause:t})}return s===null&&u.created&&(await ensureVercelSandboxBaseRuntime(u.sandbox),await applyInitialVercelNetworkPolicy(u.sandbox,n.networkPolicy)),createHandle(u.sandbox,e.sessionKey)},async prewarm(e){let a;try{a=await ensureTemplateWithUnavailableRetry({bootstrap:e.bootstrap,createOptions:n,createSandbox:r,loadSandboxModule:t,log:e.log,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${errorMessage(t)}`,{cause:t})}return i.set(e.templateKey,a.template),{reused:a.reused}}}}async function ensureTemplateWithUnavailableRetry(e){try{return await ensureTemplate(e)}catch(t){if(!isVercelSnapshotUnavailableError(t)&&!isVercelSandboxMissingError(t))throw t;return e.log?.(`cached template disappeared; rebuilding sandbox template`),await ensureTemplate(e)}}async function readTemplate(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await e.loadSandboxModule(),r=await getNamedVercelSandbox({createOptions:e.createOptions,sandboxModule:n,sandboxName:e.templateKey});if(r===null||typeof r.currentSnapshotId!=`string`)throw new SandboxTemplateNotProvisionedError({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:r.name,snapshotId:r.currentSnapshotId,templateKey:e.templateKey}}async function readTemplateForCreate(e){try{return await readTemplate(e)}catch(t){throw SandboxTemplateNotProvisionedError.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${errorMessage(t)}`,{cause:t})}}async function ensureTemplate(e){let t=await e.loadSandboxModule(),n=await getNamedVercelSandbox({createOptions:e.createOptions,sandboxModule:t,sandboxName:e.templateKey}),a=resolveVercelSandboxTags(e.createOptions.tags,e.tags),o=extractAuthorSnapshotId(e.createOptions);if(n!==null&&isUnprovisionedTerminalTemplateSandbox(n,o)&&(await n.delete(),n=null),n===null?n=await e.createSandbox({sandboxModule:t,createOptions:withBaseSetupNetworkPolicy({...e.createOptions,name:e.templateKey,persistent:!1,tags:a})}):await ensureVercelSandboxTags(n,a),typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0&&n.currentSnapshotId!==o)return{reused:!0,template:{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}};e.log?.(`preparing base runtime inside sandbox`),await ensureVercelSandboxBaseRuntime(n),await applyInitialVercelNetworkPolicy(n,e.createOptions.networkPolicy);let s=buildSandboxSession(createVercelInternalSandboxSession(n,e.templateKey),createVercelNetworkPolicySetter(n));await writeVercelSandboxSeedFiles({sandbox:n,seedFiles:e.seedFiles,session:s}),e.bootstrap!==void 0&&(e.log?.(`running sandbox bootstrap`),await e.bootstrap({use:async t=>(t!==void 0&&await n.update(t),createLoggingSandboxSession({log:e.log,session:s}))}));let c=await n.snapshot();return{reused:!1,template:{sandboxName:n.name,snapshotId:c.snapshotId,templateKey:e.templateKey}}}async function ensureSession(e){let t=getVercelSandboxName(e.existingMetadata)??e.sessionKey,n=await getNamedVercelSandbox({createOptions:e.createOptions,sandboxModule:e.sandboxModule,sandboxName:t});if(n!==null)return await ensureVercelSandboxTags(n,e.tags),{created:!1,sandbox:n};let r=createSessionCreateParams(e,t);return e.tags!==void 0&&(r.tags=e.tags),{created:!0,sandbox:await e.createSandbox({createOptions:r,sandboxModule:e.sandboxModule})}}function createSessionCreateParams(e,t){if(e.snapshotId===void 0)return withBaseSetupNetworkPolicy({...e.createOptions,name:t,persistent:!0});let{image:n,runtime:r,source:i,...a}=e.createOptions;return{...a,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}}}function withBaseSetupNetworkPolicy(e){return{...e,networkPolicy:`allow-all`}}function createHandle(e,t){return{session:buildSandboxSession(createVercelInternalSandboxSession(e,t),createVercelNetworkPolicySetter(e)),useSessionFn:async n=>(n!==void 0&&await e.update(n),buildSandboxSession(createVercelInternalSandboxSession(e,t),createVercelNetworkPolicySetter(e))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async shutdown(){await stopVercelSandbox(e)}}}async function stopVercelSandbox(e){if(!(e.status!==`running`&&e.status!==`pending`))try{await e.stop()}catch{}}function createVercelNetworkPolicySetter(e){return async t=>{await e.update({networkPolicy:t})}}function createVercelInternalSandboxSession(e,r){return{id:r,resolvePath:resolveVercelSandboxPath,async spawn(n){return adaptMultiplexedCommandToSandboxProcess({command:await e.runCommand({args:[`-lc`,n.command],cmd:`bash`,cwd:n.workingDirectory??WORKSPACE_ROOT,detached:!0,env:n.env,signal:n.abortSignal}),getOutput:e=>e.stream})},async readFile(t){return normalizeVercelReadStream(await e.readFile({path:t.path}))},async writeFile(t){let r=await streamToBuffer(t.content);await e.writeFiles([{content:r,path:t.path}])},async removePath(t){await e.fs.rm(t.path,{force:t.force,recursive:t.recursive,signal:t.abortSignal})}}}async function writeVercelSandboxSeedFiles(t){if(t.seedFiles.length===0)return;let n=await Promise.all(t.seedFiles.map(async n=>({content:typeof n.content==`string`?Buffer.from(n.content):n.content,path:await resolveSandboxModelPath({path:n.path,sandbox:t.session})})));await t.sandbox.writeFiles(n)}function resolveVercelSandboxPath(e){return e.startsWith(`/`)?e:`${WORKSPACE_ROOT}/${e}`}function isUnprovisionedTerminalTemplateSandbox(e,t){let n=e.currentSnapshotId;return typeof n==`string`&&n.length>0&&n!==t?!1:e.status===`aborted`||e.status===`failed`||e.status===`stopped`}function extractAuthorSnapshotId(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function getVercelSandboxName(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function resolveVercelSandboxTags(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>VERCEL_SANDBOX_TAG_LIMIT)throw Error(`Vercel Sandbox supports at most ${VERCEL_SANDBOX_TAG_LIMIT} tags. eve reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercel().`);return n}}async function ensureVercelSandboxTags(e,t){t===void 0||areVercelSandboxTagsEqual(e.tags,t)||await e.update({tags:t})}function areVercelSandboxTagsEqual(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length&&i.every(([e,t])=>n[e]===t)}function errorMessage(e){if(e instanceof Error){let t=e.json,n=e.text,r=typeof n==`string`&&n.length>0?n:t===void 0?void 0:JSON.stringify(t);return r===void 0?e.message:`${e.message}: ${r}`}return String(e)}const DEFAULT_SANDBOX_TIMEOUT_MS=1800*1e3,VERCEL_SANDBOX_TAG_LIMIT=5;export{createVercelSandbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseSessionCallback}from"#channel/session-callback.js";const log=createLogger(`execution.session-callback`);async function fireSessionCallbackStep(e){"use step";let n=e.serializedContext[`eve.sessionId`]??``,i=e.serializedContext[SessionCallbackKey.name];if(i!==void 0)try{let t=parseSerializedSessionCallback(i),r=e.status===`completed`?buildCompletedCallbackBody({callback:t,output:e.output,sessionId:n,usage:e.usage}):{callId:t.callId,error:{code
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{SESSION_FAILED}from"#harness/agent-handle-errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function fireSessionCallbackStep(e){"use step";let n=e.serializedContext[`eve.sessionId`]??``,i=e.serializedContext[SessionCallbackKey.name];if(i!==void 0)try{let t=parseSerializedSessionCallback(i),r=await postSessionCallbackRequest({body:e.status===`completed`?buildCompletedCallbackBody({callback:t,output:e.output,sessionId:n,usage:e.usage}):{callId:t.callId,error:{code:SESSION_FAILED,message:toErrorMessage(e.error)},kind:`session.failed`,sessionId:n,subagentName:t.subagentName},url:t.url});if(!r.ok)throw Error(`Session callback failed with HTTP ${r.status}.`)}catch(e){throw log.error(`failed to post session callback`,{error:e,sessionId:n}),e}}function buildCompletedCallbackBody(e){let t={callId:e.callback.callId,kind:`session.completed`,output:e.output??``,sessionId:e.sessionId,subagentName:e.callback.subagentName};return e.usage===void 0?t:{...t,usage:e.usage}}function parseSerializedSessionCallback(e){let t=parseSessionCallback(e);if(!t.ok)throw Error(`Serialized session callback is invalid.`,{cause:t.cause});return t.callback}export{fireSessionCallbackStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler}from"#channel/adapter.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{callAdapterEventHandler}from"#channel/adapter.js";import{encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{clearPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{clearAllProxyInputRequests,getProxyInputRequests,hasProxyInputRequests}from"#harness/proxy-input-requests.js";import{getInstrumentationRuntime}from"#harness/instrumentation-runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{withContextScope}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{emitCancelledTurn}from"#harness/cancelled-turn-emission.js";import{clearPendingSessionLimitPrompt}from"#harness/input-requests.js";import{createInstrumentationHandleEvent}from"#harness/instrumentation-native-events.js";async function settleCancelledTurnStep(a){"use step";let o=await readDurableSession(a.sessionState),s=await deserializeContext(a.serializedContext),c=s.require(ChannelKey),l=buildAdapterContext(c,s),u=s.require(BundleKey),d=resolveEffectiveAgentRuntime(u,s),f=getInstrumentationRuntime(),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:o,turnAgent:d.turnAgent}),m=getHarnessEmissionState(o.state),h=[...getProxyInputRequests(o.state).values()].some(e=>e.kind===`session-limit`);if(!(isHarnessBetweenTurns(p)&&hasProxyInputRequests(o.state)&&!h)){let t=a.parentWritable.getWriter();try{let n=await withContextScope(s,p,async n=>{let baseEmit=async n=>{let r=await callAdapterEventHandler(c,n,l);setChannelContext(s,{...c,state:{...l.state}});let i=stampMessageStreamEvent(r);await t.write(encodeMessageStreamEvent(i)),await dispatchStreamEventHooks({ctx:s,event:i,registry:u.hookRegistry})};return{result:await emitCancelledTurn(createInstrumentationHandleEvent({agentName:u.resolvedAgent.config.name,handleEvent:baseEmit,hooks:f?.hooks,sessionId:p.sessionId,turnId:activeTurnId(m)})??baseEmit,m,n.continuationToken),session:n}});m=n.result,p=n.session}finally{await f?.forceFlush(),t.releaseLock()}}let g=reconcileSessionContinuationToken(s,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(p)))),m));return{serializedContext:serializeContext(s),sessionState:createDurableSessionState({session:g})}}export{settleCancelledTurnStep};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { DeliverHookPayload
|
|
1
|
+
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
|
-
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
4
|
+
import type { TurnStepInput, TurnStepPayload } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
5
5
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
6
6
|
interface TurnTransition {
|
|
7
7
|
readonly serializedContext?: Record<string, unknown>;
|
|
@@ -37,7 +37,7 @@ export declare class TurnExecutionCursor {
|
|
|
37
37
|
/** Adopts a state transition and reports any continuation-token change once. */
|
|
38
38
|
adopt(transition: TurnTransition): Promise<void>;
|
|
39
39
|
/** Builds the next atomic turn-step input from the cursor's current state. */
|
|
40
|
-
createStepInput(input:
|
|
40
|
+
createStepInput(input: TurnStepPayload | undefined, abortSignal?: AbortSignal): TurnStepInput;
|
|
41
41
|
/**
|
|
42
42
|
* Adopts a terminal turn transition and publishes it as the turn result.
|
|
43
43
|
* The result already carries the final session state, so no separate
|