eve 0.30.6 → 0.30.8
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/chunks/{use-eve-agent-BXMIf5fR.js → use-eve-agent-Bx-ONuyb.js} +22 -0
- package/dist/src/chunks/{use-eve-agent-k-XHfrJT.js → use-eve-agent-DDoDDmJ2.js} +22 -0
- package/dist/src/cli/commands/registry-metadata.d.ts +15 -0
- package/dist/src/cli/commands/registry-metadata.js +1 -0
- package/dist/src/cli/commands/registry-package.d.ts +46 -0
- package/dist/src/cli/commands/registry-package.js +1 -0
- package/dist/src/cli/commands/registry.d.ts +1 -1
- package/dist/src/cli/commands/registry.js +4 -4
- package/dist/src/cli/commands/trace-detail.d.ts +53 -0
- package/dist/src/cli/commands/trace-detail.js +1 -0
- package/dist/src/cli/commands/trace.d.ts +4 -1
- package/dist/src/cli/commands/trace.js +4 -4
- package/dist/src/cli/dev/tui/traces/trace-content.d.ts +3 -3
- package/dist/src/cli/dev/tui/traces/trace-content.js +1 -1
- package/dist/src/cli/dev/tui/traces/trace-view.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/message-reducer-types.d.ts +3 -0
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/dynamic-subagent-lifecycle.d.ts +2 -0
- package/dist/src/context/dynamic-subagent-lifecycle.js +1 -1
- package/dist/src/execution/agent-continuation-bundle.d.ts +13 -0
- package/dist/src/execution/agent-continuation-bundle.js +1 -0
- package/dist/src/execution/agent-handle-dispatch.d.ts +32 -4
- 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 +30 -4
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/delegated-parent-result.js +1 -1
- package/dist/src/execution/dispatch-action-failures.d.ts +8 -0
- package/dist/src/execution/dispatch-action-failures.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +8 -7
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-start-operation.d.ts +15 -0
- package/dist/src/execution/dispatch-start-operation.js +1 -0
- package/dist/src/execution/forward-turn-cancellation-step.js +1 -1
- package/dist/src/execution/next-driver-action.d.ts +12 -0
- package/dist/src/execution/node-step.d.ts +1 -1
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/parked-delivery-wait.d.ts +35 -0
- package/dist/src/execution/parked-delivery-wait.js +1 -0
- package/dist/src/execution/remote-agent-dispatch.d.ts +42 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/sandbox/prewarm.js +1 -1
- package/dist/src/execution/session-timeout-steps.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-invocation.d.ts +3 -0
- package/dist/src/execution/subagent-invocation.js +1 -1
- package/dist/src/execution/subagent-tool.d.ts +7 -0
- package/dist/src/execution/subagent-tool.js +1 -1
- package/dist/src/execution/terminate-child-sessions-step.d.ts +15 -0
- package/dist/src/execution/terminate-child-sessions-step.js +1 -0
- package/dist/src/execution/tool-auth.d.ts +1 -1
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/turn-control-protocol.js +1 -1
- package/dist/src/execution/turn-execution-cursor.d.ts +3 -0
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +8 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/agent-handle-errors.d.ts +0 -2
- package/dist/src/harness/agent-handle-errors.js +1 -1
- package/dist/src/harness/emission-state.d.ts +25 -0
- package/dist/src/harness/emission-state.js +1 -0
- package/dist/src/harness/emission.d.ts +4 -36
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/handles/transitions.d.ts +16 -1
- package/dist/src/harness/handles/transitions.js +1 -1
- package/dist/src/harness/messages.d.ts +4 -2
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/ordered-stream-emitter.d.ts +3 -2
- package/dist/src/harness/ordered-stream-emitter.js +1 -1
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/tools.d.ts +1 -1
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/harness/turn-tag-state.d.ts +16 -0
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +7 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/message.d.ts +23 -3
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/discord/discordChannel.d.ts +1 -0
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +1 -0
- package/dist/src/public/channels/linear/linearChannel.d.ts +1 -0
- package/dist/src/public/channels/slack/slackChannel.d.ts +1 -0
- package/dist/src/public/channels/teams/teamsChannel.d.ts +1 -0
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +1 -0
- package/dist/src/public/definitions/channel.d.ts +1 -0
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +1 -0
- package/dist/src/public/definitions/tool.d.ts +5 -5
- package/dist/src/runtime/actions/types.d.ts +11 -2
- package/dist/src/runtime/actions/types.js +1 -1
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/runtime/framework-tools/agent.d.ts +16 -0
- package/dist/src/runtime/framework-tools/agent.js +1 -1
- package/dist/src/runtime/prompt/compose.d.ts +7 -0
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/runtime/subagents/registry.d.ts +20 -1
- package/dist/src/runtime/subagents/registry.js +1 -1
- package/dist/src/setup/integrations/github/connect.d.ts +28 -0
- package/dist/src/setup/integrations/github/connect.js +1 -0
- package/dist/src/setup/integrations/github/setup.d.ts +15 -0
- package/dist/src/setup/integrations/github/setup.js +15 -0
- package/dist/src/setup/integrations/linear/setup.js +1 -1
- package/dist/src/setup/integrations/registry.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/async-iterable.d.ts +2 -0
- package/dist/src/shared/async-iterable.js +1 -0
- package/dist/src/shared/tool-definition.d.ts +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tracing/local-trace-reader.d.ts +10 -0
- package/dist/src/tracing/local-trace-reader.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/github.mdx +11 -16
- package/docs/channels/linear.mdx +4 -2
- package/docs/concepts/security-model.md +1 -0
- package/docs/concepts/sessions-runs-and-streaming.md +3 -0
- package/docs/guides/client/streaming.mdx +1 -0
- package/docs/guides/hooks.md +1 -1
- package/docs/guides/state.md +1 -0
- package/docs/install-integrations.mdx +4 -2
- package/docs/reference/cli.md +8 -1
- package/docs/schedules.mdx +1 -0
- package/docs/subagents.mdx +28 -1
- package/docs/tools/human-in-the-loop.md +1 -0
- package/docs/tools/overview.mdx +26 -2
- package/package.json +1 -1
|
@@ -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, 4, 5];
|
|
14
|
+
readonly current: 7;
|
|
15
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
|
|
16
16
|
readonly dropped: {};
|
|
17
17
|
};
|
|
18
18
|
readonly dynamicTool: {
|
|
19
|
-
readonly current:
|
|
20
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
|
|
19
|
+
readonly current: 10;
|
|
20
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
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, 6];
|
|
29
|
+
readonly current: 8;
|
|
30
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
|
|
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, 5];
|
|
39
|
+
readonly current: 7;
|
|
40
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
|
|
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, 5];
|
|
49
|
+
readonly current: 7;
|
|
50
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
|
|
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:7,supported:[1,2,3,4,5,6,7],dropped:{}},dynamicTool:{current:10,supported:[1,2,3,4,5,6,7,8,9,10],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:7,supported:[1,2,3,4,5,6,7],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};
|
|
@@ -9,12 +9,14 @@ export declare function dispatchDynamicSubagentEvent(input: {
|
|
|
9
9
|
readonly ctx: ContextContainer;
|
|
10
10
|
readonly event: UnstampedMessageStreamEvent;
|
|
11
11
|
readonly messages: readonly ModelMessage[];
|
|
12
|
+
readonly persistentSessions: boolean;
|
|
12
13
|
readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
|
|
13
14
|
}): Promise<void>;
|
|
14
15
|
export declare function refreshDynamicSessionSubagentsForRuntimeRevision(input: {
|
|
15
16
|
readonly ctx: ContextContainer;
|
|
16
17
|
readonly event: SessionStartedStreamEvent;
|
|
17
18
|
readonly messages: readonly ModelMessage[];
|
|
19
|
+
readonly persistentSessions: boolean;
|
|
18
20
|
readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
|
|
19
21
|
readonly runtimeRevision: string;
|
|
20
22
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{createPreparedRuntimeSubagentTool}from"#runtime/subagents/registry.js";import{normalizeDynamicSubagentAgentConfig}from"#runtime/subagents/dynamic-agent-config.js";import{normalizeDynamicRemoteAgentConfig}from"#runtime/subagents/dynamic-remote-agent-config.js";const log=createLogger(`dynamic-subagents`),ALLOWED_DYNAMIC_SUBAGENT_EVENTS=new Set([`session.started`,`turn.started`]);async function resolveSelections(e){let t=await Promise.allSettled(e.resolvers.map(async
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{createPreparedRuntimeSubagentTool,getSubagentToolInputJsonSchema}from"#runtime/subagents/registry.js";import{normalizeDynamicSubagentAgentConfig}from"#runtime/subagents/dynamic-agent-config.js";import{normalizeDynamicRemoteAgentConfig}from"#runtime/subagents/dynamic-remote-agent-config.js";const log=createLogger(`dynamic-subagents`),ALLOWED_DYNAMIC_SUBAGENT_EVENTS=new Set([`session.started`,`turn.started`]);async function resolveSelections(e){let t=getSubagentToolInputJsonSchema(e.persistentSessions),n=await Promise.allSettled(e.resolvers.map(async n=>{let r=n.events[e.event.type];if(r===void 0)return[n.nodeId,null];let i=await r(e.event,buildResolveContext(e.ctx,e.messages));if(i==null)return[n.nodeId,null];if(isRemoteAgentDefinition(i)){let e=await normalizeDynamicRemoteAgentConfig({name:n.name,value:i}),r=createPreparedRuntimeSubagentTool({description:e.description,kind:`remote`,logicalPath:n.logicalPath,name:n.name,nodeId:n.nodeId,outputSchema:e.outputSchema,path:e.path,sourceId:n.sourceId,sourceKind:n.sourceKind,url:e.url},t);return[n.nodeId,{kind:`remote`,prepared:r,remoteAgent:e}]}let o=normalizeDynamicSubagentAgentConfig({name:n.name,value:i}),c=createPreparedRuntimeSubagentTool({description:o.description,kind:`subagent`,logicalPath:n.logicalPath,name:n.name,nodeId:n.nodeId,sourceId:n.sourceId,sourceKind:n.sourceKind},t);return[n.nodeId,{agentConfig:o,kind:`subagent`,prepared:c}]})),r={};for(let t=0;t<n.length;t+=1){let a=n[t],o=e.resolvers[t];if(a.status===`rejected`){log.error(`Dynamic subagent resolver (${e.event.type}) threw — omitting subagent.`,{error:toErrorMessage(a.reason),subagentName:o.name}),r[o.nodeId]=null;continue}r[a.value[0]]=a.value[1]}return r}function isRemoteAgentDefinition(e){return typeof e==`object`&&!!e&&e.kind===`remote`}async function dispatchDynamicSubagentEvent(e){if(!ALLOWED_DYNAMIC_SUBAGENT_EVENTS.has(e.event.type))return;let t=e.resolvers.filter(t=>t.eventNames.includes(e.event.type)),i=await resolveSelections({...e,resolvers:t});e.event.type===`session.started`?e.ctx.set(SessionDynamicSubagentSelectionsKey,i):e.ctx.set(TurnDynamicSubagentSelectionsKey,i)}async function refreshDynamicSessionSubagentsForRuntimeRevision(e){if(e.ctx.get(SessionDynamicSubagentRuntimeRevisionKey)===e.runtimeRevision)return;let r=e.resolvers.filter(e=>e.eventNames.includes(`session.started`)),i=await resolveSelections({...e,resolvers:r});e.ctx.set(SessionDynamicSubagentSelectionsKey,i),e.ctx.set(SessionDynamicSubagentRuntimeRevisionKey,e.runtimeRevision)}function buildDynamicSubagentTools(e){let t=e.get(SessionDynamicSubagentSelectionsKey)??{},i=e.get(TurnDynamicSubagentSelectionsKey)??{},a={...t,...i},s=[],c=new Set;for(let e of Object.values(a))if(e!==null){if(c.has(e.prepared.name))throw Error(`Found multiple active dynamic subagents named "${e.prepared.name}". Subagent names must be unique at runtime.`);c.add(e.prepared.name),s.push(createHarnessDelegationToolDefinition(e.prepared))}return s}function getDynamicSubagentSelection(e,t){let i=e.get(TurnDynamicSubagentSelectionsKey)??{};return Object.hasOwn(i,t)?i[t]??void 0:(e.get(SessionDynamicSubagentSelectionsKey)??{})[t]??void 0}export{buildDynamicSubagentTools,dispatchDynamicSubagentEvent,getDynamicSubagentSelection,refreshDynamicSessionSubagentsForRuntimeRevision};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";
|
|
2
|
+
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
|
|
3
|
+
import type { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
|
|
4
|
+
type DynamicRemoteAgentConfig = NonNullable<Extract<ReturnType<typeof getDynamicSubagentSelection>, {
|
|
5
|
+
readonly kind: "remote";
|
|
6
|
+
}>["remoteAgent"]>;
|
|
7
|
+
/** Overlays current dynamic credentials without replacing stored delivery coordinates. */
|
|
8
|
+
export declare function createAgentContinuationBundle(input: {
|
|
9
|
+
readonly action: RuntimeAgentHandleAction;
|
|
10
|
+
readonly bundle: CompiledBundle;
|
|
11
|
+
readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
|
|
12
|
+
}): CompiledBundle;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";function createAgentContinuationBundle(e){let{action:t,dynamicRemoteAgent:n}=e;if(t.kind!==`remote-agent-call`||n===void 0)return e.bundle;let r=e.bundle.subagentRegistry.subagentsByNodeId,i=Object.assign(new Map(r),{get:e=>e===t.nodeId?{definition:resolveRemoteAgentForAction({dynamicRemoteAgent:n,nodeId:e,registry:r,remoteAgentName:t.remoteAgentName})}:r.get(e)});return{...e.bundle,subagentRegistry:{...e.bundle.subagentRegistry,subagentsByNodeId:i}}}export{createAgentContinuationBundle};
|
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Continuation dispatch for stored agent handles.
|
|
3
|
+
*
|
|
4
|
+
* Owns the `agentId` leg of the runtime-action dispatch step: resolving a
|
|
5
|
+
* model-supplied agentId against the session's handle store via
|
|
6
|
+
* `prepareAgentContinuation`, delivering the follow-up message to the
|
|
7
|
+
* address the running handle records, and resolving delivery failures as
|
|
8
|
+
* dead (handle deleted) or retryable (handle restored to `parked`).
|
|
5
9
|
*/
|
|
6
10
|
import type { AgentAddress } from "#harness/handles/store.js";
|
|
7
|
-
import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
|
|
11
|
+
import type { RuntimeActionRequest, RuntimeRemoteAgentCallActionRequest, RuntimeSubagentCallActionRequest, RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
|
|
12
|
+
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
|
|
8
13
|
import type { hydrateDurableSession } from "#execution/session.js";
|
|
14
|
+
/** Runtime action kinds that may address an agent handle via `agentId`. */
|
|
15
|
+
export type RuntimeAgentHandleAction = RuntimeRemoteAgentCallActionRequest | RuntimeSubagentCallActionRequest;
|
|
16
|
+
/** Narrows an action to the kinds that may carry an `agentId` continuation. */
|
|
17
|
+
export declare function isAgentHandleAction(action: RuntimeActionRequest): action is RuntimeAgentHandleAction;
|
|
9
18
|
/** Hydrated parent session snapshot threaded through dispatch. */
|
|
10
19
|
export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;
|
|
11
20
|
/**
|
|
@@ -30,3 +39,22 @@ export type DispatchOutcome = {
|
|
|
30
39
|
readonly result: RuntimeSubagentDispatchFailure;
|
|
31
40
|
readonly session: RuntimeSession;
|
|
32
41
|
};
|
|
42
|
+
/**
|
|
43
|
+
* Delivers one `agentId` continuation to the child the handle names.
|
|
44
|
+
*
|
|
45
|
+
* Planning converts initially unknown ids into fresh starts, so an id that
|
|
46
|
+
* matches no handle here disappeared mid-batch and reports
|
|
47
|
+
* `AGENT_UNREACHABLE`. Name mismatches and busy handles report
|
|
48
|
+
* `AGENT_MISMATCH` / `AGENT_BUSY` without touching the store. Delivery
|
|
49
|
+
* failures report `AGENT_UNREACHABLE`: permanent ones resolve the handle as
|
|
50
|
+
* dead, transient ones restore it to `parked` so the model can retry the
|
|
51
|
+
* same agentId.
|
|
52
|
+
*/
|
|
53
|
+
export declare function dispatchToAgentHandle(input: {
|
|
54
|
+
readonly action: RuntimeAgentHandleAction;
|
|
55
|
+
readonly agentId: string;
|
|
56
|
+
readonly bundle: CompiledBundle;
|
|
57
|
+
readonly currentSession: RuntimeSession;
|
|
58
|
+
readonly parentToken: string;
|
|
59
|
+
readonly parentTurnId: string;
|
|
60
|
+
}): Promise<DispatchOutcome>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{};
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{isRuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{createEveCallbackRoutePath}from"#protocol/routes.js";import{continueRemoteAgentSession,isRetryableRemoteAgentContinueError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE}from"#harness/agent-handle-errors.js";import{deriveAgentOperationId}from"#harness/handles/operation-id.js";import{prepareAgentContinuation,rejectAgentEffect}from"#harness/handles/transitions.js";import{normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{err,ok}from"#shared/result.js";const log=createLogger(`execution.agent-handle-dispatch`);function isAgentHandleAction(e){return e.kind===`subagent-call`||e.kind===`remote-agent-call`}async function dispatchToAgentHandle(e){let{action:n,agentId:r,bundle:i}=e,a=n.kind===`remote-agent-call`?n.remoteAgentName:n.subagentName,o={callId:n.callId,id:deriveAgentOperationId({callId:n.callId,parentSessionId:e.currentSession.sessionId,parentTurnId:e.parentTurnId}),kind:`continue`,parentTurnId:e.parentTurnId,previousStatus:``},f=prepareAgentContinuation(e.currentSession,{agentId:r,invokedName:a,operation:o});switch(f.kind){case`unknown`:return{kind:`error`,result:createAgentErrorResult({action:n,code:AGENT_UNREACHABLE,message:`Agent with id "${r}" is no longer reachable.`}),session:e.currentSession};case`mismatch`:return{kind:`error`,result:createAgentErrorResult({action:n,code:AGENT_MISMATCH,message:`Agent "${r}" from the <agents> list does not belong to "${a}".`}),session:e.currentSession};case`busy`:return{kind:`error`,result:createAgentErrorResult({action:n,code:AGENT_BUSY,message:`Agent "${r}" is still working on its previous request. Wait for its result before continuing it.`}),session:e.currentSession};case`ready`:break}let{handle:p}=f,m=await deliverToAgentHandle({action:n,bundle:i,handle:p,parentToken:e.parentToken});if(!m.ok){let{cause:e,permanent:i}=m.error;return logError(log,`agent delivery failed`,e,{agentId:r,callId:n.callId,nodeId:p.identity.nodeId,permanent:i,subagentName:p.identity.name}),{kind:`error`,result:createAgentErrorResult({action:n,code:AGENT_UNREACHABLE,message:i?`Agent "${p.identity.name}" with id "${r}" is no longer reachable.`:`Agent "${p.identity.name}" with id "${r}" is temporarily unreachable. Try again.`}),session:rejectAgentEffect(f.session,{disposition:i?`dead`:`retryable`,operationId:o.id})}}return{address:p.address,callId:n.callId,kind:`called`,name:n.name,session:f.session,toolName:p.identity.name}}async function deliverToAgentHandle(e){let{action:t,bundle:s,handle:c}=e,{address:l,identity:u}=c;if(l.kind===`agent/remote`){if(l.continuationToken===void 0)return err({cause:Error(`Remote agent "${u.name}" returned no continuationToken at start; its deployment does not support continuations.`),permanent:!0});let n;try{n=resolveRemoteAgentForAction({nodeId:u.nodeId,remoteAgentName:u.name,registry:s.subagentRegistry.subagentsByNodeId})}catch(e){return err({cause:e,permanent:!0})}try{await continueRemoteAgentSession({callback:{callId:t.callId,subagentName:u.name,token:e.parentToken,url:createWorkflowCallbackUrl(l.callbackBaseUrl,createEveCallbackRoutePath(e.parentToken))},continuationToken:l.continuationToken,message:readSubagentMessage(t),outputSchema:normalizeRequestedOutputSchema(t.input.outputSchema),remote:{...n,url:l.url},sessionId:l.sessionId})}catch(e){return err({cause:e,permanent:!isRetryableRemoteAgentContinueError(e)})}return ok(void 0)}let d=createWorkflowRuntime({compiledArtifactsSource:s.compiledArtifactsSource,nodeId:u.nodeId});try{if((await d.dispatchSession({command:{caller:{callId:t.callId,replyTo:{kind:`hook`,token:e.parentToken},subagentName:u.name},kind:`send`,payload:{message:readSubagentMessage(t),outputSchema:normalizeRequestedOutputSchema(t.input.outputSchema)}},sessionId:l.sessionId})).status===`session_not_active`)return err({cause:Error(`Agent session "${l.sessionId}" is no longer active.`),permanent:!0})}catch(e){return err({cause:e,permanent:isRuntimeNoActiveSessionError(e)})}return ok(void 0)}function createAgentErrorResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:e.code,message:e.message},subagentName:e.action.kind===`remote-agent-call`?e.action.remoteAgentName:e.action.subagentName}}function readSubagentMessage(e){return typeof e.input.message==`string`?e.input.message:``}export{dispatchToAgentHandle,isAgentHandleAction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{cancelRemoteAgentTurn,isRetryableRemoteAgentCancelError,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.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 r;try{r=(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(r.length===0){log.warn(`no running agent handles found while cancelling descendants; nothing to cancel`,{sessionId:e.sessionState.sessionId});return}let i,getRemoteContext=()=>i??=deserializeContext(e.serializedContext).then(e=>({ctx:e,registry:e.require(BundleKey).subagentRegistry.subagentsByNodeId}));await Promise.all(r.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 a=n.address.url;try{let{ctx:t,registry:o}=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:o}),url:a},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};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* in `delegated-parent-result.ts` so the workflow step-proxy transform
|
|
5
|
-
* doesn't strip them from this file.
|
|
2
|
+
* Sends delegated task results to their parent and conversation results to
|
|
3
|
+
* the caller of each turn.
|
|
6
4
|
*/
|
|
5
|
+
import type { TurnCaller } from "#channel/types.js";
|
|
7
6
|
import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
|
|
7
|
+
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.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.
|
|
@@ -19,3 +19,29 @@ export declare function notifyDelegatedParentStep(input: {
|
|
|
19
19
|
readonly serializedContext: Record<string, unknown>;
|
|
20
20
|
readonly usage?: TokenUsage;
|
|
21
21
|
}): Promise<void>;
|
|
22
|
+
/** Settled turn payload forwarded from the driver to the caller. */
|
|
23
|
+
export interface SettledTurnNotification {
|
|
24
|
+
readonly output: unknown;
|
|
25
|
+
readonly isError?: boolean;
|
|
26
|
+
/** Usage this turn added; omitted (zero) on crash and expiry paths. */
|
|
27
|
+
readonly usage?: TokenUsage;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Sends a settled conversation turn to the caller that started it.
|
|
31
|
+
*
|
|
32
|
+
* `lifecycle` is the child engine's explicit verdict — `parked` when the
|
|
33
|
+
* child session survived the turn and can accept another delivery,
|
|
34
|
+
* `terminal` when it ended with this turn. It is carried on the result as
|
|
35
|
+
* an {@link AgentTurnOutcome} so the caller never infers lifecycle from
|
|
36
|
+
* success or error codes.
|
|
37
|
+
*/
|
|
38
|
+
export declare function notifyTurnCallerStep(input: {
|
|
39
|
+
readonly caller: TurnCaller | undefined;
|
|
40
|
+
readonly lifecycle: AgentTurnOutcome["kind"];
|
|
41
|
+
readonly sessionId: string;
|
|
42
|
+
readonly settled: SettledTurnNotification;
|
|
43
|
+
}): Promise<void>;
|
|
44
|
+
/** Resolves the caller that created a delegated conversation session. */
|
|
45
|
+
export declare function resolveInitialTurnCallerStep(input: {
|
|
46
|
+
readonly serializedContext: Record<string, unknown>;
|
|
47
|
+
}): Promise<TurnCaller | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";import{resumeHook}from"#internal/workflow/runtime.js";async function notifyDelegatedParentStep(e){"use step";if(e.result===void 0)return;let t=(await deserializeContext(e.serializedContext)).get(ChannelKey);if(t?.kind!==SUBAGENT_ADAPTER_KIND)return;let n=String(t.state?.parentContinuationToken??``);n!==``&&await resumeHook(n,{kind:`runtime-action-result`,results:[e.usage===void 0||e.result.isError===!0?e.result:{...e.result,usage:e.usage}]})}export{notifyDelegatedParentStep};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonValue}from"#shared/json.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{SUBAGENT_EXECUTION_FAILED}from"#harness/agent-handle-errors.js";import{deserializeContext}from"#context/serialize.js";import{parseSessionCallback}from"#channel/session-callback.js";import{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState}from"#execution/subagent-adapter-state.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{resumeHook}from"#internal/workflow/runtime.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.delegated-parent-notification`);async function notifyDelegatedParentStep(e){"use step";if(e.result===void 0)return;let t=(await deserializeContext(e.serializedContext)).get(ChannelKey);if(t?.kind!==SUBAGENT_ADAPTER_KIND)return;let n=String(t.state?.parentContinuationToken??``);n!==``&&await resumeHook(n,{kind:`runtime-action-result`,results:[e.usage===void 0||e.result.isError===!0?e.result:{...e.result,outcome:{...e.result.outcome,usageDelta:e.usage},usage:e.usage}]})}const ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,inputTokens:0,outputTokens:0};async function notifyTurnCallerStep(e){"use step";if(e.caller===void 0)return;let t=createSettledTurnResult({caller:e.caller,lifecycle:e.lifecycle,sessionId:e.sessionId,settled:e.settled});if(e.caller.replyTo.kind===`callback`){await postSettledTurnCallback({result:t,sessionId:e.sessionId,url:e.caller.replyTo.url});return}await resumeSettledTurnHook(e.caller.replyTo.token,t)}function createSettledTurnResult(e){let t=e.settled.usage??ZERO_TOKEN_USAGE;if(e.settled.isError===!0){let r={code:SUBAGENT_EXECUTION_FAILED,message:toErrorMessage(e.settled.output)};return{callId:e.caller.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:{kind:e.lifecycle,result:{error:r,kind:`failed`},usageDelta:t},output:r,subagentName:e.caller.subagentName}}let i=parseJsonValue(e.settled.output),a={callId:e.caller.callId,kind:`subagent-result`,origin:`child`,outcome:{kind:e.lifecycle,result:{kind:`succeeded`,output:i},usageDelta:t},output:i,subagentName:e.caller.subagentName};return e.settled.usage===void 0?a:{...a,usage:e.settled.usage}}async function resolveInitialTurnCallerStep(e){"use step";let n=e.serializedContext[SessionCallbackKey.name];if(n!==void 0){let e=parseSessionCallback(n);if(!e.ok)throw Error(`Serialized session callback is invalid.`,{cause:e.cause});return{callId:e.callback.callId,replyTo:{kind:`callback`,url:e.callback.url},subagentName:e.callback.subagentName}}let r=(await deserializeContext(e.serializedContext)).get(ChannelKey);if(!(r?.kind!==SUBAGENT_ADAPTER_KIND||!isSubagentAdapterState(r.state)))return{callId:r.state.callId,replyTo:{kind:`hook`,token:r.state.parentContinuationToken},subagentName:r.state.subagentName}}async function postSettledTurnCallback(e){let{sessionId:t}=e;if(e.result.isError===!0){await postCallbackPayload({payload:{callId:e.result.callId,error:e.result.output,kind:`turn.failed`,outcome:e.result.outcome,sessionId:t,subagentName:e.result.subagentName},url:e.url});return}await postCallbackPayload({payload:{callId:e.result.callId,kind:`turn.completed`,outcome:e.result.outcome,output:e.result.output,sessionId:t,subagentName:e.result.subagentName},url:e.url})}async function postCallbackPayload(e){let t=await postSessionCallbackRequest({body:e.payload,url:e.url});if(!t.ok)throw Error(`Turn callback failed with HTTP ${t.status}.`)}async function resumeSettledTurnHook(e,t){try{await resumeHook(e,{kind:`runtime-action-result`,results:[t]})}catch(n){if(!HookNotFoundError.is(n))throw n;log.warn(`turn caller hook no longer exists`,{callId:t.callId,callerToken:e})}}export{notifyDelegatedParentStep,notifyTurnCallerStep,resolveInitialTurnCallerStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorMessage}from"#shared/errors.js";import{
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";import{SUBAGENT_EXECUTION_FAILED}from"#harness/agent-handle-errors.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter-state.js";const ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,inputTokens:0,outputTokens:0};function createDelegatedSubagentSuccessResult(e,t){let r=e[`eve.channel`];if(r?.kind===SUBAGENT_ADAPTER_KIND)return{callId:String(r.state?.callId??``),kind:`subagent-result`,origin:`child`,outcome:{kind:`terminal`,result:{kind:`succeeded`,output:t},usageDelta:ZERO_TOKEN_USAGE},output:t,subagentName:String(r.state?.subagentName??``)}}function createDelegatedSubagentErrorResult(n,r){let i=createDelegatedSubagentSuccessResult(n,``);if(i===void 0)return;let a={code:SUBAGENT_EXECUTION_FAILED,message:toErrorMessage(r)};return{...i,isError:!0,outcome:{kind:`terminal`,result:{error:a,kind:`failed`},usageDelta:ZERO_TOKEN_USAGE},output:a}}export{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RuntimeRemoteAgentCallActionRequest, RuntimeSubagentCallActionRequest, RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
|
|
2
|
+
export declare function createUnavailableDynamicSubagentResult(action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest): RuntimeSubagentDispatchFailure;
|
|
3
|
+
export declare function getSubagentName(action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest): string;
|
|
4
|
+
export declare function createRemoteAgentStartFailureResult(input: {
|
|
5
|
+
readonly action: RuntimeRemoteAgentCallActionRequest;
|
|
6
|
+
readonly error: unknown;
|
|
7
|
+
}): RuntimeSubagentDispatchFailure;
|
|
8
|
+
export declare function createRecursiveAgentRootOnlyResult(action: RuntimeSubagentCallActionRequest): RuntimeSubagentDispatchFailure;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";import{REMOTE_AGENT_START_FAILED}from"#harness/agent-handle-errors.js";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(n){return{callId:n.action.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:REMOTE_AGENT_START_FAILED,message:toErrorMessage(n.error)},subagentName:n.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}}export{createRecursiveAgentRootOnlyResult,createRemoteAgentStartFailureResult,createUnavailableDynamicSubagentResult,getSubagentName};
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Starts every pending runtime action for the parked parent
|
|
2
|
+
* Starts or continues every pending runtime action for the parked parent
|
|
3
|
+
* session.
|
|
3
4
|
*
|
|
4
|
-
* The batch is classified into a dispatch plan first (reject /
|
|
5
|
-
* each entry dispatches and emits one
|
|
6
|
-
* event through a single tail.
|
|
7
|
-
* (`starting`) before its side effect
|
|
8
|
-
* child reports coordinates, so the
|
|
9
|
-
* every child it may have created.
|
|
5
|
+
* The batch is classified into a dispatch plan first (reject / resume /
|
|
6
|
+
* start), then each entry dispatches and emits one
|
|
7
|
+
* parent `subagent.called` control-plane event through a single tail.
|
|
8
|
+
* Every start commits an agent handle (`starting`) before its side effect
|
|
9
|
+
* and confirms it (`running`) once the child reports coordinates, so the
|
|
10
|
+
* returned snapshot-bearing state owns every child it may have created.
|
|
10
11
|
*/
|
|
11
12
|
import type { RuntimeSubagentResult } from "#runtime/actions/types.js";
|
|
12
13
|
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{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.createSession(o)).sessionId}catch(e){return logError(log,`local subagent start failed`,e,{callId:n.callId,nodeId:n.nodeId,subagentName:n.subagentName}),{kind:`error`,result:{callId:n.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:SUBAGENT_START_FAILED,message:toErrorMessage(e)},subagentName:n.subagentName},session:rejectAgentEffect(d,{disposition:`dead`,operationId:u.id})}}let p={continuationToken:a,kind:c,sessionId:f};return{address:p,callId:n.callId,kind:`called`,name:n.name,session:confirmAgentStarted(d,{address:p,operationId:u.id}),toolName:n.subagentName}}async function startRemoteSubagent(e){let{action:n}=e,r,i;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);r=e.callbackBaseUrl,i=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:n.nodeId,remoteAgentName:n.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(r){return logError(log,`remote agent start failed`,r,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:n,error:r}),session:e.currentSession}}let{identity:a,operation:o}=mintStartOperation({callId:n.callId,name:n.remoteAgentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),s=prepareAgentStart(e.currentSession,{identity:a,operation:o,target:{callbackBaseUrl:r,kind:`agent/remote`,url:i.url}});try{let t=await startRemoteAgentSession({action:n,auth:e.auth,callbackBaseUrl:r,callbackToken:e.parentContinuationToken,initiatorAuth:e.initiatorAuth,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
|
+
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{SUBAGENT_START_FAILED}from"#harness/agent-handle-errors.js";import{confirmAgentStarted,prepareAgentStart,rejectAgentEffect}from"#harness/handles/transitions.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";import{deserializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{getDynamicSubagentSelection}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{dispatchToAgentHandle,isAgentHandleAction}from"#execution/agent-handle-dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createRecursiveAgentRootOnlyResult,createRemoteAgentStartFailureResult,createUnavailableDynamicSubagentResult,getSubagentName}from"#execution/dispatch-action-failures.js";import{mintStartOperation}from"#execution/dispatch-start-operation.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{readSessionTraceContext}from"#tracing/agent-trace-context-store.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),p=getPendingRuntimeActionBatch(s.state);if(p===void 0||p.actions.length===0)return{results:[],sessionState:e.sessionState};let m=await deserializeContext(e.serializedContext),h=m.require(BundleKey),g=resolveEffectiveAgentRuntime(h,m),_=hydrateDurableSession({compactionOverrides:{thresholdPercent:g.thresholdPercent},durable:s,turnAgent:g.turnAgent}),v=m.require(ChannelKey),y=m.get(AuthKey)??null,b=m.get(CapabilitiesKey),x=m.get(ChannelInstrumentationKey),S=m.get(InitiatorAuthKey)??null,C=buildAdapterContext(v,m),w=readSessionTraceContext(e.serializedContext,_.sessionId),T=h.resolvedAgent.config.experimental?.subagentPersistentSessions===!0;getAgentHandleStore(s.state);let E=planDispatch({actions:p.actions,bundle:h,ctx:m,session:_}),D=e.parentWritable.getWriter(),O=E.filter(e=>e.kind===`start`&&e.target.kind===`local`).length,k=_,A=[];try{for(let r of E){if(r.kind===`reject`){A.push(r.result);continue}let i;switch(r.kind){case`resume`:i=await dispatchToAgentHandle({action:r.action,agentId:r.agentId,bundle:createAgentContinuationBundle({action:r.action,bundle:h,dynamicRemoteAgent:r.dynamicRemoteAgent}),currentSession:k,parentToken:e.parentContinuationToken??_.continuationToken,parentTurnId:p.event.turnId});break;case`start`:i=await startSubagent({auth:y,batchEvent:p.event,bundle:h,callbackBaseUrl:e.callbackBaseUrl,capabilities:b,channelMetadata:x,currentSession:k,fanoutSize:O,initiatorAuth:S,parentContinuationToken:e.parentContinuationToken,parentTraceContext:w,persistentSessions:T,session:_,target:r.target});break}if(k=i.session,i.kind===`error`){A.push(i.result);continue}try{let e=await callAdapterEventHandler(v,createSubagentCalledEvent({callId:i.callId,childSessionId:i.address.sessionId,name:i.name,remote:i.address.kind===`agent/remote`?{url:i.address.url}:void 0,sequence:p.event.sequence,sessionId:_.sessionId,toolName:i.toolName,turnId:p.event.turnId,workflowId:workflowEntryReference.workflowId}),C);await D.write(encodeMessageStreamEvent(stampMessageStreamEvent(e)))}catch(e){logError(log,`subagent.called emission failed`,e,{callId:i.callId,childSessionId:i.address.sessionId,toolName:i.toolName})}}}finally{D.releaseLock()}return{results:A,sessionState:k===_?e.sessionState:createDurableSessionState({session:k})}}function planDispatch(e){let t=getAgentHandleStore(e.session.state)?.handles??[];return e.actions.map(n=>{let r=n.input.agentId,i=typeof r==`string`&&r.trim()!==``?r:void 0;if(i!==void 0&&isAgentHandleAction(n)){if(t.some(e=>e.identity.id===i)){let t=e.bundle.subagentRegistry.dynamicNodeIds?.has(n.nodeId)===!0?getDynamicSubagentSelection(e.ctx,n.nodeId):void 0;return{action:n,agentId:i,dynamicRemoteAgent:n.kind===`remote-agent-call`&&t?.kind===`remote`?t.remoteAgent:void 0,kind:`resume`}}log.warn(`unknown agentId on subagent call; starting a new agent`,{agentId:i,callId:n.callId})}return classifyFreshStart({action:n,bundle:e.bundle,ctx:e.ctx,session:e.session})})}function classifyFreshStart(e){let{action:t}=e,n=e.bundle.subagentRegistry.subagentsByNodeId,r=resolveSubagentDepth(e.session),i=e.session.rootSessionId!==void 0||r.currentDepth>0,a=(t.kind===`subagent-call`||t.kind===`remote-agent-call`)&&e.bundle.subagentRegistry.dynamicNodeIds?.has(t.nodeId)===!0,o=a?getDynamicSubagentSelection(e.ctx,t.nodeId):void 0;if(a&&(o===void 0||t.kind===`subagent-call`&&o.kind!==`subagent`||t.kind===`remote-agent-call`&&o.kind!==`remote`)){let e=getSubagentName(t);return log.warn(`dynamic subagent call blocked after availability changed`,{callId:t.callId,nodeId:t.nodeId,subagentName:e}),{kind:`reject`,result:createUnavailableDynamicSubagentResult(t)}}if(isRecursiveAgentAction(t,n)&&i)return log.warn(`recursive agent call blocked outside the root session`,{callId:t.callId,currentDepth:r.currentDepth,nodeId:t.nodeId,subagentName:t.subagentName}),{kind:`reject`,result:createRecursiveAgentRootOnlyResult(t)};switch(t.kind){case`subagent-call`:{let e=o?.kind===`subagent`?o.agentConfig:void 0,r=n.get(t.nodeId),i=e?.description??(r?.definition.kind===`subagent`?r.definition.description:void 0);return{kind:`start`,target:{action:t,dynamicSubagentAgentConfig:e,kind:`local`,source:i===void 0?{type:`runtime`}:{description:i,type:`local`}}}}case`remote-agent-call`:return{kind:`start`,target:{action:t,dynamicRemoteAgent:o?.kind===`remote`?o.remoteAgent:void 0,kind:`remote`}};default:throw Error(`Unsupported runtime action kind "${t.kind}" in workflow runtime.`)}}async function startSubagent(e){switch(e.target.kind){case`local`:return startLocalSubagent({action:e.target.action,auth:e.auth,batchEvent:e.batchEvent,bundle:e.bundle,capabilities:e.capabilities,channelMetadata:e.channelMetadata,currentSession:e.currentSession,dynamicSubagentAgentConfig:e.target.dynamicSubagentAgentConfig,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,persistentSessions:e.persistentSessions,session:e.session,source:e.target.source});case`remote`:return startRemoteSubagent({action:e.target.action,auth:e.auth,batchEvent:e.batchEvent,bundle:e.bundle,callbackBaseUrl:e.callbackBaseUrl,currentSession:e.currentSession,dynamicRemoteAgent:e.target.dynamicRemoteAgent,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,persistentSessions:e.persistentSessions,session:e.session});default:return e.target}}async function startLocalSubagent(e){let{action:n,source:r}=e,i=createWorkflowRuntime({compiledArtifactsSource:e.bundle.compiledArtifactsSource,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,nodeId:n.nodeId}),{childContinuationToken:a,runInput:o}=buildSubagentRunInput({action:n,auth:e.auth,batchEvent:e.batchEvent,capabilities:e.capabilities,channelMetadata:e.channelMetadata,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,persistentSessions:e.persistentSessions,session:e.session,source:r}),c=r.type===`runtime`?`agent/self`:`agent/local`,{identity:l,operation:u}=mintStartOperation({callId:n.callId,name:n.subagentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),d=prepareAgentStart(e.currentSession,{identity:l,operation:u,target:{continuationToken:a,kind:c}}),f;try{f=(await i.createSession(o)).sessionId}catch(e){return logError(log,`local subagent start failed`,e,{callId:n.callId,nodeId:n.nodeId,subagentName:n.subagentName}),{kind:`error`,result:{callId:n.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:SUBAGENT_START_FAILED,message:toErrorMessage(e)},subagentName:n.subagentName},session:rejectAgentEffect(d,{disposition:`dead`,operationId:u.id})}}let p={continuationToken:a,kind:c,sessionId:f};return{address:p,callId:n.callId,kind:`called`,name:n.name,session:confirmAgentStarted(d,{address:p,operationId:u.id}),toolName:n.subagentName}}async function startRemoteSubagent(e){let{action:n}=e,r,i;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);r=e.callbackBaseUrl,i=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:n.nodeId,remoteAgentName:n.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(r){return logError(log,`remote agent start failed`,r,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:n,error:r}),session:e.currentSession}}let{identity:a,operation:o}=mintStartOperation({callId:n.callId,name:n.remoteAgentName,nodeId:n.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),s=prepareAgentStart(e.currentSession,{identity:a,operation:o,target:{callbackBaseUrl:r,kind:`agent/remote`,url:i.url}});try{let t=await startRemoteAgentSession({action:n,auth:e.auth,callbackBaseUrl:r,callbackToken:e.parentContinuationToken,initiatorAuth:e.initiatorAuth,persistentSessions:e.persistentSessions,remote:i,session:e.session}),a={callbackBaseUrl:r,kind:`agent/remote`,sessionId:t.sessionId,url:i.url,...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 isRecursiveAgentAction(e,t){return e.kind===`subagent-call`&&e.subagentName===`agent`&&!t.has(e.nodeId)}export{dispatchRuntimeActionsStep};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type AgentIdentity, type StartOperation } from "#harness/handles/store.js";
|
|
2
|
+
/**
|
|
3
|
+
* Mints deterministic parent-controlled ownership data before the child exists,
|
|
4
|
+
* so durable step replays derive the same handle record.
|
|
5
|
+
*/
|
|
6
|
+
export declare function mintStartOperation(input: {
|
|
7
|
+
readonly callId: string;
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly nodeId: string;
|
|
10
|
+
readonly parentSessionId: string;
|
|
11
|
+
readonly parentTurnId: string;
|
|
12
|
+
}): {
|
|
13
|
+
readonly identity: AgentIdentity;
|
|
14
|
+
readonly operation: StartOperation;
|
|
15
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{deriveAgentOperationId}from"#harness/handles/operation-id.js";import{deriveAgentId}from"#harness/handles/store.js";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}}}export{mintStartOperation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{resumeHook}from"#internal/workflow/runtime.js";async function forwardTurnCancellationStep(n){"use step";for(let r=0;r<50;r+=1)try{return await resumeHook(n.token,n.payload),!0}catch(t){if(!HookNotFoundError.is(t))throw t;if(r===49)return!1;await new Promise(e=>setTimeout(e,20))}return!1}export{forwardTurnCancellationStep};
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* strips unknown fields.
|
|
13
13
|
*/
|
|
14
14
|
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
15
|
+
import type { SettledTurn } from "#harness/types.js";
|
|
15
16
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
16
17
|
/** Discriminated union the driver workflow body dispatches on. */
|
|
17
18
|
export type NextDriverAction = {
|
|
@@ -22,6 +23,12 @@ export type NextDriverAction = {
|
|
|
22
23
|
readonly serializedContext: Record<string, unknown>;
|
|
23
24
|
/** Session-total token usage spent by the completed session. */
|
|
24
25
|
readonly usage?: TokenUsage;
|
|
26
|
+
/**
|
|
27
|
+
* Usage the final turn added beyond what earlier settled turns already
|
|
28
|
+
* reported; forwarded through the same pinned-driver-safe
|
|
29
|
+
* optional-field pattern as `cancelled`.
|
|
30
|
+
*/
|
|
31
|
+
readonly usageDelta?: TokenUsage;
|
|
25
32
|
} | {
|
|
26
33
|
readonly kind: "park";
|
|
27
34
|
readonly sessionState: DurableSessionState;
|
|
@@ -34,6 +41,11 @@ export type NextDriverAction = {
|
|
|
34
41
|
* working.
|
|
35
42
|
*/
|
|
36
43
|
readonly cancelled?: true;
|
|
44
|
+
/**
|
|
45
|
+
* Settled user-facing answer forwarded through the same pinned-driver-safe
|
|
46
|
+
* optional-field pattern as `cancelled`.
|
|
47
|
+
*/
|
|
48
|
+
readonly settled?: SettledTurn;
|
|
37
49
|
} | {
|
|
38
50
|
readonly kind: "dispatch-runtime-actions";
|
|
39
51
|
readonly pendingActionKeys: readonly string[];
|
|
@@ -4,7 +4,7 @@ import type { RuntimeIdentity } from "#protocol/message.js";
|
|
|
4
4
|
import type { RunMode } from "#shared/run-mode.js";
|
|
5
5
|
import { type RuntimeModelResolutionScope } from "#runtime/agent/resolve-model.js";
|
|
6
6
|
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
7
|
-
import {
|
|
7
|
+
import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
|
|
8
8
|
/**
|
|
9
9
|
* Factory that creates a {@link Runtime} for the given compiled
|
|
10
10
|
* artifacts source and optional node id. Matches the signature of
|
|
@@ -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{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation-runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME,isImplicitAgentToolAvailable}from"#runtime/framework-tools/agent.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node}),i=getInstrumentationRuntime(),a=createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,webSearchProvider:e.node.agent.webSearchProvider,handleEvent:e.handleEvent,instrumentation:i,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,persistentSubagentSessions:e.node.agent.config?.experimental?.subagentPersistentSessions===!0,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?a:async(e,t)=>{try{return await a(e,t)}finally{await i.forceFlush()}}}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version,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 isImplicitAgentToolAvailable({disabledFrameworkTools:e.node.agent.disabledFrameworkTools,hasAuthoredAgentTool:t.has(AGENT_TOOL_NAME),nodeId:e.node.nodeId})&&t.set(AGENT_TOOL_NAME,{description:AGENT_TOOL_DESCRIPTION,inputSchema:e.node.agent.config?.experimental?.subagentPersistentSessions===!0?PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA:SUBAGENT_TOOL_INPUT_SCHEMA,name:AGENT_TOOL_NAME,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:AGENT_TOOL_NAME}}),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};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";
|
|
2
|
+
import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
|
+
import type { SessionCommandInbox } from "#execution/session-command-inbox.js";
|
|
4
|
+
/** What the parked driver should do with the next session activity. */
|
|
5
|
+
export type NextTurnInstruction = {
|
|
6
|
+
readonly kind: "clear";
|
|
7
|
+
} | {
|
|
8
|
+
readonly kind: "compact";
|
|
9
|
+
} | {
|
|
10
|
+
readonly kind: "expired";
|
|
11
|
+
} | {
|
|
12
|
+
readonly kind: "reset";
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "closed";
|
|
15
|
+
} | {
|
|
16
|
+
readonly kind: "cancel-turn";
|
|
17
|
+
} | {
|
|
18
|
+
readonly kind: "turn";
|
|
19
|
+
readonly deliver: DeliverHookPayload;
|
|
20
|
+
readonly remainder: DeliverPayload;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Awaits the next delivery that requires driver action while the session
|
|
24
|
+
* is parked. Deliveries fully routed to a descendant leave the parent with
|
|
25
|
+
* no turn to run, so this keeps waiting until a delivery produces a parent
|
|
26
|
+
* turn, a cancellation, expiry, or hook closure. The wait is unbounded by
|
|
27
|
+
* design: a parked session lives until something addresses it.
|
|
28
|
+
*/
|
|
29
|
+
export declare function nextTurnDelivery(input: {
|
|
30
|
+
readonly bufferedDeliveries: DeliverHookPayload[];
|
|
31
|
+
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
|
|
32
|
+
readonly commandInbox: SessionCommandInbox;
|
|
33
|
+
readonly driverWritable: WritableStream<Uint8Array>;
|
|
34
|
+
readonly sessionState: DurableSessionState;
|
|
35
|
+
}): Promise<NextTurnInstruction>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{coalesceDeliveries}from"#harness/messages.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";async function nextTurnDelivery(e){for(;;){let n=await waitForNextSessionAction({bufferedDeliveries:e.bufferedDeliveries,bufferedSessionControls:e.bufferedSessionControls,commandInbox:e.commandInbox});if(n.kind!==`delivery`)return{kind:n.kind};let r=n.delivery;if(r===null)return{kind:`closed`};let i=await routeDeliverToChildren({auth:r.auth,parentWritable:e.driverWritable,payloads:r.payloads,sessionState:e.sessionState});if(i.kind===`cancel-turn`)return{kind:`cancel-turn`};if(i.remainder!==void 0)return{deliver:r,kind:`turn`,remainder:i.remainder}}}async function waitForNextSessionAction(e){let t=e.bufferedSessionControls.shift();if(t!==void 0)return{kind:t};if(e.bufferedDeliveries.length>0)return{delivery:takeBufferedTurnDelivery(e.bufferedDeliveries),kind:`delivery`};for(;;){let t=await e.commandInbox.next();if(e.commandInbox.consumeNext(),t.done)return{delivery:null,kind:`delivery`};if(t.value.kind===`session-timeout`)return{kind:`expired`};if(t.value.kind===`clear`||t.value.kind===`compact`||t.value.kind===`reset`)return{kind:t.value.kind};if(t.value.kind!==`cancel`)return{delivery:commandToDelivery(t.value),kind:`delivery`}}}function commandToDelivery(e){return{auth:e.auth,caller:e.caller,kind:`deliver`,payloads:[e.payload],requestId:e.requestId}}function takeBufferedTurnDelivery(t){let n=t.shift();if(n===void 0)throw Error(`Cannot take a turn delivery from an empty buffer.`);let r=[n],i=n.caller;for(;t.length>0;){let e=t[0];if(e===void 0||i!==void 0&&e.caller!==void 0)break;let n=t.shift();if(n===void 0)throw Error(`Buffered turn delivery disappeared while partitioning.`);r.push(n),i??=n.caller}return coalesceDeliveries(r)}export{nextTurnDelivery};
|
|
@@ -4,6 +4,7 @@ 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
|
+
import type { JsonObject } from "#shared/json.js";
|
|
7
8
|
type RemoteAgentSessionCoordinates = {
|
|
8
9
|
readonly continuationToken?: string;
|
|
9
10
|
readonly sessionId: string;
|
|
@@ -16,9 +17,50 @@ export declare function startRemoteAgentSession(input: {
|
|
|
16
17
|
readonly callbackToken?: string;
|
|
17
18
|
/** The root initiator's principal, forwarded alongside {@link auth}. */
|
|
18
19
|
readonly initiatorAuth?: SessionAuthContext | null;
|
|
20
|
+
/**
|
|
21
|
+
* Whether the dispatching agent opted into
|
|
22
|
+
* `experimental.subagentPersistentSessions`. Persistent remote children run
|
|
23
|
+
* in conversation mode so their sessions accept follow-up messages.
|
|
24
|
+
*/
|
|
25
|
+
readonly persistentSessions?: boolean;
|
|
19
26
|
readonly remote: ResolvedRuntimeRemoteAgentNode;
|
|
20
27
|
readonly session: HarnessSession;
|
|
21
28
|
}): Promise<RemoteAgentSessionCoordinates>;
|
|
29
|
+
/** Continues one remote-agent session via agentId. */
|
|
30
|
+
export declare function continueRemoteAgentSession(input: {
|
|
31
|
+
readonly callback: {
|
|
32
|
+
readonly callId: string;
|
|
33
|
+
readonly subagentName: string;
|
|
34
|
+
readonly token: string;
|
|
35
|
+
readonly url: string;
|
|
36
|
+
};
|
|
37
|
+
readonly continuationToken: string;
|
|
38
|
+
readonly message: string;
|
|
39
|
+
readonly outputSchema?: JsonObject;
|
|
40
|
+
readonly remote: ResolvedRuntimeRemoteAgentNode;
|
|
41
|
+
readonly sessionId: string;
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Failure of a continue-session request, classified at the HTTP boundary.
|
|
45
|
+
* Exported so tests can exercise {@link isRetryableRemoteAgentContinueError}
|
|
46
|
+
* with real instances instead of re-encoding the classification.
|
|
47
|
+
*/
|
|
48
|
+
export declare class RemoteAgentContinueRequestError extends Error {
|
|
49
|
+
readonly retryable: boolean;
|
|
50
|
+
constructor(message: string, options: {
|
|
51
|
+
readonly retryable: boolean;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Returns true when a failed continue request may be retried. Only a
|
|
56
|
+
* session that no longer exists (404 / SESSION_NOT_RESUMABLE) is permanent;
|
|
57
|
+
* transient HTTP and network failures stay retryable so the dispatch step
|
|
58
|
+
* keeps the agent handle and surfaces a retryable error instead of
|
|
59
|
+
* discarding it — the model decides whether to try the same agentId again
|
|
60
|
+
* (the step itself never re-sends: the callee may have accepted a delivery
|
|
61
|
+
* whose response was lost).
|
|
62
|
+
*/
|
|
63
|
+
export declare function isRetryableRemoteAgentContinueError(error: unknown): boolean;
|
|
22
64
|
export declare function cancelRemoteAgentTurn(input: {
|
|
23
65
|
readonly remote: ResolvedRuntimeRemoteAgentNode;
|
|
24
66
|
readonly sessionId: string;
|
|
@@ -1 +1 @@
|
|
|
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{
|
|
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{formatSubagentInput,normalizeRequestedOutputSchema}from"#execution/subagent-invocation.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{AgentHandleError}from"#protocol/agent-handle-error.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,persistentSession:e.persistentSessions,remote:e.remote}),mode:e.persistentSessions===!0?`conversation`:`task`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};n!==void 0&&(i.forwardedPrincipal=n);let 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}}async function continueRemoteAgentSession(e){let t=await fetch(createRemoteAgentContinueUrl(e.remote,e.sessionId),{body:JSON.stringify({callback:e.callback,continuationToken:e.continuationToken,message:e.message,outputSchema:e.outputSchema}),headers:{"content-type":`application/json`,...await resolveRemoteAgentRequestHeaders(e.remote)},method:`POST`});if(!t.ok){let n=await readRemoteAgentErrorCode(t),r=t.status===404||n===AgentHandleError.SessionNotResumable.code;throw new RemoteAgentContinueRequestError(`Remote agent "${e.remote.name}" continue-session request failed${r?` permanently`:``} with HTTP ${t.status}.`,{retryable:!r})}}var RemoteAgentContinueRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentContinueRequestError`,this.retryable=t.retryable}};function isRetryableRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.retryable}async function readRemoteAgentErrorCode(e){let t;try{t=await e.json()}catch{return}if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`code`);return typeof n==`string`?n:void 0}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.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 createRemoteAgentContinueUrl(e,t){return createRemoteAgentRouteUrl(e.url,`/eve/v1/session/${encodeURIComponent(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,persistentSession:e.persistentSession,type:`remote`}).message}function trimTrailingSlash(e){return e.endsWith(`/`)?e.slice(0,-1):e}export{RemoteAgentContinueRequestError,cancelRemoteAgentTurn,continueRemoteAgentSession,isRetryableRemoteAgentCancelError,isRetryableRemoteAgentContinueError,resolveRemoteAgentForAction,startRemoteAgentSession};
|