Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): graduate background subagents to workflow tools (#2690)

Ruiaae26311a845
diff --git a/.changeset/per-subagent-background.md b/.changeset/per-subagent-background.md
new file mode 100644
index 000000000..18f2982c1
--- /dev/null
+++ b/.changeset/per-subagent-background.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Background workflow tools now execute as their task's durable workflow run, subagents can be invoked directly from waiting workflow tools and workflow sandboxes, and workflow `agent()` calls require a replay-stable `key`.
diff --git a/apps/docs/registry.json b/apps/docs/registry.json
index e1977c8b5..bb9ec9afa 100644
--- a/apps/docs/registry.json
+++ b/apps/docs/registry.json
@@ -33,19 +33,14 @@
"type": "registry:item",
"title": "Self-modification (Experimental)",
"description": "Add an experimental, development-only source editing subagent to an eve project.",
- "dependencies": [
- "@eve/self-modification"
- ],
+ "dependencies": ["@eve/self-modification"],
"meta": {
"eve": {
"install": {
"pnpm": {
"buildScripts": [
{
- "packages": [
- "node-liblzma",
- "@mongodb-js/zstd"
- ],
+ "packages": ["node-liblzma", "@mongodb-js/zstd"],
"optional": true,
"recommendedAction": "ignore-optional",
"reason": "These optional just-bash compression accelerators are not required by the self-modification agent."
@@ -78,9 +73,7 @@
"type": "registry:item",
"title": "agent-browser",
"description": "Add browser automation tools backed by agent-browser to an eve agent.",
- "dependencies": [
- "@agent-browser/eve"
- ],
+ "dependencies": ["@agent-browser/eve"],
"files": [
{
"path": "registry/extensions/agent-browser.ts",
@@ -94,9 +87,7 @@
"type": "registry:item",
"title": "Browserbase",
"description": "Search, fetch, and automate the web with Browserbase and Stagehand.",
- "dependencies": [
- "@browserbasehq/eve"
- ],
+ "dependencies": ["@browserbasehq/eve"],
"envVars": {
"BROWSERBASE_API_KEY": ""
},
@@ -113,9 +104,7 @@
"type": "registry:item",
"title": "BlitzReels",
"description": "Turn long videos into short clips, generate media, repair edits, and export.",
- "dependencies": [
- "@blitzreels/eve"
- ],
+ "dependencies": ["@blitzreels/eve"],
"envVars": {
"BLITZREELS_API_KEY": ""
},
@@ -132,10 +121,7 @@
"type": "registry:item",
"title": "GitHub Tools",
"description": "Add scoped GitHub tools with Vercel Connect authentication and approval rules.",
- "dependencies": [
- "@github-tools/eve-extension",
- "@vercel/connect"
- ],
+ "dependencies": ["@github-tools/eve-extension", "@vercel/connect"],
"envVars": {
"GITHUB_TOKEN": ""
},
@@ -152,9 +138,7 @@
"type": "registry:item",
"title": "Jetty",
"description": "Grade agent turns, compare experiments, and store durable evaluation trajectories.",
- "dependencies": [
- "@jetty/eve"
- ],
+ "dependencies": ["@jetty/eve"],
"envVars": {
"JETTY_API_TOKEN": "",
"JETTY_COLLECTION": ""
@@ -172,9 +156,7 @@
"type": "registry:item",
"title": "KERNEL",
"description": "Let your eve agent use the Internet with KERNEL browser infrastructure, observability, and stealth.",
- "dependencies": [
- "@onkernel/eve-extension"
- ],
+ "dependencies": ["@onkernel/eve-extension"],
"envVars": {
"KERNEL_API_KEY": ""
},
@@ -191,9 +173,7 @@
"type": "registry:item",
"title": "Upstash AgentKit",
"description": "Add long-term memory, Redis Search, and durable chat history with Upstash Redis.",
- "dependencies": [
- "@upstash/agentkit-eve-extension"
- ],
+ "dependencies": ["@upstash/agentkit-eve-extension"],
"envVars": {
"UPSTASH_REDIS_REST_URL": "",
"UPSTASH_REDIS_REST_TOKEN": ""
@@ -216,11 +196,7 @@
"setup": {
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "file-memory"
- ]
+ "args": ["integration", "setup", "file-memory"]
},
"requires": ">=0.49.1",
"docs": "/docs/memory/file"
@@ -239,9 +215,7 @@
"type": "registry:item",
"title": "Supermemory",
"description": "Give your agents long-term memory, user profiles, and SuperRAG across conversations and context.",
- "dependencies": [
- "@supermemory/eve"
- ],
+ "dependencies": ["@supermemory/eve"],
"envVars": {
"SUPERMEMORY_API_KEY": ""
},
@@ -263,9 +237,7 @@
"type": "registry:item",
"title": "Kybernesis Arcana",
"description": "Give an eve agent a workspace-scoped long-term memory with recall, storage, and brain notes.",
- "dependencies": [
- "@kybernesis/arcana"
- ],
+ "dependencies": ["@kybernesis/arcana"],
"envVars": {
"ARCANA_API_KEY": "",
"ARCANA_WORKSPACE": ""
@@ -283,9 +255,7 @@
"type": "registry:item",
"title": "Hindsight",
"description": "Recall relevant context before every turn and retain each exchange automatically.",
- "dependencies": [
- "@vectorize-io/hindsight-eve"
- ],
+ "dependencies": ["@vectorize-io/hindsight-eve"],
"envVars": {
"HINDSIGHT_API_KEY": "",
"HINDSIGHT_API_URL": "",
@@ -344,9 +314,7 @@
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/vercel.ts",
@@ -366,20 +334,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "linear",
- "mcp.linear.app",
- "linear"
- ]
+ "args": ["integration", "connect", "linear", "mcp.linear.app", "linear"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/linear.ts",
@@ -399,20 +359,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "notion",
- "mcp.notion.com",
- "notion"
- ]
+ "args": ["integration", "connect", "notion", "mcp.notion.com", "notion"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/notion.ts",
@@ -432,20 +384,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "datadog",
- "mcp.datadoghq.com",
- "datadog"
- ]
+ "args": ["integration", "connect", "datadog", "mcp.datadoghq.com", "datadog"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/datadog.ts",
@@ -465,20 +409,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "honeycomb",
- "mcp.honeycomb.io",
- "honeycomb"
- ]
+ "args": ["integration", "connect", "honeycomb", "mcp.honeycomb.io", "honeycomb"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/honeycomb.ts",
@@ -513,12 +449,8 @@
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
- "devDependencies": [
- "vercel@>=58.7.0"
- ],
+ "dependencies": ["@vercel/connect"],
+ "devDependencies": ["vercel@>=58.7.0"],
"files": [
{
"path": "registry/connections/agentcard.ts",
@@ -538,20 +470,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "airtable",
- "airtable",
- "airtable"
- ]
+ "args": ["integration", "connect", "airtable", "airtable", "airtable"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/airtable.ts",
@@ -571,20 +495,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "bitly",
- "bitly",
- "bitly"
- ]
+ "args": ["integration", "connect", "bitly", "bitly", "bitly"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/bitly.ts",
@@ -604,20 +520,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "brex",
- "brex",
- "brex"
- ]
+ "args": ["integration", "connect", "brex", "brex", "brex"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/brex.ts",
@@ -637,20 +545,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "candid",
- "candid",
- "candid"
- ]
+ "args": ["integration", "connect", "candid", "candid", "candid"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/candid.ts",
@@ -670,20 +570,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "clickhouse",
- "clickhouse",
- "clickhouse"
- ]
+ "args": ["integration", "connect", "clickhouse", "clickhouse", "clickhouse"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/clickhouse.ts",
@@ -703,20 +595,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "cloudinary",
- "cloudinary",
- "cloudinary"
- ]
+ "args": ["integration", "connect", "cloudinary", "cloudinary", "cloudinary"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/cloudinary.ts",
@@ -736,20 +620,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "coda",
- "coda",
- "coda"
- ]
+ "args": ["integration", "connect", "coda", "coda", "coda"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/coda.ts",
@@ -769,20 +645,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "context",
- "mcp.context.dev",
- "context"
- ]
+ "args": ["integration", "connect", "context", "mcp.context.dev", "context"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/context.ts",
@@ -802,20 +670,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "egnyte",
- "egnyte",
- "egnyte"
- ]
+ "args": ["integration", "connect", "egnyte", "egnyte", "egnyte"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/egnyte.ts",
@@ -835,20 +695,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "embat",
- "embat",
- "embat"
- ]
+ "args": ["integration", "connect", "embat", "embat", "embat"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/embat.ts",
@@ -868,20 +720,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "hugging-face",
- "hugging-face",
- "hugging-face"
- ]
+ "args": ["integration", "connect", "hugging-face", "hugging-face", "hugging-face"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/hugging-face.ts",
@@ -901,20 +745,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "local-falcon",
- "local-falcon",
- "local-falcon"
- ]
+ "args": ["integration", "connect", "local-falcon", "local-falcon", "local-falcon"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/local-falcon.ts",
@@ -934,20 +770,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "make",
- "make",
- "make"
- ]
+ "args": ["integration", "connect", "make", "make", "make"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/make.ts",
@@ -967,20 +795,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "manufact",
- "manufact",
- "manufact"
- ]
+ "args": ["integration", "connect", "manufact", "manufact", "manufact"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/manufact.ts",
@@ -1000,20 +820,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "mem0",
- "mem0",
- "mem0"
- ]
+ "args": ["integration", "connect", "mem0", "mem0", "mem0"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/mem0.ts",
@@ -1033,20 +845,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "miro",
- "miro",
- "miro"
- ]
+ "args": ["integration", "connect", "miro", "miro", "miro"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/miro.ts",
@@ -1066,20 +870,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "mixpanel",
- "mixpanel",
- "mixpanel"
- ]
+ "args": ["integration", "connect", "mixpanel", "mixpanel", "mixpanel"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/mixpanel.ts",
@@ -1099,20 +895,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "natural",
- "mcp.natural.com",
- "natural"
- ]
+ "args": ["integration", "connect", "natural", "mcp.natural.com", "natural"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/natural.ts",
@@ -1132,22 +920,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "neon",
- "neon",
- "neon",
- "--principal-type",
- "app"
- ]
+ "args": ["integration", "connect", "neon", "neon", "neon", "--principal-type", "app"]
},
"requires": ">=0.48.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/neon.ts",
@@ -1167,20 +945,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "netlify",
- "netlify",
- "netlify"
- ]
+ "args": ["integration", "connect", "netlify", "netlify", "netlify"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/netlify.ts",
@@ -1200,20 +970,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "oreilly",
- "oreilly",
- "oreilly"
- ]
+ "args": ["integration", "connect", "oreilly", "oreilly", "oreilly"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/oreilly.ts",
@@ -1233,20 +995,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "planetscale",
- "planetscale",
- "planetscale"
- ]
+ "args": ["integration", "connect", "planetscale", "planetscale", "planetscale"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/planetscale.ts",
@@ -1266,20 +1020,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "posthog",
- "posthog",
- "posthog"
- ]
+ "args": ["integration", "connect", "posthog", "posthog", "posthog"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/posthog.ts",
@@ -1299,20 +1045,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "postman",
- "postman",
- "postman"
- ]
+ "args": ["integration", "connect", "postman", "postman", "postman"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/postman.ts",
@@ -1332,20 +1070,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "razorpay",
- "razorpay",
- "razorpay"
- ]
+ "args": ["integration", "connect", "razorpay", "razorpay", "razorpay"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/razorpay.ts",
@@ -1365,20 +1095,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "sentry",
- "sentry",
- "sentry"
- ]
+ "args": ["integration", "connect", "sentry", "sentry", "sentry"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/sentry.ts",
@@ -1398,20 +1120,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "similarweb",
- "similarweb",
- "similarweb"
- ]
+ "args": ["integration", "connect", "similarweb", "similarweb", "similarweb"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/similarweb.ts",
@@ -1431,11 +1145,7 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "shopify"
- ]
+ "args": ["integration", "setup", "shopify"]
},
"requires": ">=0.46.1"
}
@@ -1459,20 +1169,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "stripe",
- "stripe",
- "stripe"
- ]
+ "args": ["integration", "connect", "stripe", "stripe", "stripe"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/stripe.ts",
@@ -1492,20 +1194,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "supabase",
- "supabase",
- "supabase"
- ]
+ "args": ["integration", "connect", "supabase", "supabase", "supabase"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/supabase.ts",
@@ -1525,20 +1219,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "ticket-tailor",
- "ticket-tailor",
- "ticket-tailor"
- ]
+ "args": ["integration", "connect", "ticket-tailor", "ticket-tailor", "ticket-tailor"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/ticket-tailor.ts",
@@ -1558,20 +1244,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "ticktick",
- "ticktick",
- "ticktick"
- ]
+ "args": ["integration", "connect", "ticktick", "ticktick", "ticktick"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/ticktick.ts",
@@ -1604,9 +1282,7 @@
"requires": ">=0.48.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/tinybird.ts",
@@ -1626,20 +1302,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "todoist",
- "todoist",
- "todoist"
- ]
+ "args": ["integration", "connect", "todoist", "todoist", "todoist"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/todoist.ts",
@@ -1659,20 +1327,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "webflow",
- "webflow",
- "webflow"
- ]
+ "args": ["integration", "connect", "webflow", "webflow", "webflow"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/webflow.ts",
@@ -1692,20 +1352,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "wix",
- "wix",
- "wix"
- ]
+ "args": ["integration", "connect", "wix", "wix", "wix"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/wix.ts",
@@ -1725,20 +1377,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "zapier",
- "zapier",
- "zapier"
- ]
+ "args": ["integration", "connect", "zapier", "zapier", "zapier"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/zapier.ts",
@@ -1758,20 +1402,12 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "connect",
- "zomato",
- "zomato",
- "zomato"
- ]
+ "args": ["integration", "connect", "zomato", "zomato", "zomato"]
},
"requires": ">=0.29.0"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
+ "dependencies": ["@vercel/connect"],
"files": [
{
"path": "registry/connections/zomato.ts",
@@ -1791,40 +1427,28 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "slack"
- ]
+ "args": ["integration", "setup", "slack"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/slack",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect@>=0.4.2"
- ]
+ "dependencies": ["@vercel/connect@>=0.4.2"]
},
{
"name": "channel/discord",
"type": "registry:item",
"title": "Discord",
"description": "Connect an eve agent to Discord with guided connector and slash-command setup.",
- "dependencies": [
- "@vercel/connect@>=0.6.0"
- ],
+ "dependencies": ["@vercel/connect@>=0.6.0"],
"meta": {
"eve": {
"setup": {
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "discord"
- ]
+ "args": ["integration", "setup", "discord"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/discord",
@@ -1905,9 +1529,7 @@
"type": "registry:item",
"title": "Blooio",
"description": "Send and receive iMessage, RCS, and SMS through Blooio, with reactions, typing indicators, read receipts, polls, groups, capability checks, and history.",
- "dependencies": [
- "eve-channel-blooio"
- ],
+ "dependencies": ["eve-channel-blooio"],
"envVars": {
"BLOOIO_API_KEY": "",
"BLOOIO_WEBHOOK_SECRET": ""
@@ -1937,23 +1559,15 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "github"
- ]
+ "args": ["integration", "setup", "github"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/github",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect@>=0.6.0"
- ],
- "devDependencies": [
- "vercel@>=58.5.1"
- ]
+ "dependencies": ["@vercel/connect@>=0.6.0"],
+ "devDependencies": ["vercel@>=58.5.1"]
},
{
"name": "channel/linear-agent",
@@ -1966,23 +1580,15 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "linear"
- ]
+ "args": ["integration", "setup", "linear"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/linear",
"implementation": "native"
}
},
- "dependencies": [
- "@vercel/connect"
- ],
- "devDependencies": [
- "vercel@>=58.5.1"
- ]
+ "dependencies": ["@vercel/connect"],
+ "devDependencies": ["vercel@>=58.5.1"]
},
{
"name": "channel/web",
@@ -1995,11 +1601,7 @@
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "web"
- ]
+ "args": ["integration", "setup", "web"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/eve",
@@ -2247,11 +1849,7 @@
"type": "registry:item",
"title": "Google Chat",
"description": "Google Chat spaces and DMs via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/gchat",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/gchat", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-gchat.ts",
@@ -2274,11 +1872,7 @@
"type": "registry:item",
"title": "WhatsApp",
"description": "Customer messaging through WhatsApp Business Cloud via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/whatsapp",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/whatsapp", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-whatsapp.ts",
@@ -2304,11 +1898,7 @@
"type": "registry:item",
"title": "X",
"description": "Public mentions and DMs on X via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/x",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/x", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-x.ts",
@@ -2332,11 +1922,7 @@
"type": "registry:item",
"title": "Messenger",
"description": "Facebook Messenger bots with templates, buttons, and reactions via the Chat SDK.",
- "dependencies": [
- "chat",
- "@chat-adapter/messenger",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@chat-adapter/messenger", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-messenger.ts",
@@ -2361,11 +1947,7 @@
"type": "registry:item",
"title": "Zernio",
"description": "Reach seven social and messaging platforms through one Zernio integration.",
- "dependencies": [
- "chat",
- "@zernio/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@zernio/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"ZERNIO_API_KEY": "",
"ZERNIO_WEBHOOK_SECRET": ""
@@ -2389,11 +1971,7 @@
"type": "registry:item",
"title": "Velt",
"description": "Add agents to anchored comments across documents, canvases, PDFs, and video.",
- "dependencies": [
- "chat",
- "@veltdev/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@veltdev/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"VELT_API_KEY": "",
"VELT_WEBHOOK_SECRET": ""
@@ -2417,11 +1995,7 @@
"type": "registry:item",
"title": "Sendblue",
"description": "Send and receive iMessage, SMS, and RCS through Sendblue.",
- "dependencies": [
- "chat",
- "chat-adapter-sendblue",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "chat-adapter-sendblue", "@chat-adapter/state-memory"],
"envVars": {
"SENDBLUE_API_KEY": "",
"SENDBLUE_API_SECRET": "",
@@ -2446,11 +2020,7 @@
"type": "registry:item",
"title": "Novu",
"description": "Reach Slack, Teams, WhatsApp, Telegram, and email through Novu.",
- "dependencies": [
- "chat",
- "@novu/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@novu/chat-sdk-adapter", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-novu.ts",
@@ -2474,11 +2044,7 @@
"type": "registry:item",
"title": "Liveblocks",
"description": "Bring your agent into Liveblocks comment threads, mentions, and reactions.",
- "dependencies": [
- "chat",
- "@liveblocks/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@liveblocks/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"LIVEBLOCKS_SECRET_KEY": "",
"LIVEBLOCKS_WEBHOOK_SECRET": ""
@@ -2502,23 +2068,15 @@
"type": "registry:item",
"title": "Linq",
"description": "Connect an eve agent to iMessage and SMS through Linq with guided Connect or portable setup.",
- "dependencies": [
- "@vercel/connect@>=0.9.0"
- ],
- "devDependencies": [
- "vercel@>=58.5.1"
- ],
+ "dependencies": ["@vercel/connect@>=0.9.0"],
+ "devDependencies": ["vercel@>=58.5.1"],
"meta": {
"eve": {
"setup": {
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "linq"
- ]
+ "args": ["integration", "setup", "linq"]
},
"requires": ">=0.41.0",
"docs": "/docs/channels/linq",
@@ -2531,11 +2089,7 @@
"type": "registry:item",
"title": "Kapso",
"description": "Managed WhatsApp conversations, media, buttons, and history through Kapso.",
- "dependencies": [
- "chat",
- "@kapso/chat-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@kapso/chat-adapter", "@chat-adapter/state-memory"],
"envVars": {
"KAPSO_API_KEY": "",
"KAPSO_PHONE_NUMBER_ID": "",
@@ -2560,20 +2114,14 @@
"type": "registry:item",
"title": "Photon iMessage",
"description": "Connect an eve agent to iMessage through Photon with guided project and phone setup.",
- "dependencies": [
- "@vercel/connect@>=0.5.0"
- ],
+ "dependencies": ["@vercel/connect@>=0.5.0"],
"meta": {
"eve": {
"setup": {
"command": "eve",
"package": "eve",
"bin": "eve",
- "args": [
- "integration",
- "setup",
- "photon"
- ]
+ "args": ["integration", "setup", "photon"]
},
"requires": ">=0.33.0",
"docs": "/docs/channels/photon",
@@ -2586,11 +2134,7 @@
"type": "registry:item",
"title": "Dial",
"description": "Give your agent a phone number for SMS, MMS, iMessage, and voice transcripts.",
- "dependencies": [
- "chat",
- "@getdial/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@getdial/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"DIAL_API_KEY": "",
"DIAL_FROM_NUMBER_ID": "",
@@ -2615,11 +2159,7 @@
"type": "registry:item",
"title": "AgentPhone",
"description": "SMS, MMS, iMessage, and voice conversations through AgentPhone.",
- "dependencies": [
- "chat",
- "@agentphone/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@agentphone/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"AGENTPHONE_API_KEY": "",
"AGENTPHONE_AGENT_ID": "",
@@ -2644,11 +2184,7 @@
"type": "registry:item",
"title": "Lark / Feishu",
"description": "Lark and Feishu chats with native card streaming via the Chat SDK.",
- "dependencies": [
- "chat",
- "@larksuite/vercel-chat-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@larksuite/vercel-chat-adapter", "@chat-adapter/state-memory"],
"envVars": {
"LARK_APP_ID": "",
"LARK_APP_SECRET": ""
@@ -2672,11 +2208,7 @@
"type": "registry:item",
"title": "Beeper",
"description": "Matrix rooms and bridged messaging networks through Beeper.",
- "dependencies": [
- "chat",
- "@beeper/chat-adapter-matrix",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@beeper/chat-adapter-matrix", "@chat-adapter/state-memory"],
"files": [
{
"path": "registry/channels/chat-sdk-beeper.ts",
@@ -2700,11 +2232,7 @@
"type": "registry:item",
"title": "Resend",
"description": "Send and receive threaded email through Resend via the Chat SDK.",
- "dependencies": [
- "chat",
- "@resend/chat-sdk-adapter",
- "@chat-adapter/state-memory"
- ],
+ "dependencies": ["chat", "@resend/chat-sdk-adapter", "@chat-adapter/state-memory"],
"envVars": {
"RESEND_API_KEY": "",
"RESEND_WEBHOOK_SECRET": "",
@@ -2729,9 +2257,7 @@
"type": "registry:item",
"title": "Braintrust",
"description": "Trace eve agent sessions in Braintrust, including turns, steps, tool calls, and subagent interactions.",
- "dependencies": [
- "braintrust"
- ],
+ "dependencies": ["braintrust"],
"envVars": {
"BRAINTRUST_API_KEY": ""
},
@@ -2777,9 +2303,7 @@
"type": "registry:item",
"title": "Sentry",
"description": "Send agent traces to Sentry's OTLP endpoint for tracing and debugging.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"SENTRY_OTLP_TRACES_ENDPOINT": "",
"SENTRY_PUBLIC_KEY": ""
@@ -2797,9 +2321,7 @@
"type": "registry:item",
"title": "Datadog",
"description": "Export agent traces to Datadog APM alongside the rest of your stack.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"DATADOG_OTLP_TRACES_ENDPOINT": "",
"DD_API_KEY": ""
@@ -2817,9 +2339,7 @@
"type": "registry:item",
"title": "Honeycomb",
"description": "Send OpenTelemetry traces to Honeycomb and query every agent turn.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"HONEYCOMB_API_KEY": ""
},
@@ -2836,9 +2356,7 @@
"type": "registry:item",
"title": "Arize",
"description": "Export traces to Arize AX for LLM observability and evaluation.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"ARIZE_SPACE_ID": "",
"ARIZE_API_KEY": ""
@@ -2856,9 +2374,7 @@
"type": "registry:item",
"title": "Raindrop",
"description": "Send agent traces to Raindrop to detect and debug AI product issues.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"envVars": {
"RAINDROP_WRITE_KEY": ""
},
@@ -2875,9 +2391,7 @@
"type": "registry:item",
"title": "Jaeger",
"description": "Trace your agent with a local or self-hosted Jaeger OTLP backend.",
- "dependencies": [
- "@vercel/otel"
- ],
+ "dependencies": ["@vercel/otel"],
"files": [
{
"path": "registry/instrumentation/jaeger.ts",
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index 3c3360163..d7a9ca435 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -1,6 +1,6 @@
---
title: "Built-in Tools"
-description: "The default and opt-in tools eve provides, including Workflow, glob, grep, and sleep."
+description: "The default and opt-in tools eve provides, including glob, grep, and sleep."
---
eve provides a default tool set for every agent and additional tools you can add with one file. Each default occupies the same `agent/tools/<name>.ts` slot you would author yourself, so an authored definition replaces it and `disableTool()` removes it. Use this page to review what the model can call, opt into more capabilities, or override and disable defaults. For custom tools, see [Tools](../tools).
@@ -28,7 +28,7 @@ The model-facing file tools accept absolute paths and paths beginning with `$HOM
Notes:
-- **`agent`** is available only in the root session. Its child uses the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and fresh [state](./state). The child receives neither `agent` nor `Workflow`; declared subagents do not receive the built-in `agent` either. See [Subagents](../subagents).
+- **`agent`** is available only in the root session and always runs in the background. Its call returns a task receipt immediately, and task notifications deliver updates or the final result. The child uses the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and fresh [state](./state). The child receives neither `agent` nor `Workflow`; declared subagents do not receive the built-in `agent` either. See [Subagents](../subagents).
- **`load_skill`** only pulls instructions into context. It adds no new execution surface, because behavior still comes from the tools the agent already has.
- **`connection_search`** surfaces a connection's tools by their qualified name (e.g. `linear__list_issues`), which the model can then call directly. The model sees it only when the agent has connections.
- **`web_search`** has no local executor; the provider runs it. AI Gateway models use Exa by default. To use Parallel instead, export `webSearch({ provider: "parallel" })` from `agent/tools/web_search.ts`. Direct provider models continue to use their native search implementation. To supply your own implementation, override it with `defineTool()`.
@@ -40,12 +40,11 @@ Review these default tools before production use. Disable, wrap, restrict, or re
Some framework-provided tools stay out of the default set. Add the corresponding file when your agent needs one:
-| Tool | Definition to export | Purpose |
-| ---------- | --------------------------------------------------- | -------------------------------------------------- |
-| `glob` | `glob` from `eve/tools/glob` | Find sandbox files by glob pattern. |
-| `grep` | `grep` from `eve/tools/grep` | Search sandbox file contents by regex. |
-| `Workflow` | `experimental_workflow()` from `eve/tools/workflow` | Orchestrate root-agent copies from generated code. |
-| `sleep` | `sleep()` from `eve/tools/sleep` | Pause and durably resume the current turn. |
+| Tool | Definition to export | Purpose |
+| ------- | -------------------------------- | ------------------------------------------ |
+| `glob` | `glob` from `eve/tools/glob` | Find sandbox files by glob pattern. |
+| `grep` | `grep` from `eve/tools/grep` | Search sandbox file contents by regex. |
+| `sleep` | `sleep()` from `eve/tools/sleep` | Pause and durably resume the current turn. |
For example, add file discovery and content search with two files:
@@ -59,7 +58,7 @@ export { grep as default } from "eve/tools/grep";
The filename supplies the model-facing tool name. The tools run against the agent's sandbox and use the same schemas, results, and error behavior as eve's framework implementations. Wrap either definition with `defineTool({ ...glob, description: "..." })` or `defineTool({ ...grep, description: "..." })` when you need to change its description or approval policy.
-The sections below cover `Workflow` and `sleep` in more detail.
+The section below covers `sleep` in more detail.
## Override a default
@@ -125,86 +124,6 @@ Three moves shape the harness. The right one depends on whether the model should
- **Disable** when the model should not have the capability at all. A `disableTool()` sentinel removes the built-in, and the model never sees it. Reach for this to lock down `bash` or `web_fetch` in an agent that should not run shell commands or fetch arbitrary URLs.
- **Author a new tool** when you want a capability the harness does not ship. Give it a fresh slug under `agent/tools/` and it joins the built-ins instead of replacing one. See [Tools](../tools) for the authoring model.
-## Workflow tool
-
-The opt-in experimental `Workflow` tool lets the model write JavaScript that coordinates the agent's own subagents as a single durable step. The program can run them in sequence, feed one result into the next, fan out over a list, and combine the results. You enable the capability and the model decides and runs the orchestration.
-
-A single turn can already call several subagents, and parallel tool calls dispatch concurrently. What a workflow adds is _programmatic_ coordination. The program decides how many subagents to run based on an earlier result, which output feeds which call, and how to combine everything. That is logic the model cannot express as a few one-off calls.
-
-`Workflow` is a model-facing tool, not an API for authored tools, hooks, or application code. Authored code cannot submit a Workflow program or use `Workflow` to start an arbitrary user-authored Vercel Workflow. Use the [client SDK](../guides/client/overview) when application code needs to start or continue an eve session; use ordinary application APIs for other deterministic orchestration.
-
-### Enable Workflow
-
-Export the experimental Workflow definition from `agent/tools/workflow.ts`. The helper name carries the "experimental" warning, but the tool the model actually sees is named `Workflow`.
-
-```ts title="agent/tools/workflow.ts"
-import { experimental_workflow } from "eve/tools/workflow";
-
-export default experimental_workflow();
-```
-
-Without that file, the `Workflow` tool stays off. It earns its keep only when the agent has subagents (or the built-in `agent`) worth coordinating:
-
-```ts title="agent/subagents/analyst/agent.ts"
-import { defineAgent } from "eve";
-
-export default defineAgent({
- description: "Analyzes one metric: queries, computes, writes a short finding.",
- model: "anthropic/claude-opus-4.8",
-});
-```
-
-When asked for a weekly business review, the model picks the metrics, runs one `analyst` per metric in parallel, and combines the findings. The program below is the kind of JavaScript the model authors. It fans `analyst` out over a runtime-decided list of metrics and merges the results:
-
-```js
-const metrics = ["revenue", "signups", "churn"];
-const findings = await Promise.all(
- metrics.map((metric) => tools.analyst({ message: `Summarize last week's ${metric}.` })),
-);
-return findings.join("\n\n");
-```
-
-Each `tools.analyst(...)` call dispatches a child subagent, so the parent stream records one `subagent.called` per metric and one `subagent.completed` as each finishes:
-
-```json
-{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_1", "childSessionId": "ses_a1", "sequence": 0 } }
-{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_2", "childSessionId": "ses_a2", "sequence": 1 } }
-{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_3", "childSessionId": "ses_a3", "sequence": 2 } }
-{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_1", "output": "..." } }
-{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_2", "output": "..." } }
-{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_3", "output": "..." } }
-```
-
-### What a workflow can orchestrate
-
-A workflow reaches only this agent's own agents: the built-in `agent` (a copy of itself), declared [subagents](../subagents), and [remote agents](../guides/remote-agents). That is the whole list. No files, network, shell, skills, or connections. A workflow is a coordination layer over subagents, not a place to do other work. Each call can still request structured output via `outputSchema`, exactly like a direct subagent delegation.
-
-### Caps on workflow-spawned subagents
-
-Workflow orchestration is capped in two independent ways.
-
-**Per-program call budget.** One Workflow program may dispatch at most `maxSubagents` subagent calls in total, counted across the whole program — sequential and parallel calls alike. Configure it on `experimental_workflow`; the default is 100. Calls beyond the budget do not start a child session; they resolve inside the program with a `WORKFLOW_SUBAGENT_LIMIT_REACHED` error result, and the budget is stated in the tool's description so the model sizes its fan-out to fit.
-
-```ts title="agent/tools/workflow.ts"
-import { experimental_workflow } from "eve/tools/workflow";
-
-export default experimental_workflow({ maxSubagents: 4 });
-```
-
-**Root-only orchestration.** Only the root session receives `Workflow`. Children started by a workflow receive neither `Workflow` nor the built-in `agent`, so Workflow programs cannot recurse. A declared child can still call subagents defined in its own directory (see [Subagents](../subagents)).
-
-### Where the JavaScript runs
-
-The orchestration code never touches the agent's process. The runtime hands the program text to a small isolated JavaScript engine (a QuickJS sandbox) and runs it there. Nothing from the host realm crosses in, so there is no `process`, no `globalThis` from the agent, and no `import`/`require`. The program can reach exactly two things, the agent functions bridged in as `tools.<name>` and the ordinary language built-ins.
-
-That is an allowlist, not a denylist. The sandbox cannot read files, open a socket, or see an environment variable because those are not present, not because each one is blocked in turn. When the program calls an agent function, that call bridges back out to the runtime, which dispatches it exactly like a direct delegation. The orchestration glue stays inside the sandbox.
-
-### Durability, approvals, and observability
-
-- **Durable.** The whole orchestration counts as one step. Subagents dispatched together run concurrently, and if a run parks (suspends durably without holding compute; see [Execution model and durability](./execution-model-and-durability)) on a long-running or human-gated child, it resumes where it left off after a restart.
-- **Approval-safe.** A subagent that needs human approval (HITL, human-in-the-loop) mid-run surfaces its request to the user, and the workflow picks back up once that is answered, same as direct delegation.
-- **Observable.** Every orchestrated subagent emits the usual `subagent.called` / `subagent.completed` events on the parent stream and gets its own child session and stream. The telemetry matches direct delegation, so existing dashboards and cost attribution keep working.
-
## The opt-in `sleep` tool
The framework also ships a durable `sleep` tool, but does not add it to agents by default. Enable it with `agent/tools/sleep.ts`:
@@ -222,4 +141,4 @@ The model calls it with `{ seconds }` when it is useful to wait before checking
- [Tools](../tools): define your own tools, gate them on approval, and shape their output with `toModelOutput`
- [Dynamic capabilities](../guides/dynamic-capabilities): generate the tool set per session with `defineDynamic`
- [Sandbox](../sandbox): configure the sandbox used by shell and file tools
-- [Subagents](../subagents): declare the agents that `agent` and `Workflow` can call
+- [Subagents](../subagents): declare specialists that the model can call as background tasks
diff --git a/docs/concepts/context-control.md b/docs/concepts/context-control.md
index 10c256b44..268ba8bea 100644
--- a/docs/concepts/context-control.md
+++ b/docs/concepts/context-control.md
@@ -14,7 +14,7 @@ Control context by putting information in the narrowest surface that needs it. K
| A procedure needed only for some tasks | A [skill](../skills) | Its description until the model loads the full skill |
| A typed action or external operation | A [tool](../tools) or [connection](../connections) | The callable schema and the result of each call |
| Files or command execution | The [sandbox workspace](../sandbox) | A workspace hint, then files and command output the model requests through tools |
-| A specialist with a separate prompt and capabilities | A [subagent](../subagents) | Only the subagent's final result in the parent context |
+| A specialist with a separate prompt and capabilities | A [subagent](../subagents) | A receipt followed by background task notifications |
| Instructions or capabilities that vary by caller | A [dynamic capability](../guides/dynamic-capabilities) | The values resolved for the active session |
| Scoped context retrieved from cross-session storage | [Memory](../memory) | Attributed user-role messages recalled before the current delivery |
@@ -46,7 +46,7 @@ See [Sandbox](../sandbox) for workspace seeding, runtime access, backends, and l
## Delegate to a specialist with a subagent
-Use a subagent when work needs its own instructions, tools, skills, state, or sandbox. The child runs in a separate context instead of adding its working history to the parent. The parent receives the result of the delegation.
+Use a subagent when work needs its own instructions, tools, skills, state, or sandbox. The child runs in a separate context instead of adding its working history to the parent. The call returns a task receipt, and later task notifications deliver its outcome.
See [Subagents](../subagents) for the distinction between root-agent copies and declared specialists, including their isolation boundaries.
diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdx
index 78d10d48b..5719d508a 100644
--- a/docs/concepts/execution-model-and-durability.mdx
+++ b/docs/concepts/execution-model-and-durability.mdx
@@ -64,7 +64,7 @@ You don't write workflow code directly. Workflow primitives (`start()`, `resumeH
## Parked work
-Some work has to wait, including a human approving a [tool](../tools), an interactive OAuth sign-in for a [connection](../connections), or a long-running [subagent](../subagents). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives (a click, a callback, a child completing), even if that's much later. When it does, the conversation picks up exactly where it left off.
+Some work has to wait, including a human approving a [tool](../tools) or an interactive OAuth sign-in for a [connection](../connections). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives, even if that's much later. When it does, the conversation picks up exactly where it left off. Background tools and subagents return a task receipt instead, so the turn continues and later task notifications deliver progress or the outcome.
## Message delivery and steering
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index e35451dbe..92de64737 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -58,7 +58,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:
| `input.requested` | The run paused for human input ([HITL](/docs/human-in-the-loop) approval or `ask_question`); carries `requests`. |
| `input.resolved` | The server accepted terminal human-input outcomes; carries `resolutions` with responses when provided. |
| `subagent.called` | A subagent was delegated; carries `childSessionId` to attach to. |
-| `subagent.completed` | A delegated subagent finished. |
+| `subagent.completed` | A background subagent was admitted and returned its task receipt. |
| `reasoning.appended` | A reasoning text delta. |
| `reasoning.completed` | The finalized reasoning block. |
| `message.appended` | An assistant text delta. |
@@ -95,7 +95,7 @@ Note: consider the privacy, confidentiality, and user-experience implications fo
`message.completed` can fire more than once in a turn: the agent often emits interim assistant text before a tool call. To tell tool-call narration from a terminal reply, check `message.completed.data.finishReason`. `step.completed.data.finishReason` mirrors the step outcome, and usage lives on `step.completed`.
-A delegated subagent publishes progress on its own child-session stream. The parent only emits `subagent.called` with a `childSessionId`, which a client uses to attach.
+A delegated subagent publishes progress on its own child-session stream. The parent emits `subagent.called` with a `childSessionId`, which a client uses to attach. `subagent.completed` carries a working task receipt after admission; later updates and outcomes arrive as task-triggered `message.received` notifications.
`step.failed` and `turn.failed` carry `{ code, message, details? }` for the failed fragment or turn, and `session.failed` is the terminal session-level variant. `turn.cancelled` is not a failure: the cancelled turn ends without any failure event, `session.waiting` follows, and the session accepts the next message normally. Whatever the turn streamed before cancellation stays on the stream. Durable history keeps the accepted user input and previously settled work, but discards incomplete assistant output and unfinished tool state. When a turn requested an output schema, the finalized payload lands on `result.completed` as `data.result` before the turn boundary. `authorization.required` carries the sign-in challenge (`data.authorization` may include `url`, `userCode`, `expiresAt`, `instructions`), and `authorization.completed` carries `data.outcome` (`"authorized" | "declined" | "failed" | "timed-out"`).
@@ -191,7 +191,7 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel
# {"ok":true,"sessionId":"<sessionId>","status":"accepted"}
```
-`"accepted"` means the live session durably queued the request. Confirm an actual cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. If the turn is waiting on active local or remote subagents, eve also requests cancellation of every adopted child, recursively, before settling the parent. Each child reports its own cancellation boundary on its child-session stream; the parent does not emit `subagent.completed` for cancelled work. A live but already-parked session also returns `"accepted"` and consumes the command as a no-op. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.
+`"accepted"` means the live session durably queued the request. Confirm an actual cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. Background tasks that were already admitted survive initiating-turn cancellation and are stopped with `task_cancel`; background work that has not yet been admitted is rejected with the cancelled step. Each cancelled child reports its own boundary on its child-session stream. A live but already-parked session also returns `"accepted"` and consumes the command as a no-op. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.
The HTTP route returns `202` for `"accepted"` and `200` for
`"no_active_turn"`. Only the accepted result includes `sessionId`.
diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.md
index 8c601b3c0..fe21376b7 100644
--- a/docs/guides/dynamic-capabilities.md
+++ b/docs/guides/dynamic-capabilities.md
@@ -124,8 +124,8 @@ shadows the session selection for that turn, including when the turn handler
returns `null`. If a resolver throws or returns an invalid definition, eve logs the
failure and omits the subagent.
-The resolved set applies to local and remote direct delegation and the
-`Workflow` tool. eve
+The resolved set applies to local and remote direct delegation. Background subagents are not
+exposed inside the model-authored `Workflow` tool. eve
also checks availability again before starting the child, so a stale or
manually constructed call fails with `SUBAGENT_UNAVAILABLE`. Treat conditional
availability as capability composition, not as the only authorization
diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdx
index fcfe5a892..d1816eb5d 100644
--- a/docs/guides/frontend/overview.mdx
+++ b/docs/guides/frontend/overview.mdx
@@ -87,7 +87,7 @@ Most chat UIs only need `data.messages` and `status`. Drop down to `events` when
`data.messages` are eve-owned `EveMessage[]`. Common text, reasoning, file, and dynamic-tool parts follow the [AI SDK `UIMessage`](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message) rendering convention, but the types are not interchangeable. eve also exposes authorization and HITL metadata, and a file part's URL can be absent. Adapt those parts before passing messages to an API typed as `UIMessage[]`.
-When the root agent delegates, its stream emits `subagent.called` with the child's `childSessionId`, then `subagent.completed` when the child returns. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. Use the lower-level [TypeScript client](../client/overview#sessions) to attach to that ID when your UI needs live subagent activity. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.
+When the root agent delegates, its stream emits `subagent.called` with the child's `childSessionId`, then `subagent.completed` after admission with a working task receipt. Later task notifications wake the parent with updates or the final result. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. Use the lower-level [TypeScript client](../client/overview#sessions) to attach to that ID when your UI needs live subagent activity. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.
## Sending and streaming
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 3cb016be7..603aaf757 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -1,6 +1,6 @@
---
title: "Remote Agents"
-description: "Call another eve deployment as a subagent with defineRemoteAgent: same tool call as a local subagent, outbound auth, durable callback dispatch."
+description: "Call another eve deployment as a subagent with defineRemoteAgent: the same tool call as a local subagent, with outbound auth and durable callbacks."
---
`defineRemoteAgent` calls a separately deployed eve agent as if it were a local subagent. Reach for it when the specialist you delegate to is a separately owned agent behind its own URL rather than a directory in your repo.
@@ -33,7 +33,7 @@ export default defineRemoteAgent({
## Dynamic remote agents
Wrap the file in `defineDynamic` when the target or its availability depends on
-the current session. Return `defineRemoteAgent(...)` to expose it and nil to
+the current session. Return `defineRemoteAgent(...)` to expose it and `null` to
omit it:
```ts title="agent/subagents/weather.ts"
@@ -82,7 +82,7 @@ The function may be async and must return a non-empty string. `auth` and `header
To the model, a remote agent is another subagent tool. You call it the same way you call a local subagent, with a `message` and an optional `outputSchema`. The message must carry the full task, including any context the remote agent needs, because it never receives the parent's conversation history.
-To require structured output, set an `outputSchema` on the agent definition for fresh delegations or on an individual call for that turn. The structured value becomes the tool result, and the remote child remains available for follow-up messages. See [Subagents](../subagents) for continuation behavior.
+To require structured output, set an `outputSchema` on the agent definition for fresh delegations or on an individual call for that turn. The structured value arrives in the task's completion notification, and the remote child remains available for follow-up messages. See [Subagents](../subagents) for continuation behavior.
## Outbound auth
@@ -170,22 +170,21 @@ Missing, malformed, duplicate, unsampled, untrusted, and mixed-version assertion
## How remote dispatch and callbacks work
-A local subagent runs inline. A remote one runs in its own deployment, so dispatch is asynchronous:
+A remote subagent runs as a durable background task in its own deployment:
1. The parent starts a persistent conversation session on the remote's `POST /eve/v1/session`, passing a framework callback URL.
-2. The parent turn parks (suspends durably without holding compute; see [Execution model & durability](../concepts/execution-model-and-durability)) until the remote posts a terminal callback.
-3. When the callback arrives, the parent resumes and surfaces the result.
+2. The call returns `{ status: "working", taskId, agentId }` after the remote accepts the child.
+3. The callback later settles the task and sends a task notification to the parent.
The parent stream carries the same `subagent.called`, `action.result`, and `subagent.completed` events as local delegation. For a remote call, `subagent.called.data.remote.url` records the target.
-Cancelling the parent while a remote call is active sends an authenticated `POST /eve/v1/session/:childSessionId/cancel` to the remote and waits for that request to be accepted before the parent settles. eve resolves the remote's `headers` and `auth` again for every cancellation attempt, so rotating credentials work the same way as they do for session creation. Cancellation always uses the standard eve cancel path on `url`, even when `path` customizes only the create-session endpoint. The remote child reports `turn.cancelled` → `session.waiting` on its own stream; an older or unreachable remote is logged but cannot turn the parent's cancellation into a failure.
+An admitted task survives cancellation of the turn that started it; background work that has not yet been admitted is rejected with the cancelled step. Use `task_cancel` to stop an admitted task. eve resolves the remote's `headers` and `auth` again for every cancellation attempt, so rotating credentials work the same way as they do for session creation. Cancellation always uses the standard eve cancel path on `url`, even when `path` customizes only the create-session endpoint. The remote child reports `turn.cancelled` → `session.waiting` on its own stream; an older or unreachable remote is logged but cannot turn the parent's cancellation into a failure.
When the parent session ends, eve sends an authenticated `POST /eve/v1/session/:childSessionId/reset` for each remote child. Reset retires the parked remote session and recursively cleans up its descendants. The request uses freshly resolved `headers` and `auth`; failures are logged so an unreachable remote cannot block parent finalization.
-Both failure paths surface to the parent as a failed tool result, so the caller can explain or recover within the same session. A failed _start_ returns the error inline. A remote that starts and then fails posts a terminal failure callback, which the parent receives as an errored subagent result carrying the remote's error (or `REMOTE_AGENT_FAILED` when none is supplied). Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than marking the task complete, so the engine retries it.
+A failed _start_ rejects admission before a task receipt is returned. After a remote starts, a terminal failure callback fails the task and notifies the parent with the remote's error (or `REMOTE_AGENT_FAILED` when none is supplied). Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than marking the task complete, so the engine retries it.
## What to read next
- Local delegation and the isolation boundary → [Subagents](../subagents)
-- Have the model orchestrate remote agents programmatically → [Workflow tool](../concepts/built-in-tools#workflow-tool)
- Securing the receiving deployment → [Auth & route protection](./auth-and-route-protection)
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index 1ce7a710a..b2c1ec191 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -17,7 +17,7 @@ The root session receives `agent` by default. The model calls it to delegate a t
}
```
-The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent` and `Workflow`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. To run independent tasks in parallel, emit multiple `agent` calls in one response; eve runs the batch concurrently and returns every result before the root continues. Give parallel children non-overlapping write scopes.
+The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent` and `Workflow`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. The built-in `agent` always runs in the background and needs no configuration: each call returns `{ status: "working", taskId, agentId }`, then task notifications wake the parent with updates or the final result. Give parallel children non-overlapping write scopes.
`agent` is intentionally root-only. Copies created by it cannot call `agent`, and declared subagents never receive the built-in tool. If a stale or forced recursive call reaches execution, eve rejects it instead of starting another child session.
@@ -46,7 +46,9 @@ export default defineAgent({
});
```
-`description` is required. The parent reads it to decide whether to delegate, so the compiler rejects any subagent whose `agent.ts` leaves it out.
+`description` is required. The parent reads it to decide whether to delegate, so the compiler rejects any subagent whose `agent.ts` leaves it out. Every declared local or remote subagent runs as a durable background task: the call returns `{ status: "working", taskId, agentId }` immediately, then task notifications wake the parent with updates, completion, failure, or cancellation. Human input requests surface separately on the parent session.
+
+A child running as a background task receives the framework `task_update` tool. It uses `task_update` to report progress to its parent. `task_cancel` is available to sessions that own background tasks, including a child that starts nested background work.
A mounted extension can also contribute declared subagents from `extension/subagents/`. The mount namespace prefixes the subagent visible to the consuming agent node: mounting an extension as `crm` exposes its `reviewer` subagent as `crm__reviewer`. The contributed subagent keeps its own isolated tools, connections, skills, hooks, instructions, sandbox, and nested subagents, and its modules can read configuration from the extension handle. See [Extensions](./extensions#add-a-subagent) for the authoring and override behavior.
@@ -54,7 +56,7 @@ A mounted extension can also contribute declared subagents from `extension/subag
To expose a declared subagent only for certain sessions or turns, export
`defineDynamic` from that subagent's `agent.ts`. Return a `defineAgent`
-configuration to expose the subagent, or nil to omit it from the parent's tools.
+configuration to expose the subagent, or `null` to omit it from the parent's tools.
```ts title="agent/subagents/researcher/agent.ts"
import { defineAgent, defineDynamic } from "eve";
@@ -73,9 +75,9 @@ export default defineDynamic({
```
Resolvers run at `session.started` or `turn.started`; `step.started` is not
-supported for subagents. A nil result (`null` or `undefined`) removes the
+supported for subagents. A nullish result (`null` or `undefined`) removes the
subagent's description and tool definition from the model-visible surface.
-The subagent's filesystem manifest is always compiled; a non-nil result injects
+The subagent's filesystem manifest is always compiled; a non-nullish result injects
the returned agent configuration when the child runs.
Packaging controls must be available before the resolver runs. Put them on
@@ -151,7 +153,7 @@ eve lowers every subagent visible to the current agent (the root built-in copy,
Declared subagents can call nested subagents defined under their own directories. eve does not apply a separate depth limit; nesting ends where the authored directory tree ends. The built-in `agent` follows the stricter root-only rule above, so `limits.maxSubagentDepth` no longer exists.
-`Workflow` is also root-only. Child sessions can still call their own declared or remote subagents, but they receive neither `Workflow` nor the built-in `agent`. The Workflow tool's `maxSubagents` option caps the number of calls made by one program (default 100); see [Workflow tool](./concepts/built-in-tools#workflow-tool).
+Child sessions can still call their own declared or remote subagents, but they receive neither `Workflow` nor the built-in `agent`. Background subagents run through the model tool loop and are not available inside a model-authored `Workflow` program.
A directly declared subagent's tool name is the bare path-derived name, with no prefix. `agent/subagents/researcher/` registers as the tool `researcher`. A subagent supplied by a mounted extension includes the mount namespace, such as `crm__reviewer`. The model, approvals, logs, and evals reference the resulting name. Its input schema is:
@@ -169,7 +171,7 @@ Do not rely on subagent delegation by itself as an approval boundary. Put sensit
Each delegated subagent spins up its own child session and stream. The parent stream carries the control-plane events `subagent.called` and `subagent.completed`, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. To follow the child's other progress, read `subagent.called.data.childSessionId` and subscribe at `GET /eve/v1/session/:childSessionId/stream`.
-Cancelling a parent turn also requests cancellation of every active child it started, recursively through nested and remote subagents. Each affected session emits its own `turn.cancelled` → `session.waiting` boundary; the cancelled parent does not synthesize tool results or emit `subagent.completed`. A child that already completed or parked has no active turn and is a benign no-op.
+A background task that was already admitted survives cancellation of the turn that started it; background work that has not yet been admitted is rejected with the cancelled step. Use `task_cancel` to stop an admitted task. Parent-session finalization cancels remaining live tasks.
Subagent model calls automatically retry classified transient provider failures, including overload errors delivered after a stream starts. eve makes at most three fresh model-call attempts, repeating only the current uncommitted call so completed earlier steps, tool results, and sandbox work remain available to the child. Other recoverable task errors fall back to Workflow's durable step retry from the last committed session snapshot. Exhausting the transient model-call attempts or the dedicated empty-response reissue returns one failed task result instead of stacking both retry budgets; terminal errors fail immediately.
@@ -188,4 +190,3 @@ Split out a subagent when the task needs a different prompt or specialist role,
## What to read next
- [Remote agents](./guides/remote-agents): call another eve deployment as a subagent.
-- [Workflow tool](./concepts/built-in-tools#workflow-tool): have the model orchestrate its subagents programmatically (fan-out, map-reduce).
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 9d1839fb0..1f89a66dc 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -56,15 +56,16 @@ history or `toModelOutput`; only the final yield does. Treat snapshots as
last-write-wins by tool call id, not append-only progress. The durable runtime
can retry a step and replay overlapping snapshots.
-### Experimental background execution
+### Background execution
`defineTool({ execution: "background" })` receives a third `task` argument. Returning a normal
value completes the durable task with that value. Returning `task.delegated({ executor, receipt })`
-returns a `working` receipt immediately while an external executor continues the task.
-The root agent must enable `experimental.tasks`; eve rejects background tools at build time otherwise.
+returns a `working` receipt immediately while an external executor continues the task. Background
+tools are a normal execution mode and need no root-agent flag.
-This contract currently supports framework-owned task executors, including local and remote
-subagents when `experimental.tasks` is enabled. After delegating, an in-process executor reports
+Built-in, declared local, and remote subagents use this background task lifecycle automatically.
+After delegating, an
+in-process executor reports
progress with `task.send({ kind: "update", message })` and the terminal result with
`task.send({ kind: "complete", data })` (or `fail` / `cancel`). `send` is not restart-safe — an
in-memory callback dies with the process — so the cross-process executor wire remains
diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdx
index fd7b62e86..89f5b24f8 100644
--- a/docs/tools/workflows.mdx
+++ b/docs/tools/workflows.mdx
@@ -12,8 +12,8 @@ value when the run ends.
Inside the tool, everything is the [Workflow SDK](https://workflow-sdk.dev): `"use workflow"`,
`"use step"`, `createHook`, `createWebhook`, `sleep`, retries, replay. eve adds `ask` from
-`eve/workflow` — a question the human on the session's channel answers — and treats each `yield` as
-a durable progress report.
+`eve/workflow` — a question the human on the session's channel answers — and `agent` for delegating
+from a workflow tool. eve treats each `yield` as a durable progress report.
## Write one
@@ -123,6 +123,25 @@ if (answer === undefined) return { deployed: false, reason: "timed out" };
Compare the [`approval`](/docs/human-in-the-loop) policy, which gates the call before `execute` runs
and can only show the model's input. Both compose: `approval` before the run, `ask` inside it.
+## Delegate work: `agent`
+
+Workflow tools can call a visible subagent and wait for its result:
+
+```ts
+import { agent } from "eve/workflow";
+
+const result = await agent(ctx, {
+ key: "security-review",
+ target: "reviewer",
+ message: "Review the deployment plan for security risks.",
+});
+```
+
+`key` is required, non-empty, and unique within the workflow run. It makes the invocation identity
+stable across replay, so use a fixed key for each logical call site. Parallel calls must use distinct
+keys. `target` is the model-visible subagent name; pass `agentId` to continue an existing child and
+`outputSchema` to require structured output.
+
## Report progress: `yield`
A workflow body may be an async generator. Each `yield` is a durable progress snapshot; the return
diff --git a/e2e/fixtures/agent-background-tools/agent/agent.ts b/e2e/fixtures/agent-background-tools/agent/agent.ts
index 8087843ac..a14bdd39b 100644
--- a/e2e/fixtures/agent-background-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-background-tools/agent/agent.ts
@@ -11,7 +11,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
const message = [...request.userMessages].reverse().find((entry) => entry.trim() !== "") ?? "";
if (request.userMessages.some((entry) => entry.includes(SCHEDULED))) {
- return respondScheduled(request, message);
+ return respondScheduled(request);
}
if (message.includes("BACKGROUND-EXPORT-START")) {
@@ -47,7 +47,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
return "BACKGROUND-EXPORT-IDLE";
}
-function respondScheduled(request: MockModelRequest, message: string): MockModelResponse | string {
+function respondScheduled(request: MockModelRequest): MockModelResponse | string {
const taskNotification = [...request.userMessages]
.reverse()
.find((entry) => /^Background task task_[a-z0-9]+/iu.test(entry));
@@ -76,10 +76,6 @@ const base = e2eAgentConfig({ mock: respond });
export default defineAgent({
...base,
- experimental: {
- ...base.experimental,
- tasks: true,
- },
// Always author the deterministic script so this fixture never depends on a
// live model; world suites already set EVE_E2E_MODEL=mock.
model: mockModel(respond),
diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.ts
index 653b3dd63..5e758ce1f 100644
--- a/e2e/fixtures/agent-cancellation/agent/agent.ts
+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts
@@ -1,20 +1,58 @@
import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
+import type { MockModelRequest, MockModelResponse } from "eve/evals";
-const base = e2eAgentConfig({
- mock: ({ lastUserMessage }) =>
- lastUserMessage?.includes("Please wait for cancellation.") === true
- ? {
- toolCalls: [
- {
- id: "wait-for-cancellation",
- input: {},
- name: "wait-for-cancellation",
- },
- ],
- }
- : `Mock reply: ${lastUserMessage ?? ""}`,
-});
+const RECOVERY_TOKEN = "CANCELLED-SUBAGENT-RECOVERED";
+
+function respond(request: MockModelRequest): MockModelResponse | string {
+ const message = request.lastUserMessage ?? "";
+ if (message.includes("Please wait for cancellation.")) {
+ return {
+ toolCalls: [{ id: "wait-for-cancellation", input: {}, name: "wait-for-cancellation" }],
+ };
+ }
+ if (message.includes("call the sleeper subagent")) {
+ return {
+ toolCalls: [
+ {
+ id: "cancel-sleeper",
+ input: {
+ js: 'return await tools["sleeper"]({ message: "Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled." });',
+ },
+ name: "Workflow",
+ },
+ ],
+ };
+ }
+ if (message.includes("[Agents] listing")) {
+ return (
+ [...request.messages].reverse().find((entry) => entry.text.startsWith("[Agents]"))?.text ??
+ "No agents listed."
+ );
+ }
+ if (message.includes(RECOVERY_TOKEN)) {
+ const result = request.toolResults.find((entry) => entry.id === "resume-sleeper");
+ if (result !== undefined) {
+ return typeof result.output === "string" ? result.output : JSON.stringify(result.output);
+ }
+ const agentId = /agentId ("[^"]+")/u.exec(message)?.[1];
+ if (agentId === undefined) throw new Error("Recovery prompt has no sleeper agent id.");
+ return {
+ toolCalls: [
+ {
+ id: "resume-sleeper",
+ input: {
+ js: `return await tools["sleeper"]({ agentId: ${agentId}, message: ${JSON.stringify(RECOVERY_TOKEN)} });`,
+ },
+ name: "Workflow",
+ },
+ ],
+ };
+ }
+ return `Mock reply: ${message}`;
+}
+
+const base = e2eAgentConfig({ mock: respond });
export default defineAgent({
...base,
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
index 60587e148..a5d86664b 100644
--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts
@@ -1,7 +1,22 @@
import { e2eSubagentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
+const RECOVERY_TOKEN = "CANCELLED-SUBAGENT-RECOVERED";
+
export default defineAgent({
- description: "Waits until its delegated turn is cancelled.",
- ...e2eSubagentConfig(),
+ description: "Waits until its delegated turn is cancelled, then supports a recovery probe.",
+ ...e2eSubagentConfig({
+ mock: ({ lastUserMessage }) =>
+ lastUserMessage?.includes(RECOVERY_TOKEN) === true
+ ? RECOVERY_TOKEN
+ : {
+ toolCalls: [
+ {
+ id: "wait-for-cancellation",
+ input: {},
+ name: "wait-for-cancellation",
+ },
+ ],
+ },
+ }),
});
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
index fc296da3c..36b10de78 100644
--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md
@@ -4,5 +4,6 @@ You are a cancellation test sleeper.
# Rules
-- Call `wait-for-cancellation` exactly once, immediately, with no preamble.
+- If the message contains `CANCELLED-SUBAGENT-RECOVERED`, do not call any tool. Reply with exactly `CANCELLED-SUBAGENT-RECOVERED`.
+- Otherwise, call `wait-for-cancellation` exactly once, immediately, with no preamble.
- Do not call any other tool.
diff --git a/e2e/fixtures/agent-cancellation/agent/tools/workflow.ts b/e2e/fixtures/agent-cancellation/agent/tools/workflow.ts
new file mode 100644
index 000000000..8dafe3e7f
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/tools/workflow.ts
@@ -0,0 +1,3 @@
+import { experimental_workflow } from "eve/tools/workflow";
+
+export default experimental_workflow();
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
index b76c970fa..b45615d94 100644
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts
@@ -1,20 +1,24 @@
import { defineEval } from "eve/evals";
import { satisfies } from "eve/evals/expect";
+const RECOVERY_TOKEN = "CANCELLED-SUBAGENT-RECOVERED";
+
export default defineEval({
- tags: ["real-model"],
- description: "Cancel a parent turn and cascade cancellation to its local sleeper subagent.",
+ description:
+ "Cancel a parent turn, cascade cancellation to its local sleeper subagent, then resume that child.",
timeoutMs: 240_000,
async test(t) {
// Explicit directive phrasing keeps the delegation deterministic so a
// scripted mock responder can drive this eval in the world suites.
const parent = await t.start(
- "Use the sleeper subagent exactly once with message 'Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled.'",
+ "Use the Workflow tool exactly once to call the sleeper subagent with message 'Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled.' Return the sleeper result.",
);
const called = await parent.waitForEvent("subagent.called", {
data: { name: "sleeper" },
});
+ const agentId = called.data.agentId;
+ if (agentId === undefined) throw new Error("Cancelled sleeper call has no agent id.");
const child = t.target.watchTurn(called.data.childSessionId);
await child.waitForEvent("actions.requested", {
@@ -64,6 +68,25 @@ export default defineEval({
listing.messageIncludes(/sleeper/i);
listing.messageIncludes(/\(cancelled\)/);
+ const resumed = await t.send(
+ [
+ "Use the Workflow tool exactly once.",
+ `In its JavaScript, call sleeper with agentId ${JSON.stringify(agentId)} and message ${JSON.stringify(RECOVERY_TOKEN)}.`,
+ "Return the inline result and reply with it verbatim. Do not call sleeper outside Workflow.",
+ ].join(" "),
+ );
+ resumed.expectOk();
+ resumed.messageIncludes(RECOVERY_TOKEN);
+ resumed.event("subagent.called", {
+ count: 1,
+ data: {
+ agentId,
+ childSessionId: called.data.childSessionId,
+ name: "sleeper",
+ },
+ });
+
t.event("turn.cancelled", { count: 2 });
+ t.event("subagent.called", { count: 2, data: { name: "sleeper" } });
},
});
diff --git a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts
index c1ec6829d..086c9b28e 100644
--- a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts
@@ -3,10 +3,31 @@ import { defineAgent } from "eve";
import type { MockModelRequest, MockModelResponse } from "eve/evals";
const COLLISION_MARKER = "MIXED-PARK-COMPLETE-7K2M";
+const STOCK_PRICE = "178.92";
function respond(request: MockModelRequest): MockModelResponse | string {
+ const message = request.lastUserMessage ?? "";
+ const prompt = request.messages.map((entry) => entry.text).join("\n");
+ if (message.includes("Call the stock-price subagent exactly once")) {
+ return request.toolResults.some((result) => result.name === "stock-price")
+ ? "The stock price is being fetched."
+ : {
+ toolCalls: [
+ {
+ input: {
+ message:
+ 'Call the get_stock_price tool exactly once with ticker "GOOG". After it returns, do not call any tool again; return the result.',
+ },
+ name: "stock-price",
+ },
+ ],
+ };
+ }
+ if (prompt.includes("Background task reporting") && prompt.includes(STOCK_PRICE)) {
+ return `The stock price is ${STOCK_PRICE}.`;
+ }
if (request.lastUserMessage?.includes(COLLISION_MARKER) !== true) {
- return `Mock reply: ${request.lastUserMessage ?? ""}`;
+ return `Mock reply: ${message}`;
}
const gateResults = request.toolResults.filter((result) => result.name === "collision-gate");
diff --git a/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/agent.ts
index a281a6122..88510675d 100644
--- a/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/agent.ts
+++ b/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/agent.ts
@@ -4,6 +4,11 @@ import { defineAgent } from "eve";
export default defineAgent({
description:
'Look up the current stock price for a given ticker symbol. Pass the ticker symbol you want to look up in the message (e.g. "AAPL", "GOOG", or "TSLA").',
- ...e2eSubagentConfig(),
+ ...e2eSubagentConfig({
+ mock: ({ toolResults }) =>
+ toolResults.find((result) => result.name === "get_stock_price") === undefined
+ ? { toolCalls: [{ input: { ticker: "GOOG" }, name: "get_stock_price" }] }
+ : "GOOG is trading at 178.92.",
+ }),
reasoning: "high",
});
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
index 236d67805..5653b5fb4 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
@@ -1,8 +1,14 @@
import { defineEval } from "eve/evals";
+import type { EveEvalContext, EveEvalSession, EveEvalTurn } from "eve/evals";
import { equals } from "eve/evals/expect";
const GOOG_PRICE = "178.92";
+type SessionCursor = Pick<
+ EveEvalSession,
+ "pendingInputRequests" | "requireInputRequest" | "respondAll" | "sessionId" | "state"
+>;
+
/**
* Parent/child HITL proxying: the stock-price subagent's tool approval
* (`approval: once()`) surfaces on the parent stream, the approval
@@ -12,25 +18,77 @@ const GOOG_PRICE = "178.92";
export default defineEval({
tags: ["real-model"],
description: "Subagent tool approval proxied through the parent session.",
+ timeoutMs: 90_000,
async test(t) {
- await t.send(
+ const started = await t.send(
`Call the stock-price subagent exactly once with message 'Call the get_stock_price tool exactly once with ticker "GOOG". After it returns, do not call any tool again; return the result.'. After that single subagent call finishes, do not call any subagent or tool again; include the exact stock price in your final reply.`,
);
+ started.event("subagent.completed", {
+ count: 1,
+ data: {
+ backgroundTask: { status: "working" },
+ subagentName: "stock-price",
+ },
+ });
- // The child's approval request must surface on the parent stream.
- t.requireInputRequest({ toolName: "get_stock_price" });
-
- await t.sleep();
-
- const resumed = await t.respondAll("approve");
+ // Background delegation returns its receipt first. The child's approval
+ // then wakes the parent in a separate server-initiated turn.
+ const blocked = await waitForInput(t, t, "get_stock_price");
+ const resumed = await blocked.respondAll("approve");
t.check(resumed.inputRequests, equals([]));
- t.noFailedActions();
+ resumed.noFailedActions();
+ const completed = resumed.message?.includes(GOOG_PRICE)
+ ? resumed
+ : await waitForMessage(t, blocked, GOOG_PRICE);
+ completed.messageIncludes(GOOG_PRICE);
+
t.succeeded();
t.calledSubagent("stock-price", {
- output: new RegExp(GOOG_PRICE),
count: 1,
});
- t.messageIncludes(GOOG_PRICE);
+ t.noFailedActions();
},
});
+
+async function waitForInput(
+ t: EveEvalContext,
+ initialSession: SessionCursor,
+ toolName: string,
+): Promise<SessionCursor> {
+ let session = initialSession;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ if (session.pendingInputRequests.some((request) => request.action.toolName === toolName)) {
+ session.requireInputRequest({ toolName });
+ return session;
+ }
+ const live = watchNextTurn(t, session, "subagent input wait");
+ const turn = await live.result();
+ turn.noFailedActions();
+ session = live.session;
+ }
+ throw new Error(`Subagent did not surface input for tool "${toolName}" after five turns.`);
+}
+
+async function waitForMessage(
+ t: EveEvalContext,
+ initialSession: SessionCursor,
+ marker: string,
+): Promise<EveEvalTurn> {
+ let session = initialSession;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ const live = watchNextTurn(t, session, "subagent completion wait");
+ const turn = await live.result();
+ turn.noFailedActions();
+ if (turn.message?.includes(marker) === true) return turn;
+ session = live.session;
+ }
+ throw new Error(`Subagent result did not reach the parent after five turns.`);
+}
+
+function watchNextTurn(t: EveEvalContext, session: SessionCursor, operation: string) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error(`${operation} has no parent session cursor.`);
+ }
+ return t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+}
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts
index 20c42636d..878a8eb5a 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts
@@ -6,8 +6,9 @@ const COLLISION_MARKER = "MIXED-PARK-COMPLETE-7K2M";
* Regression coverage for https://github.com/vercel/eve/issues/1201.
*
* One model step requests an approval-gated tool and a subagent together.
- * The child may finish first, but the root turn must retain the approval and
- * re-park instead of resuming the model with an unanswered tool call.
+ * The background task may return its receipt first, but the root turn must
+ * retain the approval and re-park instead of resuming the model with an
+ * unanswered tool call.
*/
export default defineEval({
description: "A root approval and subagent call from one model step both survive parking.",
@@ -24,8 +25,8 @@ export default defineEval({
parked.calledSubagent("collision-child", { count: 1, status: "completed" });
parked.eventOrder([
{ type: "actions.requested" },
- { type: "input.requested" },
{ type: "subagent.completed" },
+ { type: "input.requested" },
{ type: "session.waiting" },
]);
t.requireInputRequest({ display: "confirmation", toolName: "collision-gate" });
diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
index 9dd0e5c0d..85c92c6a0 100644
--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
@@ -13,26 +13,40 @@ export default defineEval({
"A parked local child re-messaged in a later parent turn still recalls a fact from its first turn.",
tags: ["real-model"],
async test(t) {
- await t.send(
+ const started = await t.send(
[
"Call the built-in agent subagent exactly once with this message:",
`"Remember this exact fact: ${MEMORABLE_FACT} Reply only with READY."`,
- "When it returns, reply with the single word: delegated.",
+ "Acknowledge the task receipt without stating the fact. When the task completes, reply with the single word: delegated.",
].join(" "),
);
+ started.expectOk();
- await t.send(
+ const firstCompletion = t.target.watchTurn(started.sessionId, {
+ startIndex: requireStreamIndex(t),
+ });
+ const firstCompletedTurn = await firstCompletion.result();
+ firstCompletedTurn.expectOk();
+ firstCompletedTurn.messageIncludes("delegated");
+
+ const continued = await firstCompletion.session.send(
[
"Message that same agent again: call the agent subagent with the agentId shown in the latest <agents> block",
'and the message: "What exact fact did I ask you to remember? Reply with only the fact."',
"Do not state the fact yourself.",
- "When it returns, reply with the agent's exact output and no other text.",
+ "Acknowledge the task receipt without stating the fact. When the task completes, reply with the agent's exact output and no other text.",
].join(" "),
);
+ continued.expectOk();
+
+ const secondCompletedTurn = await t.target
+ .watchTurn(started.sessionId, { startIndex: requireStreamIndex(firstCompletion.session) })
+ .result();
+ secondCompletedTurn.expectOk();
+ secondCompletedTurn.messageIncludes(MEMORABLE_FACT);
t.succeeded();
t.calledSubagent("agent", { count: 2 });
- t.calledSubagent("agent", { output: new RegExp(MEMORABLE_FACT), count: 1 });
t.eventsSatisfy("both turns continue one child session", (events) => {
const childSessionIds = events.flatMap((event) =>
event.type === "subagent.called" && event.data.name === "agent"
@@ -45,7 +59,14 @@ export default defineEval({
childSessionIds[0] === childSessionIds[1]
);
});
- t.messageIncludes(MEMORABLE_FACT);
t.noFailedActions();
},
});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Parent session has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
index 3c50a3372..8ec491cb4 100644
--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
@@ -13,15 +13,21 @@ export default defineEval({
"A parked remote child re-messaged in a later parent turn still recalls a fact from its first turn.",
tags: ["real-model"],
async test(t) {
- await t.send(
+ const started = await t.send(
[
"Use the remote-loopback agent exactly once with this message (no outputSchema):",
`"Remember this exact fact: ${MEMORABLE_FACT} Reply only with READY."`,
"When it returns, reply with the single word: delegated.",
].join(" "),
);
+ started.expectOk();
+ const firstCompletion = t.target.watchTurn(started.sessionId, {
+ startIndex: requireStreamIndex(t),
+ });
+ const firstCompletedTurn = await firstCompletion.result();
+ firstCompletedTurn.expectOk();
- await t.send(
+ const continued = await firstCompletion.session.send(
[
"Message that same remote-loopback agent again: call it with the agentId shown in the latest <agents> block",
'and the message: "What exact fact did I ask you to remember? Reply with only the fact."',
@@ -29,10 +35,15 @@ export default defineEval({
"When it returns, reply with the agent's exact output and no other text.",
].join(" "),
);
+ continued.expectOk();
+ const secondCompletedTurn = await t.target
+ .watchTurn(started.sessionId, { startIndex: requireStreamIndex(firstCompletion.session) })
+ .result();
+ secondCompletedTurn.expectOk();
+ secondCompletedTurn.messageIncludes(MEMORABLE_FACT);
t.succeeded();
t.calledSubagent("remote-loopback", { count: 2 });
- t.calledSubagent("remote-loopback", { output: new RegExp(MEMORABLE_FACT), count: 1 });
t.eventsSatisfy("both turns continue one remote child session", (events) => {
const childSessionIds = events.flatMap((event) =>
event.type === "subagent.called" && event.data.name === "remote-loopback"
@@ -45,7 +56,14 @@ export default defineEval({
childSessionIds[0] === childSessionIds[1]
);
});
- t.messageIncludes(MEMORABLE_FACT);
t.noFailedActions();
},
});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Parent session has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts
index 12df7aea6..497a1639e 100644
--- a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts
@@ -1,4 +1,4 @@
-import { defineEval } from "eve/evals";
+import { defineEval, type EveEvalContext, type EveEvalSession, type EveEvalTurn } from "eve/evals";
import { equals, satisfies } from "eve/evals/expect";
const CHILD_TOKEN = "CHILD_LIMIT_CONTINUED";
@@ -22,7 +22,8 @@ export default defineEval({
timeoutMs: 90_000,
async test(t) {
await t.send(DELEGATE_PROMPT);
- const continueRequest = t.requireInputRequest({
+ const continueSession = await waitForInput(t, t);
+ const continueRequest = continueSession.requireInputRequest({
display: "confirmation",
optionIds: ["continue", "stop"],
toolName: "session_limit_continuation",
@@ -39,45 +40,87 @@ export default defineEval({
),
);
- const resumed = await t.respond([
+ const resumed = await continueSession.respond([
{
optionId: "continue",
requestId: continueRequest.requestId,
},
]);
resumed.expectOk();
- t.succeeded();
- t.calledSubagent("limited-worker", { count: 1, output: CHILD_TOKEN });
- t.messageIncludes(CHILD_TOKEN);
+ const completed = resumed.message?.includes(CHILD_TOKEN)
+ ? resumed
+ : await waitForMessage(t, continueSession, CHILD_TOKEN);
+ completed.expectOk();
+ completed.messageIncludes(CHILD_TOKEN);
t.noFailedActions();
const stopSession = t.newSession();
await stopSession.send(DELEGATE_PROMPT);
- const stopRequest = stopSession.requireInputRequest({
+ const blockedStopSession = await waitForInput(t, stopSession);
+ const stopRequest = blockedStopSession.requireInputRequest({
display: "confirmation",
optionIds: ["continue", "stop"],
toolName: "session_limit_continuation",
});
- const stopped = await stopSession.respond([
+ const stopped = await blockedStopSession.respond([
{
optionId: "stop",
requestId: stopRequest.requestId,
},
]);
stopped.expectOk();
- stopSession.notEvent("turn.failed");
- stopSession.notEvent("session.failed");
- stopSession.notEvent("session.completed");
- stopSession.event("turn.cancelled");
+ stopped.notEvent("turn.failed");
+ stopped.notEvent("session.failed");
+ stopped.notEvent("session.completed");
+ stopped.event("turn.cancelled");
t.check(stopped.status, equals("waiting"));
- const recovered = await stopSession.send(
+ const recovered = await blockedStopSession.send(
`Do not call any tool or subagent. Reply with exactly ${ROOT_RECOVERY_TOKEN} and nothing else.`,
);
recovered.expectOk();
- stopSession.succeeded();
- stopSession.calledSubagent("limited-worker", { count: 1, status: "pending" });
- stopSession.messageIncludes(ROOT_RECOVERY_TOKEN);
+ stopSession.calledSubagent("limited-worker", { count: 1 });
+ recovered.messageIncludes(ROOT_RECOVERY_TOKEN);
},
});
+
+type SessionCursor = Pick<
+ EveEvalSession,
+ "pendingInputRequests" | "requireInputRequest" | "respond" | "send" | "sessionId" | "state"
+>;
+
+async function waitForInput(t: EveEvalContext, initial: SessionCursor): Promise<SessionCursor> {
+ let session = initial;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ if (session.pendingInputRequests.length > 0) return session;
+ const live = watchNextTurn(t, session, "descendant input wait");
+ const turn = await live.result();
+ turn.noFailedActions();
+ session = live.session;
+ }
+ throw new Error("Descendant did not surface its session-limit request after five turns.");
+}
+
+async function waitForMessage(
+ t: EveEvalContext,
+ initial: SessionCursor,
+ marker: string,
+): Promise<EveEvalTurn> {
+ let session = initial;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ const live = watchNextTurn(t, session, "descendant completion wait");
+ const turn = await live.result();
+ turn.noFailedActions();
+ if (turn.message?.includes(marker) === true) return turn;
+ session = live.session;
+ }
+ throw new Error("Descendant result did not reach the parent after five turns.");
+}
+
+function watchNextTurn(t: EveEvalContext, session: SessionCursor, operation: string) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error(`${operation} has no parent session cursor.`);
+ }
+ return t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+}
diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts
index b64fd6fd5..b5a18b7fd 100644
--- a/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts
@@ -1,21 +1,39 @@
-import { defineEval } from "eve/evals";
+import { defineEval, type EveEvalContext, type EveEvalSession } from "eve/evals";
export default defineEval({
description:
"Dynamic subagents are advertised when their resolver returns an agent config and omitted when it returns nil.",
async test(t) {
const selected = await t.send("Call conditional-marker exactly once.");
-
- selected.calledSubagent("conditional-marker", {
+ selected.expectOk();
+ selected.event("subagent.completed", {
count: 1,
- output: "DYNAMIC_SUBAGENT_ENABLED",
+ data: { backgroundTask: { status: "working" }, subagentName: "conditional-marker" },
});
- selected.messageIncludes("DYNAMIC_SUBAGENT_ENABLED");
- selected.noFailedActions();
+ const completed = await waitForMessage(t, t, "DYNAMIC_SUBAGENT_ENABLED");
- const omitted = await t.send("Call omitted-marker exactly once.");
+ const omitted = await completed.send("Call omitted-marker exactly once.");
omitted.notEvent("subagent.called", { data: { name: "omitted-marker" } });
omitted.noFailedActions();
},
});
+
+async function waitForMessage(
+ t: EveEvalContext,
+ initial: Pick<EveEvalSession, "send" | "sessionId" | "state">,
+ marker: string,
+): Promise<Pick<EveEvalSession, "send" | "sessionId" | "state">> {
+ let session = initial;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error("Dynamic subagent turn has no session cursor.");
+ }
+ const live = t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+ const turn = await live.result();
+ turn.expectOk();
+ if (turn.message?.includes(marker) === true) return live.session;
+ session = live.session;
+ }
+ throw new Error(`Dynamic subagent result did not include ${marker} after five turns.`);
+}
diff --git a/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts b/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
index 5823dff40..35c7f9d90 100644
--- a/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/local-delegation.eval.ts
@@ -11,12 +11,25 @@ export default defineEval({
tags: ["real-model"],
description: "Local subagent delegation smoke: child output reaches the parent reply verbatim.",
async test(t) {
- await t.send(
+ const started = await t.send(
"Use the echo-marker subagent with message 'ping'. Once it returns, reply with the subagent's exact output included verbatim.",
);
+ started.expectOk();
+ const completed = await t.target
+ .watchTurn(started.sessionId, { startIndex: requireStreamIndex(t) })
+ .result();
+ completed.expectOk();
+ completed.messageIncludes(SUBAGENT_TOKEN);
t.succeeded();
- t.calledSubagent("echo-marker", { output: /SUBAGENT_TOKEN=echo-marker-9F2X/ });
- t.messageIncludes(SUBAGENT_TOKEN);
+ t.calledSubagent("echo-marker", { count: 1 });
},
});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Parent session has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-subagents/evals/recursive-root-only.eval.ts b/e2e/fixtures/agent-subagents/evals/recursive-root-only.eval.ts
index e1bbc5b2d..976106af7 100644
--- a/e2e/fixtures/agent-subagents/evals/recursive-root-only.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/recursive-root-only.eval.ts
@@ -7,7 +7,7 @@ export default defineEval({
tags: ["real-model"],
description: "The built-in recursive agent tool is exposed only to the root session.",
async test(t) {
- await t.send(
+ const started = await t.send(
[
"Use the built-in agent subagent exactly once.",
"Give the child this task:",
@@ -16,10 +16,24 @@ export default defineEval({
`After the child returns, reply with its exact output and no other token.`,
].join(" "),
);
+ started.expectOk();
+
+ const completed = await t.target
+ .watchTurn(started.sessionId, { startIndex: requireStreamIndex(t) })
+ .result();
+ completed.expectOk();
+ completed.messageIncludes(CHILD_TOKEN);
t.succeeded();
t.calledSubagent("agent", { count: 1 });
- t.messageIncludes(CHILD_TOKEN);
t.noFailedActions();
},
});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Parent session has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
index 72f2dd249..2581cad0e 100644
--- a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
@@ -1,4 +1,4 @@
-import { defineEval, type EveEvalTurn } from "eve/evals";
+import { defineEval, type EveEvalContext, type EveEvalSession } from "eve/evals";
const ALICE_PRIVATE_DATA = "ALICE_PRIVATE_DM_7K4M";
const BOB_PRIVATE_DATA = "BOB_PRIVATE_DM_9P2R";
@@ -20,19 +20,6 @@ const CONTINUE_CHILD_MESSAGE = [
"Reply with only the child's output.",
].join(" ");
-function requireRemoteChild(parentTurn: EveEvalTurn, expectedSessionId?: string): string {
- const call = parentTurn.events.find(
- (event) => event.type === "subagent.called" && event.data.name === "remote-loopback",
- );
- if (call?.type !== "subagent.called") {
- throw new Error("The parent turn did not call remote-loopback.");
- }
- if (expectedSessionId !== undefined && call.data.childSessionId !== expectedSessionId) {
- throw new Error("The parent turn did not continue the existing remote child.");
- }
- return call.data.childSessionId;
-}
-
/** Three users resume one remote child; each tool call resolves only its current caller's grant. */
export default defineEval({
tags: ["principal-forwarding", "real-model"],
@@ -40,16 +27,17 @@ export default defineEval({
"A persistent remote child switches between two user grants and denies a third caller with none.",
async test(t) {
// Alice creates the child and reads with her own grant.
- const aliceParent = await t.send(CREATE_CHILD_MESSAGE);
- const childSessionId = requireRemoteChild(aliceParent);
+ await t.send(CREATE_CHILD_MESSAGE);
+ const aliceParent = await waitForRemoteChild(t, t);
+ const childSessionId = aliceParent.childSessionId;
const aliceChild = await t.target.watchTurn(childSessionId).result();
let childEventCount = aliceChild.events.length;
// Bob continues the same child and must resolve Bob's grant, not Alice's.
- const bobParent = await t.send(CONTINUE_CHILD_MESSAGE, {
+ await aliceParent.session.send(CONTINUE_CHILD_MESSAGE, {
headers: { authorization: BOB_AUTHORIZATION },
});
- requireRemoteChild(bobParent, childSessionId);
+ const bobParent = await waitForRemoteChild(t, aliceParent.session, childSessionId);
const bobChild = await t.target
.watchTurn(childSessionId, { startIndex: childEventCount })
.result();
@@ -57,10 +45,10 @@ export default defineEval({
// A grantless observer continues it once more. Reusing either prior bearer
// would complete this call; correct per-turn scoping makes it fail.
- const observerParent = await t.send(CONTINUE_CHILD_MESSAGE, {
+ await bobParent.session.send(CONTINUE_CHILD_MESSAGE, {
headers: { authorization: OBSERVER_AUTHORIZATION },
});
- requireRemoteChild(observerParent, childSessionId);
+ await waitForRemoteChild(t, bobParent.session, childSessionId);
const observerChild = await t.target
.watchTurn(childSessionId, { startIndex: childEventCount })
.result();
@@ -90,3 +78,32 @@ export default defineEval({
t.succeeded();
},
});
+
+type SessionCursor = Pick<EveEvalSession, "send" | "sessionId" | "state">;
+
+async function waitForRemoteChild(
+ t: EveEvalContext,
+ initial: SessionCursor,
+ expectedSessionId?: string,
+): Promise<{ readonly childSessionId: string; readonly session: SessionCursor }> {
+ let session = initial;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error("Remote child wait has no parent session cursor.");
+ }
+ const live = t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+ const turn = await live.result();
+ const call = turn.events.find(
+ (event) => event.type === "subagent.called" && event.data.name === "remote-loopback",
+ );
+ if (call?.type === "subagent.called") {
+ if (expectedSessionId !== undefined && call.data.childSessionId !== expectedSessionId) {
+ throw new Error("The parent turn did not continue the existing remote child.");
+ }
+ return { childSessionId: call.data.childSessionId, session: live.session };
+ }
+ turn.noFailedActions();
+ session = live.session;
+ }
+ throw new Error("The parent did not call remote-loopback after five turns.");
+}
diff --git a/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.ts
index e55876e6e..d513d995a 100644
--- a/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.ts
@@ -10,7 +10,7 @@ export default defineEval({
tags: ["real-model"],
description: "Runtime subagent sessions do not receive the root-only Workflow tool.",
async test(t) {
- await t.send(
+ const started = await t.send(
[
"Use the built-in agent subagent exactly once.",
"Give the child this task:",
@@ -19,12 +19,26 @@ export default defineEval({
`After the child returns, reply with its exact output and no other token.`,
].join(" "),
);
+ started.expectOk();
+
+ const completed = await t.target
+ .watchTurn(started.sessionId, { startIndex: requireStreamIndex(t) })
+ .result();
+ completed.expectOk();
+ completed.messageIncludes(CHILD_TOKEN);
t.succeeded();
t.calledSubagent("agent", { count: 1 });
t.notCalledTool("Workflow");
t.notEvent("subagent.called", { data: { name: "echo-marker" } });
- t.messageIncludes(CHILD_TOKEN);
t.noFailedActions();
},
});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Parent session has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts
new file mode 100644
index 000000000..59c60d8cd
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts
@@ -0,0 +1,61 @@
+import { defineEval } from "eve/evals";
+
+/** Workflow calls block, can continue one child, and share one subagent budget. */
+export default defineEval({
+ tags: ["real-model"],
+ description:
+ "Workflow sandbox agent calls return inline, reuse agentId, and enforce maxSubagents.",
+ async test(t) {
+ const started = await t.send(
+ [
+ "Use the Workflow tool exactly once and call echo-marker inside it with message 'blocking first'.",
+ "Return the inline result and reply with it verbatim. Do not call echo-marker outside Workflow.",
+ ].join(" "),
+ );
+ started.expectOk();
+ const firstTurn = started.message?.includes("SUBAGENT_TOKEN=echo-marker-9F2X")
+ ? undefined
+ : t.target.watchTurn(started.sessionId, {
+ startIndex: requireStreamIndex(t),
+ });
+ const completed = firstTurn === undefined ? started : await firstTurn.result();
+ completed.expectOk();
+ completed.messageIncludes("SUBAGENT_TOKEN=echo-marker-9F2X");
+
+ const second = await (firstTurn?.session ?? t).send(
+ [
+ "Use the Workflow tool exactly once. In its JavaScript, call the same echo-marker child twice sequentially",
+ "using the agentId shown in the latest <agents> block, with messages 'blocking second' and 'blocking third'.",
+ "Then attempt a third call with that agentId and message 'blocking over limit'.",
+ "Return all three inline results and reply with them verbatim as JSON. Do not call echo-marker outside Workflow.",
+ ].join(" "),
+ );
+ second.expectOk();
+
+ t.succeeded();
+ t.calledTool("Workflow", { count: 2 });
+ t.calledSubagent("echo-marker", { count: 3 });
+ t.eventsSatisfy("all Workflow calls continue one child session", (events) => {
+ const childSessionIds = events.flatMap((event) =>
+ event.type === "subagent.called" && event.data.name === "echo-marker"
+ ? [event.data.childSessionId]
+ : [],
+ );
+ return (
+ childSessionIds.length === 3 &&
+ childSessionIds[0] !== undefined &&
+ childSessionIds.every((sessionId) => sessionId === childSessionIds[0])
+ );
+ });
+ t.messageIncludes("SUBAGENT_TOKEN=echo-marker-9F2X");
+ t.messageIncludes("WORKFLOW_SUBAGENT_LIMIT_REACHED");
+ },
+});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Parent session has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-task-reporting/agent/agent.ts b/e2e/fixtures/agent-task-reporting/agent/agent.ts
index ce44dbb17..fb7a0c6d4 100644
--- a/e2e/fixtures/agent-task-reporting/agent/agent.ts
+++ b/e2e/fixtures/agent-task-reporting/agent/agent.ts
@@ -3,10 +3,4 @@ import { defineAgent } from "eve";
const base = e2eAgentConfig();
-export default defineAgent({
- ...base,
- experimental: {
- ...base.experimental,
- tasks: true,
- },
-});
+export default defineAgent({ ...base });
diff --git a/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts b/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts
index 733bb6c1b..5eb20d85f 100644
--- a/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts
+++ b/e2e/fixtures/agent-task-reporting/evals/consolidated-report.eval.ts
@@ -8,7 +8,7 @@ const COMPLETION = /Background task (task_[a-z0-9]+) \([^)]+\) is completed\./gi
function reportingEval() {
return defineEval({
description:
- "A stock Eve agent acknowledges accepted background work, keeps partial wakes silent, and reports once after settlement.",
+ "A stock eve agent acknowledges accepted background work, keeps partial wakes silent, and reports once after settlement.",
tags: ["real-model"],
async test(t) {
const started =
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts
index b26b77983..b625825a2 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/sandbox/sandbox.ts
@@ -34,12 +34,11 @@ export const SANDBOX_MARKER_PATH = "/workspace/smoke-marker.txt";
export const SANDBOX_MARKER_TOKEN = "sandbox-bootstrap-ok-J3Q";
/**
- * Custom CLI installed during bootstrap. `/usr/local/bin` is on the default
- * PATH in the base image and is writable by the sandbox user (it is the npm
- * global prefix bin, chowned to `vercel-sandbox`), so the same install works
- * whether bootstrap runs as root (Docker) or as `vercel-sandbox` (Vercel).
+ * Custom CLI installed during bootstrap. The base image puts the sandbox
+ * user's npm global prefix on PATH, so the same install works across backends.
*/
-export const SANDBOX_CLI_PATH = "/usr/local/bin/eve-greet";
+const SANDBOX_CLI_DIRECTORY_PATH = "/home/vercel-sandbox/.local/bin";
+export const SANDBOX_CLI_PATH = `${SANDBOX_CLI_DIRECTORY_PATH}/eve-greet`;
export const SANDBOX_CLI_TOKEN = "eve-greet-cli-ok-R7M";
/** Per-session marker written by `onSession` (live session, not the template). */
@@ -144,7 +143,7 @@ export default defineSandbox({
backend,
// Bump when the bootstrap output changes so the reusable template snapshot
// is rebuilt rather than served stale.
- revalidationKey: () => "agent-tools-sandbox-bootstrap-v2",
+ revalidationKey: () => "agent-tools-sandbox-bootstrap-v3",
async bootstrap({ use }) {
const sandbox = await use();
await sandbox.writeTextFile({
@@ -153,6 +152,10 @@ export default defineSandbox({
});
// Install a custom CLI onto the PATH and make it executable. Later
// sessions inherit it from the template without re-running bootstrap.
+ const mkdir = await sandbox.run({ command: `mkdir -p ${SANDBOX_CLI_DIRECTORY_PATH}` });
+ if (mkdir.exitCode !== 0) {
+ throw new Error(`bootstrap: failed to create CLI directory: ${mkdir.stderr}`);
+ }
await sandbox.writeTextFile({ path: SANDBOX_CLI_PATH, content: CLI_SCRIPT });
const chmod = await sandbox.run({ command: `chmod +x ${SANDBOX_CLI_PATH}` });
if (chmod.exitCode !== 0) {
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
index 793532f83..100feb530 100644
--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
@@ -20,14 +20,30 @@ export default defineEval({
`Run the bash command \`cat ${PARENT_PATH} && printf %s ${CHILD_TOKEN} > ${CHILD_PATH}\` ` +
"and reply with the command output verbatim.",
);
- await t.require(childTurn.message, includes(PARENT_TOKEN));
+ childTurn.expectOk();
+ const sessionId = childTurn.sessionId;
+ if (sessionId === undefined) throw new Error("Shared sandbox turn has no session id.");
+ const completed = t.target.watchTurn(sessionId, {
+ startIndex: requireStreamIndex(t),
+ });
+ const childCompletion = await completed.result();
+ childCompletion.expectOk();
+ await t.require(childCompletion.message, includes(PARENT_TOKEN));
- const parentRead = await t.send(
+ const parentRead = await completed.session.send(
`Run the bash command \`cat ${CHILD_PATH}\` and reply with the file contents verbatim.`,
);
t.succeeded();
- t.calledSubagent("shared-sandbox", { output: new RegExp(PARENT_TOKEN) });
+ t.calledSubagent("shared-sandbox", { count: 1 });
t.check(parentRead.message, includes(CHILD_TOKEN));
},
});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Shared sandbox turn has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
index 52d2aa5a8..d84b2dbb6 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
@@ -8,8 +8,30 @@ import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/ev
*/
function respond(request: MockModelRequest): MockModelResponse | string {
const message = [...request.userMessages].reverse().find((entry) => entry.trim() !== "") ?? "";
- const roles = request.messages.map((entry) => entry.role);
- const turnHasToolResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");
+ const probe = /WORKFLOW-PROBE-blocking-local-(hitl|auth)/u.exec(message);
+ if (probe !== null) {
+ const result = request.toolResults.find((entry) => entry.name === "blocking_agent_probe");
+ if (result === undefined) {
+ return {
+ toolCalls: [{ input: { kind: probe[1] }, name: "blocking_agent_probe" }],
+ };
+ }
+ return `WORKFLOW-PROBE-RESULT ${String(result.output)}`;
+ }
+ if (message.includes("WORKFLOW-MIXED-AGENTS-START")) {
+ const mixedResults = request.toolResults.filter(
+ (result) => result.id === "blocking-agent-call" || result.id === "background-agent-call",
+ );
+ if (mixedResults.length < 2) {
+ return {
+ toolCalls: [
+ { id: "blocking-agent-call", input: { service: "api" }, name: "blocking_agent" },
+ { id: "background-agent-call", input: { service: "api" }, name: "background_agent" },
+ ],
+ };
+ }
+ return "WORKFLOW-MIXED-AGENTS-INITIAL-RESULT";
+ }
for (const [directive, tool] of [
["WORKFLOW-DEPLOY-START", "deploy_service"],
@@ -18,14 +40,14 @@ function respond(request: MockModelRequest): MockModelResponse | string {
["WORKFLOW-ESCALATE-START", "escalate_deploy"],
["WORKFLOW-HOLD-START", "hold_deploy"],
["WORKFLOW-FANOUT-START", "fanout_deploy"],
+ ["WORKFLOW-AGENT-FANOUT-START", "fanout_agents"],
] as const) {
if (!message.includes(directive)) continue;
- if (!turnHasToolResult) {
+ const result = [...request.toolResults].reverse().find((entry) => entry.name === tool);
+ if (result === undefined) {
return { toolCalls: [{ input: { service: "api" }, name: tool }] };
}
- const output = [...request.toolResults]
- .reverse()
- .find((result) => result.name === tool)?.output;
+ const output = result.output;
return `${directive.replace("-START", "-RESULT")} ${
typeof output === "string" ? output : JSON.stringify(output ?? null)
}`;
@@ -37,6 +59,9 @@ function respond(request: MockModelRequest): MockModelResponse | string {
if (message.includes("is completed") && message.includes("WORKFLOW-REPORT-COMPLETE")) {
return "WORKFLOW-REPORT-DONE";
}
+ if (message.includes("is completed") && message.includes("WORKFLOW-CHILD:api:background")) {
+ return "WORKFLOW-MIXED-AGENTS-BACKGROUND-DONE";
+ }
if (message.startsWith("Background task ")) {
return "WORKFLOW-REPORT-ACK";
}
@@ -48,10 +73,6 @@ const base = e2eAgentConfig({ mock: respond });
export default defineAgent({
...base,
- experimental: {
- ...base.experimental,
- tasks: true,
- },
// Always author the deterministic script so this fixture never depends on a
// live model; world suites already set EVE_E2E_MODEL=mock.
model: mockModel(respond),
diff --git a/e2e/fixtures/agent-workflow-tools/agent/channels/eve.ts b/e2e/fixtures/agent-workflow-tools/agent/channels/eve.ts
new file mode 100644
index 000000000..b8827446d
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/channels/eve.ts
@@ -0,0 +1,16 @@
+import { eveChannel } from "eve/channels/eve";
+
+export default eveChannel({
+ auth: (request) => {
+ const forwarded = request.headers.get("x-eve-forwarded-principal-id");
+ const principalId = forwarded ?? "workflow-e2e-user";
+ return {
+ attributes: { fixture: "workflow-agent-probes" },
+ authenticator: "e2e-fixture",
+ issuer: "e2e",
+ principalId,
+ principalType: "user",
+ subject: principalId,
+ };
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
new file mode 100644
index 000000000..845494f1c
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
@@ -0,0 +1,17 @@
+import { agent } from "eve/workflow";
+import { z } from "zod";
+
+export const workflowAgentProbeInputSchema = z.strictObject({
+ kind: z.enum(["auth", "hitl"]),
+});
+
+export async function executeWorkflowAgentProbe(
+ input: z.infer<typeof workflowAgentProbeInputSchema>,
+ ctx: Parameters<typeof agent>[0],
+): Promise<unknown> {
+ return await agent(ctx, {
+ key: `local-${input.kind}`,
+ message: `Run the ${input.kind} probe.`,
+ target: input.kind === "hitl" ? "workflow-hitl" : "workflow-auth",
+ });
+}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-auth/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-auth/agent.ts
new file mode 100644
index 000000000..865ac8a54
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-auth/agent.ts
@@ -0,0 +1,13 @@
+import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+export default defineAgent({
+ description: "Exercise a deterministic interactive-authorization child tool.",
+ model: mockModel(({ toolResults }) => {
+ const result = toolResults.find((entry) => entry.name === "auth-gate");
+ return result === undefined
+ ? { toolCalls: [{ input: { marker: "authorized" }, name: "auth-gate" }] }
+ : String(result.output);
+ }),
+ modelContextWindowTokens: 1_000_000,
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-auth/tools/auth-gate.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-auth/tools/auth-gate.ts
new file mode 100644
index 000000000..d2e1e96b8
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-auth/tools/auth-gate.ts
@@ -0,0 +1,35 @@
+import {
+ ConnectionAuthorizationRequiredError,
+ defineInteractiveAuthorization,
+} from "eve/connections";
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+const auth = defineInteractiveAuthorization<{ marker: string }>({
+ async getToken() {
+ throw new ConnectionAuthorizationRequiredError("workflow-auth");
+ },
+ async startAuthorization({ callbackUrl }) {
+ const url = new URL(callbackUrl);
+ url.searchParams.set("code", "workflow-auth-ok");
+ return {
+ challenge: { displayName: "Workflow Auth", url: url.href },
+ resume: { marker: "workflow-auth-resume" },
+ };
+ },
+ async completeAuthorization({ callback, resume }) {
+ if (callback.params.code !== "workflow-auth-ok" || resume?.marker !== "workflow-auth-resume") {
+ throw new Error("Workflow authorization state mismatch.");
+ }
+ return { token: "workflow-auth-token" };
+ },
+});
+
+export default defineTool({
+ description: "Return a deterministic marker after interactive authorization.",
+ inputSchema: z.strictObject({ marker: z.string() }),
+ async execute({ marker }, ctx) {
+ await ctx.getToken(auth, { authKey: "workflow-auth", displayName: "Workflow Auth" });
+ return `WORKFLOW-AUTH:${marker}`;
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-hitl/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-hitl/agent.ts
new file mode 100644
index 000000000..96cc41bba
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-hitl/agent.ts
@@ -0,0 +1,13 @@
+import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+export default defineAgent({
+ description: "Exercise a deterministic approval-gated child tool.",
+ model: mockModel(({ toolResults }) => {
+ const result = toolResults.find((entry) => entry.name === "approval-gate");
+ return result === undefined
+ ? { toolCalls: [{ input: { marker: "approved" }, name: "approval-gate" }] }
+ : String(result.output);
+ }),
+ modelContextWindowTokens: 1_000_000,
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-hitl/tools/approval-gate.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-hitl/tools/approval-gate.ts
new file mode 100644
index 000000000..82a699ff0
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-hitl/tools/approval-gate.ts
@@ -0,0 +1,12 @@
+import { defineTool } from "eve/tools";
+import { once } from "eve/tools/approval";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Return a deterministic marker after human approval.",
+ approval: once(),
+ inputSchema: z.strictObject({ marker: z.string() }),
+ execute({ marker }) {
+ return `WORKFLOW-HITL:${marker}`;
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.ts
new file mode 100644
index 000000000..9875d0b13
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-marker/agent.ts
@@ -0,0 +1,8 @@
+import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+export default defineAgent({
+ description: "Return deterministic markers for workflow-subagent e2e coverage.",
+ model: mockModel(({ lastUserMessage }) => `WORKFLOW-CHILD:${lastUserMessage ?? ""}`),
+ modelContextWindowTokens: 1_000_000,
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
new file mode 100644
index 000000000..91ffac8ac
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
@@ -0,0 +1,18 @@
+import { defineTool } from "eve/tools";
+import { agent } from "eve/workflow";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Run one subagent from a background workflow tool.",
+ execution: "background",
+ inputSchema: z.strictObject({ service: z.string() }),
+ async execute({ service }, ctx) {
+ "use workflow";
+
+ return await agent(ctx, {
+ key: "background-child",
+ message: `${service}:background`,
+ target: "workflow-marker",
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
new file mode 100644
index 000000000..cce17dc21
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
@@ -0,0 +1,17 @@
+import { defineTool } from "eve/tools";
+import { agent } from "eve/workflow";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Run one subagent from a waiting workflow tool.",
+ inputSchema: z.strictObject({ service: z.string() }),
+ async execute({ service }, ctx) {
+ "use workflow";
+
+ return await agent(ctx, {
+ key: "blocking-child",
+ message: `${service}:blocking`,
+ target: "workflow-marker",
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts
new file mode 100644
index 000000000..312e691b4
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts
@@ -0,0 +1,15 @@
+import { defineTool } from "eve/tools";
+
+import {
+ executeWorkflowAgentProbe,
+ workflowAgentProbeInputSchema,
+} from "../lib/workflow-agent-probe.ts";
+
+export default defineTool({
+ description: "Run a blocking local or remote subagent HITL/authorization probe.",
+ inputSchema: workflowAgentProbeInputSchema,
+ async execute(input, ctx) {
+ "use workflow";
+ return await executeWorkflowAgentProbe(input, ctx);
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
new file mode 100644
index 000000000..a42cfcd6f
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
@@ -0,0 +1,24 @@
+import { defineTool } from "eve/tools";
+import { agent } from "eve/workflow";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Call two workflow-owned subagents in parallel and return both inline results.",
+ inputSchema: z.strictObject({ service: z.string() }),
+ async execute({ service }, ctx) {
+ "use workflow";
+
+ return await Promise.all([
+ agent(ctx, {
+ key: "replica-0",
+ message: `${service}:replica-0`,
+ target: "workflow-marker",
+ }),
+ agent(ctx, {
+ key: "replica-1",
+ message: `${service}:replica-1`,
+ target: "workflow-marker",
+ }),
+ ]);
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts
new file mode 100644
index 000000000..e5d5c24c3
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts
@@ -0,0 +1,28 @@
+import { defineEval } from "eve/evals";
+
+export default defineEval({
+ description:
+ "An authored waiting workflow tool blocks on two parallel agent() calls and returns both inline results.",
+ timeoutMs: 60_000,
+ async test(t) {
+ const turn = await t.send("WORKFLOW-AGENT-FANOUT-START");
+ turn.expectOk();
+ turn.calledTool("fanout_agents", { count: 1, status: "completed" });
+ turn.event("subagent.called", { data: { name: "workflow-marker" }, count: 2 });
+ turn.messageIncludes("api:replica-0");
+ turn.messageIncludes("api:replica-1");
+ turn.eventsSatisfy("both children start before the waiting tool resolves", (events) => {
+ const called = events.flatMap((event, index) =>
+ event.type === "subagent.called" && event.data.name === "workflow-marker" ? [index] : [],
+ );
+ const toolResult = events.findIndex(
+ (event) =>
+ event.type === "action.result" &&
+ event.data.result.kind === "tool-result" &&
+ event.data.result.toolName === "fanout_agents",
+ );
+ return called.length === 2 && toolResult >= 0 && Math.max(...called) < toolResult;
+ });
+ t.noFailedActions();
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/agent-probe.blocking.local.auth.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.blocking.local.auth.eval.ts
new file mode 100644
index 000000000..a843c24c4
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.blocking.local.auth.eval.ts
@@ -0,0 +1,11 @@
+import { defineEval } from "eve/evals";
+
+import { runProbe } from "./agent-probe.shared.ts";
+
+export default defineEval({
+ description: "Blocking local workflow subagent proxies interactive authorization.",
+ timeoutMs: 90_000,
+ async test(t) {
+ await runProbe(t, { kind: "auth" });
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/agent-probe.blocking.local.hitl.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.blocking.local.hitl.eval.ts
new file mode 100644
index 000000000..f7c3e98dc
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.blocking.local.hitl.eval.ts
@@ -0,0 +1,11 @@
+import { defineEval } from "eve/evals";
+
+import { runProbe } from "./agent-probe.shared.ts";
+
+export default defineEval({
+ description: "Blocking local workflow subagent proxies human approval.",
+ timeoutMs: 90_000,
+ async test(t) {
+ await runProbe(t, { kind: "hitl" });
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts
new file mode 100644
index 000000000..190f35a6d
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-probe.shared.ts
@@ -0,0 +1,101 @@
+import type { EveEvalContext, EveEvalSession, EveEvalTurn } from "eve/evals";
+
+export type ProbeCase = { readonly kind: "auth" | "hitl" };
+
+type SessionCursor = Pick<
+ EveEvalSession,
+ "pendingInputRequests" | "requireInputRequest" | "respondAll" | "sessionId" | "state"
+>;
+
+export async function runProbe(t: EveEvalContext, probe: ProbeCase): Promise<void> {
+ const directive = `WORKFLOW-PROBE-blocking-local-${probe.kind}`;
+ const started = await t.send(directive);
+ started.expectOk();
+
+ if (probe.kind === "hitl") {
+ const blocked = await waitForInput(t, t, "approval-gate");
+ const approved = await blocked.respondAll("approve");
+ approved.expectOk();
+ await waitForMarker(t, blocked, approved, "WORKFLOW-HITL:approved");
+ } else {
+ const required = await waitForEvent(t, t, started, "authorization.required");
+ const url = required.event.data.authorization?.url;
+ if (url === undefined) throw new Error("Authorization probe produced no callback URL.");
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`Authorization callback failed (${response.status}).`);
+ await waitForEvent(t, required.session, undefined, "authorization.completed");
+ await waitForMarker(t, required.session, undefined, "WORKFLOW-AUTH:authorized");
+ }
+
+ t.succeeded();
+ t.noFailedActions();
+}
+
+async function waitForInput(
+ t: EveEvalContext,
+ initial: SessionCursor,
+ toolName: string,
+): Promise<SessionCursor> {
+ let session = initial;
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ if (session.pendingInputRequests.some((request) => request.action.toolName === toolName)) {
+ session.requireInputRequest({ toolName });
+ return session;
+ }
+ const live = watchNext(t, session);
+ const turn = await live.result();
+ turn.noFailedActions();
+ session = live.session;
+ }
+ throw new Error(`Probe did not surface input for ${toolName}.`);
+}
+
+async function waitForMarker(
+ t: EveEvalContext,
+ initial: SessionCursor,
+ initialTurn: EveEvalTurn | undefined,
+ marker: string,
+): Promise<EveEvalTurn> {
+ if (initialTurn?.message?.includes(marker) === true) return initialTurn;
+ let session = initial;
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ const live = watchNext(t, session);
+ const turn = await live.result();
+ turn.noFailedActions();
+ if (turn.message?.includes(marker) === true) return turn;
+ session = live.session;
+ }
+ throw new Error(`Probe did not produce ${marker}.`);
+}
+
+async function waitForEvent<T extends "authorization.completed" | "authorization.required">(
+ t: EveEvalContext,
+ initial: SessionCursor,
+ initialTurn: EveEvalTurn | undefined,
+ type: T,
+): Promise<{
+ readonly event: Extract<EveEvalTurn["events"][number], { readonly type: T }>;
+ readonly session: SessionCursor;
+}> {
+ let session = initial;
+ let turn = initialTurn;
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ const event = turn?.events.find(
+ (candidate): candidate is Extract<EveEvalTurn["events"][number], { readonly type: T }> =>
+ candidate.type === type,
+ );
+ if (event !== undefined) return { event, session };
+ const live = watchNext(t, session);
+ turn = await live.result();
+ turn.noFailedActions();
+ session = live.session;
+ }
+ throw new Error(`Probe did not surface ${type}.`);
+}
+
+function watchNext(t: EveEvalContext, session: SessionCursor) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error("Probe session cursor is incomplete.");
+ }
+ return t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+}
diff --git a/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts
new file mode 100644
index 000000000..91907428c
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/mixed-agent-resolution.eval.ts
@@ -0,0 +1,45 @@
+import { defineEval } from "eve/evals";
+
+export default defineEval({
+ description:
+ "One model step mixes waiting and background workflow tools; waiting agent results resolve inline and the background result wakes a later turn.",
+ async test(t) {
+ const initial = await t.send("WORKFLOW-MIXED-AGENTS-START");
+ initial.expectOk();
+ initial.calledTool("blocking_agent", { count: 1, status: "completed" });
+ initial.calledTool("background_agent", { count: 1, status: "completed" });
+ initial.event("subagent.called", { data: { name: "workflow-marker" }, count: 1 });
+ initial.messageIncludes("WORKFLOW-MIXED-AGENTS-INITIAL-RESULT");
+ initial.notEvent("message.received", {
+ data: { message: /WORKFLOW-CHILD:api:background/u },
+ });
+
+ const sessionId = initial.sessionId;
+ if (sessionId === undefined) throw new Error("Mixed workflow turn has no session id.");
+ const completed = await t.target
+ .watchTurn(sessionId, { startIndex: requireStreamIndex(t) })
+ .result();
+ completed.expectOk();
+ completed.messageIncludes("WORKFLOW-REPORT-ACK");
+ completed.event("message.received", { count: 1 });
+ completed.eventsSatisfy("background child result wakes the later turn", (events) =>
+ events.some(
+ (event) =>
+ event.type === "message.received" &&
+ JSON.stringify(event.data.message).includes("api:background"),
+ ),
+ );
+
+ t.succeeded();
+ t.event("subagent.called", { data: { name: "workflow-marker" }, count: 2 });
+ t.noFailedActions();
+ },
+});
+
+function requireStreamIndex(session: {
+ readonly state?: { readonly streamIndex?: number };
+}): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error("Mixed workflow turn has no stream index.");
+ return streamIndex;
+}
diff --git a/e2e/fixtures/fixture-tasks/agent/agent.ts b/e2e/fixtures/fixture-tasks/agent/agent.ts
index 924f3b1b4..038245332 100644
--- a/e2e/fixtures/fixture-tasks/agent/agent.ts
+++ b/e2e/fixtures/fixture-tasks/agent/agent.ts
@@ -24,7 +24,6 @@ function respond(request: MockModelRequest): MockModelResponse | string {
if (request.userMessages.some((entry) => entry.includes("TASK-UPDATE-PROGRESS"))) {
return "TASK-UPDATE-RECEIVED";
}
- if (message.includes("TASK-UPDATE-CHILD")) return sendTaskUpdate(request);
if (message.includes("TASK-FANOUT-INTERACTIVE-CHECK")) return "TASK-FANOUT-INTERACTIVE-OK";
if (message.includes("TASK-CANCEL-NOW")) return cancelWorkerTask(request);
if (message.includes("CHILD-TASK-EXCLUSIVITY-RACE")) return raceBusyWorker(request);
@@ -41,7 +40,13 @@ function respond(request: MockModelRequest): MockModelResponse | string {
);
}
if (message.startsWith("TASK-A3-UNKNOWN-VERIFY ")) {
- return inspectTerminalTask(request, "task-a3-unknown-verify", "TASK-A3-UNKNOWN", message);
+ return inspectTerminalTask(
+ request,
+ "task-a3-unknown-verify",
+ "TASK-A3-UNKNOWN",
+ message,
+ "failed",
+ );
}
if (message.startsWith("TASK-D6-PARTIAL-FANOUT-VERIFY ")) {
return inspectTerminalTask(
@@ -169,7 +174,7 @@ function startTaskUpdateChild(request: MockModelRequest): MockModelResponse | st
{
id: "task-update-child",
input: { message: "TASK-UPDATE-CHILD" },
- name: "agent",
+ name: "update-worker",
},
],
};
@@ -240,29 +245,6 @@ function latestTaskState(messages: readonly string[]): TaskState | undefined {
return parsed as TaskState;
}
-function sendTaskUpdate(request: MockModelRequest): MockModelResponse | string {
- const result = resultById(request, "task-update-progress");
- if (result === undefined) {
- return {
- toolCalls: [
- {
- id: "task-update-progress",
- input: { message: "TASK-UPDATE-PROGRESS" },
- name: "task_update",
- },
- ],
- };
- }
- if (
- result.output === null ||
- typeof result.output !== "object" ||
- Reflect.get(result.output, "status") !== "sent"
- ) {
- throw new Error("task_update did not confirm delivery.");
- }
- return "TASK-UPDATE-CHILD-DONE";
-}
-
function fanoutTasks(request: MockModelRequest, size: number): MockModelResponse | string {
const pending = Array.from({ length: size }, (_, index) => index + 1).filter(
(index) => resultById(request, `task-fanout-${index}`) === undefined,
@@ -651,7 +633,6 @@ const base = e2eAgentConfig();
export default defineAgent({
...base,
- experimental: { ...base.experimental, tasks: true },
// These evals target orchestration, not model planning. Keep every suite
// deterministic while retaining the workflow-world override from `base`.
model: mockModel(respond),
diff --git a/e2e/fixtures/fixture-tasks/agent/subagents/update-worker/agent.ts b/e2e/fixtures/fixture-tasks/agent/subagents/update-worker/agent.ts
new file mode 100644
index 000000000..dbf48c00d
--- /dev/null
+++ b/e2e/fixtures/fixture-tasks/agent/subagents/update-worker/agent.ts
@@ -0,0 +1,31 @@
+import { defineAgent } from "eve";
+import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
+
+function respond(request: MockModelRequest): MockModelResponse | string {
+ const result = request.toolResults.find((entry) => entry.id === "task-update-progress");
+ if (result === undefined) {
+ return {
+ toolCalls: [
+ {
+ id: "task-update-progress",
+ input: { message: "TASK-UPDATE-PROGRESS" },
+ name: "task_update",
+ },
+ ],
+ };
+ }
+ if (
+ result.output === null ||
+ typeof result.output !== "object" ||
+ Reflect.get(result.output, "status") !== "sent"
+ ) {
+ throw new Error("task_update did not confirm delivery.");
+ }
+ return "TASK-UPDATE-CHILD-DONE";
+}
+
+export default defineAgent({
+ description: "Report one deterministic task update to the parent.",
+ model: mockModel(respond),
+ modelContextWindowTokens: 1_000_000,
+});
diff --git a/e2e/fixtures/fixture-tasks/evals/shared.ts b/e2e/fixtures/fixture-tasks/evals/shared.ts
index 2d6b84fab..1f54fd38a 100644
--- a/e2e/fixtures/fixture-tasks/evals/shared.ts
+++ b/e2e/fixtures/fixture-tasks/evals/shared.ts
@@ -166,7 +166,8 @@ export async function waitForTaskStatus(
status: string,
): Promise<EveEvalTurn> {
let currentSession = session;
- const deadline = performance.now() + 15_000;
+ const timeoutMs = 30_000;
+ const deadline = performance.now() + timeoutMs;
let attempt = 0;
while (performance.now() < deadline) {
const followed = await sendAndFollowQueuedTurn(
@@ -196,7 +197,7 @@ export async function waitForTaskStatus(
await t.sleep(100);
}
throw new Error(
- `Task ${taskId} did not reach "${status}" within 15 seconds (${attempt} verification attempts).`,
+ `Task ${taskId} did not reach "${status}" within ${timeoutMs / 1_000} seconds (${attempt} verification attempts).`,
);
}
diff --git a/e2e/fixtures/fixture-tasks/evals/task-transition.ts b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
index ecbcf6a3d..96ded2dff 100644
--- a/e2e/fixtures/fixture-tasks/evals/task-transition.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
@@ -37,6 +37,7 @@ type SemanticEvent =
| "input-requested"
| "authorization-required"
| "authorization-completed"
+ | "task-failed-notification"
| "task-ready-notification"
| "task-update-notification";
@@ -276,10 +277,10 @@ export const TASK_TRANSITIONS = {
input: "dispatch-start",
guards: ["child-start-is-unreachable"],
expected: {
- outcome: "rejected",
- postState: { lifecycle: "absent", dispatch: "rejected", ownership: "unowned" },
- events: { suppressed: ["background-receipt"] },
- sideEffects: { executed: ["child-dispatch"], suppressed: ["task-index-write"] },
+ outcome: "accepted",
+ postState: { lifecycle: "failed", dispatch: "acknowledged", ownership: "owned" },
+ events: { emitted: ["background-receipt", "task-failed-notification"] },
+ sideEffects: { executed: ["child-dispatch", "task-index-write"] },
},
}),
"task.dispatch-batch.start.accepted-partial-failure": transition({
@@ -288,8 +289,8 @@ export const TASK_TRANSITIONS = {
guards: ["one-member-is-unreachable", "other-members-are-reachable"],
expected: {
outcome: "accepted",
- postState: { dispatch: "acknowledged", ownership: "owned" },
- events: { emitted: ["background-receipt"] },
+ postState: { lifecycle: ["working", "failed"], dispatch: "acknowledged", ownership: "owned" },
+ events: { emitted: ["background-receipt", "task-failed-notification"] },
sideEffects: { executed: ["child-dispatch", "task-index-write"] },
},
}),
diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts
index 2379082de..2102b19c9 100644
--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch-batch.start.accepted-partial-failure.eval.ts
@@ -1,17 +1,17 @@
import { type EveEvalTurn } from "eve/evals";
import { satisfies } from "eve/evals/expect";
-import { parseToolErrorOutput, requireTaskView, waitForCompletedTask } from "./shared.js";
+import { requireTaskView, waitForCompletedTask, waitForTaskStatus } from "./shared.js";
import { defineTaskEval } from "./task-transition.js";
const FIRST_CALL_ID = "task-d6-success-first";
const FAILED_CALL_ID = "task-d6-failure-middle";
const THIRD_CALL_ID = "task-d6-success-third";
-/** A failed middle dispatch does not stop later siblings or enter the task index. */
+/** A failed middle dispatch does not stop later siblings from completing. */
export default defineTaskEval({
description:
- "An ordered success/failure/success fanout admits both siblings and excludes the failed start.",
+ "An ordered success/failure/success fanout admits every sibling and records the unreachable child as failed.",
transition: {
primary: "task.dispatch-batch.start.accepted-partial-failure",
dimensions: { transport: "mixed", parentPhase: "active" },
@@ -41,54 +41,21 @@ export default defineTaskEval({
receipts,
satisfies(
(values: readonly BackgroundReceipt[]) =>
- values.length === 2 &&
+ values.length === 3 &&
values.some(({ callId }) => callId === FIRST_CALL_ID) &&
+ values.some(({ callId }) => callId === FAILED_CALL_ID) &&
values.some(({ callId }) => callId === THIRD_CALL_ID) &&
- new Set(values.map(({ taskId }) => taskId)).size === 2,
- "first and third entries return distinct working task receipts",
+ new Set(values.map(({ taskId }) => taskId)).size === 3,
+ "every fanout entry returns a distinct working task receipt",
),
);
const firstTaskId = requireReceiptTaskId(receipts, FIRST_CALL_ID);
+ const failedTaskId = requireReceiptTaskId(receipts, FAILED_CALL_ID);
const thirdTaskId = requireReceiptTaskId(receipts, THIRD_CALL_ID);
- started.eventsSatisfy(
- "failed middle start has no task id, receipt, or index admission",
- (events) => {
- const failed = events.filter(
- (event) =>
- event.type === "action.result" &&
- event.data.result.kind === "tool-result" &&
- event.data.result.callId === FAILED_CALL_ID,
- );
- const event = failed[0];
- if (event?.type !== "action.result") return false;
- const result = event.data.result;
- if (result.kind !== "tool-result") return false;
- const output = parseToolErrorOutput(result.output);
- return (
- failed.length === 1 &&
- event.data.status === "failed" &&
- result.isError === true &&
- output !== null &&
- typeof output === "object" &&
- Reflect.get(output, "code") === "REMOTE_AGENT_START_FAILED" &&
- !Object.hasOwn(output, "taskId") &&
- !events.some(
- (event) => event.type === "subagent.called" && event.data.callId === FAILED_CALL_ID,
- ) &&
- !events.some(
- (event) =>
- event.type === "subagent.completed" &&
- event.data.callId === FAILED_CALL_ID &&
- event.data.backgroundTask !== undefined,
- )
- );
- },
- );
started.event("subagent.completed", {
- count: 1,
+ count: 2,
data: {
- backgroundTask: { status: "working", taskId: thirdTaskId },
- callId: THIRD_CALL_ID,
+ backgroundTask: { status: "working" },
subagentName: "busy-worker",
},
});
@@ -107,6 +74,14 @@ export default defineTaskEval({
thirdTaskId,
);
assertCompletedBusyWorker(thirdCompleted, thirdTaskId, "TASK-D6-THIRD-SUCCESS");
+ const failed = await waitForTaskStatus(
+ t,
+ t,
+ "TASK-D6-PARTIAL-FANOUT-UNKNOWN",
+ failedTaskId,
+ "failed",
+ );
+ assertFailedUnstartableWorker(failed, failedTaskId);
},
});
@@ -148,3 +123,24 @@ function assertCompletedBusyWorker(turn: EveEvalTurn, taskId: string, marker: st
throw new Error(`Task ${taskId} did not complete with marker ${marker}.`);
}
}
+
+function assertFailedUnstartableWorker(turn: EveEvalTurn, taskId: string): void {
+ turn.expectOk();
+ turn.messageIncludes("TASK-D6-UNKNOWN");
+ const view = requireTaskView(turn.requireToolCall("task_cancel").output, taskId);
+ const metadata = Reflect.get(view, "metadata");
+ const lastOutput = Reflect.get(view, "lastOutput");
+ if (
+ Reflect.get(view, "status") !== "failed" ||
+ metadata === null ||
+ typeof metadata !== "object" ||
+ Reflect.get(metadata, "kind") !== "subagent" ||
+ Reflect.get(metadata, "mode") !== "remote" ||
+ Reflect.get(metadata, "name") !== "unstartable-worker" ||
+ lastOutput === null ||
+ typeof lastOutput !== "object" ||
+ Reflect.get(lastOutput, "type") !== "error"
+ ) {
+ throw new Error(`Task ${taskId} did not fail with unstartable-worker metadata.`);
+ }
+}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts
index 2582bf40d..ea97b5e39 100644
--- a/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task.dispatch.start.rejected-unreachable.eval.ts
@@ -1,12 +1,12 @@
import { defineTaskEval } from "./task-transition.js";
-import { parseToolErrorOutput } from "./shared.js";
+import { requireBackgroundTaskId, requireTaskView, waitForTaskStatus } from "./shared.js";
const CALL_ID = "task-a3-unstartable-worker";
-/** A failed remote start never admits its prepared task or child session. */
+/** A failed remote start is recorded as the admitted background task's terminal state. */
export default defineTaskEval({
description:
- "An unreachable remote URL fails dispatch without exposing a receipt, task id, or child session.",
+ "An unreachable remote URL returns a task receipt, then fails that task without killing the parent.",
transition: {
primary: "task.dispatch.start.rejected-unreachable",
dimensions: { transport: "remote", parentPhase: "active" },
@@ -15,47 +15,67 @@ export default defineTaskEval({
const started = await t.send("TASK-A3-DISPATCH-START-FAILURE");
started.expectOk();
started.messageIncludes("TASK-A3-PARENT-SURVIVED");
- started.calledTool("unstartable-worker", {
+ started.event("subagent.completed", {
count: 1,
- output: isStartFailureWithoutTaskId,
- status: "failed",
- });
- started.eventsSatisfy(
- "failed start exposes no task id, receipt, child session, or index admission",
- (events) => {
- const failed = events.flatMap((event) =>
- event.type === "action.result" &&
- event.data.result.kind === "tool-result" &&
- event.data.result.callId === CALL_ID
- ? [event]
- : [],
- );
- const result = failed[0]?.data.result;
- return (
- failed.length === 1 &&
- failed[0]?.data.status === "failed" &&
- result?.kind === "tool-result" &&
- result.isError === true &&
- isStartFailureWithoutTaskId(result.output) &&
- !events.some(
- (event) =>
- event.type === "subagent.completed" &&
- event.data.callId === CALL_ID &&
- event.data.backgroundTask !== undefined,
- ) &&
- !events.some((event) => event.type === "subagent.called" && event.data.callId === CALL_ID)
- );
+ data: {
+ backgroundTask: { status: "working" },
+ callId: CALL_ID,
+ subagentName: "unstartable-worker",
},
- );
+ });
+ const taskId = requireBackgroundTaskId(started);
+ started.eventsSatisfy("unreachable start exposes one working task receipt", (events) => {
+ const completed = events.flatMap((event) =>
+ event.type === "action.result" &&
+ event.data.result.kind === "tool-result" &&
+ event.data.result.callId === CALL_ID
+ ? [event]
+ : [],
+ );
+ const result = completed[0]?.data.result;
+ const output = result?.output;
+ return (
+ completed.length === 1 &&
+ completed[0]?.data.status === "completed" &&
+ result?.kind === "tool-result" &&
+ output !== null &&
+ typeof output === "object" &&
+ Reflect.get(output, "status") === "working" &&
+ Reflect.get(output, "taskId") === taskId
+ );
+ });
+
+ const failed = await waitForTaskStatus(t, t, "TASK-A3-UNKNOWN-VERIFY", taskId, "failed");
+ failed.expectOk();
+ failed.messageIncludes("TASK-A3-UNKNOWN");
+ const view = requireTaskView(failed.requireToolCall("task_cancel").output, taskId);
+ if (
+ Reflect.get(view, "status") !== "failed" ||
+ !hasTaskMetadata(view, "unstartable-worker", "remote") ||
+ !hasErrorOutput(view)
+ ) {
+ throw new Error(`Task ${taskId} did not fail with remote unstartable-worker metadata.`);
+ }
},
});
-function isStartFailureWithoutTaskId(output: unknown): boolean {
- output = parseToolErrorOutput(output);
+function hasTaskMetadata(task: Record<string, unknown>, name: string, mode: string): boolean {
+ const metadata = Reflect.get(task, "metadata");
+ return (
+ metadata !== null &&
+ typeof metadata === "object" &&
+ Reflect.get(metadata, "kind") === "subagent" &&
+ Reflect.get(metadata, "mode") === mode &&
+ Reflect.get(metadata, "name") === name &&
+ typeof Reflect.get(metadata, "agentId") === "string"
+ );
+}
+
+function hasErrorOutput(task: Record<string, unknown>): boolean {
+ const lastOutput = Reflect.get(task, "lastOutput");
return (
- output !== null &&
- typeof output === "object" &&
- Reflect.get(output, "code") === "REMOTE_AGENT_START_FAILED" &&
- !Object.hasOwn(output, "taskId")
+ lastOutput !== null &&
+ typeof lastOutput === "object" &&
+ Reflect.get(lastOutput, "type") === "error"
);
}
diff --git a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts
index 6573dcc52..4a605574a 100644
--- a/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task.input.answer.accepted-complete.remote.eval.ts
@@ -60,9 +60,9 @@ export default defineTaskEval({
satisfies(
(task: Record<string, unknown>) =>
Reflect.get(task, "status") === "completed" &&
- hasRemoteMetadata(task) &&
+ hasRemoteSubagentMetadata(task) &&
hasRemotePrincipalOutput(task),
- "completed remote task retains remote mode and the HTTP child principal",
+ "completed remote task retains subagent identity and the HTTP child principal",
),
);
@@ -75,7 +75,7 @@ export default defineTaskEval({
},
});
-function hasRemoteMetadata(task: Record<string, unknown>): boolean {
+function hasRemoteSubagentMetadata(task: Record<string, unknown>): boolean {
const metadata = Reflect.get(task, "metadata");
return (
metadata !== null &&
diff --git a/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.ts
index 72c660d63..5a097d980 100644
--- a/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.ts
@@ -34,7 +34,7 @@ export default defineTaskEval({
(event) =>
event.type === "message.received" &&
messageText(event.data.message).includes(
- `Background task ${taskId} (agent) update: ${UPDATE}`,
+ `Background task ${taskId} (update-worker) update: ${UPDATE}`,
),
),
"parent receives the child update with its owning task identity",
diff --git a/packages/eve/extension-contracts/compatibility/channel/v13.ts b/packages/eve/extension-contracts/compatibility/channel/v13.ts
new file mode 100644
index 000000000..67e58f0bb
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v13.ts
@@ -0,0 +1,3 @@
+import { disableRoute } from "#public/channels/index.js";
+
+export default disableRoute();
diff --git a/packages/eve/extension-contracts/compatibility/connection/v11.ts b/packages/eve/extension-contracts/compatibility/connection/v11.ts
new file mode 100644
index 000000000..c9adb6c9f
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v11.ts
@@ -0,0 +1,6 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+export default defineMcpClientConnection({
+ description: "Call-aware MCP service",
+ url: "https://example.com/mcp",
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v15.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v15.ts
new file mode 100644
index 000000000..745446593
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v15.ts
@@ -0,0 +1,8 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineInstructions({ markdown: `Use session ${ctx.session.id} for correlation.` }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v14.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v14.ts
new file mode 100644
index 000000000..bd9ab80cf
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v14.ts
@@ -0,0 +1,11 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineSkill({
+ description: `Review session ${ctx.session.id}.`,
+ markdown: "# Review\n\nCheck each claim.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v22.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v22.ts
new file mode 100644
index 000000000..ddbbac129
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v22.ts
@@ -0,0 +1,18 @@
+import { z } from "zod";
+
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineTool({
+ description: "Echo the active session.",
+ inputSchema: z.object({ note: z.string() }),
+ execute: ({ note }, toolCtx) => ({
+ callId: toolCtx.callId,
+ note,
+ sessionId: ctx.session.id,
+ }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v17.ts b/packages/eve/extension-contracts/compatibility/hook/v17.ts
new file mode 100644
index 000000000..c32db5c59
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v17.ts
@@ -0,0 +1,9 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "subagent.completed"(event, ctx) {
+ console.info(event.data.subagentName, ctx.session.id);
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/schedule/v6.ts b/packages/eve/extension-contracts/compatibility/schedule/v6.ts
new file mode 100644
index 000000000..58d9be225
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/schedule/v6.ts
@@ -0,0 +1,8 @@
+import { defineSchedule } from "#public/schedules/index.js";
+
+export default defineSchedule({
+ cron: "0 0 * * *",
+ run({ waitUntil }) {
+ waitUntil(Promise.resolve());
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/subagent/v6.ts b/packages/eve/extension-contracts/compatibility/subagent/v6.ts
new file mode 100644
index 000000000..344e5db11
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/subagent/v6.ts
@@ -0,0 +1,6 @@
+import { defineAgent } from "#public/index.js";
+
+export default defineAgent({
+ description: "Delegate research tasks.",
+ model: "anthropic/claude-sonnet-5",
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v24.ts b/packages/eve/extension-contracts/compatibility/tool/v24.ts
new file mode 100644
index 000000000..c8dabaad9
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v24.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Start a durable report task.",
+ execution: "background",
+ inputSchema: z.object({ reportId: z.string() }),
+ execute(input, _ctx, task) {
+ return task.delegated({
+ executor: { data: { reportId: input.reportId }, kind: "report" },
+ receipt: { reportId: input.reportId },
+ });
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v14.json b/packages/eve/extension-contracts/reports/channel/v14.json
new file mode 100644
index 000000000..d289b5df8
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v14.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 14,
+ "sha256": "eb932e232bdefdbeb4358de8f7fecccddf67baed17e71d9fbed1555bead48e86",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v12.json b/packages/eve/extension-contracts/reports/connection/v12.json
new file mode 100644
index 000000000..2efcb4c87
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v12.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 12,
+ "sha256": "69d22d69b7411006d36686ec67df3de81a68be1ca8a5238bac04fce9ad50e8c7",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v16.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v16.json
new file mode 100644
index 000000000..527010ecb
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v16.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 16,
+ "sha256": "d6c2b727f1f02127f96aac31813529ebfd45067e549b30376dd88e8365234d78",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v15.json b/packages/eve/extension-contracts/reports/dynamicSkill/v15.json
new file mode 100644
index 000000000..c82ede1ef
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v15.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 15,
+ "sha256": "1a34d47ade9b8113e9db522945bea1f6c56fb3878031b4761129530da1ca6c21",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v23.json b/packages/eve/extension-contracts/reports/dynamicTool/v23.json
new file mode 100644
index 000000000..4e47383d9
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v23.json
@@ -0,0 +1,13 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 23,
+ "sha256": "902b3b37752e7d7e070b341c3833538e790b94a471cc191efd63cae7d9783c56",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v18.json b/packages/eve/extension-contracts/reports/hook/v18.json
new file mode 100644
index 000000000..c741a7518
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v18.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 18,
+ "sha256": "b276055c24897026f08cf33f7a9e5d53e1cd2fce14e2ece4efa11c5016dd9931",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v7.json b/packages/eve/extension-contracts/reports/schedule/v7.json
new file mode 100644
index 000000000..5e469e3cb
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v7.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 7,
+ "sha256": "591afc007ec146b159a16f1ba44fd99f666e531ad83d7b961be2ecd0e4059679",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/subagent/v7.json b/packages/eve/extension-contracts/reports/subagent/v7.json
new file mode 100644
index 000000000..3cd1c3d88
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/subagent/v7.json
@@ -0,0 +1,20 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "subagent",
+ "epoch": 7,
+ "sha256": "6fde9d4b8913773aa431c4bd986b90acfd3940be974ebb9c44c804bfd1daa958",
+ "exports": [
+ "AgentCompactionDefinition",
+ "AgentDefinition",
+ "AgentModelDefinition",
+ "AgentStaticModelDefinition",
+ "DefinedAgent",
+ "DynamicLocalSubagentDefinition",
+ "DynamicSubagentDefinition",
+ "RemoteAgentDefinition",
+ "RemoteAgentDefinitionInput",
+ "defineAgent",
+ "defineDynamic",
+ "defineRemoteAgent"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v25.json b/packages/eve/extension-contracts/reports/tool/v25.json
new file mode 100644
index 000000000..51bdb4793
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v25.json
@@ -0,0 +1,19 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 25,
+ "sha256": "880966f00df23ac59216283605e724e894d889c712c2f21db62253d9d3881401",
+ "exports": [
+ "defaultWebSearch",
+ "defineTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "isWebSearchToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch"
+ ]
+}
diff --git a/packages/eve/src/acp/adapter.test.ts b/packages/eve/src/acp/adapter.test.ts
index 3d50edf9a..9f43264f1 100644
--- a/packages/eve/src/acp/adapter.test.ts
+++ b/packages/eve/src/acp/adapter.test.ts
@@ -153,6 +153,13 @@ describe("EveAcpAdapter", () => {
data: {
actions: [
{ callId: "call-1", input: { city: "SF" }, kind: "tool-call", toolName: "weather" },
+ {
+ callId: "workflow-1",
+ input: { report: "weekly" },
+ kind: "workflow-tool-call",
+ toolName: "publish",
+ workflowId: "publish-workflow",
+ },
],
sequence: 3,
stepIndex: 0,
@@ -193,11 +200,13 @@ describe("EveAcpAdapter", () => {
"agent_message_chunk",
"agent_thought_chunk",
"tool_call",
+ "tool_call",
"tool_call_update",
]);
expect(notifications.slice(0, 2).map(({ params }) => (params as any).update.messageId)).toEqual(
["t1:message:0", "t1:thought:0"],
);
+ expect((notifications[3]!.params as any).update.title).toBe("publish");
expect(JSON.stringify(notifications)).not.toContain("secret");
});
diff --git a/packages/eve/src/acp/adapter.ts b/packages/eve/src/acp/adapter.ts
index 0c2769ff6..2813560f4 100644
--- a/packages/eve/src/acp/adapter.ts
+++ b/packages/eve/src/acp/adapter.ts
@@ -491,7 +491,7 @@ function promptContent(params: PromptRequest): Array<{ type: "text"; text: strin
function toolCallForAction(action: RuntimeActionRequest): ToolCall {
const title =
- action.kind === "tool-call"
+ action.kind === "tool-call" || action.kind === "workflow-tool-call"
? action.toolName
: action.kind === "load-skill"
? "Load skill"
diff --git a/packages/eve/src/channel/subagent-emitter.test.ts b/packages/eve/src/channel/subagent-emitter.test.ts
index 5a4ef7063..06646d6e7 100644
--- a/packages/eve/src/channel/subagent-emitter.test.ts
+++ b/packages/eve/src/channel/subagent-emitter.test.ts
@@ -4,7 +4,7 @@ import {
deserializeRuntimeAdapter,
} from "#runtime/channels/registry.js";
import type { ChannelAdapter } from "#channel/adapter.js";
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
describe("subagent adapter", () => {
it("round-trips durable delegation metadata through the ChannelKey codec", async () => {
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index b33fea57a..c84bd7091 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -5,6 +5,7 @@ import type { CancelTurnResult as ProtocolCancelTurnResult } from "#protocol/can
import type { RunMode } from "#shared/run-mode.js";
import type {
RuntimeSubagentChildResult,
+ RuntimeSubagentDispatchFailure,
RuntimeToolResultActionResult,
} from "#shared/action-types.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
@@ -13,7 +14,12 @@ import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
import type { JsonObject } from "#shared/json.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import type { ForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
-import type { TaskView } from "#tasks/types.js";
+import type {
+ TaskAgentRequestDelivery,
+ TaskAuthorizationEventDelivery,
+ TaskInputRequestDelivery,
+ TaskView,
+} from "#tasks/types.js";
export type { ContextAccessor } from "#context/key.js";
export type { ChannelInstrumentationProjection } from "#channel/instrumentation.js";
@@ -174,15 +180,11 @@ export interface DeliverPayload {
/** Framework-only task envelopes consumed before adapter/model delivery. */
readonly task?: {
/** Task HITL input-request batches for the parent's pre-model router. */
- readonly inputRequests?: readonly {
- readonly hookPayload: SubagentInputRequestHookPayload;
- readonly taskId: string;
- }[];
- /** Task authorization events projected through the parent channel. */
- readonly authorizationEvents?: readonly {
- readonly hookPayload: SubagentAuthorizationEventHookPayload;
- readonly taskId: string;
- }[];
+ readonly inputRequests?: readonly TaskInputRequestDelivery[];
+ /** Agent spawn/settlement requests a task-owned workflow run needs the parent to apply. */
+ readonly agentRequests?: readonly TaskAgentRequestDelivery[];
+ /** Task child authorization events re-emitted through the parent channel. */
+ readonly authorizationEvents?: readonly TaskAuthorizationEventDelivery[];
/** Terminal views cached before task-run retention expires. */
readonly views?: readonly TaskView[];
};
@@ -295,11 +297,16 @@ export interface ClearSessionHookPayload {
/**
* Results resumed back into a parked parent workflow by the work it
* dispatched: child-produced subagent results and authored workflow tool
- * results. Parent-produced dispatch results never travel through this hook.
+ * results. Workflow-owner dispatch failures use the same private reply hook so
+ * `agent()` can settle instead of waiting forever.
*/
export interface RuntimeActionResultHookPayload {
readonly kind: "runtime-action-result";
- readonly results: readonly (RuntimeSubagentChildResult | RuntimeToolResultActionResult)[];
+ readonly results: readonly (
+ | RuntimeSubagentChildResult
+ | RuntimeSubagentDispatchFailure
+ | RuntimeToolResultActionResult
+ )[];
}
/**
@@ -438,6 +445,8 @@ export interface SessionCapabilities {
*/
export interface RunInput {
readonly adapter: ChannelAdapter<any>;
+ /** Framework task that owns this run, when the run is a task executor. */
+ readonly taskId?: string;
/**
* Registered channel name for root sessions started from an authored
* channel route. Framework runs omit this and use their framework
@@ -517,12 +526,6 @@ export interface RunInput {
* for that axis.
*/
readonly limits?: RunSessionLimits;
- /**
- * Framework-owned depth of delegated local subagent sessions. Root sessions
- * omit this and are treated as depth 0; each local child receives
- * parent depth + 1.
- */
- readonly subagentDepth?: number;
/** Framework-owned metadata for a protocol-neutral external invocation. */
readonly externalInvocation?: {
readonly continuationToken: string;
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 9ff44ad74..b585ead80 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -257,14 +257,7 @@ const kernelEffect = z
action: z
.enum(["subagent-call", "task-update", "task-cancel", "workflow-tool-call"])
.optional(),
- audience: z.array(
- z.enum([
- "root-session",
- "delegated-task-child",
- "requires-request-input",
- "below-subagent-depth",
- ]),
- ),
+ audience: z.array(z.enum(["root-session", "delegated-task-child", "requires-request-input"])),
kind: z.enum(["request-input", "dispatch", "provider-tool"]),
sourceId: z.string(),
})
diff --git a/packages/eve/src/client/message-action-parts.ts b/packages/eve/src/client/message-action-parts.ts
index 27c95a5c2..eb913576a 100644
--- a/packages/eve/src/client/message-action-parts.ts
+++ b/packages/eve/src/client/message-action-parts.ts
@@ -102,6 +102,7 @@ export function normalizeActionRequest(action: RuntimeActionRequest): ActionDesc
toolName: "eve:load-skill",
};
case "tool-call":
+ case "workflow-tool-call":
return {
kind: "tool-call",
name: action.toolName,
diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.ts
index 7ac44aa3d..64208b596 100644
--- a/packages/eve/src/client/message-reducer.test.ts
+++ b/packages/eve/src/client/message-reducer.test.ts
@@ -204,6 +204,38 @@ describe("defaultMessageReducer", () => {
expect(data).toBe(settled);
});
+ it("projects workflow tool requests as named tool parts", () => {
+ const reducer = defaultMessageReducer();
+ const data = reduceServerEvents(reducer, reducer.initial(), [
+ createActionsRequestedEvent({
+ actions: [
+ {
+ callId: "call_publish",
+ input: { report: "weekly" },
+ kind: "workflow-tool-call",
+ toolName: "publish",
+ workflowId: "publish-workflow",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn_1",
+ }),
+ ]);
+
+ expect(data.messages[0]?.parts).toContainEqual({
+ input: { report: "weekly" },
+ state: "input-available",
+ stepIndex: 0,
+ toolCallId: "call_publish",
+ toolMetadata: {
+ eve: { inputRequest: undefined, kind: "tool-call", name: "publish" },
+ },
+ toolName: "publish",
+ type: "dynamic-tool",
+ });
+ });
+
it("removes an unfinished streamed tool input when the turn is cancelled", () => {
const reducer = defaultMessageReducer();
const data = reduceServerEvents(reducer, reducer.initial(), [
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 419876483..11a92dc78 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,34 +22,36 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 24,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24],
+ current: 25,
+ supported: [
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+ ],
dropped: { 15: "TaskExec replaces stageEffect with send" },
},
dynamicTool: {
- current: 22,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22],
+ current: 23,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
channel: {
- current: 13,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13],
+ current: 14,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
schedule: {
- current: 6,
- supported: [1, 2, 3, 4, 6],
+ current: 7,
+ supported: [1, 2, 3, 4, 6, 7],
dropped: {
5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
subagent: {
- current: 6,
- supported: [3, 4, 6],
+ current: 7,
+ supported: [3, 4, 6, 7],
dropped: {
1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",
2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",
@@ -57,16 +59,16 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 11,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 11],
+ current: 12,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
10: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
hook: {
- current: 17,
- supported: [10, 11, 12, 13, 14, 15, 17],
+ current: 18,
+ supported: [10, 11, 12, 13, 14, 15, 17, 18],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
2: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -82,16 +84,16 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
skill: { current: 1, supported: [1], dropped: {} },
dynamicSkill: {
- current: 14,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14],
+ current: 15,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15],
dropped: {
13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
instructions: { current: 2, supported: [1, 2], dropped: {} },
dynamicInstructions: {
- current: 15,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15],
+ current: 16,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16],
dropped: {
14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.ts
index df60495f1..90d380579 100644
--- a/packages/eve/src/compiler/manifest.test.ts
+++ b/packages/eve/src/compiler/manifest.test.ts
@@ -154,4 +154,19 @@ describe("compiled agent manifest v44", () => {
}),
).toThrow();
});
+
+ it("rejects the removed tasks field in compiled manifests", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const removedExperimentalConfig = { tasks: true } as unknown;
+
+ expect(() =>
+ compiledAgentManifestSchema.parse({
+ ...manifest,
+ config: {
+ ...manifest.config,
+ experimental: removedExperimentalConfig,
+ },
+ }),
+ ).toThrow();
+ });
});
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 568e34496..9cc208fce 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -608,7 +608,6 @@ const compiledAgentConfigBaseFields = {
experimental: z
.object({
instrumentationProviders: z.boolean().optional(),
- tasks: z.boolean().optional(),
workflow: compiledAgentWorkflowDefinitionSchema.optional(),
})
.strict()
@@ -1200,7 +1199,6 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiled
? undefined
: {
instrumentationProviders: config.experimental.instrumentationProviders,
- tasks: config.experimental.tasks,
workflow:
config.experimental.workflow === undefined
? undefined
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index 213d341fd..9113bcc0f 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -180,10 +180,6 @@ function normalizeExperimentalDefinition(
compiledExperimental.instrumentationProviders = experimental.instrumentationProviders;
}
- if (experimental.tasks !== undefined) {
- compiledExperimental.tasks = experimental.tasks;
- }
-
if (experimental.workflow !== undefined) {
compiledExperimental.workflow = {
world: experimental.workflow.world,
diff --git a/packages/eve/src/compiler/normalize-manifest-helpers.ts b/packages/eve/src/compiler/normalize-manifest-helpers.ts
index 39c2a9fbc..c0012f772 100644
--- a/packages/eve/src/compiler/normalize-manifest-helpers.ts
+++ b/packages/eve/src/compiler/normalize-manifest-helpers.ts
@@ -34,11 +34,6 @@ export function assertRootOnlyConfig(
`Workflow runtime configuration is only supported on the root agent config. Remove "experimental.workflow" from "${agentId}".`,
);
}
- if (config.experimental?.tasks !== undefined) {
- throw new Error(
- `Background tasks are only supported on the root agent config. Remove "experimental.tasks" from "${agentId}".`,
- );
- }
}
export function assertApplicationOverlayCanApplyToAllNodes(logicalPaths: readonly string[]): void {
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index 0e010e5c0..65f72e4a7 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -132,11 +132,7 @@ describe("compileAgentManifest source graph", () => {
const graph = await resolveRuntimeAgentGraph({ manifest: serialized, moduleMap });
expect(serialized.tools.find((tool) => tool.name === "agent")).toMatchObject({
- behavior: {
- availability: ["root-session"],
- handling: { action: "self-agent", kind: "dispatch" },
- },
- hasExecute: false,
+ hasExecute: true,
});
expect(serialized.tools.find((tool) => tool.name === "ask_question")).toMatchObject({
behavior: {
@@ -153,11 +149,11 @@ describe("compileAgentManifest source graph", () => {
hasExecute: false,
});
expect(graph.root.turnAgent.tools.find((tool) => tool.name === "agent")).toMatchObject({
- behavior: {
- handling: {
- kind: "dispatch",
- target: { kind: "self-agent-call", nodeId: "__root__", subagentName: "agent" },
- },
+ rootOnly: true,
+ task: {
+ nodeId: "__root__",
+ resultKind: "subagent",
+ workflowId: expect.stringContaining("subagentToolExecuteWorkflow"),
},
});
expect(graph.root.turnAgent.tools.find((tool) => tool.name === "web_search")).toMatchObject({
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index b41313982..eb0c85e2e 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -138,16 +138,6 @@ export async function compileAgentManifest(
owner: { kind: "application" },
});
- const allNodeManifests = [root.manifest, ...root.descendants.map((node) => node.agent)];
- const backgroundTool = allNodeManifests
- .flatMap((node) => node.tools)
- .find((tool) => tool.execution === "background");
- if (backgroundTool !== undefined && root.manifest.config.experimental?.tasks !== true) {
- throw new Error(
- `Background tool "${backgroundTool.name}" requires experimental.tasks: true in the root agent config.`,
- );
- }
-
const diagnosticsSummary = summarizeCompilerDiagnostics(diagnostics);
const subagents: CompiledSubagentNode[] = root.descendants.map((subagent) =>
subagent.configResolver === undefined
diff --git a/packages/eve/src/compiler/normalize-subagent.test.ts b/packages/eve/src/compiler/normalize-subagent.test.ts
new file mode 100644
index 000000000..804b831ac
--- /dev/null
+++ b/packages/eve/src/compiler/normalize-subagent.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+
+import { normalizeSubagentConfig } from "#compiler/normalize-subagent.js";
+import { defineAgent } from "#public/definitions/agent.js";
+import { defineRemoteAgent } from "#public/definitions/remote-agent.js";
+
+describe("normalizeSubagentConfig", () => {
+ it("normalizes a local agent definition as a subagent", () => {
+ const normalized = normalizeSubagentConfig(
+ defineAgent({
+ description: "Research deeply.",
+ model: "openai/gpt-5.5",
+ }),
+ "Invalid subagent.",
+ );
+
+ expect(normalized).toEqual({
+ definition: {
+ description: "Research deeply.",
+ model: "openai/gpt-5.5",
+ },
+ kind: "local",
+ });
+ });
+
+ it("normalizes a remote subagent", () => {
+ expect(
+ normalizeSubagentConfig(
+ defineRemoteAgent({
+ description: "Review remotely.",
+ url: "https://review.example.com",
+ }),
+ "Invalid subagent.",
+ ),
+ ).toMatchObject({ kind: "remote" });
+ });
+});
diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.ts
index 0a347b26a..da3ccf0b5 100644
--- a/packages/eve/src/compiler/normalize-subagent.ts
+++ b/packages/eve/src/compiler/normalize-subagent.ts
@@ -17,7 +17,10 @@ const ALLOWED_DYNAMIC_SUBAGENT_EVENTS = new Set<DynamicToolEventName>([
]);
export type NormalizedSubagentConfig =
- | { readonly kind: "local"; readonly definition: unknown }
+ | {
+ readonly kind: "local";
+ readonly definition: unknown;
+ }
| {
readonly build?: { readonly externalDependencies?: readonly string[] };
readonly eventNames: readonly DynamicToolEventName[];
diff --git a/packages/eve/src/compiler/subagent-execution.scenario.test.ts b/packages/eve/src/compiler/subagent-execution.scenario.test.ts
new file mode 100644
index 000000000..92877b150
--- /dev/null
+++ b/packages/eve/src/compiler/subagent-execution.scenario.test.ts
@@ -0,0 +1,55 @@
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { compileAgentManifest } from "#compiler/normalize-manifest.js";
+import { discoverAgent } from "#discover/discover-agent.js";
+import { useScenarioApp } from "#internal/testing/scenario-app.js";
+
+describe("subagent compilation", () => {
+ const scenarioApp = useScenarioApp();
+
+ it("compiles a local subagent without an execution selector", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts":
+ "export default { model: 'openai/gpt-5.5', modelContextWindowTokens: 200000 };\n",
+ "agent/subagents/researcher/agent.ts":
+ "export default { description: 'Research.', model: 'openai/gpt-5.5', modelContextWindowTokens: 200000 };\n",
+ },
+ name: "subagent-execution-edge",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ const manifest = await compileAgentManifest(discovered.manifest);
+ const child = manifest.subagents[0];
+
+ expect(child).not.toHaveProperty("execution");
+ if (child?.configResolver !== undefined) throw new Error("Expected a static child.");
+ expect(child?.agent.tools.map((tool) => tool.name)).toEqual(
+ expect.arrayContaining(["task_cancel", "task_update"]),
+ );
+ });
+
+ it("compiles a subagent without root configuration", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts":
+ "export default { model: 'openai/gpt-5.5', modelContextWindowTokens: 200000 };\n",
+ "agent/subagents/researcher/agent.ts":
+ "export default { description: 'Research.', model: 'openai/gpt-5.5', modelContextWindowTokens: 200000 };\n",
+ },
+ name: "subagent-execution-gate",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+
+ await expect(compileAgentManifest(discovered.manifest)).resolves.toMatchObject({
+ subagents: [expect.objectContaining({ name: "researcher" })],
+ });
+ });
+});
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
index df7057543..a402b3942 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
@@ -46,18 +46,9 @@ describe("dynamic subagent lifecycle", () => {
expect(buildDynamicSubagentTools(ctx)).toMatchObject([
{
- behavior: {
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
- },
- },
- description: "Research the request.",
+ description: expect.stringContaining("Research the request."),
name: "researcher",
+ resultKind: "subagent",
},
]);
expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toBeDefined();
@@ -94,6 +85,70 @@ describe("dynamic subagent lifecycle", () => {
expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toBeUndefined();
});
+ it("runs every dynamic local and remote selection in the background", async () => {
+ const ctx = createContext();
+ const created = createResolver({ eventNames: ["session.started", "turn.started"] });
+ const resolver: ResolvedDynamicSubagentResolver = {
+ ...created.resolver,
+ events: {
+ "session.started": () =>
+ defineAgent({
+ description: "Research in the background.",
+ model: "openai/gpt-5.5",
+ modelContextWindowTokens: 200_000,
+ }),
+ "turn.started": () =>
+ defineRemoteAgent({
+ description: "Review remotely.",
+ url: "https://review.example.com",
+ }),
+ },
+ };
+
+ await dispatchDynamicSubagentEvent({
+ ctx,
+ event: createSessionStartedEvent(),
+ messages: [],
+ resolvers: [resolver],
+ });
+ expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.resultKind).toBe("subagent");
+
+ await dispatchDynamicSubagentEvent({
+ ctx,
+ event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),
+ messages: [],
+ resolvers: [resolver],
+ });
+ expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ expect(buildDynamicSubagentTools(ctx)[0]?.resultKind).toBe("subagent");
+ });
+
+ it("exposes a dynamic selection without root configuration", async () => {
+ const ctx = createContext();
+ const created = createResolver();
+ const resolver: ResolvedDynamicSubagentResolver = {
+ ...created.resolver,
+ events: {
+ "session.started": () =>
+ defineAgent({
+ description: "Research in the background.",
+ model: "openai/gpt-5.5",
+ modelContextWindowTokens: 200_000,
+ }),
+ },
+ };
+
+ await dispatchDynamicSubagentEvent({
+ ctx,
+ event: createSessionStartedEvent(),
+ messages: [],
+ resolvers: [resolver],
+ });
+
+ expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ });
+
it("lets a turn-scoped agent config switch the subagent model", async () => {
const ctx = createContext();
const created = createResolver({
@@ -143,6 +198,25 @@ describe("dynamic subagent lifecycle", () => {
});
});
+ it("runs dynamic local selections in the background", async () => {
+ const ctx = createContext();
+ const selected = defineAgent({
+ description: "Research the request.",
+ model: "openai/gpt-5.5",
+ modelContextWindowTokens: 200_000,
+ });
+ const created = createResolver({ handler: () => selected });
+
+ await dispatchDynamicSubagentEvent({
+ ctx,
+ event: createSessionStartedEvent(),
+ messages: [],
+ resolvers: [created.resolver],
+ });
+
+ expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ });
+
it("exposes a remote subagent with the returned remote config", async () => {
const ctx = createContext();
const created = createResolver();
@@ -179,18 +253,9 @@ describe("dynamic subagent lifecycle", () => {
expect(buildDynamicSubagentTools(ctx)).toMatchObject([
{
- behavior: {
- handling: {
- kind: "dispatch",
- target: {
- kind: "remote-agent-call",
- nodeId: "subagents/researcher",
- remoteAgentName: "researcher",
- },
- },
- },
- description: "Research on the remote deployment.",
+ description: expect.stringContaining("Research on the remote deployment."),
name: "researcher",
+ resultKind: "subagent",
},
]);
expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toMatchObject({
@@ -214,6 +279,24 @@ describe("dynamic subagent lifecycle", () => {
);
});
+ it("runs dynamic remote selections in the background", async () => {
+ const ctx = createContext();
+ const remoteAgent = defineRemoteAgent({
+ description: "Research on the remote deployment.",
+ url: "https://research.example.com",
+ });
+ const created = createResolver({ handler: () => remoteAgent });
+
+ await dispatchDynamicSubagentEvent({
+ ctx,
+ event: createSessionStartedEvent(),
+ messages: [],
+ resolvers: [created.resolver],
+ });
+
+ expect(buildDynamicSubagentTools(ctx)[0]?.execution).toBe("background");
+ });
+
it("omits an invalid non-null result", async () => {
const ctx = createContext();
const { resolver } = createResolver({
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
index ad45a9291..d49d3ca82 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
@@ -6,14 +6,10 @@ import type { ContextReader } from "#context/key.js";
import {
SessionDynamicSubagentRuntimeRevisionKey,
SessionDynamicSubagentSelectionsKey,
- TasksEnabledKey,
TurnDynamicSubagentSelectionsKey,
type DurableDynamicSubagentSelection,
} from "#context/keys.js";
-import {
- createBackgroundSubagentHarnessDefinition,
- createHarnessDelegationToolDefinition,
-} from "#execution/delegation-tool.js";
+import { createPreparedWorkflowToolHarnessDefinition } from "#execution/tools/workflow/background.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { createLogger } from "#internal/logging.js";
import type { SessionStartedStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -173,11 +169,7 @@ export function buildDynamicSubagentTools(input: ContextReader): readonly Harnes
);
}
names.add(selection.prepared.name);
- tools.push(
- input.get(TasksEnabledKey) === true
- ? createBackgroundSubagentHarnessDefinition(selection.prepared)
- : createHarnessDelegationToolDefinition(selection.prepared),
- );
+ tools.push(createPreparedWorkflowToolHarnessDefinition(selection.prepared));
}
return tools;
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 70188aa85..d504493f4 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -116,8 +116,6 @@ export type SessionTraceSeed = SessionTraceContext;
export const SessionTraceSeedKey = new ContextKey<SessionTraceSeed>("eve.sessionTraceSeed");
export const OtelTraceEnabledKey = new ContextKey<boolean>("eve.otelTraceEnabled");
-export const SubagentDepthKey = new ContextKey<number>("eve.subagentDepth");
-
/**
* Session-level capability flags (see {@link SessionCapabilities}). Set
* on root runs by channel routes and inherited pointwise by subagent
@@ -250,9 +248,6 @@ export const StepDynamicToolMetadataKey = new ContextKey<readonly PersistedDynam
"eve.stepDynamicToolMetadata",
);
-/** Whether this turn executes subagent definitions as durable background tools. */
-export const TasksEnabledKey = new ContextKey<boolean>("eve.tasksEnabled");
-
export type DurableDynamicSubagentSelection =
| {
readonly agentConfig: DynamicSubagentAgentConfig;
diff --git a/packages/eve/src/evals/mock-model.ts b/packages/eve/src/evals/mock-model.ts
index b5ce87220..738a83550 100644
--- a/packages/eve/src/evals/mock-model.ts
+++ b/packages/eve/src/evals/mock-model.ts
@@ -1,7 +1,7 @@
import type { LanguageModel } from "ai";
import { MockLanguageModelV3 } from "ai/test";
-import { AGENTS_SNIPPET_LABEL } from "#harness/handles/prompt.js";
+import { AGENTS_SNIPPET_LABEL } from "#subagents/handles/prompt.js";
import { isPendingApprovalsSnippet } from "#harness/hitl/approval-prompt.js";
type GenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 77e8ff88d..6ca9497bd 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -6,7 +6,7 @@ import {
handleLegacyConnectionCallbackRequest,
} from "#execution/connections/callback-route.js";
import { handleActivityRequest } from "#execution/activity-route.js";
-import { handleSessionCallbackRequest } from "#execution/session-callback-route.js";
+import { handleSessionCallbackRequest } from "#subagents/callback-route.js";
import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
import {
handleWorkflowWebhookRequest,
diff --git a/packages/eve/src/execution/activity-work-id.ts b/packages/eve/src/execution/activity-work-id.ts
index d32b7b543..fc685751f 100644
--- a/packages/eve/src/execution/activity-work-id.ts
+++ b/packages/eve/src/execution/activity-work-id.ts
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
export function deriveRootTurnActivityWorkId(input: {
readonly sessionId: string;
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
deleted file mode 100644
index 449b04e4a..000000000
--- a/packages/eve/src/execution/agent-handle-dispatch.ts
+++ /dev/null
@@ -1,443 +0,0 @@
-/**
- * Continuation dispatch for stored agent handles.
- *
- * Owns the `agentId` leg of the runtime-action dispatch step: resolving a
- * model-supplied agentId against the session's handle store via
- * `prepareAgentContinuation`, delivering the follow-up message to the
- * address the running handle records, and resolving delivery failures as
- * dead (handle deleted) or retryable (handle restored to `parked`).
- */
-
-import type { ActivityObserverConfig, SessionAuthContext } from "#channel/types.js";
-import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import {
- getAgentHandleStore,
- type AgentAddress,
- type AgentHandle,
- type AgentIdentity,
- type ContinueOperation,
-} from "#harness/handles/store.js";
-import {
- prepareAgentContinuation,
- rejectAgentEffect,
- removeTaskAgentAddress,
-} from "#harness/handles/transitions.js";
-import type {
- RuntimeActionRequest,
- RuntimeRemoteAgentCallActionRequest,
- RuntimeSubagentCallActionRequest,
- RuntimeSubagentDispatchFailure,
-} from "#shared/action-types.js";
-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
-import {
- continueRemoteAgentSession,
- isAmbiguousRemoteAgentContinueError,
- isRetryableRemoteAgentContinueError,
- resolveRemoteAgentForAction,
-} from "#execution/remote-agent-dispatch.js";
-import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
-import type { hydrateDurableSession } from "#execution/session.js";
-import { normalizeRequestedOutputSchema } from "#execution/subagent-invocation.js";
-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
-import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
-import { createLogger, logError } from "#internal/logging.js";
-import { createEveCallbackRoutePath } from "#protocol/routes.js";
-import { err, ok, type Result } from "#shared/result.js";
-import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
-
-const log = createLogger("execution.agent-handle-dispatch");
-
-/** Runtime action kinds that may address an agent handle via `agentId`. */
-export type RuntimeAgentHandleAction =
- | RuntimeRemoteAgentCallActionRequest
- | RuntimeSubagentCallActionRequest;
-
-/** Narrows an action to the kinds that may carry an `agentId` continuation. */
-export function isAgentHandleAction(
- action: RuntimeActionRequest,
-): action is RuntimeAgentHandleAction {
- return action.kind === "subagent-call" || action.kind === "remote-agent-call";
-}
-
-/** Hydrated parent session snapshot threaded through dispatch. */
-export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;
-
-/**
- * Outcome of dispatching one planned runtime action: an adopted child ready
- * for the `subagent.called` emission tail, or a per-action error result.
- * Either way the (possibly updated) session snapshot rides along.
- *
- * `address` is the same confirmed {@link AgentAddress} recorded on the
- * child's running handle; consumers project it into wire shapes (e.g. the
- * flat `childSessionId` / `remote` fields of `subagent.called`) at the
- * emission site instead of this type re-encoding them.
- */
-export type DispatchOutcome =
- | {
- readonly address: AgentAddress;
- readonly callId: string;
- readonly kind: "called";
- readonly name: string;
- readonly session: RuntimeSession;
- readonly toolName: string;
- }
- | {
- readonly deliveryAmbiguous?: boolean;
- readonly kind: "error";
- readonly result: RuntimeSubagentDispatchFailure;
- readonly session: RuntimeSession;
- };
-
-/**
- * Delivers one `agentId` continuation to the child the handle names.
- *
- * Planning converts initially unknown ids into fresh starts, so an id that
- * matches no handle here disappeared mid-batch and reports
- * `AGENT_UNREACHABLE`. Name mismatches and busy handles report
- * `AGENT_MISMATCH` / `AGENT_BUSY` without touching the store. Delivery
- * failures report `AGENT_UNREACHABLE`: permanent ones resolve the handle as
- * dead, transient ones restore it to `parked` so the model can retry the
- * same agentId.
- */
-export async function dispatchToAgentHandle(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly activityObserver?: ActivityObserverConfig;
- readonly agentId: string;
- readonly auth: SessionAuthContext | null;
- readonly bundle: CompiledBundle;
- readonly currentSession: RuntimeSession;
- readonly parentToken: string;
- readonly parentTurnId: string;
-}): Promise<DispatchOutcome> {
- const { action, agentId, bundle } = input;
- const invokedName =
- action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;
- const operation: ContinueOperation = {
- callId: action.callId,
- id: deriveAgentOperationId({
- callId: action.callId,
- parentSessionId: input.currentSession.sessionId,
- parentTurnId: input.parentTurnId,
- }),
- kind: "continue",
- parentTurnId: input.parentTurnId,
- // Placeholder: prepareAgentContinuation records the handle's actual
- // pre-delivery status so a retryable rejection can restore it.
- previousStatus: "",
- };
- // Prepared against the in-progress session so a handle resolved earlier in
- // this batch is already gone.
- const prepared = prepareAgentContinuation(input.currentSession, {
- agentId,
- invokedName,
- operation,
- });
-
- switch (prepared.kind) {
- case "unknown":
- // Planning resolved this id against the store, so the handle was
- // deleted by an earlier action in this batch; no retry can reach it.
- return {
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_UNREACHABLE,
- message: `Agent with id "${agentId}" is no longer reachable.`,
- }),
- session: input.currentSession,
- };
- case "mismatch":
- return {
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_MISMATCH,
- message: `Agent "${agentId}" from the <agents> list does not belong to "${invokedName}".`,
- }),
- session: input.currentSession,
- };
- case "busy":
- return {
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_BUSY,
- message: `Agent "${agentId}" is still working on its previous request. Wait for its result before continuing it.`,
- }),
- session: input.currentSession,
- };
- case "ready":
- break;
- }
-
- const { handle } = prepared;
- // Not exactly-once: `prepareAgentContinuation` only moved the handle to
- // `running` on the step's working snapshot, which durably commits when the
- // enclosing dispatch step's result commits. If delivery succeeds and the
- // step dies before that commit, replay starts from `parked` and delivers
- // the same operation again — the same start-effect/step-commit window
- // accepted for child starts. The callee has no receiver-side dedup for
- // this; `prepareAgentContinuation` treating the recorded operation as a
- // replay only makes the parent-side transition idempotent.
- const delivery = await deliverToAgentAddress({
- action,
- activityObserver: input.activityObserver,
- address: handle.address,
- auth: input.auth,
- bundle,
- identity: handle.identity,
- parentToken: input.parentToken,
- });
- if (!delivery.ok) {
- const { cause, permanent } = delivery.error;
- logError(log, "agent delivery failed", cause, {
- agentId,
- callId: action.callId,
- nodeId: handle.identity.nodeId,
- permanent,
- subagentName: handle.identity.name,
- });
- // Only permanent failures resolve the handle as dead (forfeiting the
- // child's accumulated conversation); a transiently unreachable agent is
- // restored to `parked` so the model can retry the same agentId.
- return {
- deliveryAmbiguous: delivery.error.deliveryAmbiguous,
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_UNREACHABLE,
- message: permanent
- ? `Agent "${handle.identity.name}" with id "${agentId}" is no longer reachable.`
- : `Agent "${handle.identity.name}" with id "${agentId}" is temporarily unreachable. Try again.`,
- }),
- session: rejectAgentEffect(prepared.session, {
- disposition: permanent ? "dead" : "retryable",
- operationId: operation.id,
- }),
- };
- }
-
- return {
- address: handle.address,
- callId: action.callId,
- kind: "called",
- name: action.name,
- session: prepared.session,
- toolName: handle.identity.name,
- };
-}
-
-/** Delivers a tasks-mode continuation without creating a second lifecycle claim. */
-export async function dispatchToTaskAgentAddress(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly activityObserver?: ActivityObserverConfig;
- readonly agentId: string;
- readonly auth: SessionAuthContext | null;
- readonly bundle: CompiledBundle;
- readonly currentSession: RuntimeSession;
- readonly parentToken: string;
-}): Promise<DispatchOutcome> {
- const { action, agentId } = input;
- const invokedName =
- action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;
- const record = (getAgentHandleStore(input.currentSession.state)?.handles ?? []).find(
- (handle): handle is Extract<AgentHandle, { phase: "addressed" }> =>
- handle.phase === "addressed" && handle.identity.id === agentId,
- );
- if (record === undefined) {
- return {
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_UNREACHABLE,
- message: `Agent with id "${agentId}" is no longer reachable.`,
- }),
- session: input.currentSession,
- };
- }
- if (record.identity.name !== invokedName) {
- return {
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_MISMATCH,
- message: `Agent "${agentId}" from the <agents> list does not belong to "${invokedName}".`,
- }),
- session: input.currentSession,
- };
- }
-
- const delivery = await deliverToAgentAddress({
- action,
- activityObserver: input.activityObserver,
- address: record.address,
- auth: input.auth,
- bundle: input.bundle,
- identity: record.identity,
- parentToken: input.parentToken,
- });
- if (!delivery.ok) {
- const { cause, permanent } = delivery.error;
- logError(log, "task agent delivery failed", cause, {
- agentId,
- callId: action.callId,
- nodeId: record.identity.nodeId,
- permanent,
- subagentName: record.identity.name,
- });
- return {
- deliveryAmbiguous: delivery.error.deliveryAmbiguous,
- kind: "error",
- result: createAgentErrorResult({
- action,
- code: AGENT_UNREACHABLE,
- message: permanent
- ? `Agent "${record.identity.name}" with id "${agentId}" is no longer reachable.`
- : `Agent "${record.identity.name}" with id "${agentId}" is temporarily unreachable. Try again.`,
- }),
- session: permanent
- ? removeTaskAgentAddress(input.currentSession, agentId)
- : input.currentSession,
- };
- }
-
- return {
- address: record.address,
- callId: action.callId,
- kind: "called",
- name: action.name,
- session: input.currentSession,
- toolName: record.identity.name,
- };
-}
-
-/**
- * Attempts the continuation delivery once and classifies the failure.
- *
- * Transient failures are never retried automatically: the callee may have
- * accepted the message even though the response was lost, so a re-send could
- * deliver the same turn twice. The caller surfaces a retryable
- * AGENT_UNREACHABLE instead and the model decides whether to try again.
- * Throwing is equally unsafe — a durable-step retry would re-dispatch
- * already-started siblings.
- */
-async function deliverToAgentAddress(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly activityObserver?: ActivityObserverConfig;
- readonly address: AgentAddress;
- readonly auth: SessionAuthContext | null;
- readonly bundle: CompiledBundle;
- readonly identity: AgentIdentity;
- readonly parentToken: string;
-}): Promise<
- Result<
- void,
- { readonly cause: unknown; readonly deliveryAmbiguous: boolean; readonly permanent: boolean }
- >
-> {
- const { action, address, bundle, identity } = input;
-
- if (address.kind === "agent/remote") {
- let resolvedRemote;
- try {
- resolvedRemote = resolveRemoteAgentForAction({
- nodeId: identity.nodeId,
- remoteAgentName: identity.name,
- registry: bundle.subagentRegistry.subagentsByNodeId,
- });
- } catch (error) {
- // The agent's node is gone from the compiled bundle; no retry can
- // reach this handle again.
- return err({ cause: error, deliveryAmbiguous: false, permanent: true });
- }
- try {
- await continueRemoteAgentSession({
- activityObserver: input.activityObserver,
- auth: input.auth,
- callback: {
- callId: action.callId,
- subagentName: identity.name,
- taskId: readTaskIdFromInboxToken(input.parentToken),
- token: input.parentToken,
- url: createWorkflowCallbackUrl(
- address.callbackBaseUrl,
- createEveCallbackRoutePath(input.parentToken),
- ),
- },
- message: readSubagentMessage(action),
- outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),
- remote: { ...resolvedRemote, url: address.url },
- sessionId: address.sessionId,
- });
- } catch (error) {
- return err({
- cause: error,
- deliveryAmbiguous: isAmbiguousRemoteAgentContinueError(error),
- permanent: !isRetryableRemoteAgentContinueError(error),
- });
- }
- return ok(undefined);
- }
-
- const childRuntime = createWorkflowRuntime({
- compiledArtifactsSource: bundle.compiledArtifactsSource,
- nodeId: identity.nodeId,
- });
- try {
- const result = await childRuntime.dispatchSession({
- command: {
- auth: input.auth,
- caller: {
- activityObserver: input.activityObserver,
- callId: action.callId,
- replyTo: { kind: "hook", token: input.parentToken },
- subagentName: identity.name,
- taskId: readTaskIdFromInboxToken(input.parentToken),
- },
- kind: "send",
- payload: {
- message: readSubagentMessage(action),
- outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),
- },
- },
- sessionId: address.sessionId,
- });
- if (result.status === "session_not_active") {
- return err({
- cause: new Error(`Agent session "${address.sessionId}" is no longer active.`),
- deliveryAmbiguous: false,
- permanent: true,
- });
- }
- } catch (error) {
- const permanent = isRuntimeNoActiveSessionError(error);
- return err({ cause: error, deliveryAmbiguous: !permanent, permanent });
- }
- return ok(undefined);
-}
-
-export function createAgentErrorResult(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly code: string;
- readonly message: string;
-}): RuntimeSubagentDispatchFailure {
- return {
- callId: input.action.callId,
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: input.code,
- message: input.message,
- },
- subagentName:
- input.action.kind === "remote-agent-call"
- ? input.action.remoteAgentName
- : input.action.subagentName,
- };
-}
-
-function readSubagentMessage(action: RuntimeAgentHandleAction): string {
- return typeof action.input.message === "string" ? action.input.message : "";
-}
diff --git a/packages/eve/src/execution/agent-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.ts
index e52474864..1680ea873 100644
--- a/packages/eve/src/execution/agent-messaging.scenario.test.ts
+++ b/packages/eve/src/execution/agent-messaging.scenario.test.ts
@@ -18,7 +18,7 @@ const PARENT_RESULT = `PARENT_RECALLED=${CODEWORD}`;
const REMOTE_MEMORY_TOKEN = "remote-memory-scenario-token";
function createScriptedParentAgentSource(subagentName: string): string {
- const agentIdPattern = `<agent id="([^"]+)" name="${subagentName}">`;
+ const agentIdPattern = `<agent id="([^"]+)" name="${subagentName}"(?: [^>]*)?>`;
return `import { defineAgent } from "eve";
import { mockModel } from "eve/evals";
@@ -28,7 +28,7 @@ const SUBAGENT_NAME = ${JSON.stringify(subagentName)};
const AGENT_ID_PATTERN = new RegExp(${JSON.stringify(agentIdPattern)}, "u");
const model = mockModel((request) => {
- const childResults = request.toolResults.filter((result) => result.name === SUBAGENT_NAME);
+ const childResults = request.toolResults.filter((result) => result.name === "Workflow");
if (childResults.length === 0) {
return {
@@ -36,9 +36,9 @@ const model = mockModel((request) => {
{
id: "memory-exchange-1",
input: {
- message: \`Remember the codeword \${CODEWORD}. Confirm that you stored it.\`,
+ js: \`return await tools[\${JSON.stringify(SUBAGENT_NAME)}]({ message: \${JSON.stringify("Remember the codeword " + CODEWORD + ". Confirm that you stored it.")} });\`,
},
- name: SUBAGENT_NAME,
+ name: "Workflow",
},
],
};
@@ -58,10 +58,9 @@ const model = mockModel((request) => {
{
id: "memory-exchange-2",
input: {
- agentId,
- message: "What codeword did I ask you to remember? Reply with the codeword.",
+ js: \`return await tools[\${JSON.stringify(SUBAGENT_NAME)}]({ agentId: \${JSON.stringify(agentId)}, message: "What codeword did I ask you to remember? Reply with the codeword." });\`,
},
- name: SUBAGENT_NAME,
+ name: "Workflow",
},
],
};
@@ -139,6 +138,8 @@ const AGENT_MESSAGING_DESCRIPTOR: ScenarioAppDescriptor = {
"agent/agent.ts": createScriptedParentAgentSource("memory-child"),
"agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
"agent/instructions.md": "Run the scripted memory-child exchanges.\n",
+ "agent/tools/workflow.ts":
+ 'import { experimental_workflow } from "eve/tools/workflow";\nexport default experimental_workflow();\n',
"agent/subagents/memory-child/agent.ts": MEMORY_AGENT_SOURCE,
"agent/subagents/memory-child/instructions.md":
"Remember facts from earlier turns and answer follow-up questions from that history.\n",
@@ -164,6 +165,8 @@ function createRemoteAgentMessagingDescriptor(remoteUrl: string): ScenarioAppDes
"agent/agent.ts": createScriptedParentAgentSource("remote-memory-child"),
"agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
"agent/instructions.md": "Run the scripted remote-memory-child exchanges.\n",
+ "agent/tools/workflow.ts":
+ 'import { experimental_workflow } from "eve/tools/workflow";\nexport default experimental_workflow();\n',
"agent/subagents/remote-memory-child.ts": `import { defineRemoteAgent } from "eve";
import { bearer } from "eve/agents/auth";
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
index ab3460e55..b1ae34070 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
@@ -7,9 +7,9 @@ import {
cancelRemoteAgentTurn,
isRetryableRemoteAgentCancelError,
resolveRemoteAgentForAction,
-} from "#execution/remote-agent-dispatch.js";
+} from "#subagents/remote-dispatch.js";
import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#harness/handles/store.js";
+import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#subagents/handles/store.js";
import type { HarnessSession } from "#harness/types.js";
vi.mock("#context/serialize.js", () => ({
@@ -20,7 +20,7 @@ vi.mock("./workflow-runtime.js", () => ({
requestWorkflowTurnCancellation: vi.fn(),
}));
-vi.mock("./remote-agent-dispatch.js", () => ({
+vi.mock("../subagents/remote-dispatch.js", () => ({
cancelRemoteAgentTurn: vi.fn(),
isRetryableRemoteAgentCancelError: vi.fn(),
resolveRemoteAgentForAction: vi.fn(),
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.ts
index a6d940fb9..95586027b 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts
@@ -6,11 +6,11 @@ import {
cancelRemoteAgentTurn,
isRetryableRemoteAgentCancelError,
resolveRemoteAgentForAction,
-} from "#execution/remote-agent-dispatch.js";
-import { cancelToolRun } from "#execution/tool-run/cancel.js";
+} from "#subagents/remote-dispatch.js";
+import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";
import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import { getToolRuns, type ToolRunRecord } from "#harness/tool-runs.js";
-import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
+import { getWorkflowToolRuns, type WorkflowToolRunRecord } from "#harness/workflow-tool-runs.js";
+import { getAgentHandleStore, type AgentHandle } from "#subagents/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
@@ -24,7 +24,7 @@ const CANCEL_RETRY_INITIAL_DELAY_MS = 250;
const CANCEL_RETRY_MAX_DELAY_MS = 1_500;
const log = createLogger("execution.cancel-descendant-turns");
-type RunningAgentHandle = Extract<AgentHandle, { phase: "running" }>;
+type RunningAgentHandle = Extract<AgentHandle, { phase: "claimed" | "running" }>;
/**
* Cancels every running delegated child recorded in the agent handle store
@@ -37,13 +37,16 @@ export async function cancelDescendantTurnsStep(input: {
"use step";
let running: readonly RunningAgentHandle[];
- let toolRuns: readonly ToolRunRecord[];
+ let workflowToolRuns: readonly WorkflowToolRunRecord[];
try {
const session = await readDurableSession(input.sessionState);
+ workflowToolRuns = getWorkflowToolRuns(session.state);
+ const workflowOwnerIds = new Set(workflowToolRuns.map((run) => run.runId));
running = (getAgentHandleStore(session.state)?.handles ?? []).filter(
- (handle): handle is RunningAgentHandle => handle.phase === "running",
+ (handle): handle is RunningAgentHandle =>
+ handle.phase === "running" ||
+ (handle.phase === "claimed" && workflowOwnerIds.has(handle.ownerId)),
);
- toolRuns = getToolRuns(session.state);
} catch (error) {
logError(log, "failed to read pending descendants during cancellation", error, {
sessionId: input.sessionState.sessionId,
@@ -52,7 +55,9 @@ export async function cancelDescendantTurnsStep(input: {
}
await Promise.all(
- toolRuns.map((record) => cancelToolRun(record, "The turn that called the tool was cancelled.")),
+ workflowToolRuns.map((record) =>
+ cancelWorkflowToolRun(record, "The turn that called the tool was cancelled."),
+ ),
);
if (running.length === 0) return;
@@ -88,7 +93,7 @@ async function cancelLocalDescendant(input: {
});
if (final.status !== "accepted") {
log.warn("descendant cancel was never accepted; the child may run to completion", {
- callId: handle.operation.callId,
+ callId: readHandleCallId(handle),
childSessionId: handle.address.sessionId,
finalStatus: final.status,
subagentName: handle.identity.name,
@@ -96,7 +101,7 @@ async function cancelLocalDescendant(input: {
}
} catch (error) {
logError(log, "failed to cancel local descendant turn", error, {
- callId: handle.operation.callId,
+ callId: readHandleCallId(handle),
childSessionId: handle.address.sessionId,
subagentName: handle.identity.name,
});
@@ -135,7 +140,7 @@ async function cancelRemoteDescendant(input: {
});
if (final.status !== "accepted") {
log.warn("remote descendant cancel was never accepted; the child may run to completion", {
- callId: handle.operation.callId,
+ callId: readHandleCallId(handle),
childSessionId: handle.address.sessionId,
finalStatus: final.status,
remoteAgentName: handle.identity.name,
@@ -143,13 +148,17 @@ async function cancelRemoteDescendant(input: {
}
} catch (error) {
logError(log, "failed to cancel remote descendant turn", error, {
- callId: handle.operation.callId,
+ callId: readHandleCallId(handle),
childSessionId: handle.address.sessionId,
remoteAgentName: handle.identity.name,
});
}
}
+function readHandleCallId(handle: RunningAgentHandle): string | undefined {
+ return handle.phase === "running" ? handle.operation.callId : handle.callId;
+}
+
async function requestCancellationWithRetry(input: {
readonly request: () => Promise<CancelTurnResult>;
readonly shouldRetryError: (error: unknown) => boolean;
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
new file mode 100644
index 000000000..05be8e471
--- /dev/null
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -0,0 +1,283 @@
+/** Shared owner-side dispatch context preparation. */
+
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import type { ActivityObserverConfig } from "#channel/types.js";
+import { type ChannelAdapter, type ChannelAdapterContext } from "#channel/adapter.js";
+import {
+ ActivityObserverKey,
+ AuthKey,
+ CapabilitiesKey,
+ ChannelInstrumentationKey,
+ InitiatorAuthKey,
+ LocalDevRequestKey,
+ type LocalDevRequestProvenance,
+ ParentSessionKey,
+ SandboxKey,
+} from "#context/keys.js";
+import { ContextContainer } from "#context/container.js";
+import { withContextScope } from "#context/run-step.js";
+import {
+ BundleKey,
+ ChannelKey,
+ type CompiledBundle,
+} from "#runtime/sessions/runtime-context-keys.js";
+import { deserializeContext } from "#context/serialize.js";
+import type { RuntimeSession } from "#subagents/handle-dispatch.js";
+import { getAgentHandleStore } from "#subagents/handles/store.js";
+import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
+import {
+ assertUniqueCoordinationCallIds,
+ getPendingCoordinationBatch,
+ setPendingCoordinationBatch,
+} from "#harness/coordination.js";
+import { activeTurnId } from "#harness/active-turn-id.js";
+import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
+import type {
+ RuntimeActionResult,
+ RuntimeToolCallActionRequest,
+ RuntimeWorkflowTaskRequest,
+} from "#shared/action-types.js";
+import type { SessionParent } from "#channel/types.js";
+import {
+ createDurableSessionState,
+ type DurableSessionState,
+ readDurableSession,
+} from "#execution/durable-session-store.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { buildSubagentRunInput } from "#subagents/tool.js";
+import { readSessionTraceContext } from "#tracing/agent-trace-context-store.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+
+export type DispatchPlanEntry =
+ | { readonly kind: "task-control"; readonly action: RuntimeToolCallActionRequest }
+ | { readonly kind: "workflow-task"; readonly task: RuntimeWorkflowTaskRequest };
+
+/** Input shared by direct and Workflow-originated owner-side dispatch. */
+export interface CoordinationDispatchInput {
+ readonly callbackBaseUrl?: string;
+ /** Internal hook that receives child completion and HITL payloads. */
+ readonly parentContinuationToken?: string;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+/** Owner-side results plus any task-control work that still needs acknowledgement. */
+export interface CoordinationDispatchResult {
+ readonly results: readonly RuntimeActionResult[];
+ readonly sessionState: DurableSessionState;
+ readonly pendingTasks: readonly {
+ readonly taskInboxToken: string;
+ readonly taskId: string;
+ readonly taskRunId: string;
+ }[];
+}
+
+/** Everything preflight produces before either step's dispatch loop runs. */
+export interface PreparedCoordinationDispatch<PlanEntry = DispatchPlanEntry> {
+ readonly adapter: ChannelAdapter;
+ readonly adapterCtx: ChannelAdapterContext;
+ readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
+ readonly batch: DispatchBatch;
+ readonly bundle: CompiledBundle;
+ readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
+ readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ /** Number of local children sharing the parent's remaining token quota. */
+ readonly fanoutSize: number;
+ readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
+ readonly localDevRequest?: LocalDevRequestProvenance;
+ /** Lineage of the session running this dispatch, when it is itself a delegated child. */
+ readonly parentSession: SessionParent | undefined;
+ readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly activityObserver?: ActivityObserverConfig & {
+ readonly workIdentity: ActivityWorkIdentityV1;
+ };
+ readonly sandboxSessionId: string;
+ readonly serializedContext: Record<string, unknown>;
+ readonly plan: readonly PlanEntry[];
+ readonly session: RuntimeSession;
+ readonly sessionState: DurableSessionState;
+}
+
+/**
+ * Runs every dispatch precondition that may throw — durable reads, context
+ * deserialization, handle-store validation, and batch planning — before
+ * the caller acquires the parent stream writer, so a preflight failure
+ * never leaks the writer lock. Returns undefined when no actions are
+ * pending.
+ */
+export async function prepareCoordinationDispatch(input: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<PreparedCoordinationDispatch | undefined> {
+ const durableSession = await readDurableSession(input.sessionState);
+ const pending = getPendingCoordinationBatch(durableSession.state);
+
+ if (pending === undefined) return undefined;
+ const requests = [...pending.runtimeActions, ...pending.tasks];
+ if (requests.length === 0) return undefined;
+ const turnId = pending.event.turnId || activeTurnId(input.sessionState.emissionState);
+ const event = pending.event.turnId === turnId ? pending.event : { ...pending.event, turnId };
+ const ctx = await deserializeContext(input.serializedContext);
+ const prepared = await prepareActionDispatch({
+ batch: {
+ event,
+ localFanoutSize: pending.localFanoutSize,
+ requests,
+ },
+ ctx,
+ durableSession,
+ plan: () => planDispatch({ requests }),
+ serializedContext: input.serializedContext,
+ });
+ if (event === pending.event) {
+ return { ...prepared, sessionState: input.sessionState };
+ }
+
+ const session = setPendingCoordinationBatch({
+ ...pending,
+ event,
+ session: prepared.session,
+ });
+ return {
+ ...prepared,
+ session,
+ sessionState: createDurableSessionState({ session }),
+ };
+}
+
+type DispatchRequest = RuntimeToolCallActionRequest | RuntimeWorkflowTaskRequest;
+
+interface DispatchBatch {
+ readonly event: {
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
+ };
+ readonly localFanoutSize?: number;
+ readonly requests: readonly { readonly callId: string }[];
+}
+
+export async function prepareActionDispatch<PlanEntry>(input: {
+ readonly batch: DispatchBatch;
+ readonly ctx: ContextContainer;
+ readonly durableSession: Awaited<ReturnType<typeof readDurableSession>>;
+ readonly fanoutSize?: number;
+ readonly plan: (input: {
+ readonly bundle: CompiledBundle;
+ readonly ctx: ContextContainer;
+ readonly requests: DispatchBatch["requests"];
+ readonly session: RuntimeSession;
+ }) => readonly PlanEntry[];
+ readonly planSharesSandbox?: (input: {
+ readonly bundle: CompiledBundle;
+ readonly plan: readonly PlanEntry[];
+ }) => boolean;
+ readonly serializedContext: Record<string, unknown>;
+}): Promise<Omit<PreparedCoordinationDispatch<PlanEntry>, "sessionState">> {
+ const { batch, durableSession } = input;
+ assertUniqueCoordinationCallIds(batch.requests);
+
+ const ctx = input.ctx;
+ const bundle = ctx.require(BundleKey);
+ const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
+ let session = hydrateDurableSession({
+ compactionOverrides: {
+ thresholdPercent: effectiveAgent.thresholdPercent,
+ },
+ durable: durableSession,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ const adapter = ctx.require(ChannelKey);
+
+ // A corrupt handle store and rejected actions must resolve before sandbox
+ // initialization, which can provision backend resources and run onSession.
+ getAgentHandleStore(durableSession.state);
+ const plan = input.plan({
+ bundle,
+ ctx,
+ requests: batch.requests,
+ session,
+ });
+
+ const sandboxSessionId = resolveActiveSandboxSessionId(adapter.state, session.sessionId);
+ if (input.planSharesSandbox?.({ bundle, plan }) === true) {
+ try {
+ const scoped = await withContextScope(ctx, session, async (enrichedSession) => {
+ await ctx.require(SandboxKey).get();
+ return { result: undefined, session: enrichedSession };
+ });
+ session = scoped.session;
+ } finally {
+ ctx.clearVirtualContext();
+ }
+ }
+
+ return {
+ adapter,
+ adapterCtx: buildAdapterContext(adapter, ctx),
+ auth: ctx.get(AuthKey) ?? null,
+ batch,
+ bundle,
+ capabilities: ctx.get(CapabilitiesKey),
+ channelMetadata: ctx.get(ChannelInstrumentationKey),
+ fanoutSize: input.fanoutSize ?? batch.localFanoutSize ?? 0,
+ initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
+ localDevRequest: ctx.get(LocalDevRequestKey),
+ parentSession: ctx.get(ParentSessionKey),
+ parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
+ plan,
+ activityObserver: resolvePreparedActivity(
+ ctx.get(ActivityObserverKey),
+ session,
+ batch.event.turnId,
+ ),
+ sandboxSessionId,
+ serializedContext: input.serializedContext,
+ session,
+ };
+}
+
+function resolvePreparedActivity(
+ activityObserver: ActivityObserverConfig | undefined,
+ session: RuntimeSession,
+ turnId: string,
+): (ActivityObserverConfig & { readonly workIdentity: ActivityWorkIdentityV1 }) | undefined {
+ if (activityObserver === undefined) return undefined;
+ return {
+ sink: activityObserver.sink,
+ workIdentity: activityObserver.workIdentity ?? {
+ id: deriveRootTurnActivityWorkId({ sessionId: session.sessionId, turnId }),
+ kind: "root-turn",
+ rootSessionId: session.rootSessionId ?? session.sessionId,
+ rootTurnId: turnId,
+ sessionId: session.sessionId,
+ turnId,
+ },
+ };
+}
+
+function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string): string {
+ if (typeof adapterState !== "object" || adapterState === null) return sessionId;
+ const value = (adapterState as Record<string, unknown>).sandboxSessionId;
+ return typeof value === "string" && value.length > 0 ? value : sessionId;
+}
+
+function planDispatch(input: {
+ readonly requests: readonly DispatchRequest[];
+}): DispatchPlanEntry[] {
+ return input.requests.map((request): DispatchPlanEntry => {
+ if (request.kind === "tool-call") {
+ if (!isTaskControlAction(request)) {
+ throw new Error(`Unsupported task control "${request.toolName}".`);
+ }
+ return { action: request, kind: "task-control" };
+ }
+ if (request.kind === "workflow-task") {
+ return { kind: "workflow-task", task: request };
+ }
+ const unsupported = request as { readonly kind?: unknown };
+ throw new Error(`Unsupported coordination request "${String(unsupported.kind)}".`);
+ });
+}
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
new file mode 100644
index 000000000..634a9e76c
--- /dev/null
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -0,0 +1,198 @@
+/** Starts workflow-tool runs for pending blocking actions from either source. */
+
+import { deserializeContext } from "#context/serialize.js";
+import {
+ prepareCoordinationDispatch,
+ type CoordinationDispatchInput,
+ type CoordinationDispatchResult,
+} from "#execution/coordination-dispatch-shared.js";
+import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import { hydrateDurableSession } from "#execution/session.js";
+import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";
+import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
+import { deliverTaskUpdate } from "#execution/tasks/child/update.js";
+import { startWorkflowTask } from "#execution/tools/workflow/start.js";
+import { setPendingCoordinationBatch } from "#harness/coordination.js";
+import {
+ getPendingWorkflowInterrupt,
+ setPendingWorkflowUsedCalls,
+} from "#harness/workflow-interrupt-state.js";
+import {
+ planWorkflowSubagentDispatch,
+ type WorkflowSubagentDispatchPlan,
+} from "#harness/workflow-subagent-limit.js";
+import { buildWorkflowTasksFromInterrupt } from "#harness/workflow-task-state.js";
+import { createLogger } from "#internal/logging.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import type {
+ RuntimeActionResult,
+ RuntimeSubagentDispatchFailure,
+ RuntimeWorkflowTaskRequest,
+} from "#shared/action-types.js";
+
+const workflowTaskLog = createLogger("execution.dispatch-workflow-tasks");
+
+type CoordinationDispatchStepInput = CoordinationDispatchInput & {
+ readonly action: "park" | "dispatch-workflow-tasks";
+};
+
+export async function dispatchCoordinationStep(
+ input: CoordinationDispatchStepInput,
+): Promise<CoordinationDispatchResult> {
+ "use step";
+
+ // Model-driven actions already have a coordination batch. Dynamic Workflow
+ // tasks first need their interrupt lowered into that same representation.
+ const normalized =
+ input.action === "dispatch-workflow-tasks"
+ ? await normalizeWorkflowTaskInterrupt(input)
+ : { results: [], sessionState: input.sessionState };
+ const prepared = await prepareCoordinationDispatch({
+ serializedContext: input.serializedContext,
+ sessionState: normalized.sessionState,
+ });
+ if (prepared === undefined) {
+ return {
+ results: normalized.results,
+ sessionState: normalized.sessionState,
+ pendingTasks: [],
+ };
+ }
+
+ const { batch, session } = prepared;
+ let nextSession = session;
+ const results: RuntimeActionResult[] = [];
+ const pendingTasks: BackgroundTask[] = [];
+
+ for (const entry of prepared.plan) {
+ if (entry.kind === "workflow-task") {
+ const started = await startWorkflowTask({
+ auth: prepared.auth,
+ batchEvent: batch.event,
+ initiatorAuth: prepared.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken ?? session.continuationToken,
+ parentSession: prepared.parentSession,
+ session: nextSession,
+ task: entry.task,
+ });
+ nextSession = started.session;
+ if (started.result !== undefined) results.push(started.result);
+ continue;
+ }
+ if (entry.kind === "task-control") {
+ const control = await executeTaskControlAction({
+ action: entry.action,
+ adapter: prepared.adapter,
+ bundle: prepared.bundle,
+ cancelOwnedWork: cancelBackgroundAgentTask,
+ deliverUpdate: deliverTaskUpdate,
+ parentStepIndex: batch.event.stepIndex,
+ parentTurnId: batch.event.turnId,
+ serializedContext: prepared.serializedContext,
+ session: nextSession,
+ });
+ nextSession = control.session;
+ if (control.pendingTask !== undefined) pendingTasks.push(control.pendingTask);
+ results.push(control.result);
+ continue;
+ }
+ }
+
+ return {
+ results: [...results, ...normalized.results],
+ sessionState:
+ nextSession === session
+ ? prepared.sessionState
+ : createDurableSessionState({ session: nextSession }),
+ pendingTasks,
+ };
+}
+
+async function normalizeWorkflowTaskInterrupt(input: CoordinationDispatchInput): Promise<{
+ readonly results: readonly RuntimeActionResult[];
+ readonly sessionState: CoordinationDispatchInput["sessionState"];
+}> {
+ const durableSession = await readDurableSession(input.sessionState);
+ const pending = getPendingWorkflowInterrupt(durableSession.state);
+ if (pending === undefined) {
+ return { results: [], sessionState: input.sessionState };
+ }
+
+ const tasks = buildWorkflowTasksFromInterrupt(pending.interrupt);
+ if (tasks.length === 0) {
+ return { results: [], sessionState: input.sessionState };
+ }
+
+ const ctx = await deserializeContext(input.serializedContext);
+ const bundle = ctx.require(BundleKey);
+ const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
+ const plan = planWorkflowSubagentDispatch({
+ tasks,
+ maxSubagents: durableSession.workflowMaxSubagents,
+ usedCalls: pending.usedCalls,
+ });
+ const blockedResults = plan.blocked.map((action) => {
+ workflowTaskLog.warn("workflow subagent limit reached; blocking delegated call", {
+ callId: action.callId,
+ maxSubagents: plan.maxSubagents,
+ subagentName: getWorkflowTaskName(action),
+ usedCalls: plan.usedCalls,
+ });
+ return createWorkflowSubagentLimitResult({ action, plan });
+ });
+
+ if (plan.allowed.length === 0) {
+ return { results: blockedResults, sessionState: input.sessionState };
+ }
+
+ const session = hydrateDurableSession({
+ compactionOverrides: {
+ thresholdPercent: effectiveAgent.thresholdPercent,
+ },
+ durable: durableSession,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ const sessionWithUsage = setPendingWorkflowUsedCalls({
+ session,
+ usedCalls:
+ pending.usedCalls + plan.allowed.filter((task) => task.resultKind === "subagent").length,
+ });
+ const sessionWithBatch = setPendingCoordinationBatch({
+ runtimeActions: [],
+ tasks: plan.allowed,
+ event: { sequence: 0, stepIndex: 0, turnId: "workflow-dispatch" },
+ responseMessages: [],
+ session: sessionWithUsage,
+ });
+
+ return {
+ results: blockedResults,
+ sessionState: createDurableSessionState({ session: sessionWithBatch }),
+ };
+}
+
+function createWorkflowSubagentLimitResult(input: {
+ readonly action: RuntimeWorkflowTaskRequest;
+ readonly plan: WorkflowSubagentDispatchPlan;
+}): RuntimeSubagentDispatchFailure {
+ const subagentName = getWorkflowTaskName(input.action);
+
+ return {
+ callId: input.action.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: "WORKFLOW_SUBAGENT_LIMIT_REACHED",
+ maxSubagents: input.plan.maxSubagents,
+ message: `Workflow subagent limit reached (${String(input.plan.maxSubagents)}); "${subagentName}" was not called.`,
+ },
+ subagentName,
+ };
+}
+
+function getWorkflowTaskName(action: RuntimeWorkflowTaskRequest): string {
+ return action.resultKind === "subagent" ? action.toolName : action.kind;
+}
diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.ts
index 0a67d068a..9c997ee96 100644
--- a/packages/eve/src/execution/create-session-step.test.ts
+++ b/packages/eve/src/execution/create-session-step.test.ts
@@ -22,7 +22,7 @@ describe("createSessionStep", () => {
it("adds task_update guidance to a task-owned session system prompt", async () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
resolvedAgent: {
- config: { experimental: { tasks: true } },
+ config: {},
},
turnAgent: {
...TestTurnAgent,
@@ -48,11 +48,12 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
sessionId: "sess-child",
- taskOwned: true,
+ taskId: "task-1",
});
expect(state.snapshot?.session.agent.system).toContain("Background task updates");
expect(state.snapshot?.session.agent.system).toContain("what you are currently doing");
+ expect(state.snapshot?.session.taskId).toBe("task-1");
expect(state.snapshot?.session.state).toBeUndefined();
});
@@ -68,7 +69,7 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
sessionId: "sess-child",
- taskOwned: true,
+ taskId: "task-1",
});
expect(state.snapshot?.session.agent.system).not.toContain("Background task updates");
@@ -105,8 +106,8 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
inheritedLimits: { maxInputTokensPerSession: 3_000_000, maxOutputTokensPerSession: false },
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
});
expect(state.snapshot?.session.limits).toEqual({
@@ -126,8 +127,8 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
inheritedLimits: { maxInputTokensPerSession: false, maxOutputTokensPerSession: false },
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
});
expect(state.snapshot?.session.limits).toEqual({});
@@ -147,8 +148,8 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
inheritedLimits: { maxInputTokensPerSession: 2_000_000, maxOutputTokensPerSession: false },
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
});
expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(2_000_000);
@@ -168,8 +169,8 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
inheritedLimits: { maxInputTokensPerSession: 2_000_000, maxOutputTokensPerSession: false },
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
});
expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(1_000_000);
@@ -189,8 +190,8 @@ describe("createSessionStep", () => {
compiledArtifactsSource: { kind: "bundled" },
continuationToken: "subagent:test",
inheritedLimits: { maxInputTokensPerSession: 500_000, maxOutputTokensPerSession: false },
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
});
expect(state.snapshot?.session.limits?.maxInputTokensPerSession).toBe(500_000);
diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.ts
index b95f555bf..7401ea2d1 100644
--- a/packages/eve/src/execution/create-session-step.ts
+++ b/packages/eve/src/execution/create-session-step.ts
@@ -13,7 +13,7 @@ import type { RunSessionLimits } from "#channel/types.js";
import type { JsonObject } from "#shared/json.js";
import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
-import { TASK_UPDATE_SESSION_INSTRUCTION } from "#execution/tasks/child/instructions.js";
+import { TASK_UPDATE_SESSION_INSTRUCTION } from "#tools/framework/task-update.js";
/**
* Result returned by {@link createSessionStep}.
@@ -40,8 +40,7 @@ export async function createSessionStep(input: {
readonly nodeId?: string;
readonly rootSessionId?: string;
readonly sessionId: string;
- readonly subagentDepth?: number;
- readonly taskOwned?: boolean;
+ readonly taskId?: string;
}): Promise<CreateSessionStepResult> {
"use step";
@@ -54,8 +53,7 @@ export async function createSessionStep(input: {
input.dynamicSubagentAgentConfig,
);
const taskUpdatesEnabled =
- input.taskOwned === true &&
- bundle.resolvedAgent.config?.experimental?.tasks === true &&
+ input.taskId !== undefined &&
effectiveAgent.turnAgent.tools.some(
(tool) =>
tool.kind === "authored-tool" &&
@@ -87,8 +85,8 @@ export async function createSessionStep(input: {
outputSchema: input.outputSchema,
rootSessionId: input.rootSessionId,
sessionId: input.sessionId,
- subagentDepth: input.subagentDepth,
systemPromptAdditions: taskUpdatesEnabled ? [TASK_UPDATE_SESSION_INSTRUCTION] : undefined,
+ taskId: input.taskId,
turnAgent: effectiveAgent.turnAgent,
workflowMaxSubagents: bundle.resolvedAgent.workflowTool?.maxSubagents,
});
diff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.ts
deleted file mode 100644
index e2763cd17..000000000
--- a/packages/eve/src/execution/delegation-tool.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
-import { defineSubagent } from "#execution/tools/subagent/local.js";
-import { defineRemoteSubagent } from "#execution/tools/subagent/remote.js";
-import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";
-import type { PreparedDispatchTarget } from "#tools/behavior.js";
-import {
- UNSPECIFIED_INPUT_SCHEMA,
- toInputSchema,
- toOutputSchema,
- type ToolSchemaSource,
-} from "#tools/schema.js";
-
-type HarnessDelegationTool = Pick<
- PreparedRuntimeDelegationTool,
- "behavior" | "description" | "name"
-> & {
- readonly inputSchema?: ToolSchemaSource | null;
- readonly outputSchema?: ToolSchemaSource | null;
-};
-
-type AgentDispatchTarget = Extract<
- PreparedDispatchTarget,
- {
- readonly kind: "remote-agent-call" | "self-agent-call" | "subagent-call";
- }
->;
-
-export function createHarnessDelegationToolDefinition(
- tool: HarnessDelegationTool,
-): HarnessToolDefinition {
- return {
- behavior: tool.behavior,
- description: tool.description ?? "",
- inputSchema: toInputSchema(tool.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,
- name: tool.name,
- outputSchema: toOutputSchema(tool.outputSchema) ?? undefined,
- };
-}
-
-export function createBackgroundSubagentHarnessDefinition(
- tool: HarnessDelegationTool,
-): HarnessToolDefinition {
- const target = tool.behavior?.handling;
- if (target?.kind !== "dispatch") {
- throw new Error(`Background subagent tool "${tool.name}" has no prepared dispatch target.`);
- }
- if (
- target.target.kind === "task-cancel" ||
- target.target.kind === "task-update" ||
- target.target.kind === "workflow-tool-call"
- ) {
- throw new Error(
- `Background subagent tool "${tool.name}" cannot dispatch ${target.target.kind}.`,
- );
- }
- const definition = createBackgroundSubagentDefinition({
- description: tool.description ?? "",
- name: tool.name,
- target: target.target,
- });
- const execute = createToolExecuteWithAuth({
- execute: definition.execute,
- execution: definition.execution,
- scope: tool.name,
- });
- return {
- behavior: tool.behavior,
- description: definition.description,
- execute,
- execution: definition.execution,
- inputSchema: toInputSchema(definition.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,
- name: tool.name,
- outputSchema: toOutputSchema(definition.outputSchema) ?? undefined,
- };
-}
-
-function createBackgroundSubagentDefinition(input: {
- readonly description: string;
- readonly name: string;
- readonly target: AgentDispatchTarget;
-}) {
- switch (input.target.kind) {
- case "remote-agent-call":
- return defineRemoteSubagent({
- description: input.description,
- name: input.name,
- target: input.target,
- });
- case "self-agent-call":
- case "subagent-call":
- return defineSubagent({
- description: input.description,
- name: input.name,
- target: input.target,
- });
- }
-}
diff --git a/packages/eve/src/execution/deliver-payloads.test.ts b/packages/eve/src/execution/deliver-payloads.test.ts
index 6ca529bef..a1f8b1e82 100644
--- a/packages/eve/src/execution/deliver-payloads.test.ts
+++ b/packages/eve/src/execution/deliver-payloads.test.ts
@@ -61,4 +61,54 @@ describe("coalesceDeliverPayloads", () => {
preservedAdapterMetadata: { source: "synthetic-callback" },
});
});
+
+ it("preserves task agent requests and authorization events across queued payloads", () => {
+ const agentRequests = [
+ {
+ replyTo: "agent-reply-1",
+ request: {
+ input: { message: "Find it", target: "first" },
+ invocationId: "call-1:first",
+ kind: "agent-invoke" as const,
+ },
+ taskId: "task-1",
+ },
+ {
+ replyTo: "agent-reply-2",
+ request: {
+ input: { message: "Find it", target: "second" },
+ invocationId: "call-2:second",
+ kind: "agent-invoke" as const,
+ },
+ taskId: "task-2",
+ },
+ ];
+ const authorizationEvents = [1, 2].map((index) => ({
+ hookPayload: {
+ callId: `call-${index}`,
+ childSessionId: `child-${index}`,
+ event: { data: { index }, type: "authorization.required" } as never,
+ kind: "subagent-authorization-event" as const,
+ subagentName: `agent-${index}`,
+ },
+ taskId: `task-${index}`,
+ }));
+
+ expect(
+ coalesceDeliverPayloads([
+ {
+ task: {
+ agentRequests: [agentRequests[0]!],
+ authorizationEvents: [authorizationEvents[0]!],
+ },
+ },
+ {
+ task: {
+ agentRequests: [agentRequests[1]!],
+ authorizationEvents: [authorizationEvents[1]!],
+ },
+ },
+ ]),
+ ).toEqual({ task: { agentRequests, authorizationEvents } });
+ });
});
diff --git a/packages/eve/src/execution/deliver-payloads.ts b/packages/eve/src/execution/deliver-payloads.ts
index 2f4940fff..d674aa80d 100644
--- a/packages/eve/src/execution/deliver-payloads.ts
+++ b/packages/eve/src/execution/deliver-payloads.ts
@@ -19,12 +19,14 @@ export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): De
const merged: Record<string, unknown> = {};
const inputRequests: NonNullable<TaskEnvelope["inputRequests"]>[number][] = [];
+ const agentRequests: NonNullable<TaskEnvelope["agentRequests"]>[number][] = [];
const authorizationEvents: NonNullable<TaskEnvelope["authorizationEvents"]>[number][] = [];
const views: NonNullable<TaskEnvelope["views"]>[number][] = [];
let turnInput: StepInput = {};
for (const payload of payloads) {
inputRequests.push(...(payload.task?.inputRequests ?? []));
+ agentRequests.push(...(payload.task?.agentRequests ?? []));
authorizationEvents.push(...(payload.task?.authorizationEvents ?? []));
views.push(...(payload.task?.views ?? []));
for (const [key, value] of Object.entries(payload)) {
@@ -41,6 +43,7 @@ export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): De
const task: Record<string, unknown> = {};
if (inputRequests.length > 0) task.inputRequests = inputRequests;
+ if (agentRequests.length > 0) task.agentRequests = agentRequests;
if (authorizationEvents.length > 0) task.authorizationEvents = authorizationEvents;
if (views.length > 0) task.views = views;
if (Object.keys(task).length > 0) merged.task = task;
diff --git a/packages/eve/src/execution/dispatch-action-failures.ts b/packages/eve/src/execution/dispatch-action-failures.ts
index d2b357aae..d5e866b66 100644
--- a/packages/eve/src/execution/dispatch-action-failures.ts
+++ b/packages/eve/src/execution/dispatch-action-failures.ts
@@ -1,13 +1,13 @@
-import { REMOTE_AGENT_START_FAILED } from "#harness/agent-handle-errors.js";
+import { REMOTE_AGENT_START_FAILED } from "#subagents/agent-handle-errors.js";
import type {
- RuntimeRemoteAgentCallActionRequest,
- RuntimeSubagentCallActionRequest,
+ RuntimeRemoteAgentDispatchRequest,
+ RuntimeSubagentDispatchRequest,
RuntimeSubagentDispatchFailure,
} from "#shared/action-types.js";
import { toErrorMessage } from "#shared/errors.js";
export function createUnavailableDynamicSubagentResult(
- action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,
+ action: RuntimeSubagentDispatchRequest | RuntimeRemoteAgentDispatchRequest,
): RuntimeSubagentDispatchFailure {
const subagentName = getSubagentName(action);
return {
@@ -24,13 +24,13 @@ export function createUnavailableDynamicSubagentResult(
}
export function getSubagentName(
- action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,
+ action: RuntimeSubagentDispatchRequest | RuntimeRemoteAgentDispatchRequest,
): string {
return action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;
}
export function createRemoteAgentStartFailureResult(input: {
- readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly action: RuntimeRemoteAgentDispatchRequest;
readonly error: unknown;
}): RuntimeSubagentDispatchFailure {
return {
@@ -47,7 +47,7 @@ export function createRemoteAgentStartFailureResult(input: {
}
export function createRecursiveAgentRootOnlyResult(
- action: RuntimeSubagentCallActionRequest,
+ action: RuntimeSubagentDispatchRequest,
): RuntimeSubagentDispatchFailure {
return {
callId: action.callId,
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
deleted file mode 100644
index 5b2ca3410..000000000
--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
+++ /dev/null
@@ -1,629 +0,0 @@
-/**
- * Machinery shared by the two runtime-action dispatch steps:
- * `dispatchRuntimeActionsStep` (plain mode) and `dispatchTaskStep`
- * (task mode). Both run the same preflight → plan → dispatch → emit
- * skeleton over one pending batch and differ only in the per-entry
- * delegation lifecycle, so planning and the replay-safe
- * `subagent.called` emission tail live here.
- */
-
-import { buildAdapterContext } from "#channel/adapter-context.js";
-import type { ActivityObserverConfig, SessionParent } from "#channel/types.js";
-import {
- callAdapterEventHandler,
- type ChannelAdapter,
- type ChannelAdapterContext,
-} from "#channel/adapter.js";
-import {
- ActivityObserverKey,
- AuthKey,
- CapabilitiesKey,
- ChannelInstrumentationKey,
- InitiatorAuthKey,
- ParentSessionKey,
- SandboxKey,
- type LocalDevRequestProvenance,
-} from "#context/keys.js";
-import { type AlsContext, ContextContainer } from "#context/container.js";
-import { withContextScope } from "#context/run-step.js";
-import {
- BundleKey,
- ChannelKey,
- type CompiledBundle,
-} from "#runtime/sessions/runtime-context-keys.js";
-import { deserializeContext } from "#context/serialize.js";
-import {
- type DispatchOutcome,
- type RuntimeAgentHandleAction,
- type RuntimeSession,
-} from "#execution/agent-handle-dispatch.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
-import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
-import {
- assertUniqueRuntimeActionCallIds,
- getPendingRuntimeActionBatch,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
-import {
- createSubagentCalledEvent,
- encodeMessageStreamEvent,
- stampMessageStreamEvent,
-} from "#protocol/message.js";
-import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
-import type {
- RuntimeActionResult,
- RuntimeRemoteAgentCallActionRequest,
- RuntimeSubagentCallActionRequest,
- RuntimeSubagentDispatchFailure,
-} from "#shared/action-types.js";
-import type {
- PendingAgentDispatchAction,
- PendingDispatchAction,
- PendingTaskControlAction,
- PendingWorkflowToolAction,
-} from "#shared/dispatch-action.js";
-import {
- createDurableSessionState,
- type DurableSessionState,
- readDurableSession,
-} from "#execution/durable-session-store.js";
-import {
- createRecursiveAgentRootOnlyResult,
- createUnavailableDynamicSubagentResult,
- getSubagentName,
-} from "#execution/dispatch-action-failures.js";
-import { hydrateDurableSession } from "#execution/session.js";
-import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
-import { workflowEntryReference } from "#execution/workflow-runtime.js";
-import { createLogger, logError } from "#internal/logging.js";
-import { readSessionTraceContext } from "#tracing/agent-trace-context-store.js";
-import { resolveSubagentDepth } from "#harness/subagent-depth.js";
-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";
-import { isWorkflowToolAction } from "#execution/tool-run/dispatch.js";
-import { isSubagentDelegationAction } from "#harness/subagent-depth.js";
-import { resolvePreparedAgentAction } from "#execution/prepared-agent-action.js";
-
-const log = createLogger("execution.dispatch-runtime-actions");
-
-type DynamicSubagentAgentConfig = NonNullable<
- Extract<
- ReturnType<typeof getDynamicSubagentSelection>,
- { readonly kind: "subagent" }
- >["agentConfig"]
->;
-
-type DynamicRemoteAgentConfig = NonNullable<
- Extract<
- ReturnType<typeof getDynamicSubagentSelection>,
- { readonly kind: "remote" }
- >["remoteAgent"]
->;
-
-export type DispatchPlanEntry =
- | {
- readonly kind: "resume";
- readonly action: RuntimeAgentHandleAction;
- readonly agentId: string;
- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
- }
- | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
- | { readonly kind: "start"; readonly target: DispatchStartTarget }
- | { readonly kind: "task-control"; readonly action: PendingTaskControlAction }
- | { readonly kind: "workflow-tool"; readonly action: PendingWorkflowToolAction };
-
-export type DispatchStartTarget =
- | {
- readonly kind: "local";
- readonly action: RuntimeSubagentCallActionRequest;
- readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
- readonly selfAgent: boolean;
- readonly source: SubagentInputSource;
- }
- | {
- readonly kind: "remote";
- readonly action: RuntimeRemoteAgentCallActionRequest;
- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
- };
-
-/** Input contract shared by both dispatch steps so the turn workflow can select either. */
-export interface RuntimeActionDispatchInput {
- readonly callbackBaseUrl?: string;
- /** Internal hook that receives child completion and HITL payloads. */
- readonly parentContinuationToken?: string;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}
-
-/**
- * Result contract shared by both dispatch steps. `pendingTasks` is
- * always empty in plain mode; keeping it on both keeps the turn
- * workflow's acknowledgement call site uniform.
- */
-export interface RuntimeActionDispatchResult {
- readonly results: readonly RuntimeActionResult[];
- readonly sessionState: DurableSessionState;
- readonly pendingTasks: readonly {
- readonly taskInboxToken: string;
- readonly taskId: string;
- readonly taskRunId: string;
- }[];
-}
-
-/** Everything preflight produces before either step's dispatch loop runs. */
-export interface PreparedRuntimeActionDispatch {
- readonly adapter: ChannelAdapter;
- readonly adapterCtx: ChannelAdapterContext;
- readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
- readonly batch: NonNullable<ReturnType<typeof getPendingRuntimeActionBatch>>;
- readonly bundle: CompiledBundle;
- readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
- readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
- /**
- * Number of freshly started local subagents in the plan. The parent's
- * remaining token quota is split across these, the children that
- * actually receive an enforced cap: continuations already run under
- * their own budget, and remote agents run on their own deployment
- * under their own limits, so neither dilutes the local shares.
- */
- readonly fanoutSize: number;
- readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
- readonly localDevRequest?: LocalDevRequestProvenance;
- /** Lineage of the session running this dispatch, when it is itself a delegated child. */
- readonly parentSession: SessionParent | undefined;
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
- readonly activityObserver?: ActivityObserverConfig & {
- readonly workIdentity: ActivityWorkIdentityV1;
- };
- readonly sandboxSessionId: string;
- readonly serializedContext: Record<string, unknown>;
- readonly plan: readonly DispatchPlanEntry[];
- readonly session: RuntimeSession;
-}
-
-interface PreparedPendingRuntimeActionDispatch extends PreparedRuntimeActionDispatch {
- /** Returns the durable baseline corresponding to `session`. */
- readonly getBaselineSessionState: () => DurableSessionState;
-}
-
-/**
- * Runs every dispatch precondition that may throw — durable reads, context
- * deserialization, handle-store validation, and batch planning — before
- * the caller acquires the parent stream writer, so a preflight failure
- * never leaks the writer lock. Returns undefined when no actions are
- * pending.
- */
-export async function prepareRuntimeActionDispatch(input: {
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
- /**
- * Classify task-control calls as
- * task-control plan entries. Only task mode plans them; in plain mode
- * those calls fail as unsupported batch actions.
- */
- readonly taskControls: boolean;
-}): Promise<PreparedPendingRuntimeActionDispatch | undefined> {
- const durableSession = await readDurableSession(input.sessionState);
- const batch = getPendingRuntimeActionBatch(durableSession.state);
-
- if (batch === undefined || batch.actions.length === 0) return undefined;
- const parentTurnId = batch.event.turnId || activeTurnId(input.sessionState.emissionState);
- const sessionStateRepaired = batch.event.turnId !== parentTurnId;
- const repairedBatch = sessionStateRepaired
- ? { ...batch, event: { ...batch.event, turnId: parentTurnId } }
- : batch;
- const ctx = await deserializeContext(input.serializedContext);
- const prepared = await prepareActionDispatch({
- batch: repairedBatch,
- ctx,
- durableSession,
- serializedContext: input.serializedContext,
- taskControls: input.taskControls,
- });
- if (!sessionStateRepaired) {
- return { ...prepared, getBaselineSessionState: () => input.sessionState };
- }
-
- const session = setPendingRuntimeActionBatch({
- ...repairedBatch,
- session: prepared.session,
- });
-
- return {
- ...prepared,
- getBaselineSessionState: () => createDurableSessionState({ session }),
- session,
- };
-}
-
-export async function prepareAgentActionDispatch(input: {
- readonly action: PendingAgentDispatchAction;
- readonly ctx: AlsContext;
- readonly event: {
- readonly sequence: number;
- readonly stepIndex: number;
- readonly turnId: string;
- };
- readonly localFanoutSize: number;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<PreparedRuntimeActionDispatch> {
- const durableSession = await readDurableSession(input.sessionState);
- return await prepareActionDispatch({
- batch: { actions: [input.action], event: input.event, responseMessages: [] },
- ctx: copyDurableContext(input.ctx),
- durableSession,
- fanoutSize: input.localFanoutSize,
- serializedContext: input.serializedContext,
- taskControls: false,
- });
-}
-
-function copyDurableContext(ctx: AlsContext): ContextContainer {
- const copy = new ContextContainer();
- for (const [key, value] of ctx.entries()) copy.set(key, value);
- return copy;
-}
-
-async function prepareActionDispatch(input: {
- readonly batch: NonNullable<ReturnType<typeof getPendingRuntimeActionBatch>>;
- readonly ctx: ContextContainer;
- readonly durableSession: Awaited<ReturnType<typeof readDurableSession>>;
- readonly fanoutSize?: number;
- readonly serializedContext: Record<string, unknown>;
- readonly taskControls: boolean;
-}): Promise<PreparedRuntimeActionDispatch> {
- const { batch, durableSession } = input;
- assertUniqueRuntimeActionCallIds(batch.actions);
-
- const ctx = input.ctx;
- const bundle = ctx.require(BundleKey);
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- let session = hydrateDurableSession({
- compactionOverrides: {
- thresholdPercent: effectiveAgent.thresholdPercent,
- },
- durable: durableSession,
- turnAgent: effectiveAgent.turnAgent,
- });
- const adapter = ctx.require(ChannelKey);
-
- // A corrupt handle store and rejected actions must resolve before sandbox
- // initialization, which can provision backend resources and run onSession.
- getAgentHandleStore(durableSession.state);
- const plan = planDispatch({
- actions: batch.actions,
- bundle,
- ctx,
- session,
- taskControls: input.taskControls,
- });
-
- const sandboxSessionId = resolveActiveSandboxSessionId(adapter.state, session.sessionId);
- if (planSharesSandbox({ bundle, plan })) {
- try {
- const scoped = await withContextScope(ctx, session, async (enrichedSession) => {
- await ctx.require(SandboxKey).get();
- return { result: undefined, session: enrichedSession };
- });
- session = scoped.session;
- } finally {
- ctx.clearVirtualContext();
- }
- }
-
- return {
- adapter,
- adapterCtx: buildAdapterContext(adapter, ctx),
- auth: ctx.get(AuthKey) ?? null,
- batch,
- bundle,
- capabilities: ctx.get(CapabilitiesKey),
- channelMetadata: ctx.get(ChannelInstrumentationKey),
- fanoutSize:
- input.fanoutSize ??
- plan.filter((entry) => entry.kind === "start" && entry.target.kind === "local").length,
- initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
- localDevRequest: ctx.localDevRequest,
- parentSession: ctx.get(ParentSessionKey),
- parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
- plan,
- activityObserver: resolvePreparedActivity(
- ctx.get(ActivityObserverKey),
- session,
- batch.event.turnId,
- ),
- sandboxSessionId,
- serializedContext: input.serializedContext,
- session,
- };
-}
-
-function resolvePreparedActivity(
- activityObserver: ActivityObserverConfig | undefined,
- session: RuntimeSession,
- turnId: string,
-): (ActivityObserverConfig & { readonly workIdentity: ActivityWorkIdentityV1 }) | undefined {
- if (activityObserver === undefined) return undefined;
- return {
- sink: activityObserver.sink,
- workIdentity: activityObserver.workIdentity ?? {
- id: deriveRootTurnActivityWorkId({ sessionId: session.sessionId, turnId }),
- kind: "root-turn",
- rootSessionId: session.rootSessionId ?? session.sessionId,
- rootTurnId: turnId,
- sessionId: session.sessionId,
- turnId,
- },
- };
-}
-
-function planSharesSandbox(input: {
- readonly bundle: CompiledBundle;
- readonly plan: readonly DispatchPlanEntry[];
-}): boolean {
- const graph = (input.bundle as Partial<CompiledBundle>).graph;
- return input.plan.some((entry) => {
- if (entry.kind !== "start" || entry.target.kind !== "local") return false;
- return (
- entry.target.selfAgent ||
- graph?.nodesByNodeId.get(entry.target.action.nodeId)?.sandboxRegistry.sandbox.definition
- .inheritsParent === true
- );
- });
-}
-
-function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string): string {
- if (typeof adapterState !== "object" || adapterState === null) return sessionId;
- const value = (adapterState as Record<string, unknown>).sandboxSessionId;
- return typeof value === "string" && value.length > 0 ? value : sessionId;
-}
-
-/**
- * Emits the parent `subagent.called` control-plane event for one adopted
- * child. Emission is observability, not control flow: a failure is logged
- * and swallowed, because a throw escaping the dispatch loop would durably
- * replay the step and re-dispatch children that already started.
- */
-export async function emitSubagentCalled(input: {
- readonly adapter: ChannelAdapter;
- readonly adapterCtx: ChannelAdapterContext;
- readonly batchEvent: { readonly sequence: number; readonly turnId: string };
- readonly entry: Extract<DispatchPlanEntry, { readonly kind: "resume" | "start" }>;
- readonly outcome: Extract<DispatchOutcome, { readonly kind: "called" }>;
- readonly sessionId: string;
- readonly writer: WritableStreamDefaultWriter<Uint8Array>;
-}): Promise<void> {
- const { entry, outcome } = input;
- try {
- const action = entry.kind === "resume" ? entry.action : entry.target.action;
- const dynamicRemoteAgent =
- entry.kind === "resume"
- ? entry.dynamicRemoteAgent
- : entry.target.kind === "remote"
- ? entry.target.dynamicRemoteAgent
- : undefined;
- const parentEvent = await callAdapterEventHandler(
- input.adapter,
- createSubagentCalledEvent({
- callId: outcome.callId,
- childSessionId: outcome.address.sessionId,
- name: outcome.name,
- remote:
- outcome.address.kind === "agent/remote"
- ? {
- // The proxy route re-resolves outbound auth from this key via
- // resolveRemoteAgentStreamHeaders: a node id lands in
- // subagentRegistry.subagentsByNodeId (static definition), a
- // credentialsStepId lands in the step registry (dynamic
- // definition). Both sides of this ternary must stay in sync
- // with that lookup order.
- resolverId:
- dynamicRemoteAgent === undefined
- ? action.nodeId
- : dynamicRemoteAgent.credentialsStepId,
- url: outcome.address.url,
- }
- : undefined,
- sequence: input.batchEvent.sequence,
- sessionId: input.sessionId,
- toolName: outcome.toolName,
- turnId: input.batchEvent.turnId,
- workflowId: workflowEntryReference.workflowId,
- }),
- input.adapterCtx,
- );
- await input.writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(parentEvent)));
- } catch (error) {
- logError(log, "subagent.called emission failed", error, {
- callId: outcome.callId,
- childSessionId: outcome.address.sessionId,
- toolName: outcome.toolName,
- });
- }
-}
-
-/**
- * Classifies every batch action before anything dispatches, so invalid
- * batches fail without starting children and rejections never interleave
- * with dispatch work.
- *
- * This is the single place that decides fresh start vs. continuation:
- * an omitted, null, empty, or whitespace-only agentId is a fresh start
- * (strict tool-calling providers force every schema property to be present,
- * so models emit `""`/`null` when they mean "no continuation"), and an
- * agentId that matches no stored handle also falls back to a fresh start —
- * models sometimes pass a hallucinated or stale id, and hard-failing made
- * them conclude the subagent itself was unavailable. Only an id that
- * resolves to a stored handle becomes a resume.
- */
-function planDispatch(input: {
- readonly actions: readonly PendingDispatchAction[];
- readonly bundle: CompiledBundle;
- readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
- readonly session: RuntimeSession;
- readonly taskControls: boolean;
-}): DispatchPlanEntry[] {
- const handles = getAgentHandleStore(input.session.state)?.handles ?? [];
-
- return input.actions.map((action): DispatchPlanEntry => {
- if (input.taskControls && isTaskControlAction(action)) {
- return { action, kind: "task-control" };
- }
- if (isWorkflowToolAction(action)) {
- return { action, kind: "workflow-tool" };
- }
-
- if (!isSubagentDelegationAction(action)) {
- throw new Error(
- `Unsupported prepared dispatch target "${action.target.kind}" in workflow runtime.`,
- );
- }
- const resolved = resolvePreparedAgentAction(action);
-
- const rawAgentId = action.input.agentId;
- const agentId =
- typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;
- if (agentId !== undefined) {
- // Resume classification runs before the recursion guard: an agentId
- // continuation resumes an already-adopted child rather than starting
- // a new one. Unknown ids go through classifyFreshStart below, which
- // re-applies the guard the resume path bypasses.
- if (handles.some((handle) => handle.identity.id === agentId)) {
- const dynamicSubagentSelection =
- input.bundle.subagentRegistry.dynamicNodeIds?.has(resolved.action.nodeId) === true
- ? getDynamicSubagentSelection(input.ctx, resolved.action.nodeId)
- : undefined;
- return {
- action: resolved.action,
- agentId,
- dynamicRemoteAgent:
- resolved.action.kind === "remote-agent-call" &&
- dynamicSubagentSelection?.kind === "remote"
- ? dynamicSubagentSelection.remoteAgent
- : undefined,
- kind: "resume",
- };
- }
- log.warn("unknown agentId on subagent call; starting a new agent", {
- agentId,
- callId: action.callId,
- });
- }
-
- return classifyFreshStart({
- action: resolved.action,
- bundle: input.bundle,
- ctx: input.ctx,
- selfAgent: resolved.selfAgent,
- session: input.session,
- });
- });
-}
-
-/**
- * Classifies one action for fresh dispatch: rejected by the recursion guard,
- * or started against a local/remote target. Shared by plain starts and the
- * unknown-agentId fallback, so both paths enforce the same guard.
- */
-function classifyFreshStart(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly bundle: CompiledBundle;
- readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
- readonly selfAgent: boolean;
- readonly session: RuntimeSession;
-}): Extract<DispatchPlanEntry, { kind: "reject" | "start" }> {
- const { action } = input;
- const registry = input.bundle.subagentRegistry.subagentsByNodeId;
- const subagentDepth = resolveSubagentDepth(input.session);
- const outsideRootSession =
- input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;
-
- const isDynamicSubagent =
- (action.kind === "subagent-call" || action.kind === "remote-agent-call") &&
- input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
- const dynamicSubagentSelection = isDynamicSubagent
- ? getDynamicSubagentSelection(input.ctx, action.nodeId)
- : undefined;
- if (
- isDynamicSubagent &&
- (dynamicSubagentSelection === undefined ||
- (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
- (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
- ) {
- const subagentName = getSubagentName(action);
- log.warn("dynamic subagent call blocked after availability changed", {
- callId: action.callId,
- nodeId: action.nodeId,
- subagentName,
- });
- return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };
- }
-
- if (input.selfAgent && action.kind !== "subagent-call") {
- throw new Error("A self-agent dispatch target must resolve to a local subagent action.");
- }
- if (input.selfAgent && outsideRootSession && action.kind === "subagent-call") {
- log.warn("recursive agent call blocked outside the root session", {
- callId: action.callId,
- currentDepth: subagentDepth.currentDepth,
- nodeId: action.nodeId,
- subagentName: action.subagentName,
- });
- return { kind: "reject", result: createRecursiveAgentRootOnlyResult(action) };
- }
-
- switch (action.kind) {
- case "subagent-call": {
- const dynamicAgentConfig =
- dynamicSubagentSelection?.kind === "subagent"
- ? dynamicSubagentSelection.agentConfig
- : undefined;
- const registered = registry.get(action.nodeId);
- const description =
- dynamicAgentConfig?.description ??
- (registered?.definition.kind === "subagent"
- ? registered.definition.description
- : undefined);
- const source: SubagentInputSource =
- description !== undefined
- ? {
- description,
- outputSchema:
- dynamicAgentConfig?.outputSchema ??
- input.bundle.graph?.nodesByNodeId.get(action.nodeId)?.turnAgent?.outputSchema,
- type: "local",
- }
- : { outputSchema: input.bundle.turnAgent.outputSchema, type: "runtime" };
- return {
- kind: "start",
- target: {
- action,
- dynamicSubagentAgentConfig: dynamicAgentConfig,
- kind: "local",
- selfAgent: input.selfAgent,
- source,
- },
- };
- }
- case "remote-agent-call":
- return {
- kind: "start",
- target: {
- action,
- dynamicRemoteAgent:
- dynamicSubagentSelection?.kind === "remote"
- ? dynamicSubagentSelection.remoteAgent
- : undefined,
- kind: "remote",
- },
- };
- default: {
- const _exhaustive: never = action;
- return _exhaustive;
- }
- }
-}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
deleted file mode 100644
index 19c47e1c3..000000000
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ /dev/null
@@ -1,1583 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import type { ChannelAdapter } from "#channel/adapter.js";
-import type { SessionAuthContext } from "#channel/types.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
-import { ContextContainer, loadContext } from "#context/container.js";
-import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";
-import type { DurableSessionState } from "#execution/durable-session-store.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
-import { prepareAgentActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";
-import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";
-import {
- getPendingRuntimeActionBatch,
- resolvePendingRuntimeActions,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
-import {
- AGENT_HANDLES_STATE_KEY,
- deriveAgentId,
- getAgentHandleStore,
- type AgentHandle,
-} from "#harness/handles/store.js";
-import type { HarnessSession } from "#harness/types.js";
-import { getSessionTaskIndex } from "#tasks/session-index.js";
-import { recordSessionTask } from "#tasks/session-index.js";
-import * as taskRunControl from "#execution/tasks/parent/run-parent.js";
-import {
- ActivityObserverKey,
- AuthKey,
- CapabilitiesKey,
- ChannelInstrumentationKey,
- InitiatorAuthKey,
- type LocalDevRequestProvenance,
- SessionIdKey,
- SessionKey,
- SessionTraceSeedKey,
-} from "#context/keys.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import type {
- SandboxBackend,
- SandboxBackendCreateInput,
-} from "#public/definitions/sandbox-backend.js";
-import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
-import type { ResolvedSandboxDefinition } from "#runtime/types.js";
-import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
-
-const mocks = vi.hoisted(() => ({
- continueRemoteAgentSession: vi.fn(),
- createDurableSessionState: vi.fn(),
- deserializeContext: vi.fn(),
- dispatchSession: vi.fn(),
- hydrateDurableSession: vi.fn(),
- readDurableSession: vi.fn(),
- resumeHook: vi.fn(),
- createSession: vi.fn(),
- startRemoteAgentSession: vi.fn(),
- startWorkflowOnCurrentDeployment: vi.fn(),
- waitForCommandHookOwner: vi.fn(),
-}));
-
-vi.mock("#context/serialize.js", () => ({
- deserializeContext: mocks.deserializeContext,
-}));
-
-vi.mock("#execution/durable-session-store.js", () => ({
- createDurableSessionState: mocks.createDurableSessionState,
- readDurableSession: mocks.readDurableSession,
-}));
-
-vi.mock("#internal/workflow/runtime.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#internal/workflow/runtime.js")>()),
- resumeHook: mocks.resumeHook,
-}));
-
-vi.mock("#execution/session.js", () => ({
- hydrateDurableSession: mocks.hydrateDurableSession,
- mintSubagentContinuationToken: (seed: string) => `subagent:${seed}`,
-}));
-
-vi.mock("#execution/workflow-runtime.js", () => ({
- createWorkflowRuntime: () => ({
- createSession: mocks.createSession,
- dispatchSession: mocks.dispatchSession,
- }),
- workflowEntryReference: { workflowId: "workflow//eve//workflowEntry" },
- startWorkflowOnCurrentDeployment: mocks.startWorkflowOnCurrentDeployment,
- taskRunWorkflowReference: { workflowId: "workflow//eve//taskRun" },
- waitForCommandHookOwner: mocks.waitForCommandHookOwner,
-}));
-
-// Only the network calls are mocked; error classification and registry
-// resolution stay real so these tests cannot drift from the production
-// retry/forfeit policy.
-vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/remote-agent-dispatch.js")>()),
- continueRemoteAgentSession: mocks.continueRemoteAgentSession,
- startRemoteAgentSession: mocks.startRemoteAgentSession,
-}));
-
-const ADAPTER: ChannelAdapter = { kind: "channel:test" };
-const BASE_STATE: DurableSessionState = {
- continuationToken: "parent-token",
- emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
- hasProxyInputRequests: false,
- sessionId: "parent-session",
- version: 1,
-};
-const CHILD_SESSION_ID = "child-session-123456789012";
-const TURN_AUTH: SessionAuthContext = {
- attributes: { user_id: "U456" },
- authenticator: "slack-webhook",
- issuer: "slack",
- principalId: "slack:U456",
- principalType: "user",
- subject: "U456",
-};
-
-const PARKED_START_OPERATION_ID = deriveAgentOperationId({
- callId: "call-0",
- parentSessionId: "parent-session",
- parentTurnId: "turn-0",
-});
-
-const LOCAL_CHILD_CONTINUATION_TOKEN = "subagent:parent:child";
-
-const LOCAL_PARKED_HANDLE: AgentHandle = {
- address: {
- continuationToken: LOCAL_CHILD_CONTINUATION_TOKEN,
- kind: "agent/local",
- sessionId: CHILD_SESSION_ID,
- },
- identity: {
- id: deriveAgentId("research", PARKED_START_OPERATION_ID),
- name: "research",
- nodeId: "subagents/research",
- },
- lastStatus: "initial result",
- phase: "parked",
-};
-
-const REMOTE_PARKED_HANDLE: AgentHandle = {
- address: {
- callbackBaseUrl: "https://caller.example.com",
- kind: "agent/remote",
- sessionId: "remote-session-123456789012",
- url: "https://remote.example.com",
- },
- identity: {
- id: deriveAgentId("research", PARKED_START_OPERATION_ID),
- name: "research",
- nodeId: "remote/research",
- },
- lastStatus: "initial result",
- phase: "parked",
-};
-
-const REMOTE_REGISTRY_DEFINITION = {
- description: "Remote research",
- kind: "remote",
- name: "research",
- nodeId: "remote/research",
- path: "/eve/v1/session",
- url: "https://registry.example.com",
-} as const;
-
-beforeEach(() => {
- vi.clearAllMocks();
- mocks.createSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID });
- mocks.waitForCommandHookOwner.mockImplementation(async (token: string) => ({
- runId: token.startsWith("subagent:") ? CHILD_SESSION_ID : "task-run-1",
- }));
- mocks.dispatchSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID, status: "accepted" });
- mocks.continueRemoteAgentSession.mockResolvedValue(undefined);
- mocks.startRemoteAgentSession.mockResolvedValue({
- sessionId: "remote-session-123456789012",
- });
- mocks.startWorkflowOnCurrentDeployment.mockResolvedValue({ runId: "task-run-1" });
- mocks.resumeHook.mockResolvedValue({ runId: "task-run-1" });
- mocks.hydrateDurableSession.mockImplementation(({ durable }) => durable);
- mocks.createDurableSessionState.mockImplementation(({ session }) => ({
- ...BASE_STATE,
- snapshot: { session, version: 1 },
- }));
-});
-
-describe("dispatchRuntimeActionsStep child starts", () => {
- const startOperationId = deriveAgentOperationId({
- callId: "call-1",
- parentSessionId: "parent-session",
- parentTurnId: "turn-1",
- });
-
- it("plans an in-step agent call from the live context", async () => {
- const session = createBaseSession();
- const ctx = new ContextContainer();
- ctx.set(ActivityObserverKey, {
- sink: {
- url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- });
- ctx.set(AuthKey, null);
- ctx.set(ChannelKey, ADAPTER);
- ctx.set(BundleKey, {
- compiledArtifactsSource: {},
- resolvedAgent: {
- config: { experimental: { tasks: true } },
- },
- subagentRegistry: {
- subagentsByNodeId: new Map([
- ["remote/research", { definition: REMOTE_REGISTRY_DEFINITION }],
- ]),
- },
- turnAgent: session.agent,
- } as never);
- mocks.readDurableSession.mockResolvedValue(session);
- mocks.deserializeContext.mockRejectedValue(
- new Error(
- "A development Workflow generation selector was resumed outside a generation-bound delivery.",
- ),
- );
-
- const prepared = await prepareAgentActionDispatch({
- action: {
- callId: "call-1",
- description: "Research",
- input: { message: "research this" },
- target: {
- kind: "remote-agent-call",
- nodeId: "remote/research",
- remoteAgentName: "research",
- },
- toolName: "research",
- },
- ctx,
- event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
- localFanoutSize: 0,
- serializedContext: {
- [BundleKey.name]: { source: { kind: "development" } },
- },
- sessionState: BASE_STATE,
- });
-
- expect(prepared.plan).toEqual([
- expect.objectContaining({
- kind: "start",
- target: expect.objectContaining({ kind: "remote" }),
- }),
- ]);
- expect(prepared.activityObserver?.workIdentity).toMatchObject({
- id: deriveRootTurnActivityWorkId({ sessionId: session.sessionId, turnId: "turn-1" }),
- sessionId: session.sessionId,
- turnId: "turn-1",
- });
- expect(mocks.deserializeContext).not.toHaveBeenCalled();
- });
-
- it("owns a local child before the start effect and confirms its running address", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
- });
- const writes: Uint8Array[] = [];
- const traceId = "1".repeat(32);
- const actionSpanId = "3".repeat(16);
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(writes),
- serializedContext: {
- "eve.harness.agentTrace": {
- actions: {
- "action-1": {
- attemptIndex: 0,
- callId: "call-1",
- kind: "subagent-call",
- name: "research",
- parent: { spanId: "2".repeat(16), traceFlags: 1, traceId },
- rootSessionId: "parent-session",
- sessionId: "parent-session",
- spanId: actionSpanId,
- startTimeMs: 1_700_000_000_000,
- stepIndex: 0,
- turnId: "turn-1",
- },
- },
- sessions: {},
- turns: {},
- },
- },
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([]);
- expect(mocks.createSession).toHaveBeenCalledTimes(1);
- expect(mocks.createSession).toHaveBeenCalledWith(
- expect.objectContaining({
- parentTraceContext: { isRemote: false, spanId: actionSpanId, traceFlags: 1, traceId },
- }),
- );
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [
- {
- address: {
- continuationToken: "subagent:parent-session:call-1",
- kind: "agent/local",
- sessionId: CHILD_SESSION_ID,
- },
- identity: {
- id: deriveAgentId("research", startOperationId),
- name: "research",
- nodeId: "subagents/research",
- },
- operation: {
- callId: "call-1",
- id: startOperationId,
- kind: "start",
- parentTurnId: "turn-1",
- },
- phase: "running",
- },
- ],
- });
- expect(writes).toHaveLength(1);
- });
-
- it("carries verified local-dev provenance into a local child start", async () => {
- const session = createStartSession({ kind: "local" });
- const localDevRequest: LocalDevRequestProvenance = {
- address: "127.0.0.1",
- interactiveClient: true,
- signature: "parent-signed",
- };
- installContext(session, undefined, false, null, localDevRequest);
- mocks.createSession.mockImplementation(async () => {
- expect(loadContext().localDevRequest).toEqual(localDevRequest);
- return { sessionId: CHILD_SESSION_ID };
- });
-
- await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(mocks.createSession).toHaveBeenCalledOnce();
- });
-
- it("uses the active session turn when pending batch metadata has an empty turn id", async () => {
- const session = createStartSession({
- event: { sequence: 3, stepIndex: 2, turnId: "" },
- kind: "local",
- });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
- });
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: {
- ...BASE_STATE,
- emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },
- },
- });
-
- const resultState = readResultSessionState(result, session);
- expect(getPendingRuntimeActionBatch(resultState)?.event.turnId).toBe("turn_3");
- expect(getAgentHandleStore(resultState)).toMatchObject({
- handles: [{ operation: { parentTurnId: "turn_3" } }],
- });
- });
-
- it("persists the active turn when dispatch leaves agent handles unchanged", async () => {
- const session = createStartSession({
- event: { sequence: 3, stepIndex: 2, turnId: "" },
- kind: "remote",
- });
- installContext(session, {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: "remote/research",
- });
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: {
- ...BASE_STATE,
- emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },
- },
- });
-
- const resultState = readResultSessionState(result, session);
- expect(getAgentHandleStore(resultState)).toBeUndefined();
- expect(getPendingRuntimeActionBatch(resultState)?.event.turnId).toBe("turn_3");
- expect(mocks.createDurableSessionState).toHaveBeenCalledTimes(1);
- });
-
- it("uses the active session turn for task-mode dispatch", async () => {
- const session = createStartSession({
- event: { sequence: 3, stepIndex: 2, turnId: "" },
- kind: "local",
- });
- installContext(
- session,
- { definition: { description: "Research", kind: "subagent" }, nodeId: "subagents/research" },
- true,
- );
- vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({ runId: "task-run-1" });
-
- const result = await dispatchTaskStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: {
- ...BASE_STATE,
- emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },
- },
- });
-
- const resultState = readResultSessionState(result, session);
- expect(getPendingRuntimeActionBatch(resultState)?.event.turnId).toBe("turn_3");
- expect(getSessionTaskIndex(resultState)).toEqual([
- expect.objectContaining({ createdByTurnId: "turn_3" }),
- ]);
- });
-
- it("opens a shared parent sandbox with session context and durable backend tags", async () => {
- const session = createStartSession({ kind: "local" });
- const observedSessionIds: string[] = [];
- const { backend, create } = createSandboxBackend();
- const registry = createSandboxRegistry(backend, ({ ctx }) => {
- observedSessionIds.push(ctx.session.id, loadContext().require(SessionKey).sessionId);
- });
- installSandboxContext({
- child: { inheritsParent: true, name: "research", nodeId: "subagents/research" },
- registry,
- session,
- });
-
- await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(observedSessionIds).toEqual(["parent-session", "parent-session"]);
- expect(create).toHaveBeenCalledWith(
- expect.objectContaining({
- tags: {
- agent: "parent-agent",
- channel: "channel:test",
- sessionId: "parent-session",
- },
- }),
- );
- expect(mocks.createSession).toHaveBeenCalledWith(
- expect.objectContaining({
- adapter: expect.objectContaining({
- state: expect.objectContaining({
- parentSandboxState: expect.objectContaining({ initialized: true }),
- sandboxSessionId: "parent-session",
- }),
- }),
- }),
- );
- });
-
- it("opens a shared parent sandbox for a background-task child", async () => {
- const session = createStartSession({ kind: "local" });
- const { backend, create } = createSandboxBackend();
- installSandboxContext({
- child: { inheritsParent: true, name: "research", nodeId: "subagents/research" },
- registry: createSandboxRegistry(backend),
- session,
- });
- vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({ runId: "task-run-1" });
-
- await dispatchTaskStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(create).toHaveBeenCalledTimes(1);
- expect(mocks.createSession).toHaveBeenCalledWith(
- expect.objectContaining({
- adapter: expect.objectContaining({
- state: expect.objectContaining({ sandboxSessionId: "parent-session" }),
- }),
- mode: "conversation",
- }),
- );
- });
-
- it("does not open the parent sandbox for a declared subagent named agent", async () => {
- const session = createNamedStartSession({
- name: "agent",
- nodeId: "subagents/agent",
- });
- const { backend, create } = createSandboxBackend();
- installSandboxContext({
- child: { inheritsParent: false, name: "agent", nodeId: "subagents/agent" },
- registry: createSandboxRegistry(backend),
- session,
- });
-
- await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(create).not.toHaveBeenCalled();
- expect(mocks.createSession).toHaveBeenCalledTimes(1);
- const childInput = mocks.createSession.mock.calls[0]?.[0];
- expect(childInput?.adapter.state).not.toHaveProperty("parentSandboxState");
- expect(childInput?.adapter.state).not.toHaveProperty("sandboxSessionId");
- });
-
- it("rejects recursive self-delegation before opening the parent sandbox", async () => {
- const session = createNamedStartSession({
- name: "agent",
- nodeId: "__root__",
- selfAgent: true,
- session: { rootSessionId: "root-session", subagentDepth: 1 },
- });
- const { backend, create } = createSandboxBackend();
- installSandboxContext({ registry: createSandboxRegistry(backend), session });
- vi.spyOn(console, "warn").mockImplementation(() => {});
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([
- expect.objectContaining({
- output: expect.objectContaining({ code: "RECURSIVE_AGENT_ROOT_ONLY" }),
- }),
- ]);
- expect(create).not.toHaveBeenCalled();
- expect(mocks.createSession).not.toHaveBeenCalled();
- });
-
- it("records a tasks-mode child as an address and derives task identity separately", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(
- session,
- { definition: { description: "Research", kind: "subagent" }, nodeId: "subagents/research" },
- true,
- );
- vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({
- runId: "task-run-1",
- });
-
- // Tasks-mode dispatch routes through dispatchTaskStep; the turn workflow
- // never sends `experimental.tasks` agents to dispatchRuntimeActionsStep.
- const result = await dispatchTaskStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
- const state = readResultSessionState(result, session);
- const agentId = deriveAgentId("research", startOperationId);
-
- expect(result.results[0]).toMatchObject({
- origin: "child",
- output: { agentId, status: "working" },
- });
- expect(getAgentHandleStore(state)).toEqual({
- handles: [
- {
- address: {
- continuationToken: "subagent:parent-session:call-1",
- kind: "agent/local",
- sessionId: CHILD_SESSION_ID,
- },
- identity: {
- id: agentId,
- name: "research",
- nodeId: "subagents/research",
- },
- phase: "addressed",
- },
- ],
- });
- expect(getSessionTaskIndex(state)).toEqual([
- expect.objectContaining({
- metadata: expect.objectContaining({ agentId }),
- taskRunId: "task-run-1",
- }),
- ]);
- });
-
- it("silently rejects a tasks-mode start that failed before index admission", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(
- session,
- { definition: { description: "Research", kind: "subagent" }, nodeId: "subagents/research" },
- true,
- );
- mocks.createSession.mockRejectedValue(new Error("child start failed"));
- vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({ runId: "task-run-1" });
-
- const result = await dispatchTaskStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
- const state = readResultSessionState(result, session);
-
- expect(result.pendingTasks).toEqual([]);
- expect(getSessionTaskIndex(state)).toEqual([]);
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: { code: "SUBAGENT_START_FAILED" },
- });
- expect(mocks.resumeHook).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({ command: expect.objectContaining({ kind: "reject-dispatch" }) }),
- );
- });
-
- it("adopts the child a replayed start already created instead of failing it", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
- });
- // A retried dispatch step re-derives the same deterministic child
- // continuation token, so the first attempt's child owns it.
- mocks.createSession.mockResolvedValue({ sessionId: "duplicate-child" });
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([]);
- expect(getAgentHandleStore(readResultSessionState(result, session))?.handles[0]).toMatchObject({
- address: { kind: "agent/local", sessionId: CHILD_SESSION_ID },
- });
- });
-
- it("rejects the prepared handle when the local start fails", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
- });
- mocks.createSession.mockRejectedValue(new Error("runtime unavailable"));
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: { code: "SUBAGENT_START_FAILED" },
- });
- // The store was written (prepare committed ownership before the effect)
- // and the dead start was rejected, so no handle survives.
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [],
- });
- });
-
- it("adopts the child a replayed start already created instead of failing it", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
- });
- // A retried dispatch step re-derives the same deterministic child
- // continuation token, so the first attempt's child owns it.
- mocks.createSession.mockResolvedValue({ sessionId: "duplicate-child" });
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([]);
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [
- expect.objectContaining({
- address: {
- continuationToken: "subagent:parent-session:call-1",
- kind: "agent/local",
- sessionId: CHILD_SESSION_ID,
- },
- phase: "running",
- }),
- ],
- });
- });
-
- it("owns a remote child with its confirmed remote address", async () => {
- const session = createStartSession({ kind: "remote" });
- const traceId = "4".repeat(32);
- const actionSpanId = "5".repeat(16);
- installContext(
- session,
- {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: "remote/research",
- },
- false,
- null,
- undefined,
- "private",
- );
-
- const result = await dispatchRuntimeActionsStep({
- callbackBaseUrl: "https://caller.example.com",
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {
- [SessionTraceSeedKey.name]: {
- decision: { action: "record", recordInputs: true, recordOutputs: true },
- forwardedTracePolicy: {
- ceiling: { recordInputs: true, recordOutputs: true },
- originAudience: "public",
- },
- spanId: "3".repeat(16),
- traceFlags: 1,
- traceId,
- },
- "eve.harness.agentTrace": {
- actions: {
- "action-1": {
- attemptIndex: 0,
- callId: "call-1",
- kind: "remote-agent-call",
- name: "research",
- parent: { spanId: "2".repeat(16), traceFlags: 1, traceId },
- rootSessionId: "parent-session",
- sessionId: "parent-session",
- spanId: actionSpanId,
- startTimeMs: 1_700_000_000_000,
- stepIndex: 0,
- turnId: "turn-1",
- },
- },
- sessions: {},
- turns: {},
- },
- },
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([]);
- expect(mocks.startRemoteAgentSession).toHaveBeenCalledWith(
- expect.objectContaining({
- originAudience: "public",
- parentTraceContext: expect.objectContaining({
- decision: { action: "record", recordInputs: false, recordOutputs: false },
- forwardedTracePolicy: {
- ceiling: { recordInputs: true, recordOutputs: true },
- originAudience: "public",
- },
- isRemote: false,
- spanId: actionSpanId,
- traceFlags: 1,
- traceId,
- }),
- }),
- );
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [
- expect.objectContaining({
- address: {
- callbackBaseUrl: "https://caller.example.com",
- credentialResolver: { resolverId: "remote/research" },
- kind: "agent/remote",
- sessionId: "remote-session-123456789012",
- url: "https://registry.example.com",
- },
- phase: "running",
- }),
- ],
- });
- });
-
- it("rejects the prepared handle when the remote start fails", async () => {
- const session = createStartSession({ kind: "remote" });
- installContext(session, {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: "remote/research",
- });
- mocks.startRemoteAgentSession.mockRejectedValue(new Error("HTTP 500"));
-
- const result = await dispatchRuntimeActionsStep({
- callbackBaseUrl: "https://caller.example.com",
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: { code: "REMOTE_AGENT_START_FAILED" },
- });
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [],
- });
- });
-
- it("binds the child result through the running handle and deletes it on terminal settlement", async () => {
- const session = createStartSession({ kind: "local" });
- installContext(session, {
- definition: { description: "Research", kind: "subagent" },
- nodeId: "subagents/research",
- });
-
- const dispatched = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
- // Only `state` changes across the dispatch step; graft the committed
- // state map onto the in-memory session instead of re-hydrating.
- const committedSession: HarnessSession = {
- ...session,
- state: dispatched.sessionState.snapshot?.session.state,
- };
-
- // A result for a callId no running handle records never settles the call.
- const unbound = await resolvePendingRuntimeActions({
- session: committedSession,
- stepInput: {
- runtimeActionResults: [
- {
- callId: "call-unknown",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "terminal",
- result: { kind: "succeeded", output: "stray" },
- usageDelta: {
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- inputTokens: 0,
- outputTokens: 0,
- },
- },
- output: "stray",
- subagentName: "research",
- },
- ],
- },
- });
- expect(unbound.outcome).toBe("unresolved");
-
- const resolved = await resolvePendingRuntimeActions({
- session: committedSession,
- stepInput: {
- runtimeActionResults: [
- {
- callId: "call-1",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "terminal",
- result: { kind: "succeeded", output: "done" },
- usageDelta: {
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- inputTokens: 0,
- outputTokens: 0,
- },
- },
- output: "done",
- subagentName: "research",
- },
- ],
- },
- });
- expect(resolved.outcome).toBe("resolved");
- expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });
- });
-});
-
-describe("dispatchRuntimeActionsStep agent delivery", () => {
- it("rejects a tasks-mode continuation while the addressed agent has active work", async () => {
- const addressedHandle: AgentHandle = {
- address: LOCAL_PARKED_HANDLE.address,
- identity: LOCAL_PARKED_HANDLE.identity,
- phase: "addressed",
- };
- let session = createPendingSession({
- handle: addressedHandle,
- agentId: addressedHandle.identity.id,
- });
- session = recordSessionTask(session, {
- taskInboxToken: "task-token",
- createdByTurnId: "turn-previous",
- metadata: {
- agentId: addressedHandle.identity.id,
- kind: "subagent",
- mode: "local",
- name: addressedHandle.identity.name,
- },
- operationId: "operation-active",
- taskId: "task_active",
- taskRunId: "task-run-active",
- });
- installContext(session, undefined, true);
- vi.spyOn(taskRunControl, "readLatestTaskView").mockResolvedValue({
- metadata: {
- agentId: addressedHandle.identity.id,
- kind: "subagent",
- mode: "local",
- name: addressedHandle.identity.name,
- },
- status: "working",
- taskId: "task_active",
- });
-
- const result = await dispatchTaskStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: { code: "AGENT_BUSY", message: expect.stringContaining("task_active") },
- });
- expect(mocks.dispatchSession).not.toHaveBeenCalled();
- expect(mocks.startWorkflowOnCurrentDeployment).not.toHaveBeenCalled();
- });
-
- it("passes the active turn principal to a tasks-mode continuation", async () => {
- const addressedHandle: AgentHandle = {
- address: LOCAL_PARKED_HANDLE.address,
- identity: LOCAL_PARKED_HANDLE.identity,
- phase: "addressed",
- };
- const session = createPendingSession({
- handle: addressedHandle,
- agentId: addressedHandle.identity.id,
- });
- installContext(session, undefined, true, TURN_AUTH);
-
- const result = await dispatchTaskStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(mocks.dispatchSession).toHaveBeenCalledWith({
- command: expect.objectContaining({
- auth: TURN_AUTH,
- kind: "send",
- }),
- sessionId: CHILD_SESSION_ID,
- });
- expect(result.results[0]).toMatchObject({
- origin: "child",
- output: { agentId: addressedHandle.identity.id, status: "working" },
- });
- });
-
- const continueOperationId = deriveAgentOperationId({
- callId: "call-1",
- parentSessionId: "parent-session",
- parentTurnId: "turn-1",
- });
-
- it("delivers the raw message to a parked local handle and records the running operation", async () => {
- const session = createPendingSession({
- handle: LOCAL_PARKED_HANDLE,
- agentId: LOCAL_PARKED_HANDLE.identity.id,
- });
- installContext(session);
- const writes: Uint8Array[] = [];
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(writes),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([]);
- expect(mocks.dispatchSession).toHaveBeenCalledWith({
- command: {
- caller: {
- callId: "call-1",
- replyTo: { kind: "hook", token: "turn-inbox" },
- subagentName: "research",
- },
- kind: "send",
- auth: null,
- payload: {
- message: "continue with raw input",
- outputSchema: undefined,
- },
- },
- sessionId: CHILD_SESSION_ID,
- });
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [
- {
- address: LOCAL_PARKED_HANDLE.address,
- identity: LOCAL_PARKED_HANDLE.identity,
- operation: {
- callId: "call-1",
- id: continueOperationId,
- kind: "continue",
- parentTurnId: "turn-1",
- previousStatus: "initial result",
- },
- phase: "running",
- },
- ],
- });
- expect(writes).toHaveLength(1);
- });
-
- it.each([
- { agentId: "ag_research:missing", title: "matches no stored handle" },
- { agentId: "", title: "is an empty string from a strict provider" },
- { agentId: null, title: "is null from a strict provider" },
- ])("starts a fresh agent when the agentId $title", async ({ agentId }) => {
- const session = createPendingSession({ agentId, handle: undefined });
- installContext(session);
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([]);
- expect(mocks.createSession).toHaveBeenCalledTimes(1);
- expect(mocks.dispatchSession).not.toHaveBeenCalled();
- // The fallback dispatches through the normal start path: the fresh
- // child is owned by a confirmed running handle, not the stale id.
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [
- expect.objectContaining({
- address: expect.objectContaining({ sessionId: CHILD_SESSION_ID }),
- phase: "running",
- }),
- ],
- });
- });
-
- it.each([
- {
- handle: {
- ...LOCAL_PARKED_HANDLE,
- identity: { ...LOCAL_PARKED_HANDLE.identity, name: "writer" },
- },
- agentId: LOCAL_PARKED_HANDLE.identity.id,
- code: "AGENT_MISMATCH",
- title: "mismatched",
- },
- {
- handle: {
- address: LOCAL_PARKED_HANDLE.address,
- identity: LOCAL_PARKED_HANDLE.identity,
- operation: {
- callId: "call-other",
- id: "op-other",
- kind: "start",
- parentTurnId: "turn-0",
- },
- phase: "running",
- } satisfies AgentHandle,
- agentId: LOCAL_PARKED_HANDLE.identity.id,
- code: "AGENT_BUSY",
- title: "busy",
- },
- ])("returns $code for a $title agent", async ({ handle, agentId, code }) => {
- const session = createPendingSession({ handle, agentId });
- installContext(session);
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results).toEqual([
- expect.objectContaining({
- isError: true,
- output: expect.objectContaining({ code }),
- }),
- ]);
- expect(mocks.dispatchSession).not.toHaveBeenCalled();
- expect(mocks.continueRemoteAgentSession).not.toHaveBeenCalled();
- // Addressing mistakes and busy conflicts never touch the store.
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual(
- getAgentHandleStore(session.state),
- );
- });
-
- it("returns AGENT_UNREACHABLE and removes a stale local handle", async () => {
- const session = createPendingSession({
- handle: LOCAL_PARKED_HANDLE,
- agentId: LOCAL_PARKED_HANDLE.identity.id,
- });
- installContext(session);
- mocks.dispatchSession.mockResolvedValue({ status: "session_not_active" });
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: { code: "AGENT_UNREACHABLE" },
- });
- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
- handles: [],
- });
- });
-
- it("reports AGENT_UNREACHABLE when the handle disappears mid-batch instead of starting a fresh agent", async () => {
- // Two continuations to one agentId in a single batch: the first delivery
- // fails permanently and deletes the handle, so the second — planned as a
- // resume while the handle still existed — must fail rather than fall
- // back to an unplanned fresh start.
- const session = setPendingRuntimeActionBatch({
- actions: [1, 2].map((n) => ({
- callId: `call-${n}`,
- description: "Research",
- input: { agentId: LOCAL_PARKED_HANDLE.identity.id, message: `continue ${n}` },
- target: {
- kind: "subagent-call" as const,
- nodeId: "subagents/research",
- subagentName: "research",
- },
- toolName: "research",
- })),
- event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
- responseMessages: [],
- session: createBaseSession(LOCAL_PARKED_HANDLE),
- });
- installContext(session);
- mocks.dispatchSession.mockResolvedValue({ status: "session_not_active" });
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(mocks.dispatchSession).toHaveBeenCalledTimes(1);
- expect(mocks.createSession).not.toHaveBeenCalled();
- expect(result.results).toEqual([
- expect.objectContaining({
- isError: true,
- output: expect.objectContaining({ code: "AGENT_UNREACHABLE" }),
- }),
- expect.objectContaining({
- isError: true,
- output: expect.objectContaining({ code: "AGENT_UNREACHABLE" }),
- }),
- ]);
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [],
- });
- });
-
- it("continues a stored remote handle and maps a permanent failure to AGENT_UNREACHABLE", async () => {
- const session = createPendingSession({
- handle: REMOTE_PARKED_HANDLE,
- agentId: REMOTE_PARKED_HANDLE.identity.id,
- });
- installContext(
- session,
- {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,
- },
- false,
- TURN_AUTH,
- );
- mocks.continueRemoteAgentSession.mockRejectedValue(
- new RemoteAgentContinueRequestError(
- "continue-session request failed permanently with HTTP 404.",
- { deliveryAmbiguous: false, retryable: false },
- ),
- );
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(mocks.continueRemoteAgentSession).toHaveBeenCalledWith(
- expect.objectContaining({
- auth: TURN_AUTH,
- message: "continue with raw input",
- remote: expect.objectContaining({
- nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,
- url: "https://remote.example.com",
- }),
- sessionId: "remote-session-123456789012",
- }),
- );
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: { code: "AGENT_UNREACHABLE" },
- });
- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
- handles: [],
- });
- });
-
- it("surfaces a transient remote continue failure without retrying and restores the parked handle", async () => {
- const session = createPendingSession({
- handle: REMOTE_PARKED_HANDLE,
- agentId: REMOTE_PARKED_HANDLE.identity.id,
- });
- installContext(session, {
- definition: REMOTE_REGISTRY_DEFINITION,
- nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,
- });
- mocks.continueRemoteAgentSession.mockRejectedValue(new Error("HTTP 503"));
-
- // A rethrow would durably replay the whole step and re-dispatch started
- // siblings, and a re-send could double-deliver a turn the callee already
- // accepted — so the failure settles as a retryable error in one attempt.
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(mocks.continueRemoteAgentSession).toHaveBeenCalledTimes(1);
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: {
- code: "AGENT_UNREACHABLE",
- message: expect.stringContaining("temporarily unreachable"),
- },
- });
- // The child may still be alive: the handle is restored to parked with
- // its pre-delivery status so the model can retry the same agentId.
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [REMOTE_PARKED_HANDLE],
- });
- });
-
- it("forfeits a remote handle whose agent node is gone from the registry", async () => {
- const session = createPendingSession({
- handle: REMOTE_PARKED_HANDLE,
- agentId: REMOTE_PARKED_HANDLE.identity.id,
- });
- // No remote registry entry installed: resolution fails before delivery.
- installContext(session);
-
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
- parentWritable: createWritable(),
- serializedContext: {},
- sessionState: BASE_STATE,
- });
-
- expect(mocks.continueRemoteAgentSession).not.toHaveBeenCalled();
- expect(result.results[0]).toMatchObject({
- isError: true,
- output: {
- code: "AGENT_UNREACHABLE",
- message: expect.stringContaining("no longer reachable"),
- },
- });
- expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
- handles: [],
- });
- });
-});
-
-/**
- * The step returns the input state unchanged when the session object is
- * untouched; otherwise the mocked `createDurableSessionState` carries the
- * updated session on `snapshot`.
- */
-function readResultSessionState(
- result: Awaited<ReturnType<typeof dispatchRuntimeActionsStep>>,
- originalSession: HarnessSession,
-): HarnessSession["state"] {
- return result.sessionState.snapshot?.session.state ?? originalSession.state;
-}
-
-function createBaseSession(handle?: AgentHandle): HarnessSession {
- const base: HarnessSession = {
- agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- };
- return handle === undefined
- ? base
- : { ...base, state: { [AGENT_HANDLES_STATE_KEY]: { handles: [handle] } } };
-}
-
-function createStartSession(input: {
- readonly event?: {
- readonly sequence: number;
- readonly stepIndex: number;
- readonly turnId: string;
- };
- readonly kind: "local" | "remote";
-}): HarnessSession {
- return setPendingRuntimeActionBatch({
- actions: [
- input.kind === "local"
- ? {
- callId: "call-1",
- description: "Research",
- input: { message: "research this" },
- target: {
- kind: "subagent-call",
- nodeId: "subagents/research",
- subagentName: "research",
- },
- toolName: "research",
- }
- : {
- callId: "call-1",
- description: "Research",
- input: { message: "research this" },
- target: {
- kind: "remote-agent-call",
- nodeId: "remote/research",
- remoteAgentName: "research",
- },
- toolName: "research",
- },
- ],
- event: input.event ?? { sequence: 1, stepIndex: 2, turnId: "turn-1" },
- responseMessages: [],
- session: createBaseSession(),
- });
-}
-
-function createNamedStartSession(input: {
- readonly name: string;
- readonly nodeId: string;
- readonly selfAgent?: boolean;
- readonly session?: Partial<HarnessSession>;
-}): HarnessSession {
- return setPendingRuntimeActionBatch({
- actions: [
- {
- callId: "call-1",
- description: `Delegate to ${input.name}`,
- input: { message: "research this" },
- target: input.selfAgent
- ? {
- kind: "self-agent-call",
- nodeId: input.nodeId,
- subagentName: input.name,
- }
- : {
- kind: "subagent-call",
- nodeId: input.nodeId,
- subagentName: input.name,
- },
- toolName: input.name,
- },
- ],
- event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
- responseMessages: [],
- session: { ...createBaseSession(), ...input.session },
- });
-}
-
-function createPendingSession(input: {
- readonly handle?: AgentHandle;
- readonly agentId: string | null;
-}): HarnessSession {
- return setPendingRuntimeActionBatch({
- actions: [
- {
- callId: "call-1",
- description: "Research",
- input: { agentId: input.agentId, message: "continue with raw input" },
- target: {
- kind: "subagent-call",
- nodeId: "subagents/research",
- subagentName: "research",
- },
- toolName: "research",
- },
- ],
- event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
- responseMessages: [],
- session: createBaseSession(input.handle),
- });
-}
-
-function installContext(
- session: HarnessSession,
- remote?: { readonly definition: unknown; readonly nodeId: string },
- tasks = false,
- auth: SessionAuthContext | null = null,
- localDevRequest?: LocalDevRequestProvenance,
- channelAudience?: ChannelAudience,
-): void {
- const subagentsByNodeId = new Map<string, { definition: unknown }>();
- if (remote !== undefined) {
- subagentsByNodeId.set(remote.nodeId, { definition: remote.definition });
- }
- const bundle = {
- compiledArtifactsSource: {},
- resolvedAgent: {
- config: tasks ? { experimental: { tasks: true } } : {},
- },
- subagentRegistry: { subagentsByNodeId },
- turnAgent: {
- id: "test-agent",
- instructions: [],
- model: { id: "test-model" },
- skills: [],
- tools: [],
- workspaceSpec: {},
- },
- };
- const values = new Map<unknown, unknown>([
- [AuthKey, auth],
- [BundleKey, bundle],
- [CapabilitiesKey, undefined],
- [
- ChannelInstrumentationKey,
- channelAudience === undefined
- ? undefined
- : { kind: "slack", metadata: { audience: channelAudience } },
- ],
- [InitiatorAuthKey, null],
- [ChannelKey, ADAPTER],
- ]);
- mocks.deserializeContext.mockResolvedValue({
- get localDevRequest() {
- return localDevRequest;
- },
- get: (key: unknown) => values.get(key),
- require: (key: unknown) => {
- if (!values.has(key)) throw new Error("missing context key");
- return values.get(key);
- },
- });
- mocks.readDurableSession.mockResolvedValue(session);
-}
-
-function createSandboxBackend() {
- const sandbox = mockSandbox({ id: "shared-parent-sandbox" });
- const create = vi.fn(async (input: SandboxBackendCreateInput) => ({
- captureState: async () => ({
- backendName: "test",
- metadata: {},
- sessionKey: input.sessionKey,
- }),
- delete: async () => {},
- session: sandbox.session,
- shutdown: async () => {},
- stop: async () => {},
- useSessionFn: async () => sandbox.session,
- }));
- return {
- backend: { create, name: "test", prewarm: vi.fn(async () => ({ reused: false })) },
- create,
- };
-}
-
-function createSandboxRegistry(
- backend: SandboxBackend,
- onSession?: ResolvedSandboxDefinition["onSession"],
-): RuntimeSandboxRegistry {
- return {
- sandbox: {
- definition: {
- backend,
- logicalPath: "agent/sandbox.ts",
- onSession,
- sourceId: "agent/sandbox",
- sourceKind: "module",
- },
- workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
- },
- };
-}
-
-function installSandboxContext(input: {
- readonly child?: {
- readonly inheritsParent: boolean;
- readonly name: string;
- readonly nodeId: string;
- };
- readonly registry: RuntimeSandboxRegistry;
- readonly session: HarnessSession;
-}): void {
- const root = {
- agent: { config: { name: "parent-agent" }, connections: [] },
- nodeId: "__root__",
- sandboxRegistry: input.registry,
- turnAgent: input.session.agent,
- };
- const nodesByNodeId = new Map<string, unknown>([["__root__", root]]);
- const subagentsByNodeId = new Map<string, unknown>();
- if (input.child !== undefined) {
- nodesByNodeId.set(input.child.nodeId, {
- sandboxRegistry: {
- sandbox: {
- definition: { inheritsParent: input.child.inheritsParent },
- },
- },
- });
- subagentsByNodeId.set(input.child.nodeId, {
- definition: {
- description: `Delegate to ${input.child.name}`,
- kind: "subagent",
- },
- });
- }
-
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(InitiatorAuthKey, null);
- ctx.set(SessionIdKey, input.session.sessionId);
- ctx.set(ChannelKey, ADAPTER);
- ctx.set(BundleKey, {
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- graph: { nodesByNodeId, root },
- resolvedAgent: { config: {} },
- subagentRegistry: { subagentsByNodeId },
- turnAgent: input.session.agent,
- } as never);
-
- mocks.deserializeContext.mockResolvedValue(ctx);
- mocks.readDurableSession.mockResolvedValue(input.session);
-}
-
-function createWritable(writes: Uint8Array[] = []): WritableStream<Uint8Array> {
- return new WritableStream({
- write(chunk) {
- writes.push(chunk);
- },
- });
-}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
deleted file mode 100644
index 6c9a7da8e..000000000
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
- * Starts or continues every pending runtime action for the parked parent
- * session, with children reporting straight back to the parent turn via
- * `parentContinuationToken`.
- *
- * The batch is classified into a dispatch plan first (reject / resume /
- * start), then each entry dispatches and emits one
- * parent `subagent.called` control-plane event through a single tail.
- * Every start commits an agent handle (`starting`) before its side effect
- * and confirms it (`running`) once the child reports coordinates, so the
- * returned snapshot-bearing state owns every child it may have created.
- *
- * Agents running `experimental.tasks` never reach this step: the turn
- * workflow selects `dispatchTaskStep`, the task-mode sibling that wraps
- * each dispatch in the delegated-task lifecycle.
- */
-
-import { type DispatchOutcome, dispatchToAgentHandle } from "#execution/agent-handle-dispatch.js";
-import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";
-import {
- emitSubagentCalled,
- prepareRuntimeActionDispatch,
- type RuntimeActionDispatchInput,
- type RuntimeActionDispatchResult,
-} from "#execution/dispatch-runtime-actions-shared.js";
-import { startSubagent } from "#execution/dispatch-runtime-actions-start.js";
-import { startWorkflowTool } from "#execution/tool-run/dispatch.js";
-import { createDurableSessionState } from "#execution/durable-session-store.js";
-import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
-import type { RuntimeActionResult } from "#shared/action-types.js";
-
-export async function dispatchRuntimeActionsStep(
- input: RuntimeActionDispatchInput,
-): Promise<RuntimeActionDispatchResult> {
- "use step";
-
- const prepared = await prepareRuntimeActionDispatch({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- taskControls: false,
- });
- if (prepared === undefined) {
- return { results: [], sessionState: input.sessionState, pendingTasks: [] };
- }
-
- const { batch, bundle, session } = prepared;
- // Acquired only once preflight can no longer throw, so a planning failure
- // never leaks the writer lock.
- const writer = input.parentWritable.getWriter();
-
- let nextSession = session;
- const results: RuntimeActionResult[] = [];
-
- try {
- for (const entry of prepared.plan) {
- if (entry.kind === "reject") {
- results.push(entry.result);
- continue;
- }
- if (entry.kind === "workflow-tool") {
- const started = await startWorkflowTool({
- action: entry.action,
- batchEvent: batch.event,
- ownerInboxToken: input.parentContinuationToken,
- prepared,
- session: nextSession,
- });
- nextSession = started.session;
- if (started.result !== undefined) results.push(started.result);
- continue;
- }
- if (entry.kind === "task-control") {
- // Unreachable: the plan was built with `taskControls: false`.
- throw new Error("Task-control actions require the task dispatch step.");
- }
-
- let outcome: DispatchOutcome;
- switch (entry.kind) {
- case "resume":
- outcome = await dispatchToAgentHandle({
- action: entry.action,
- activityObserver:
- prepared.activityObserver === undefined
- ? undefined
- : deriveChildActivityObserverConfig({
- activityObserver: prepared.activityObserver,
- callId: entry.action.callId,
- kind: entry.action.kind === "remote-agent-call" ? "remote-agent" : "subagent",
- name:
- entry.action.kind === "remote-agent-call"
- ? entry.action.remoteAgentName
- : entry.action.subagentName,
- parentSessionId: session.sessionId,
- parentTurnId: batch.event.turnId,
- }),
- agentId: entry.agentId,
- auth: prepared.auth,
- bundle: createAgentContinuationBundle({
- action: entry.action,
- bundle,
- dynamicRemoteAgent: entry.dynamicRemoteAgent,
- }),
- currentSession: nextSession,
- parentToken: input.parentContinuationToken ?? session.continuationToken,
- parentTurnId: batch.event.turnId,
- });
- break;
- case "start":
- outcome = await startSubagent({
- auth: prepared.auth,
- batchEvent: batch.event,
- bundle,
- callbackBaseUrl: input.callbackBaseUrl,
- capabilities: prepared.capabilities,
- channelMetadata: prepared.channelMetadata,
- currentSession: nextSession,
- fanoutSize: prepared.fanoutSize,
- initiatorAuth: prepared.initiatorAuth,
- localDevRequest: prepared.localDevRequest,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext: prepared.parentTraceContext,
- activityObserver: prepared.activityObserver,
- sandboxSessionId: prepared.sandboxSessionId,
- serializedContext: prepared.serializedContext,
- session,
- taskOwned: false,
- target: entry.target,
- });
- break;
- }
-
- nextSession = outcome.session;
- if (outcome.kind === "error") {
- results.push(outcome.result);
- continue;
- }
-
- await emitSubagentCalled({
- adapter: prepared.adapter,
- adapterCtx: prepared.adapterCtx,
- batchEvent: batch.event,
- entry,
- outcome,
- sessionId: session.sessionId,
- writer,
- });
- }
- } finally {
- writer.releaseLock();
- }
-
- return {
- results,
- sessionState:
- nextSession === session
- ? prepared.getBaselineSessionState()
- : createDurableSessionState({ session: nextSession }),
- pendingTasks: [],
- };
-}
diff --git a/packages/eve/src/execution/dispatch-start-operation.ts b/packages/eve/src/execution/dispatch-start-operation.ts
index a8149e0b8..d4da5532d 100644
--- a/packages/eve/src/execution/dispatch-start-operation.ts
+++ b/packages/eve/src/execution/dispatch-start-operation.ts
@@ -1,5 +1,9 @@
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import { deriveAgentId, type AgentIdentity, type StartOperation } from "#harness/handles/store.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
+import {
+ deriveAgentId,
+ type AgentIdentity,
+ type StartOperation,
+} from "#subagents/handles/store.js";
/**
* Mints deterministic parent-controlled ownership data before the child exists,
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
deleted file mode 100644
index aa7ab5236..000000000
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { deserializeContext } from "#context/serialize.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
-import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";
-import {
- createDurableSessionState,
- type DurableSessionState,
- readDurableSession,
-} from "#execution/durable-session-store.js";
-import { hydrateDurableSession } from "#execution/session.js";
-import {
- getPendingWorkflowInterrupt,
- setPendingWorkflowUsedCalls,
-} from "#harness/workflow-interrupt-state.js";
-import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
-import { buildRuntimeActionsFromWorkflowInterrupt } from "#harness/workflow-runtime-action-state.js";
-import {
- planWorkflowSubagentDispatch,
- type WorkflowSubagentDispatchPlan,
-} from "#harness/workflow-subagent-limit.js";
-import { getSubagentDelegationName, isSubagentDelegationAction } from "#harness/subagent-depth.js";
-import { createLogger } from "#internal/logging.js";
-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import type { RuntimeSubagentDispatchFailure, RuntimeActionResult } from "#shared/action-types.js";
-import type { PendingDispatchAction } from "#shared/dispatch-action.js";
-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
-
-const log = createLogger("execution.dispatch-workflow-runtime-actions");
-
-/** Dispatches the child-agent action currently blocking a dynamic workflow. */
-export async function dispatchWorkflowRuntimeActionsStep(input: {
- readonly callbackBaseUrl?: string;
- readonly parentContinuationToken?: string;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<{
- readonly results: readonly RuntimeActionResult[];
- readonly sessionState: DurableSessionState;
- readonly pendingTasks: readonly {
- readonly taskInboxToken: string;
- readonly taskId: string;
- readonly taskRunId: string;
- }[];
-}> {
- "use step";
-
- const durableSession = await readDurableSession(input.sessionState);
- const pending = getPendingWorkflowInterrupt(durableSession.state);
- if (pending === undefined) {
- return { results: [], sessionState: input.sessionState, pendingTasks: [] };
- }
-
- const actions = buildRuntimeActionsFromWorkflowInterrupt(pending.interrupt);
- if (actions.length === 0) {
- return { results: [], sessionState: input.sessionState, pendingTasks: [] };
- }
-
- const ctx = await deserializeContext(input.serializedContext);
- const bundle = ctx.require(BundleKey);
- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
-
- const plan = planWorkflowSubagentDispatch({
- actions,
- maxSubagents: durableSession.workflowMaxSubagents,
- usedCalls: pending.usedCalls,
- });
-
- const blockedResults = plan.blocked.map((action) => {
- log.warn("workflow subagent limit reached; blocking delegated call", {
- callId: action.callId,
- maxSubagents: plan.maxSubagents,
- subagentName: isSubagentDelegationAction(action)
- ? getSubagentDelegationName(action)
- : action.target.kind,
- usedCalls: plan.usedCalls,
- });
- return createWorkflowSubagentLimitResult({ action, plan });
- });
-
- if (plan.allowed.length === 0) {
- return { results: blockedResults, sessionState: input.sessionState, pendingTasks: [] };
- }
-
- const session = hydrateDurableSession({
- compactionOverrides: {
- thresholdPercent: effectiveAgent.thresholdPercent,
- },
- durable: durableSession,
- turnAgent: effectiveAgent.turnAgent,
- });
-
- const sessionWithUsage = setPendingWorkflowUsedCalls({
- session,
- usedCalls: pending.usedCalls + plan.allowed.length,
- });
- const sessionWithBatch = setPendingRuntimeActionBatch({
- actions: plan.allowed,
- event: { sequence: 0, stepIndex: 0, turnId: "workflow-dispatch" },
- responseMessages: [],
- session: sessionWithUsage,
- });
-
- // Interrupt-sourced batches obey the same mode split as model-authored
- // ones: task agents wrap every delegation in the task lifecycle.
- const dispatchStep =
- bundle.resolvedAgent.config?.experimental?.tasks === true
- ? dispatchTaskStep
- : dispatchRuntimeActionsStep;
- const dispatched = await dispatchStep({
- callbackBaseUrl: input.callbackBaseUrl,
- parentContinuationToken: input.parentContinuationToken,
- parentWritable: input.parentWritable,
- serializedContext: input.serializedContext,
- sessionState: createDurableSessionState({ session: sessionWithBatch }),
- });
-
- if (blockedResults.length === 0) {
- return dispatched;
- }
-
- return {
- results: [...dispatched.results, ...blockedResults],
- sessionState: dispatched.sessionState,
- pendingTasks: dispatched.pendingTasks,
- };
-}
-
-function createWorkflowSubagentLimitResult(input: {
- readonly action: PendingDispatchAction;
- readonly plan: WorkflowSubagentDispatchPlan;
-}): RuntimeSubagentDispatchFailure {
- const subagentName = isSubagentDelegationAction(input.action)
- ? getSubagentDelegationName(input.action)
- : input.action.target.kind;
-
- return {
- callId: input.action.callId,
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: "WORKFLOW_SUBAGENT_LIMIT_REACHED",
- maxSubagents: input.plan.maxSubagents,
- message: `Workflow subagent limit reached (${String(input.plan.maxSubagents)}); "${subagentName}" was not called.`,
- },
- subagentName,
- };
-}
diff --git a/packages/eve/src/execution/durable-session-store.test.ts b/packages/eve/src/execution/durable-session-store.test.ts
index 0c032b99a..7d30ccbb0 100644
--- a/packages/eve/src/execution/durable-session-store.test.ts
+++ b/packages/eve/src/execution/durable-session-store.test.ts
@@ -54,8 +54,8 @@ describe("durable-session-store cross-version contract", () => {
// Closed contract: pending-batch flags live on `NextDriverAction`
// arms, not on the driver-visible state.
expect(state).not.toHaveProperty("hasPendingInputBatch");
- expect(state).not.toHaveProperty("hasPendingRuntimeActionBatch");
- expect(state).not.toHaveProperty("pendingRuntimeActionKeys");
+ expect(state).not.toHaveProperty("hasPendingCoordinationBatch");
+ expect(state).not.toHaveProperty("pendingCoordinationCallIds");
expect(state).not.toHaveProperty("snapshot");
});
@@ -127,8 +127,14 @@ describe("durable-session-store cross-version contract", () => {
{ kind: "done", output: "ok", serializedContext: ctx, sessionState: baseState },
{ kind: "park", serializedContext: ctx, sessionState: baseState },
{
- kind: "dispatch-runtime-actions",
- pendingActionKeys: ["subagent-call:foo:call-1"],
+ kind: "dispatch-coordination",
+ pendingCallIds: ["call-1"],
+ serializedContext: ctx,
+ sessionState: baseState,
+ },
+ {
+ kind: "dispatch-workflow-tasks",
+ pendingCallIds: ["call-2"],
serializedContext: ctx,
sessionState: baseState,
},
@@ -136,7 +142,7 @@ describe("durable-session-store cross-version contract", () => {
// Lock the closed-contract kind set. Adding a new arm is breaking.
expect(new Set(arms.map((a) => a.kind))).toEqual(
- new Set(["done", "park", "dispatch-runtime-actions"]),
+ new Set(["done", "park", "dispatch-coordination", "dispatch-workflow-tasks"]),
);
});
diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.ts
index 08ca4345c..00a4158eb 100644
--- a/packages/eve/src/execution/durable-session-store.ts
+++ b/packages/eve/src/execution/durable-session-store.ts
@@ -85,7 +85,7 @@ export interface DurableSession {
readonly outputSchema?: JsonObject;
readonly state?: SessionStateMap;
readonly sandboxState?: SandboxState;
- readonly subagentDepth?: number;
+ readonly taskId?: string;
readonly workflowMaxSubagents?: number;
readonly agent: {
readonly system: string;
diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.ts
index 5c9d12ae7..4b9d23120 100644
--- a/packages/eve/src/execution/eve-workflow-attributes.ts
+++ b/packages/eve/src/execution/eve-workflow-attributes.ts
@@ -17,7 +17,7 @@
* - `$eve.type` — `"session" | "turn" | "subagent"`
* - `$eve.parent` — sessionId of the **immediate** parent
* - `$eve.root` — sessionId of the **root** session in the chain
- * - `$eve.parent_call` — parent runtime-action tool call id (subagent rows only)
+ * - `$eve.parent_call` — parent task tool-call id (subagent rows only)
* - `$eve.parent_turn` — parent turn id that dispatched the subagent (subagent rows only)
* - `$eve.subagent` — active compiled graph node id (subagent rows only)
* - `$eve.trigger` — channel adapter kind (session/subagent rows)
diff --git a/packages/eve/src/execution/finalize-terminal-session.ts b/packages/eve/src/execution/finalize-terminal-session.ts
deleted file mode 100644
index 992a999f1..000000000
--- a/packages/eve/src/execution/finalize-terminal-session.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { TurnCaller } from "#channel/types.js";
-import {
- notifyDelegatedParentStep,
- notifyTurnCallerStep,
-} from "#execution/delegated-parent-notification.js";
-import { createDelegatedSubagentSuccessResult } from "#execution/delegated-parent-result.js";
-import type { DurableSessionState } from "#execution/durable-session-store.js";
-import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
-import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
-import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
-import type { RunMode } from "#shared/run-mode.js";
-
-/** Completes a session that terminates outside a turn. */
-export async function finalizeTerminalSession(input: {
- readonly caller: TurnCaller | undefined;
- readonly driverWritable: WritableStream<Uint8Array>;
- readonly mode: RunMode;
- readonly notifyCaller: boolean;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
- readonly terminalState: { terminalEmitted: boolean };
-}): Promise<{ readonly output: unknown }> {
- await terminateChildSessionsStep({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
- await emitTerminalSessionCompletionStep({
- parentWritable: input.driverWritable,
- serializedContext: input.serializedContext,
- });
- input.terminalState.terminalEmitted = true;
-
- if (!input.notifyCaller) return { output: "" };
-
- if (input.mode === "task") {
- await fireSessionCallbackStep({
- output: "",
- serializedContext: input.serializedContext,
- status: "completed",
- });
- await notifyDelegatedParentStep({
- result: createDelegatedSubagentSuccessResult(input.serializedContext, ""),
- serializedContext: input.serializedContext,
- });
- } else if (input.caller !== undefined) {
- await notifyTurnCallerStep({
- caller: input.caller,
- lifecycle: "terminal",
- sessionId: input.sessionState.sessionId,
- settled: { output: "" },
- });
- }
- return { output: "" };
-}
diff --git a/packages/eve/src/execution/inline-turn.ts b/packages/eve/src/execution/inline-turn.ts
index f00a8190e..767023eda 100644
--- a/packages/eve/src/execution/inline-turn.ts
+++ b/packages/eve/src/execution/inline-turn.ts
@@ -105,8 +105,8 @@ export async function runInlineTurn(input: {
}
if (
- result.action === "dispatch-workflow-runtime-actions" ||
- (result.action === "park" && result.pendingRuntimeActionKeys !== undefined)
+ result.action === "dispatch-workflow-tasks" ||
+ (result.action === "park" && result.pendingCoordinationCallIds !== undefined)
) {
return childOutcome(control, initialStep);
}
diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
index fa5c91aa0..5d2268730 100644
--- a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
@@ -12,9 +12,9 @@ import { SessionCallbackKey, SessionIdKey } from "#context/keys.js";
import {
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
-} from "#execution/delegated-parent-notification.js";
-import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
-import { startRemoteAgentSession } from "#execution/remote-agent-dispatch.js";
+} from "#subagents/parent-notification.js";
+import { fireSessionCallbackStep } from "#subagents/callback-step.js";
+import { startRemoteAgentSession } from "#subagents/remote-dispatch.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import { authHookToken, CallbackBaseUrlKey, getHookUrl } from "#harness/authorization.js";
import {
diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.ts
index 62c2010d7..1ffc4930d 100644
--- a/packages/eve/src/execution/next-driver-action.ts
+++ b/packages/eve/src/execution/next-driver-action.ts
@@ -42,16 +42,13 @@ export type DurableStepResult = (
readonly authorizationNames?: readonly string[];
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
- readonly pendingRuntimeActionKeys?: readonly string[];
- /** The batch starts workflow tool runs, which report to the turn's run channels. */
- readonly startsWorkflowToolRuns?: boolean;
- readonly tasksEnabled?: boolean;
+ readonly pendingCoordinationCallIds?: readonly string[];
readonly sleepDurationMs?: number;
readonly settled?: SettledTurn;
}
| {
- readonly action: "dispatch-workflow-runtime-actions";
- readonly pendingRuntimeActionKeys: readonly string[];
+ readonly action: "dispatch-workflow-tasks";
+ readonly pendingTaskCallIds: readonly string[];
readonly sleepDurationMs?: number;
}
) &
@@ -94,14 +91,14 @@ export type NextDriverAction =
readonly settled?: SettledTurn;
}
| {
- readonly kind: "dispatch-runtime-actions";
- readonly pendingActionKeys: readonly string[];
+ readonly kind: "dispatch-coordination";
+ readonly pendingCallIds: readonly string[];
readonly sessionState: DurableSessionState;
readonly serializedContext: Record<string, unknown>;
}
| {
- readonly kind: "dispatch-workflow-runtime-actions";
- readonly pendingActionKeys: readonly string[];
+ readonly kind: "dispatch-workflow-tasks";
+ readonly pendingCallIds: readonly string[];
readonly sessionState: DurableSessionState;
readonly serializedContext: Record<string, unknown>;
};
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index 336f9c7ce..71110730e 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -12,7 +12,6 @@ import {
} from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { appendPendingInputBatch } from "#harness/input-requests.js";
-import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
import { createInstrumentationHooks } from "#instrumentation/lifecycle.js";
import {
bindInstrumentationRuntime,
@@ -25,14 +24,18 @@ import { ROOT_RUNTIME_AGENT_NODE_ID, type ResolvedRuntimeAgentNode } from "#runt
import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";
import type { RuntimeToolRegistry } from "#runtime/tools/registry.js";
import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";
+import { createPreparedRuntimeSubagentTool } from "#runtime/subagents/registry.js";
import { createExecutionNodeStep, createNodeHarnessTools } from "#execution/node-step.js";
-import { countLocalSubagentCalls } from "#execution/tools/subagent/local.js";
import { createSession } from "#execution/session.js";
import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registry.js";
import { defineTool } from "#tools/definition.js";
import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";
import { toInputSchema } from "#tools/schema.js";
-import { AGENT_TOOL_DESCRIPTION } from "#tools/framework/agent-contract.js";
+import {
+ AGENT_TOOL_DESCRIPTION,
+ AGENT_TOOL_NAME,
+ SUBAGENT_TOOL_INPUT_SCHEMA,
+} from "#tools/framework/agent-contract.js";
vi.mock("ai", () => ({
ToolLoopAgent: vi.fn(),
@@ -113,80 +116,6 @@ function setupMockAgentForToolExecution(toolName: string, args: unknown): void {
: never);
}
-function setupMockAgentForToolCall(toolName: string, args: unknown): void {
- vi.mocked(ToolLoopAgent).mockImplementation(function (
- this: Record<string, unknown>,
- settings: Record<string, unknown>,
- ) {
- const prepareStep = settings.prepareStep as
- | ((...args: unknown[]) => Promise<unknown>)
- | undefined;
- const onStepFinish = settings.onStepFinish as
- | ((...args: unknown[]) => Promise<unknown>)
- | undefined;
-
- this.generate = vi.fn().mockImplementation(async (options: { messages: unknown[] }) => {
- if (prepareStep) {
- await prepareStep({
- context: undefined,
- messages: options.messages,
- model: {},
- stepNumber: 0,
- steps: [],
- });
- }
-
- const result = {
- content: [
- {
- input: args,
- toolCallId: "call-subagent-1",
- toolName,
- type: "tool-call",
- },
- ],
- finishReason: "tool-calls",
- response: {
- messages: [
- {
- content: [
- {
- input: args,
- toolCallId: "call-subagent-1",
- toolName,
- type: "tool-call",
- },
- ],
- role: "assistant",
- },
- ],
- },
- text: undefined,
- toolCalls: [
- {
- input: args,
- toolCallId: "call-subagent-1",
- toolName,
- type: "tool-call",
- },
- ],
- toolResults: [],
- usage: undefined,
- };
-
- if (onStepFinish) {
- await onStepFinish(result);
- }
-
- return { ...result, responseMessages: result.response.messages };
- });
-
- return this as unknown as ToolLoopAgent;
- } as unknown as ConstructorParameters<typeof ToolLoopAgent> extends [infer S]
- ? (settings: S) => ToolLoopAgent
- : never);
-}
-
function createEmptyToolRegistry(): RuntimeToolRegistry {
return {
preparedTools: [],
@@ -211,35 +140,14 @@ function createTestNode(
turnAgent?: RuntimeTurnAgent,
overrides: Partial<ResolvedRuntimeAgentNode> = {},
): ResolvedRuntimeAgentNode {
- const sandboxRegistry = createStubSandboxRegistry();
- const agent: ResolvedRuntimeAgentNode["agent"] = {
- channels: [],
- connections: [],
- dynamicConnectionResolvers: [],
- dynamicInstructionsResolvers: [],
- dynamicSkillResolvers: [],
- dynamicToolResolvers: [],
- hooks: [],
- instructions: [],
- memories: [],
- metadata: {
- agentRoot: "",
- appRoot: "",
- diagnosticsSummary: { errors: 0, warnings: 0 },
- },
- sandbox: sandboxRegistry.sandbox.definition,
- skills: [],
- tools: [],
- workspaceResourceRoot: sandboxRegistry.sandbox.workspaceResourceRoot,
- workspaceSpec: { rootEntries: [] },
- };
+ const agent = {} as ResolvedRuntimeAgentNode["agent"];
return {
agent,
channels: [],
hookRegistry: createEmptyHookRegistry(),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- sandboxRegistry,
+ sandboxRegistry: createStubSandboxRegistry(),
subagentRegistry: {
dynamicNodeIds: new Set(),
dynamicResolvers: [],
@@ -255,43 +163,21 @@ function createTestNode(
async function createNodeWithSourceOwnedTools(input: {
readonly names: readonly string[];
- readonly tasks?: boolean;
readonly turnTools?: StaticRuntimeTurnAgent["tools"];
}): Promise<ResolvedRuntimeAgentNode> {
- const toolRegistry = await createRuntimeToolRegistry(
- {
- tools: input.names.map((name) => ({
- behavior:
- name === "agent"
- ? {
- availability: ["root-session"],
- handling: { action: "self-agent", kind: "dispatch" },
- }
- : name === "ask_question"
- ? {
- availability: ["requires-request-input"],
- handling: { kind: "request-input", request: "question" },
- }
- : name === "task_cancel"
- ? {
- availability: ["root-session"],
- handling: { action: "task-cancel", kind: "dispatch" },
- }
- : {
- availability: ["delegated-task-child"],
- handling: { action: "task-update", kind: "dispatch" },
- },
- description: name === "agent" ? AGENT_TOOL_DESCRIPTION : `${name} programmatic tool.`,
- inputSchema: null,
- logicalPath: `tools/${name}.ts`,
- name,
- owner: { feature: "test", kind: "framework" },
- sourceId: `framework:tools/${name}.ts`,
- sourceKind: "module",
- })),
- },
- { nodeId: ROOT_RUNTIME_AGENT_NODE_ID },
- );
+ const toolRegistry = await createRuntimeToolRegistry({
+ tools: input.names.map((name) => ({
+ description: name === AGENT_TOOL_NAME ? AGENT_TOOL_DESCRIPTION : `${name} programmatic tool.`,
+ execute: async () => `${name}-sentinel`,
+ execution: name === AGENT_TOOL_NAME ? "background" : undefined,
+ inputSchema: name === AGENT_TOOL_NAME ? SUBAGENT_TOOL_INPUT_SCHEMA : null,
+ logicalPath: `tools/${name}.ts`,
+ name,
+ owner: { feature: "test", kind: "framework" },
+ sourceId: `framework:tools/${name}.ts`,
+ sourceKind: "module",
+ })),
+ });
const node = createTestNode(
createTestTurnAgent({
tools: [...toolRegistry.preparedTools, ...(input.turnTools ?? [])],
@@ -303,7 +189,6 @@ async function createNodeWithSourceOwnedTools(input: {
agent: {
...node.agent,
config: {
- experimental: { tasks: input.tasks === true },
model: { id: "test-model" },
name: "test",
},
@@ -335,7 +220,7 @@ describe("createNodeHarnessTools", () => {
expect(createNodeHarnessTools({ node }).get("ask_question")?.execute).toBeUndefined();
});
- it("lowers the compiled framework agent tool to the canonical dispatch action", async () => {
+ it("lowers the compiled framework agent tool as a background tool", async () => {
const node = await createNodeWithSourceOwnedTools({ names: ["agent"] });
const agentTool = createNodeHarnessTools({ node }).get("agent");
@@ -345,133 +230,65 @@ describe("createNodeHarnessTools", () => {
expect(agentTool?.description).toContain("include essential context");
expect(agentTool?.description).toContain("non-overlapping scopes");
expect(agentTool?.description).not.toContain("eve");
- expect(agentTool?.behavior?.handling).toEqual({
- kind: "dispatch",
- target: {
- kind: "self-agent-call",
- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- subagentName: "agent",
- },
- });
+ expect(agentTool?.execution).toBe("background");
+ expect(agentTool?.runtimeAction).toBeUndefined();
+ expect(agentTool?.execute).toBeDefined();
});
- it("omits compiled task-control tools unless experimental.tasks is on", async () => {
+ it("lowers compiled task-control tools from their framework definitions", async () => {
const node = await createNodeWithSourceOwnedTools({
names: ["task_cancel", "task_update"],
});
const tools = createNodeHarnessTools({ node });
for (const name of ["task_cancel", "task_update"]) {
- expect(tools.has(name)).toBe(false);
- }
- });
-
- it("lowers compiled task-control tools when experimental.tasks is on", async () => {
- const tools = createNodeHarnessTools({
- node: await createNodeWithSourceOwnedTools({
- names: ["task_cancel", "task_update"],
- tasks: true,
- }),
- });
-
- for (const name of ["task_cancel", "task_update"]) {
- expect(tools.get(name)?.behavior?.handling).toEqual({
- kind: "dispatch",
- target: { kind: name === "task_cancel" ? "task-cancel" : "task-update" },
- });
+ expect(tools.get(name)?.runtimeAction).toEqual({ kind: "task-control" });
expect(tools.get(name)?.execute).toBeUndefined();
}
expect(tools.has("task_sleep")).toBe(false);
});
- it("executes compiled local and remote delegation tools in the selected task mode", async () => {
+ it("executes compiled local and remote delegation tools as background tasks", async () => {
const delegationTools: StaticRuntimeTurnAgent["tools"] = [
- {
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "subagents/research",
- subagentName: "research",
- },
- },
- },
+ createPreparedRuntimeSubagentTool({
description: "Delegate local research.",
- inputSchema: { type: "object" },
kind: "subagent",
logicalPath: "subagents/research",
name: "research",
nodeId: "subagents/research",
sourceId: "subagents/research",
- },
- {
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "remote-agent-call",
- nodeId: "remote-agents/reviewer",
- remoteAgentName: "reviewer",
- },
- },
- },
+ sourceKind: "module",
+ }),
+ createPreparedRuntimeSubagentTool({
description: "Delegate remote review.",
- inputSchema: { type: "object" },
kind: "remote",
logicalPath: "remote-agents/reviewer",
name: "reviewer",
nodeId: "remote-agents/reviewer",
+ path: "/eve/v1/session",
sourceId: "remote-agents/reviewer",
- },
- ];
- const legacy = createNodeHarnessTools({
- node: await createNodeWithSourceOwnedTools({
- names: ["agent"],
- turnTools: delegationTools,
+ sourceKind: "module",
+ url: "https://review.example.com",
}),
- });
- expect(legacy.get("research")?.behavior?.handling).toMatchObject({
- kind: "dispatch",
- target: { kind: "subagent-call" },
- });
- expect(legacy.get("reviewer")?.behavior?.handling).toMatchObject({
- kind: "dispatch",
- target: { kind: "remote-agent-call" },
- });
- expect(legacy.get("research")?.execution).toBeUndefined();
- expect(legacy.get("reviewer")?.execution).toBeUndefined();
-
- const background = createNodeHarnessTools({
+ ];
+ const tools = createNodeHarnessTools({
node: await createNodeWithSourceOwnedTools({
names: ["agent"],
- tasks: true,
turnTools: delegationTools,
}),
});
- for (const name of ["agent", "research", "reviewer"]) {
- expect(background.get(name)?.execution).toBe("background");
- expect(background.get(name)?.execute).toBeDefined();
- expect(background.get(name)?.behavior?.handling?.kind).toBe("dispatch");
+ for (const name of ["research", "reviewer"]) {
+ expect(tools.get(name)?.execution).toBe("background");
+ expect(tools.get(name)?.execute).toBeDefined();
+ expect(tools.get(name)?.runtimeAction).toBeUndefined();
+ expect(tools.get(name)?.resultKind).toBe("subagent");
+ expect(tools.get(name)?.workflowId).toBe("workflow//eve//subagentToolExecuteWorkflow");
}
- expect(
- countLocalSubagentCalls(
- ["agent", "research", "reviewer"].map((name) => {
- const definition = background.get(name);
- if (definition?.execute === undefined) {
- throw new Error(`Missing background executor for ${name}.`);
- }
- return { definition };
- }),
- ),
- ).toBe(2);
});
it("does not recreate task tools absent from the compiled graph", async () => {
const tools = createNodeHarnessTools({
- node: await createNodeWithSourceOwnedTools({ names: ["task_update"], tasks: true }),
+ node: await createNodeWithSourceOwnedTools({ names: ["task_update"] }),
});
expect(tools.has("task_update")).toBe(true);
@@ -480,10 +297,9 @@ describe("createNodeHarnessTools", () => {
});
describe("createExecutionNodeStep", () => {
- it("keeps the instrumentation drain on the root harness-step critical path", async () => {
+ it("builds a usable harness step for the root node", async () => {
setupMockAgentForToolExecution("regular-tool", { question: "Run the tool." });
- const flush = Promise.withResolvers<void>();
- const forceFlush = vi.fn(() => flush.promise);
+ const forceFlush = vi.fn(async () => undefined);
const runtime: InstrumentationRuntime = {
forceFlush,
hooks: createInstrumentationHooks([]),
@@ -545,35 +361,24 @@ describe("createExecutionNodeStep", () => {
turn: { id: "root-turn", sequence: 0 },
});
- let stepSettled = false;
- const resultPromise = contextStorage
- .run(ctx, () =>
- step(
- createSession({
- continuationToken: "test-root",
- sessionId: "sess-root",
- turnAgent: rootNode.turnAgent,
- }),
- {
- message: "Run the tool.",
- },
- ),
- )
- .finally(() => {
- stepSettled = true;
- });
-
- await vi.waitFor(() => expect(forceFlush).toHaveBeenCalledOnce());
- expect(stepSettled).toBe(false);
- flush.resolve();
- const result = await resultPromise;
+ const result = await contextStorage.run(ctx, () =>
+ step(
+ createSession({
+ continuationToken: "test-root",
+ sessionId: "sess-root",
+ turnAgent: rootNode.turnAgent,
+ }),
+ {
+ message: "Run the tool.",
+ },
+ ),
+ );
expect(result.next).toEqual({ done: true, output: "tool-output" });
expect(resolveRuntimeModelReference).toHaveBeenCalledWith(
rootNode.turnAgent.model,
modelResolutionScope,
);
- expect(stepSettled).toBe(true);
});
it("prepares persisted step tools with the node's dynamic resolvers", async () => {
@@ -611,14 +416,13 @@ describe("createExecutionNodeStep", () => {
},
};
setupMockAgentForToolExecution("wired_dynamic_tool", {});
- const stepInput = {
+ const step = createExecutionNodeStep({
createRuntime: () => createNoopRuntime(),
instrumentation: undefined,
- mode: "task" as const,
+ mode: "task",
modelResolutionScope: { moduleMap: { nodes: {} }, nodeId: undefined },
node,
- };
- const step = createExecutionNodeStep(stepInput);
+ });
const responder = {
attributes: {},
@@ -722,168 +526,4 @@ describe("createExecutionNodeStep", () => {
expect.objectContaining({ callId: "call-wired_dynamic_tool" }),
);
});
-
- it("always advertises load_skill when the node has no compiled skills", async () => {
- setupMockAgentForToolExecution("load_skill", { skill: "deploy-note" });
- const toolRegistry = await createRuntimeToolRegistry({
- tools: [
- {
- behavior: {
- availability: [],
- presentation: "load-skill",
- },
- description: "Load one skill.",
- execute: async () => "deploy-note instructions",
- inputSchema: toInputSchema({ type: "object" }),
- logicalPath: "tools/load_skill.ts",
- name: "load_skill",
- owner: { feature: "load-skill", kind: "framework" },
- sourceId: "framework:tools/load_skill.ts",
- sourceKind: "module",
- },
- ],
- });
- const rootNode = createTestNode(createTestTurnAgent({ tools: toolRegistry.preparedTools }), {
- toolRegistry,
- });
- expect(rootNode.agent.skills).toEqual([]);
- const step = createExecutionNodeStep({
- createRuntime: () => createNoopRuntime(),
- instrumentation: undefined,
- mode: "task",
- modelResolutionScope: { moduleMap: { nodes: {} }, nodeId: undefined },
- node: rootNode,
- });
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(InitiatorAuthKey, null);
- ctx.set(BundleKey, {
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- } as never);
- ctx.set(ChannelKey, { kind: "http" });
- ctx.set(SessionIdKey, "sess-root");
- ctx.set(SessionKey, {
- auth: { current: null, initiator: null },
- sessionId: "sess-root",
- turn: { id: "root-turn", sequence: 0 },
- });
-
- const result = await contextStorage.run(ctx, () =>
- step(
- createSession({
- continuationToken: "test-root",
- sessionId: "sess-root",
- turnAgent: rootNode.turnAgent,
- }),
- { message: "Load the deploy note skill." },
- ),
- );
-
- expect(result.next).toEqual({ done: true, output: "deploy-note instructions" });
- });
-
- it("records visible subagent tools as pending runtime actions", async () => {
- setupMockAgentForToolCall("child-agent", { task: "Delegate this." });
-
- const createRuntime = vi.fn();
-
- const testCompiledArtifactsSource = createBundledRuntimeCompiledArtifactsSource();
- const rootNode = createTestNode(
- createTestTurnAgent({
- tools: [
- {
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "child-node",
- subagentName: "child-agent",
- },
- },
- },
- description: "Delegate work to the child agent.",
- inputSchema: { type: "object" },
- kind: "subagent",
- logicalPath: "subagents/child",
- name: "child-agent",
- nodeId: "child-node",
- sourceId: "subagents/child",
- },
- ],
- }),
- );
- const step = createExecutionNodeStep({
- createRuntime,
- instrumentation: undefined,
- mode: "task",
- modelResolutionScope: {
- moduleMap: { nodes: {} },
- nodeId: undefined,
- },
- node: rootNode,
- });
-
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(InitiatorAuthKey, null);
- ctx.set(BundleKey, { compiledArtifactsSource: testCompiledArtifactsSource } as never);
- ctx.set(ChannelKey, { kind: "http" });
- ctx.set(SessionIdKey, "parent-session");
- ctx.set(SessionKey, {
- auth: { current: null, initiator: null },
- sessionId: "parent-session",
- turn: { id: "parent-turn", sequence: 0 },
- });
-
- const result = await contextStorage.run(ctx, async () =>
- step(
- createSession({
- continuationToken: "test-root",
- sessionId: "sess-root",
- turnAgent: rootNode.turnAgent,
- }),
- {
- message: "Delegate this.",
- },
- ),
- );
-
- expect(result.next).toBeNull();
- expect(createRuntime).not.toHaveBeenCalled();
- expect(getPendingRuntimeActionBatch(result.session.state)).toEqual({
- actions: [
- {
- callId: "call-subagent-1",
- description: "Delegate work to the child agent.",
- input: { task: "Delegate this." },
- target: {
- kind: "subagent-call",
- nodeId: "child-node",
- subagentName: "child-agent",
- },
- toolName: "child-agent",
- },
- ],
- event: {
- sequence: 0,
- stepIndex: 0,
- turnId: "",
- },
- responseMessages: [
- {
- content: [
- {
- input: { task: "Delegate this." },
- toolCallId: "call-subagent-1",
- toolName: "child-agent",
- type: "tool-call",
- },
- ],
- role: "assistant",
- },
- ],
- });
- });
});
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index a5d5db73e..3b4a62703 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -3,19 +3,14 @@ import type { LanguageModel } from "ai";
import type { Runtime, SessionCapabilities } from "#channel/types.js";
import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";
import { preparePersistedStepDynamicToolMetadata } from "#context/dynamic-tool-lifecycle.js";
-import {
- createBackgroundSubagentHarnessDefinition,
- createHarnessDelegationToolDefinition,
-} from "#execution/delegation-tool.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { ExecutionInstrumentation } from "#instrumentation/runtime.js";
+import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
import { createToolLoopHarness } from "#harness/tool-loop.js";
import type { HandleEventFn, HarnessToolMap, StepFn } from "#harness/types.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { createLogger } from "#internal/logging.js";
import type { RuntimeIdentity } from "#protocol/message.js";
-import type { PreparedDispatchTarget } from "#tools/behavior.js";
-import type { ToolExecution } from "#tools/definition.js";
import { UNSPECIFIED_INPUT_SCHEMA } from "#tools/schema.js";
import type { RunMode } from "#shared/run-mode.js";
import {
@@ -23,14 +18,19 @@ import {
type RuntimeModelResolutionScope,
} from "#runtime/agent/resolve-model.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { createTaskToolHarnessDefinitions } from "#execution/tools/tasks.js";
import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";
-import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
+import type { PreparedRuntimeTool, PreparedRuntimeWorkflowTask } from "#runtime/sessions/turn.js";
import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
-import { createWorkflowToolBackgroundExecute } from "#execution/tool-run/background.js";
+import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";
+import {
+ createPreparedWorkflowToolHarnessDefinition,
+ createWorkflowToolHarnessDefinition,
+} from "#execution/tools/workflow/background.js";
const log = createLogger("execution.node-step");
@@ -109,11 +109,10 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): St
historyView: input.historyView,
instrumentation: sessionInstrumentation,
mode: input.mode,
- tasksEnabled: input.node.agent.config?.experimental?.tasks === true,
onCompaction: preserveFrameworkStateOnCompaction,
- prepareStepDynamicTools: (prepareInput) =>
+ resolveStepDynamicTools: (resolveInput) =>
preparePersistedStepDynamicToolMetadata({
- ...prepareInput,
+ ...resolveInput,
resolvers: input.node.agent.dynamicToolResolvers ?? [],
}),
dispatchDynamicModelEvent: dispatchModelEvent,
@@ -186,20 +185,17 @@ function createRuntimeDynamicModelEventDispatcher(
* Resolves unified {@link HarnessToolDefinition}s from the node's registries.
*
* For authored tools: copies all lifecycle fields from the resolved definition.
- * For subagent tools: selects the existing runtime-action definition or the
- * background `defineTool` definition from the node's `experimental.tasks` setting.
+ * Prepared workflow-task tools share the workflow-tool harness path.
* Tools without `execute` (provider-managed) get entries with schema but no execute.
*/
export function createNodeHarnessTools(input: {
readonly node: ResolvedRuntimeAgentNode;
}): HarnessToolMap {
const tools = new Map<string, HarnessToolDefinition>();
- const tasksEnabled = input.node.agent.config?.experimental?.tasks === true;
for (const tool of input.node.turnAgent.tools) {
const definition = resolveHarnessToolDefinition({
node: input.node,
- tasksEnabled,
tool,
});
@@ -213,17 +209,26 @@ export function createNodeHarnessTools(input: {
function resolveHarnessToolDefinition(input: {
readonly node: ResolvedRuntimeAgentNode;
- readonly tasksEnabled: boolean;
readonly tool: PreparedRuntimeTool;
}): HarnessToolDefinition | null {
- if (input.tool.kind === "subagent" || input.tool.kind === "remote") {
- return input.tasksEnabled
- ? createBackgroundSubagentHarnessDefinition(input.tool)
- : createHarnessDelegationToolDefinition(input.tool);
- }
-
const registeredTool = findRegisteredRuntimeTool(input.node.toolRegistry, input.tool.name);
+ if (isPreparedRuntimeWorkflowTool(input.tool)) {
+ if (registeredTool === null) {
+ return createPreparedWorkflowToolHarnessDefinition(input.tool);
+ }
+ return createWorkflowToolHarnessDefinition({
+ definition: createRegisteredHarnessToolDefinition({
+ behavior: input.tool.behavior,
+ definition: registeredTool.definition,
+ rootOnly: input.tool.rootOnly,
+ }),
+ nodeId: input.tool.task.nodeId,
+ resultKind: input.tool.task.resultKind,
+ workflowId: input.tool.task.workflowId,
+ });
+ }
+
if (registeredTool === null) {
// Declared on the graph but absent from the registry (failed import, renamed export).
log.warn("declared tool is not registered — omitting from toolset", {
@@ -233,49 +238,64 @@ function resolveHarnessToolDefinition(input: {
return null;
}
- const def = registeredTool.definition;
- const dispatchTarget =
- input.tool.behavior?.handling?.kind === "dispatch"
- ? input.tool.behavior.handling.target
- : undefined;
- if (
- !input.tasksEnabled &&
- (dispatchTarget?.kind === "task-cancel" || dispatchTarget?.kind === "task-update")
- ) {
- return null;
- }
- if (dispatchTarget?.kind === "self-agent-call" && input.tasksEnabled) {
- const behavior = input.tool.behavior;
- if (behavior === undefined) {
- throw new Error(`Self-agent tool "${input.tool.name}" has no prepared behavior.`);
+ return createRegisteredHarnessToolDefinition({
+ behavior: input.tool.behavior,
+ definition: registeredTool.definition,
+ rootOnly: input.tool.rootOnly,
+ });
+}
+
+type PreparedRuntimeWorkflowTool = PreparedRuntimeTool & {
+ readonly task: PreparedRuntimeWorkflowTask;
+};
+
+function isPreparedRuntimeWorkflowTool(
+ tool: PreparedRuntimeTool,
+): tool is PreparedRuntimeWorkflowTool {
+ return tool.task !== undefined;
+}
+
+function createRegisteredHarnessToolDefinition(input: {
+ readonly behavior?: HarnessToolDefinition["behavior"];
+ readonly definition: ResolvedToolDefinition;
+ readonly rootOnly?: boolean;
+}): HarnessToolDefinition {
+ const def = input.definition;
+ if (def.owner.kind === "framework") {
+ const taskDefinition = createTaskToolHarnessDefinitions().find(
+ (definition) => definition.name === def.name,
+ );
+ if (taskDefinition !== undefined) {
+ return { ...taskDefinition, behavior: input.behavior };
}
- return createBackgroundSubagentHarnessDefinition({
- behavior,
- description: input.tool.description,
- inputSchema: input.tool.inputSchema,
- name: input.tool.name,
- outputSchema: input.tool.outputSchema,
- });
}
const rawExecute = def.execute;
+ const isFrameworkRequestInput =
+ def.owner.kind === "framework" && def.name === ASK_QUESTION_TOOL_NAME;
- return {
- behavior: input.tool.behavior,
+ const definition: HarnessToolDefinition = {
approvalKey: def.approvalKey,
+ behavior: input.behavior,
description: def.description,
execution: def.execution,
- execute: resolveAuthoredExecute({
- dispatchTarget,
- execution: def.execution,
- rawExecute,
- scope: def.name,
- }),
+ execute: isFrameworkRequestInput
+ ? undefined
+ : resolveAuthoredExecute({
+ rawExecute,
+ scope: def.name,
+ }),
+ frameworkAction:
+ def.owner.kind === "framework" && def.name === LOAD_SKILL_TOOL_NAME
+ ? "load-skill"
+ : undefined,
inputSchema: def.inputSchema ?? UNSPECIFIED_INPUT_SCHEMA,
name: def.name,
approval: def.approval,
outputSchema: def.outputSchema,
+ rootOnly: input.rootOnly,
toModelOutput: def.toModelOutput,
};
+ return definition;
}
/**
@@ -285,24 +305,12 @@ function resolveHarnessToolDefinition(input: {
* which builds a token-aware context. Providers passed to
* `ctx.getToken(provider)` use tool-qualified auth scopes.
* - Tools without `execute` (provider-managed) stay `undefined`.
- * - A workflow body never runs inside the model step: a background one is
- * started from the harness, a waiting one is dispatched by the turn.
*/
function resolveAuthoredExecute(input: {
- readonly dispatchTarget: PreparedDispatchTarget | undefined;
- readonly execution: ToolExecution | undefined;
readonly rawExecute: ResolvedToolDefinition["execute"];
readonly scope: string;
}): HarnessToolDefinition["execute"] {
const { rawExecute, scope } = input;
- if (input.dispatchTarget?.kind === "workflow-tool-call") {
- return input.execution === "background"
- ? createWorkflowToolBackgroundExecute({
- toolName: scope,
- workflowId: input.dispatchTarget.workflowId,
- })
- : undefined;
- }
if (rawExecute === undefined) {
return undefined;
}
diff --git a/packages/eve/src/execution/pending-turn-state.ts b/packages/eve/src/execution/pending-turn-state.ts
index 7be2369e2..9009c175e 100644
--- a/packages/eve/src/execution/pending-turn-state.ts
+++ b/packages/eve/src/execution/pending-turn-state.ts
@@ -1,8 +1,7 @@
import { getPendingAuthorization } from "#harness/authorization.js";
import { hasPendingInputBatch } from "#harness/input-requests.js";
-import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { getPendingCoordinationBatch } from "#harness/coordination.js";
import type { HarnessSession } from "#harness/types.js";
-import { getPendingDispatchActionKey } from "#runtime/actions/keys.js";
/** Derives the workflow fields used to select the next action at the park boundary. */
export function derivePendingState(session: HarnessSession): {
@@ -10,10 +9,9 @@ export function derivePendingState(session: HarnessSession): {
readonly authorizationNames?: readonly string[];
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
- readonly pendingRuntimeActionKeys?: readonly string[];
- readonly startsWorkflowToolRuns?: boolean;
+ readonly pendingCoordinationCallIds?: readonly string[];
} {
- const batch = getPendingRuntimeActionBatch(session.state);
+ const batch = getPendingCoordinationBatch(session.state);
const pendingAuth = getPendingAuthorization(session.state);
const base = {
authorizationAttemptIds: pendingAuth?.challenges.flatMap((challenge) =>
@@ -26,9 +24,8 @@ export function derivePendingState(session: HarnessSession): {
if (batch === undefined) return base;
return {
...base,
- pendingRuntimeActionKeys: batch.actions.map((action) => getPendingDispatchActionKey(action)),
- startsWorkflowToolRuns: batch.actions.some(
- (action) => action.target.kind === "workflow-tool-call",
+ pendingCoordinationCallIds: [...batch.runtimeActions, ...batch.tasks].map(
+ (request) => request.callId,
),
};
}
diff --git a/packages/eve/src/execution/prepared-agent-action.ts b/packages/eve/src/execution/prepared-agent-action.ts
deleted file mode 100644
index a4ad6e765..000000000
--- a/packages/eve/src/execution/prepared-agent-action.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";
-import type { PendingAgentDispatchAction } from "#shared/dispatch-action.js";
-
-/** Converts a prepared dispatch identity into the existing agent transport contract. */
-export function resolvePreparedAgentAction(action: PendingAgentDispatchAction): {
- readonly action: RuntimeAgentHandleAction;
- readonly selfAgent: boolean;
-} {
- const common = {
- callId: action.callId,
- description: action.description,
- input: action.input,
- name: action.toolName,
- nodeId: action.target.nodeId,
- };
- switch (action.target.kind) {
- case "remote-agent-call":
- return {
- action: {
- ...common,
- kind: "remote-agent-call",
- remoteAgentName: action.target.remoteAgentName,
- },
- selfAgent: false,
- };
- case "self-agent-call":
- return {
- action: {
- ...common,
- kind: "subagent-call",
- subagentName: action.target.subagentName,
- },
- selfAgent: true,
- };
- case "subagent-call":
- return {
- action: {
- ...common,
- kind: "subagent-call",
- subagentName: action.target.subagentName,
- },
- selfAgent: false,
- };
- }
-}
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index ba8c017bd..c37c67c08 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -5,10 +5,10 @@ import {
readDurableSession,
replaceDurableSessionSnapshot,
} from "#execution/durable-session-store.js";
-import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
+import { routeDeliverPayload } from "#subagents/hitl-proxy.js";
import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
-import { resumeToolRunAnswers } from "#execution/tool-run/answer.js";
+import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";
import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
import type { InputResponse } from "#shared/input.js";
import { findSessionTaskEntry } from "#tasks/session-index.js";
@@ -143,10 +143,9 @@ export async function routeProxiedDeliverStep(
let retired = false;
for (const child of children.values()) {
- // Task-owned children are addressed through their run, never
- // directly: the run must forward and clear the batch under one
- // durable decision, or a late answer could unblock a question the
- // child raised after this one.
+ // A task-owned executor is addressed through its task controller. The
+ // controller forwards the answer and clears `input_required` as one
+ // durable decision, so its view cannot claim the child resumed first.
const taskId = child.taskId;
if (taskId !== undefined) {
const entry = findSessionTaskEntry(durableSession.state, taskId);
@@ -169,16 +168,13 @@ export async function routeProxiedDeliverStep(
mergeStrandedResponses(parentPayloads, child, taskId);
continue;
}
- // Hand-off to the task run succeeded. Retire the parent-visible
- // routes so a later click cannot re-enter the same batch after the
- // run has already accepted (or no-op'd) this answer.
durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
retired = true;
continue;
}
if (child.answerHook !== undefined) {
- await resumeToolRunAnswers(
+ await resumeWorkflowToolRunAnswers(
child.childContinuationToken,
coalesceDeliverPayloads(child.payloads).inputResponses,
);
diff --git a/packages/eve/src/execution/route-child-delivery.test.ts b/packages/eve/src/execution/route-child-delivery.test.ts
index 447529881..5e9ea6c73 100644
--- a/packages/eve/src/execution/route-child-delivery.test.ts
+++ b/packages/eve/src/execution/route-child-delivery.test.ts
@@ -1,20 +1,36 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
-import { emitRecordedTaskInputRequestStep } from "#execution/subagent-event-proxy-step.js";
+import {
+ emitRecordedTaskInputRequestStep,
+ runProxySubagentEventStep,
+} from "#subagents/event-proxy-step.js";
import { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";
+import { acceptTaskAuthorizationEventStep } from "#execution/tools/subagent/accept-event-step.js";
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { dispatchTaskAgentInvocationStep } from "#execution/tools/subagent/invoke-step.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
-vi.mock("#execution/subagent-event-proxy-step.js", () => ({
+vi.mock("#subagents/event-proxy-step.js", () => ({
emitRecordedTaskInputRequestStep: vi.fn(),
+ runProxySubagentEventStep: vi.fn(),
}));
vi.mock("#execution/tasks/parent/hitl-proxy-steps.js", () => ({
recordTaskInputRequestStep: vi.fn(),
}));
+vi.mock("#execution/tools/subagent/accept-event-step.js", () => ({
+ acceptTaskAuthorizationEventStep: vi.fn(),
+}));
vi.mock("#execution/proxied-deliver-step.js", () => ({
routeProxiedDeliverStep: vi.fn(),
}));
+vi.mock("#execution/tools/subagent/invoke-step.js", () => ({
+ dispatchTaskAgentInvocationStep: vi.fn(),
+}));
+vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
+ resumeHookStep: vi.fn(),
+}));
const state = (hasProxyInputRequests: boolean): DurableSessionState => ({
continuationToken: "parent-token",
@@ -24,27 +40,19 @@ const state = (hasProxyInputRequests: boolean): DurableSessionState => ({
version: 1,
});
-const hookPayload = {
- callId: "call-task",
- childContinuationToken: "child-token",
- childSessionId: "child-session",
- event: {
- requests: [
- {
- action: { callId: "call-q", input: {}, kind: "tool-call" as const, toolName: "ask" },
- kind: "question" as const,
- prompt: "Which?",
- requestId: "request-1",
- },
- ],
- sequence: 1,
- stepIndex: 2,
- turnId: "turn_child",
+const taskRequest = {
+ replyTo: "eve:workflow-tool-run-answer:run-1:0",
+ request: {
+ action: { callId: "call-q", input: {}, kind: "tool-call" as const, toolName: "ask" },
+ kind: "question" as const,
+ prompt: "Which?",
+ requestId: "request-1",
},
- kind: "subagent-input-request" as const,
- subagentName: "research",
+ sequence: 1,
+ stepIndex: 2,
+ taskId: "task-1",
+ turnId: "turn_child",
};
-
describe("task HITL delivery routing", () => {
beforeEach(() => vi.resetAllMocks());
@@ -52,7 +60,7 @@ describe("task HITL delivery routing", () => {
const recordedState = state(true);
vi.mocked(recordTaskInputRequestStep).mockResolvedValue({
accepted: true,
- hookPayload,
+ request: taskRequest,
sessionState: recordedState,
});
vi.mocked(emitRecordedTaskInputRequestStep).mockResolvedValue({
@@ -69,7 +77,7 @@ describe("task HITL delivery routing", () => {
const result = await routeDeliverToChildren({
delivery: {
kind: "deliver",
- payloads: [{ task: { inputRequests: [{ hookPayload, taskId: "task-1" }] } }],
+ payloads: [{ task: { inputRequests: [taskRequest] } }],
},
parentWritable: new WritableStream<Uint8Array>(),
serializedContext: {},
@@ -78,9 +86,12 @@ describe("task HITL delivery routing", () => {
expect(result).toMatchObject({ kind: "continue", remainder: undefined });
expect(recordTaskInputRequestStep).toHaveBeenCalledOnce();
+ expect(recordTaskInputRequestStep).toHaveBeenCalledWith(
+ expect.objectContaining({ request: taskRequest }),
+ );
expect(emitRecordedTaskInputRequestStep).toHaveBeenCalledOnce();
expect(emitRecordedTaskInputRequestStep).toHaveBeenCalledWith(
- expect.objectContaining({ hookPayload }),
+ expect.objectContaining({ request: taskRequest }),
);
expect(vi.mocked(recordTaskInputRequestStep).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(emitRecordedTaskInputRequestStep).mock.invocationCallOrder[0] ?? 0,
@@ -96,7 +107,7 @@ describe("task HITL delivery routing", () => {
const result = await routeDeliverToChildren({
delivery: {
kind: "deliver",
- payloads: [{ task: { inputRequests: [{ hookPayload, taskId: "foreign-task" }] } }],
+ payloads: [{ task: { inputRequests: [{ ...taskRequest, taskId: "foreign-task" }] } }],
},
parentWritable: new WritableStream<Uint8Array>(),
serializedContext: {},
@@ -108,6 +119,123 @@ describe("task HITL delivery routing", () => {
expect(routeProxiedDeliverStep).not.toHaveBeenCalled();
});
+ it("proxies a task-owned agent authorization event through the parent channel", async () => {
+ const nextState = state(false);
+ const event = {
+ callId: "call-1",
+ childSessionId: "child-1",
+ event: {
+ data: {
+ description: "Authorize Linear",
+ name: "linear",
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn-child",
+ },
+ type: "authorization.required" as const,
+ },
+ kind: "subagent-authorization-event" as const,
+ subagentName: "research",
+ };
+ vi.mocked(runProxySubagentEventStep).mockResolvedValue({
+ serializedContext: { adapter: "updated" },
+ sessionState: nextState,
+ });
+ vi.mocked(acceptTaskAuthorizationEventStep).mockResolvedValue(true);
+
+ const result = await routeDeliverToChildren({
+ delivery: {
+ kind: "deliver",
+ payloads: [
+ {
+ task: {
+ authorizationEvents: [{ hookPayload: event, taskId: "task-1" }],
+ },
+ },
+ ],
+ },
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state(false),
+ });
+
+ expect(acceptTaskAuthorizationEventStep).toHaveBeenCalledWith(
+ expect.objectContaining({
+ delivery: { hookPayload: event, taskId: "task-1" },
+ }),
+ );
+ expect(runProxySubagentEventStep).toHaveBeenCalledWith(
+ expect.objectContaining({ hookPayload: event }),
+ );
+ expect(result).toMatchObject({
+ kind: "continue",
+ serializedContext: { adapter: "updated" },
+ sessionState: nextState,
+ });
+ });
+
+ it("dispatches agent invocations against the parent state and replies with immediate errors", async () => {
+ const nextState = state(false);
+ const result = {
+ callId: "call-1:research",
+ isError: true as const,
+ kind: "subagent-result" as const,
+ origin: "dispatch" as const,
+ output: { code: "AGENT_UNREACHABLE", message: "gone" },
+ subagentName: "research",
+ };
+ vi.mocked(dispatchTaskAgentInvocationStep).mockResolvedValue({
+ kind: "failed",
+ result,
+ sessionState: nextState,
+ });
+
+ const routed = await routeDeliverToChildren({
+ delivery: {
+ kind: "deliver",
+ payloads: [
+ {
+ task: {
+ agentRequests: [
+ {
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke" as const,
+ },
+ taskId: "task-1",
+ },
+ ],
+ },
+ },
+ ],
+ },
+ parentWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { source: "parent" },
+ sessionState: state(false),
+ });
+
+ expect(dispatchTaskAgentInvocationStep).toHaveBeenCalledWith({
+ ownerId: "task-1",
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke",
+ },
+ serializedContext: { source: "parent" },
+ sessionState: state(false),
+ taskId: "task-1",
+ });
+ expect(resumeHookStep).toHaveBeenCalledWith("agent-reply", {
+ kind: "runtime-action-result",
+ results: [result],
+ });
+ expect(acceptTaskAuthorizationEventStep).not.toHaveBeenCalled();
+ expect(routed).toMatchObject({ sessionState: nextState });
+ });
+
it("reindexes ordinary metadata after consuming task-only payloads", async () => {
const routedState = state(true);
vi.mocked(routeProxiedDeliverStep).mockResolvedValue({
diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.ts
index a4d76d2ed..51b48136f 100644
--- a/packages/eve/src/execution/route-child-delivery.ts
+++ b/packages/eve/src/execution/route-child-delivery.ts
@@ -6,14 +6,15 @@ import {
type RoutedDeliverResult,
} from "#execution/proxied-deliver-step.js";
import {
- emitRecordedTaskAuthorizationEventStep,
emitRecordedTaskInputRequestStep,
-} from "#execution/subagent-event-proxy-step.js";
+ runProxySubagentEventStep,
+} from "#subagents/event-proxy-step.js";
import {
- acceptTaskAuthorizationEventStep,
recordTerminalTaskViewsStep,
recordTaskInputRequestStep,
} from "#execution/tasks/parent/hitl-proxy-steps.js";
+import { acceptTaskAuthorizationEventStep } from "#execution/tools/subagent/accept-event-step.js";
+import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";
/**
* Coalesces inbound deliver payloads and routes any descendant-bound input
@@ -35,25 +36,16 @@ export async function routeDeliverToChildren(input: {
let serializedContext = input.serializedContext;
let sessionState = input.sessionState;
- if ((payload.task?.views?.length ?? 0) > 0) {
- sessionState = await recordTerminalTaskViewsStep({
- sessionState,
- views: payload.task?.views ?? [],
- });
- }
-
for (const request of payload.task?.inputRequests ?? []) {
const recorded = await recordTaskInputRequestStep({
- hookPayload: request.hookPayload,
- serializedContext,
+ request,
sessionState,
- taskId: request.taskId,
});
sessionState = recorded.sessionState;
if (!recorded.accepted) continue;
const emitted = await emitRecordedTaskInputRequestStep({
- hookPayload: recorded.hookPayload,
parentWritable: input.parentWritable,
+ request: recorded.request,
serializedContext,
sessionState,
});
@@ -61,15 +53,26 @@ export async function routeDeliverToChildren(input: {
sessionState = emitted.sessionState;
}
- for (const request of payload.task?.authorizationEvents ?? []) {
- const accepted = await acceptTaskAuthorizationEventStep({
- hookPayload: request.hookPayload,
- sessionState,
- taskId: request.taskId,
- });
+ for (const request of payload.task?.agentRequests ?? []) {
+ const applied = await applyTaskAgentRequest(
+ { ...request, ownerId: request.taskId },
+ {
+ parentWritable: input.parentWritable,
+ serializedContext,
+ sessionState,
+ },
+ );
+ serializedContext = applied.serializedContext;
+ sessionState = applied.sessionState;
+ }
+
+ // Authorization is display-only: the callback completes against the child,
+ // so the parent re-emits the event without recording a proxy input request.
+ for (const delivery of payload.task?.authorizationEvents ?? []) {
+ const accepted = await acceptTaskAuthorizationEventStep({ delivery, sessionState });
if (!accepted) continue;
- const emitted = await emitRecordedTaskAuthorizationEventStep({
- hookPayload: request.hookPayload,
+ const emitted = await runProxySubagentEventStep({
+ hookPayload: delivery.hookPayload,
parentWritable: input.parentWritable,
serializedContext,
sessionState,
@@ -78,6 +81,16 @@ export async function routeDeliverToChildren(input: {
sessionState = emitted.sessionState;
}
+ // Child settlement carries the authoritative parked/terminal handle verdict
+ // and is enqueued before the task's terminal view. Preserve that ordering
+ // when several task deliveries are coalesced into one parent turn.
+ if ((payload.task?.views?.length ?? 0) > 0) {
+ sessionState = await recordTerminalTaskViewsStep({
+ sessionState,
+ views: payload.task?.views ?? [],
+ });
+ }
+
const ordinaryPayloads: DeliverPayload[] = [];
const ordinaryMetadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][] = [];
for (const [sourcePayloadIndex, sourcePayload] of input.delivery.payloads.entries()) {
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index c3dfabe89..d45c0e37a 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -16,7 +16,6 @@ import {
ActivityObserverKey,
ScheduleIdKey,
SessionCallbackKey,
- SubagentDepthKey,
} from "#context/keys.js";
import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
@@ -88,10 +87,6 @@ export function buildRunContext(input: {
ctx.set(ParentTraceContextKey, run.parentTraceContext);
}
- if (run.subagentDepth !== undefined) {
- ctx.set(SubagentDepthKey, run.subagentDepth);
- }
-
// `run.limits` deliberately never enters the context: inherited limits ride
// the typed workflow-entry payload into `createSessionStep` and live on the
// session from then on.
diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.ts
index 75791e04f..8fee18b18 100644
--- a/packages/eve/src/execution/session-command-inbox.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.test.ts
@@ -1,13 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { SessionInboxPayload } from "#execution/session-command-inbox.js";
-import { createSessionCommandInbox } from "#execution/session-command-inbox.js";
-import { SESSION_INBOX_WIRE_VERSION } from "#execution/wire/session-inbox-contract.js";
+import {
+ createSessionCommandInbox,
+ type SessionInboxPayload,
+} from "#execution/session-command-inbox.js";
const createHookMock = vi.fn();
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: (...args: unknown[]) => createHookMock(...args),
+ getWritable: vi.fn(),
}));
describe("createSessionCommandInbox", () => {
@@ -121,7 +123,7 @@ describe("createSessionCommandInbox", () => {
);
expect(createHookMock).toHaveBeenCalledOnce();
expect(createHookMock).toHaveBeenCalledWith({
- metadata: { sessionInboxWireVersion: SESSION_INBOX_WIRE_VERSION },
+ metadata: { sessionInboxWireVersion: 4 },
token: "stable",
});
await inbox.dispose();
diff --git a/packages/eve/src/execution/session-command-inbox.ts b/packages/eve/src/execution/session-command-inbox.ts
index fdf3f9707..14ee3da18 100644
--- a/packages/eve/src/execution/session-command-inbox.ts
+++ b/packages/eve/src/execution/session-command-inbox.ts
@@ -11,13 +11,11 @@ import {
SESSION_INBOX_WIRE_VERSION,
SESSION_INBOX_WIRE_VERSION_METADATA_KEY,
} from "#execution/wire/session-inbox-contract.js";
-
/**
* Payloads accepted by a session driver's stable and channel aliases.
*
- * This union is the hook's transport typing only; consumers interpret every
- * payload through `sessionInboxWire.decode` in `execution/wire/session-inbox-wire.ts`,
- * which owns the versioned wire schema and its legacy-shape fallbacks.
+ * This union is the hook's transport typing only. The driver routes payloads
+ * after the inbox surfaces them; the inbox owns no command semantics.
*/
export type SessionInboxPayload =
| DeliverHookPayload
diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
index dcdd7fcdf..46e4a4499 100644
--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
@@ -9,6 +9,7 @@ import {
} from "#internal/testing/events.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { workflowEntry } from "#execution/workflow-entry.js";
+import { experimental_workflow } from "#tools/workflow.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
/**
@@ -145,13 +146,19 @@ describe("session-limit continuation decline integration", () => {
it("fails a zero-quota delegation fast and declines the root's own prompt", async () => {
const runtime = await createTestRuntime({
agent: { limits: { maxInputTokensPerSession: 1 }, name: "limit-decline-child" },
+ modules: [
+ {
+ loadNamespace: async () => ({ default: experimental_workflow() }),
+ logicalPath: "tools/workflow.ts",
+ },
+ ],
});
const continuationToken = "http:limit-decline-child";
await runtime.run(async () => {
const run = await start(workflowEntry, [
{
- input: { message: "Delegate to a subagent: summarize the weather." },
+ input: { message: "Delegate through Workflow to a subagent: summarize the weather." },
serializedContext: {
...buildSerializedContext({
channelKind: "http",
diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.ts
index 7eb062c85..5f3d69931 100644
--- a/packages/eve/src/execution/session.test.ts
+++ b/packages/eve/src/execution/session.test.ts
@@ -250,8 +250,8 @@ describe("createSession", () => {
it("leaves delegated subagent sessions uncapped by default", () => {
const session = createSession({
continuationToken: "subagent-token",
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
turnAgent: createTestTurnAgent(),
});
@@ -273,8 +273,8 @@ describe("createSession", () => {
const session = createSession({
continuationToken: "subagent-token",
limits: { maxInputTokensPerSession: false },
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
turnAgent: createTestTurnAgent(),
});
@@ -302,8 +302,8 @@ describe("createSession", () => {
continuationToken: "subagent-token",
history: [],
limits: {},
+ rootSessionId: "sess-root",
sessionId: "sess-child",
- subagentDepth: 1,
},
turnAgent: createTestTurnAgent(),
});
@@ -341,11 +341,11 @@ describe("createSession", () => {
expect(hydrated.outputSchema).toEqual(runOutputSchema);
});
- it("persists subagent depth through durable session projection and hydration", () => {
+ it("persists delegated root lineage through durable session projection and hydration", () => {
const session = createSession({
- continuationToken: "root-token",
- sessionId: "sess-root",
- subagentDepth: 2,
+ continuationToken: "subagent-token",
+ rootSessionId: "sess-root",
+ sessionId: "sess-child",
turnAgent: createTestTurnAgent(),
});
@@ -355,8 +355,8 @@ describe("createSession", () => {
turnAgent: createTestTurnAgent(),
});
- expect(durable.subagentDepth).toBe(2);
- expect(hydrated.subagentDepth).toBe(2);
+ expect(durable.rootSessionId).toBe("sess-root");
+ expect(hydrated.rootSessionId).toBe("sess-root");
});
it("persists session token limits through durable session projection and hydration", () => {
diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.ts
index fa11653af..775138afe 100644
--- a/packages/eve/src/execution/session.ts
+++ b/packages/eve/src/execution/session.ts
@@ -72,8 +72,8 @@ export interface CreateSessionInput {
readonly turnAgent: RuntimeTurnAgent;
readonly limits?: AuthoredSessionLimits;
readonly outputSchema?: HarnessSession["outputSchema"];
- readonly subagentDepth?: number;
readonly systemPromptAdditions?: readonly string[];
+ readonly taskId?: string;
readonly workflowMaxSubagents?: number;
}
@@ -106,8 +106,8 @@ export function createSession(input: CreateSessionInput): HarnessSession {
if (input.outputSchema !== undefined) {
session.outputSchema = input.outputSchema;
}
- if (input.subagentDepth !== undefined) {
- session.subagentDepth = input.subagentDepth;
+ if (input.taskId !== undefined) {
+ session.taskId = input.taskId;
}
if (input.workflowMaxSubagents !== undefined) {
session.workflowMaxSubagents = input.workflowMaxSubagents;
@@ -212,7 +212,7 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
sandboxState?: HarnessSession["sandboxState"];
sessionId: string;
state?: HarnessSession["state"];
- subagentDepth?: number;
+ taskId?: string;
workflowMaxSubagents?: number;
} = {
agent: { system: session.agent.system },
@@ -245,8 +245,8 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
if (session.state !== undefined) {
durable.state = session.state;
}
- if (session.subagentDepth !== undefined) {
- durable.subagentDepth = session.subagentDepth;
+ if (session.taskId !== undefined) {
+ durable.taskId = session.taskId;
}
if (session.workflowMaxSubagents !== undefined) {
durable.workflowMaxSubagents = session.workflowMaxSubagents;
@@ -302,8 +302,8 @@ export function hydrateDurableSession(input: {
if (durable.state !== undefined) {
session.state = durable.state;
}
- if (durable.subagentDepth !== undefined) {
- session.subagentDepth = durable.subagentDepth;
+ if (durable.taskId !== undefined) {
+ session.taskId = durable.taskId;
}
if (durable.workflowMaxSubagents !== undefined) {
session.workflowMaxSubagents = durable.workflowMaxSubagents;
@@ -322,9 +322,9 @@ function createSessionToolDefinitions(turnAgent: RuntimeTurnAgent): SessionToolD
function resolveSessionLimits(input: {
readonly limits?: AuthoredSessionLimits;
- readonly subagentDepth?: number;
+ readonly rootSessionId?: string;
}): SessionLimits {
- const isSubagent = input.subagentDepth !== undefined && input.subagentDepth > 0;
+ const isSubagent = input.rootSessionId !== undefined;
const maxInputTokensPerSession = resolveSessionTokenLimit({
authored: input.limits?.maxInputTokensPerSession,
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
index 463f1c268..1dab3e347 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
@@ -5,13 +5,14 @@ import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-a
import { createDurableSessionState } from "#execution/durable-session-store.js";
import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";
import { setHarnessEmissionState } from "#harness/emission.js";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import { recordWorkflowToolRun } from "#harness/workflow-tool-runs.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
import {
AGENT_HANDLES_STATE_KEY,
deriveAgentId,
getAgentHandleStore,
type AgentHandle,
-} from "#harness/handles/store.js";
+} from "#subagents/handles/store.js";
import type { HarnessSession } from "#harness/types.js";
const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());
@@ -84,6 +85,23 @@ const PARKED_HANDLE: AgentHandle = {
phase: "parked",
};
+const CLAIMED_HANDLE: AgentHandle = {
+ address: {
+ continuationToken: "subagent:child-claimed",
+ kind: "agent/local",
+ sessionId: "child-session-claimed",
+ },
+ callId: "workflow-call",
+ identity: {
+ id: "ag_research:workflow",
+ name: "research",
+ nodeId: "subagents/research",
+ },
+ operationId: "workflow-operation",
+ ownerId: "workflow-run",
+ phase: "claimed",
+};
+
function createCancelledTurnSession(handles: readonly AgentHandle[]): HarnessSession {
return setHarnessEmissionState(
{
@@ -141,4 +159,34 @@ describe("settleCancelledTurnStep handle store", () => {
);
});
});
+
+ it("releases a cancelled workflow claim with a resumable cancelled status", async () => {
+ const runtime = await createTestRuntime({ agent: { name: "settle-cancel-claim" } });
+
+ await runtime.run(async () => {
+ const session = recordWorkflowToolRun(createCancelledTurnSession([CLAIMED_HANDLE]), {
+ callId: "workflow-call",
+ hookToken: "workflow-hook",
+ resultKind: "tool",
+ runId: "workflow-run",
+ toolName: "Workflow",
+ });
+ const result = await settleCancelledTurnStep({
+ parentWritable: new WritableStream<Uint8Array>({ write() {} }),
+ serializedContext: buildSerializedContext(),
+ sessionState: createDurableSessionState({ session }),
+ });
+
+ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
+ handles: [
+ {
+ address: CLAIMED_HANDLE.address,
+ identity: CLAIMED_HANDLE.identity,
+ lastStatus: "(cancelled)",
+ phase: "parked",
+ },
+ ],
+ });
+ });
+ });
});
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index acd9b3b8f..ede5572c8 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -25,9 +25,12 @@ import {
getProxyInputRequests,
hasProxyInputRequests,
} from "#harness/proxy-input-requests.js";
-import { abandonRunningAgentTurns } from "#harness/handles/transitions.js";
-import { clearPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
-import { clearToolRuns } from "#harness/tool-runs.js";
+import {
+ abandonAgentInvocationOwners,
+ abandonRunningAgentTurns,
+} from "#subagents/handles/transitions.js";
+import { clearPendingCoordinationBatch } from "#harness/coordination.js";
+import { clearWorkflowToolRuns, getWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";
import { clearPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
@@ -48,7 +51,7 @@ export interface CancelledTurnSettleResult {
/**
* Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,
- * drops pending runtime-action state, and persists the between-turns
+ * drops pending coordination state, and persists the between-turns
* session. Runs in the *driver* run, whose wake sources exclude the
* cancel hook, so a queued cancel wake cannot re-dispatch it.
*/
@@ -135,18 +138,25 @@ export async function settleCancelledTurnStep(input: {
// violation holds, so the next delivery gets a fresh prompt instead of
// queueing forever behind a stale one.
//
- // `abandonRunningAgentTurns`: `cancelDescendantTurnsStep` already ran and
- // the cancelled turn's inbox is gone, so a child settlement can never
- // reach this store again. This is the last write that can move those
- // handles out of `running`.
+ // Descendant cancellation already ran and the cancelled turn's inbox is
+ // gone, so a child settlement can never reach this store again. This is the
+ // last write that can park turn-owned `running` and workflow-owned `claimed`
+ // handles.
+ const workflowToolRuns = getWorkflowToolRuns(session.state);
+ session = abandonAgentInvocationOwners(
+ session,
+ new Set(workflowToolRuns.map((run) => run.runId)),
+ );
const cancelledSession = reconcileSessionContinuationToken(
ctx,
setHarnessEmissionState(
clearPendingSessionLimitPrompt(
clearAllProxyInputRequests(
clearPendingWorkflowInterrupt(
- clearPendingRuntimeActionBatch(
- clearToolRuns(abandonRunningAgentTurns({ ...session, outputSchema: undefined })),
+ clearPendingCoordinationBatch(
+ clearWorkflowToolRuns(
+ abandonRunningAgentTurns({ ...session, outputSchema: undefined }),
+ ),
),
),
),
diff --git a/packages/eve/src/execution/stable-workflow-names.ts b/packages/eve/src/execution/stable-workflow-names.ts
index c8bad2d60..9e38e27c2 100644
--- a/packages/eve/src/execution/stable-workflow-names.ts
+++ b/packages/eve/src/execution/stable-workflow-names.ts
@@ -7,7 +7,7 @@ export const WORKFLOW_ENTRY_NAME = "workflowEntry";
export const TURN_WORKFLOW_NAME = "turnWorkflow";
export const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";
export const TASK_RUN_WORKFLOW_NAME = "taskRunWorkflow";
-export const TOOL_RUN_WORKFLOW_NAME = "toolRunWorkflow";
+export const WORKFLOW_TOOL_RUN_WORKFLOW_NAME = "workflowToolRunWorkflow";
export const ACTIVITY_COLLECTOR_WORKFLOW_NAME = "activityCollectorWorkflow";
export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
@@ -15,6 +15,6 @@ export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
TURN_WORKFLOW_NAME,
SESSION_TIMEOUT_WORKFLOW_NAME,
TASK_RUN_WORKFLOW_NAME,
- TOOL_RUN_WORKFLOW_NAME,
+ WORKFLOW_TOOL_RUN_WORKFLOW_NAME,
ACTIVITY_COLLECTOR_WORKFLOW_NAME,
]);
diff --git a/packages/eve/src/execution/task-event-callback.ts b/packages/eve/src/execution/task-event-callback.ts
index efbbadce8..b3598ea1c 100644
--- a/packages/eve/src/execution/task-event-callback.ts
+++ b/packages/eve/src/execution/task-event-callback.ts
@@ -1,6 +1,6 @@
import type { ContextContainer } from "#context/container.js";
import { ContinuationTokenKey, SessionCallbackKey, SessionIdKey } from "#context/keys.js";
-import { fireTaskEventCallbackStep } from "#execution/session-callback-step.js";
+import { fireTaskEventCallbackStep } from "#subagents/callback-step.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
/**
diff --git a/packages/eve/src/execution/tasks/child/instructions.ts b/packages/eve/src/execution/tasks/child/instructions.ts
deleted file mode 100644
index e90658c1a..000000000
--- a/packages/eve/src/execution/tasks/child/instructions.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { CHANNEL_CONTEXT_KEY_NAME, SESSION_CALLBACK_CONTEXT_KEY_NAME } from "#context/key-names.js";
-import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
-
-export const TASK_UPDATE_SESSION_INSTRUCTION =
- "Background task updates\nYou are running as a background task. For multi-step work, use `task_update` at meaningful milestones to briefly state what you are currently doing. Keep updates terse and activity-focused; do not include preliminary findings or results. Do not wait for a response, and return your final result normally.";
-
-/** True when the serialized caller binding points at a durable task inbox. */
-export function isTaskOwnedSerializedContext(serializedContext: Record<string, unknown>): boolean {
- const callback = serializedContext[SESSION_CALLBACK_CONTEXT_KEY_NAME];
- if (
- callback !== null &&
- typeof callback === "object" &&
- typeof Reflect.get(callback, "taskId") === "string"
- ) {
- return true;
- }
- const channel = serializedContext[CHANNEL_CONTEXT_KEY_NAME];
- if (channel === null || typeof channel !== "object") return false;
- const state = Reflect.get(channel, "state");
- if (state === null || typeof state !== "object") return false;
- const token = Reflect.get(state, "parentContinuationToken");
- return typeof token === "string" && readTaskIdFromInboxToken(token) !== undefined;
-}
diff --git a/packages/eve/src/execution/tasks/child/steps.test.ts b/packages/eve/src/execution/tasks/child/steps.test.ts
index e9d796654..092d699cc 100644
--- a/packages/eve/src/execution/tasks/child/steps.test.ts
+++ b/packages/eve/src/execution/tasks/child/steps.test.ts
@@ -1,15 +1,26 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ deliverTaskInputResponsesStep,
formatTaskNotification,
- projectTaskActivitySettlement,
+ wakeTaskAgentRequestParentStep,
} from "#execution/tasks/child/steps.js";
+import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";
import type { TaskView } from "#tasks/types.js";
+import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
+
+vi.mock("#execution/wire/session-inbox-resume.js", () => ({ resumeSessionInbox: vi.fn() }));
+vi.mock("#execution/tools/workflow/answer.js", () => ({
+ resumeWorkflowToolRunAnswers: vi.fn(),
+}));
+
+afterEach(() => {
+ vi.resetAllMocks();
+ vi.unstubAllGlobals();
+});
const metadata = {
- agentId: "agent-reviewer",
- kind: "subagent" as const,
- mode: "local" as const,
+ kind: "tool" as const,
name: "reviewer",
};
@@ -43,43 +54,6 @@ const notificationCases: readonly { readonly expected: string; readonly view: Ta
},
];
-describe("projectTaskActivitySettlement", () => {
- afterEach(() => vi.unstubAllGlobals());
-
- it("projects terminal task settlement", () => {
- expect(
- projectTaskActivitySettlement({
- activityObserver: {
- sink: {
- url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity: {
- id: "work:task",
- kind: "task",
- rootSessionId: "root",
- rootTurnId: "turn",
- },
- },
- settledAt: "2026-01-01T00:00:00.000Z",
- view: notificationCases[0]!.view,
- }),
- ).toEqual([
- expect.objectContaining({ kind: "work.settled", outcome: "completed", workId: "work:task" }),
- ]);
- });
-
- it("does nothing for nonterminal task views", () => {
- expect(
- projectTaskActivitySettlement({
- activityObserver: undefined,
- settledAt: "2026-01-01T00:00:00.000Z",
- view: { metadata, status: "working", taskId: "task-1" },
- }),
- ).toEqual([]);
- });
-});
-
describe("formatTaskNotification", () => {
it.each(notificationCases)(
"includes terminal output in the parent notification",
@@ -98,3 +72,125 @@ describe("formatTaskNotification", () => {
expect(formatTaskNotification(view)).toBe("Background task task-1 (reviewer) is cancelled.");
});
});
+
+describe("deliverTaskInputResponsesStep", () => {
+ const answer = {
+ childContinuationToken: "eve:eve:op:0123456789abcdef0123456789abcdef",
+ inputResponses: [
+ { optionId: "approve", requestId: "req-1" },
+ { requestId: "stale", text: "ignore" },
+ ],
+ kind: "input-response" as const,
+ taskId: "task-1",
+ };
+
+ it("delivers a local child answer through the child session inbox", async () => {
+ await expect(deliverTaskInputResponsesStep({ answer, requestIds: ["req-1"] })).resolves.toBe(
+ "delivered",
+ );
+
+ expect(resumeSessionInbox).toHaveBeenCalledWith(answer.childContinuationToken, {
+ auth: undefined,
+ kind: "send",
+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },
+ taskDeliveryId: "task-1:req-1",
+ });
+ });
+
+ it("posts a remote child answer to its narrowed task-input route", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const remoteAnswer = {
+ ...answer,
+ childResponseUrl: "https://remote.example/eve/v1/task-input/eve%3Atask-input%3Atoken",
+ };
+
+ await expect(
+ deliverTaskInputResponsesStep({ answer: remoteAnswer, requestIds: ["req-1"] }),
+ ).resolves.toBe("delivered");
+
+ expect(fetchMock).toHaveBeenCalledWith(remoteAnswer.childResponseUrl, {
+ body: JSON.stringify({ inputResponses: [{ optionId: "approve", requestId: "req-1" }] }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ redirect: "error",
+ });
+ expect(resumeSessionInbox).not.toHaveBeenCalled();
+ });
+
+ it("keeps the task blocked when a remote child no longer has a pending input", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 404 })));
+
+ await expect(
+ deliverTaskInputResponsesStep({
+ answer: { ...answer, childResponseUrl: "https://remote.example/eve/v1/task-input/token" },
+ requestIds: ["req-1"],
+ }),
+ ).resolves.toBe("unreachable");
+ });
+
+ it("resumes a workflow tool's private answer hook directly", async () => {
+ const workflowToolRunAnswer = {
+ ...answer,
+ childContinuationToken: "eve:workflow-tool-run-answer:run-1:0",
+ };
+
+ await expect(
+ deliverTaskInputResponsesStep({
+ answer: workflowToolRunAnswer,
+ answerHook: { runId: "run-1" },
+ requestIds: ["req-1"],
+ }),
+ ).resolves.toBe("delivered");
+
+ expect(resumeWorkflowToolRunAnswers).toHaveBeenCalledWith(
+ "eve:workflow-tool-run-answer:run-1:0",
+ [{ optionId: "approve", requestId: "req-1" }],
+ );
+ });
+});
+
+describe("wakeTaskAgentRequestParentStep", () => {
+ it("forwards an agent invocation through the typed task envelope", async () => {
+ const request = {
+ from: {
+ callId: "call-1",
+ execution: "background" as const,
+ input: {},
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke" as const,
+ },
+ };
+
+ await wakeTaskAgentRequestParentStep({ request, taskId: "task-1", token: "parent-token" });
+
+ expect(resumeSessionInbox).toHaveBeenCalledWith("parent-token", {
+ kind: "send",
+ payload: {
+ task: {
+ agentRequests: [
+ {
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke",
+ },
+ taskId: "task-1",
+ },
+ ],
+ },
+ },
+ taskDeliveryId: "task-1:agent:run-1:call-1:research",
+ });
+ });
+});
diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.ts
index 2c554b343..891e5d0a3 100644
--- a/packages/eve/src/execution/tasks/child/steps.ts
+++ b/packages/eve/src/execution/tasks/child/steps.ts
@@ -1,27 +1,25 @@
import { getWritable } from "#compiled/@workflow/core/index.js";
+import type { SessionAuthContext, SessionCommand } from "#channel/types.js";
import type {
- ActivityObserverConfig,
- SessionAuthContext,
- SessionCommand,
- SubagentAuthorizationEventHookPayload,
- SubagentInputRequestHookPayload,
-} from "#channel/types.js";
-import { submitActivity } from "#execution/submit-activity.js";
+ WorkflowToolAuthorizationRequest,
+ WorkflowToolRunRequestMessage,
+} from "#execution/tools/workflow/messages.js";
+import type { WorkflowToolRunTaskInputRequest } from "./workflow.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
-import { resumeToolRunAnswers } from "#execution/tool-run/answer.js";
+import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";
import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
import { createLogger } from "#internal/logging.js";
-import type { ActivityEventV1 } from "#protocol/activity.js";
import type { JsonValue } from "#shared/json.js";
import {
isTerminalTaskStatus,
- taskAuthorizationRequestId,
TASK_VIEW_STREAM_NAMESPACE,
+ taskAuthorizationRequestId,
+ type TaskAgentRequestDelivery,
+ type TaskAuthorizationEventDelivery,
type TaskInboundAnswerInput,
- type TaskInboundAuthorizationEvent,
- type TaskInboundInputRequest,
type TaskInboundUpdate,
+ type TaskInputRequestDelivery,
type TaskView,
} from "#tasks/types.js";
@@ -32,10 +30,7 @@ const log = createLogger("execution.tasks.run");
* stream. Only the task run workflow calls this, which is what makes
* the run the single writer readers can trust without re-validating.
*/
-export async function appendTaskViewStep(input: {
- readonly activityObserver?: ActivityObserverConfig;
- readonly view: TaskView;
-}): Promise<void> {
+export async function appendTaskViewStep(input: { readonly view: TaskView }): Promise<void> {
"use step";
const writable = getWritable<TaskView>({ namespace: TASK_VIEW_STREAM_NAMESPACE });
@@ -45,77 +40,6 @@ export async function appendTaskViewStep(input: {
} finally {
writer.releaseLock();
}
-
- const events = projectTaskActivitySettlement({
- activityObserver: input.activityObserver,
- settledAt: new Date().toISOString(),
- view: input.view,
- });
- void submitActivity({ events, sink: input.activityObserver?.sink });
-}
-
-export function projectTaskActivitySettlement(input: {
- readonly activityObserver: ActivityObserverConfig | undefined;
- readonly settledAt: string;
- readonly view: TaskView;
-}): readonly ActivityEventV1[] {
- const work = input.activityObserver?.workIdentity;
- const status = input.view.status;
- if (
- work === undefined ||
- (status !== "completed" && status !== "failed" && status !== "cancelled")
- )
- return [];
- return [
- {
- eventId: `${work.id}:settled:${status}`,
- kind: "work.settled",
- outcome: status,
- settledAt: input.settledAt,
- workId: work.id,
- },
- ];
-}
-
-/** Re-emits a task-owned child authorization event through the parent channel. */
-export async function wakeTaskAuthorizationParentStep(input: {
- readonly request: TaskInboundAuthorizationEvent;
- readonly taskId: string;
- readonly token: string;
-}): Promise<void> {
- "use step";
-
- const hookPayload: SubagentAuthorizationEventHookPayload = {
- callId: input.request.callId,
- childSessionId: input.request.childSessionId,
- event: input.request.event,
- kind: "subagent-authorization-event",
- subagentName: input.request.subagentName,
- };
- const data = input.request.event.data;
- const payload: {
- message?: string;
- task: {
- authorizationEvents: {
- hookPayload: SubagentAuthorizationEventHookPayload;
- taskId: string;
- }[];
- };
- } = { task: { authorizationEvents: [{ hookPayload, taskId: input.taskId }] } };
- if (input.request.event.type === "authorization.required") {
- payload.message = `Background task ${input.taskId} needs authorization.`;
- }
- const command: SessionCommand = {
- kind: "send",
- payload,
- taskDeliveryId: `${input.taskId}:authorization:${input.request.event.type}:${data.turnId}:${data.stepIndex}:${data.sequence}:${taskAuthorizationRequestId(input.request.event)}`,
- };
- try {
- await resumeSessionInbox(input.token, command);
- } catch (error) {
- if (isTaskWorkflowTargetGone(error)) return;
- throw error;
- }
}
/**
@@ -178,33 +102,105 @@ export async function wakeTaskUpdateParentStep(input: {
}
}
-/** Sends an exact local-task HITL batch to the parent's pre-model router. */
-export async function wakeTaskInputRequestParentStep(input: {
- readonly request: TaskInboundInputRequest;
+/** Forwards one agent spawn or settlement request to the parent session. */
+export async function wakeTaskAgentRequestParentStep(input: {
+ readonly request: WorkflowToolRunRequestMessage;
+ readonly taskId: string;
+ readonly token: string;
+}): Promise<void> {
+ "use step";
+
+ const request = input.request.request;
+ if (request.kind !== "agent-invoke" && request.kind !== "agent-settled") {
+ throw new Error("Cannot forward task input as an agent request.");
+ }
+ const delivery: TaskAgentRequestDelivery = {
+ replyTo: input.request.replyTo,
+ request,
+ taskId: input.taskId,
+ };
+ const invocationId =
+ request.kind === "agent-invoke" ? request.invocationId : `${request.result.callId}:settled`;
+ const command: SessionCommand = {
+ kind: "send",
+ payload: { task: { agentRequests: [delivery] } },
+ taskDeliveryId: `${input.taskId}:agent:${input.request.from.runId}:${invocationId}`,
+ };
+ try {
+ await resumeSessionInbox(input.token, command);
+ } catch (error) {
+ if (!isTaskWorkflowTargetGone(error)) throw error;
+ }
+}
+
+/** Re-emits a task child's authorization event through the parent channel. */
+export async function wakeTaskAuthorizationParentStep(input: {
+ readonly request: WorkflowToolAuthorizationRequest;
+ readonly taskId: string;
+ readonly token: string;
+}): Promise<void> {
+ "use step";
+
+ const { event: hookPayload } = input.request;
+ const data = hookPayload.event.data;
+ const payload: {
+ message?: string;
+ task: { authorizationEvents: TaskAuthorizationEventDelivery[] };
+ } = { task: { authorizationEvents: [{ hookPayload, taskId: input.taskId }] } };
+ if (hookPayload.event.type === "authorization.required") {
+ payload.message = `Background task ${input.taskId} needs authorization.`;
+ }
+ const command: SessionCommand = {
+ kind: "send",
+ payload,
+ taskDeliveryId: `${input.taskId}:authorization:${hookPayload.event.type}:${data.turnId}:${data.stepIndex}:${data.sequence}:${taskAuthorizationRequestId(hookPayload.event)}`,
+ };
+ try {
+ await resumeSessionInbox(input.token, command);
+ } catch (error) {
+ if (!isTaskWorkflowTargetGone(error)) throw error;
+ }
+}
+
+/** Sends a workflow-body question to the owning parent's pre-model router. */
+export async function wakeWorkflowTaskInputRequestParentStep(input: {
+ readonly request: WorkflowToolRunTaskInputRequest;
readonly taskId: string;
readonly token: string;
}): Promise<void> {
"use step";
+ const delivery: TaskInputRequestDelivery =
+ input.request.requests === undefined
+ ? {
+ replyTo: input.request.replyTo,
+ request: input.request.request,
+ sequence: input.request.sequence,
+ stepIndex: input.request.stepIndex,
+ taskId: input.taskId,
+ turnId: input.request.turnId,
+ }
+ : {
+ replyTo: input.request.replyTo,
+ requests: input.request.requests,
+ sequence: input.request.sequence,
+ stepIndex: input.request.stepIndex,
+ taskId: input.taskId,
+ turnId: input.request.turnId,
+ };
const command: SessionCommand = {
kind: "send",
payload: {
task: {
- inputRequests: [
- {
- hookPayload: input.request as SubagentInputRequestHookPayload,
- taskId: input.taskId,
- },
- ],
+ inputRequests: [delivery],
},
},
- taskDeliveryId: `${input.taskId}:input:${input.request.event.turnId}:${input.request.event.stepIndex}:${input.request.event.sequence}`,
+ taskDeliveryId: `${input.taskId}:input:${input.request.turnId}:${input.request.stepIndex}:${input.request.sequence}`,
};
try {
await resumeSessionInbox(input.token, command);
} catch (error) {
- if (isTaskWorkflowTargetGone(error)) return;
- throw error;
+ if (!isTaskWorkflowTargetGone(error)) throw error;
}
}
@@ -247,7 +243,7 @@ export async function deliverTaskInputResponsesStep(input: {
if (!response.ok)
throw new Error(`Remote task input delivery failed with HTTP ${response.status}.`);
} else if (input.answerHook !== undefined) {
- await resumeToolRunAnswers(
+ await resumeWorkflowToolRunAnswers(
input.answer.childContinuationToken,
command.payload.inputResponses,
);
diff --git a/packages/eve/src/execution/tasks/child/update-step.ts b/packages/eve/src/execution/tasks/child/update-step.ts
new file mode 100644
index 000000000..301c13c4b
--- /dev/null
+++ b/packages/eve/src/execution/tasks/child/update-step.ts
@@ -0,0 +1,12 @@
+import { resumeHook } from "#internal/workflow/runtime.js";
+import type { TaskInboundUpdate } from "#tasks/types.js";
+
+/** Forwards a local task-owned child's progress update to its active parent hook. */
+export async function forwardLocalTaskUpdateStep(input: {
+ readonly parentContinuationToken: string;
+ readonly update: TaskInboundUpdate;
+}): Promise<void> {
+ "use step";
+
+ await resumeHook(input.parentContinuationToken, input.update);
+}
diff --git a/packages/eve/src/execution/tasks/child/update.test.ts b/packages/eve/src/execution/tasks/child/update.test.ts
deleted file mode 100644
index 839c74338..000000000
--- a/packages/eve/src/execution/tasks/child/update.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { fireTaskUpdateCallbackStep } from "#execution/session-callback-step.js";
-import { executeTaskUpdate } from "#execution/tasks/child/update.js";
-
-const resumeHookMock = vi.fn();
-
-vi.mock("#compiled/@workflow/core/runtime.js", () => ({
- resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),
-}));
-vi.mock("#execution/session-callback-step.js", () => ({
- fireTaskUpdateCallbackStep: vi.fn(),
-}));
-
-const action = {
- callId: "update-call",
- input: { message: "Found three matching records." },
- kind: "tool-call" as const,
- toolName: "task_update",
-};
-
-afterEach(() => vi.resetAllMocks());
-
-describe("executeTaskUpdate", () => {
- it("sends local updates through the owning task inbox", async () => {
- const token = "task:task_abc:0123456789abcdef0123456789abcdef";
- const result = await executeTaskUpdate({
- action,
- adapter: {
- kind: "subagent",
- state: {
- callId: "parent-call",
- parentContinuationToken: token,
- parentSessionId: "parent-session",
- subagentName: "agent",
- },
- } as never,
- updateIndex: 2,
- updateEpoch: "turn-child",
- serializedContext: {},
- });
-
- expect(resumeHookMock).toHaveBeenCalledWith(token, {
- callId: "update-call",
- updateIndex: 2,
- updateEpoch: "turn-child",
- kind: "task-update",
- message: "Found three matching records.",
- });
- expect(result).toMatchObject({ output: { status: "sent", taskId: "task_abc" } });
- });
-
- it("sends remote updates through the owning task callback", async () => {
- vi.mocked(fireTaskUpdateCallbackStep).mockResolvedValue("task_abc");
- const callback = {
- callId: "parent-call",
- subagentName: "agent",
- taskId: "task_abc",
- token: "task-token",
- url: "https://parent.example/eve/v1/callback/task-token",
- };
- const result = await executeTaskUpdate({
- action,
- adapter: undefined,
- updateIndex: 2,
- updateEpoch: "turn-child",
- serializedContext: { "eve.sessionCallback": callback },
- });
-
- expect(fireTaskUpdateCallbackStep).toHaveBeenCalledWith({
- callback,
- callId: "update-call",
- updateIndex: 2,
- updateEpoch: "turn-child",
- message: "Found three matching records.",
- });
- expect(result).toMatchObject({ output: { status: "sent", taskId: "task_abc" } });
- });
-});
diff --git a/packages/eve/src/execution/tasks/child/update.ts b/packages/eve/src/execution/tasks/child/update.ts
index 07a5f0b2d..066fe464b 100644
--- a/packages/eve/src/execution/tasks/child/update.ts
+++ b/packages/eve/src/execution/tasks/child/update.ts
@@ -1,79 +1,32 @@
import type { ChannelAdapter } from "#channel/adapter.js";
-import { SessionCallbackKey } from "#context/keys.js";
-import { fireTaskUpdateCallbackStep } from "#execution/session-callback-step.js";
-import {
- isSubagentAdapterState,
- SUBAGENT_ADAPTER_KIND,
-} from "#execution/subagent-adapter-state.js";
-import { createTaskControlError } from "#execution/tasks/parent/control-shared.js";
-import { resumeHook } from "#internal/workflow/runtime.js";
-import type { RuntimeActionResult } from "#shared/action-types.js";
-import type { TaskControlInvocation } from "#shared/dispatch-action.js";
-import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
+import { forwardLocalTaskUpdateStep } from "#execution/tasks/child/update-step.js";
+import { fireTaskUpdateCallbackStep } from "#subagents/callback-step.js";
+import { isSubagentAdapterState, SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import type { TaskInboundUpdate } from "#tasks/types.js";
-/** Sends one child-authored progress update over its existing parent transport. */
-export async function executeTaskUpdate(input: {
- readonly action: TaskControlInvocation;
- readonly adapter: ChannelAdapter | undefined;
- readonly updateIndex: number;
- readonly updateEpoch: string;
- readonly serializedContext: Record<string, unknown> | undefined;
-}): Promise<RuntimeActionResult> {
- const message = readUpdateMessage(input.action.input);
- if (message === undefined) {
- return createTaskControlError(input.action, "Provide a non-empty `message`.");
- }
-
- const callback = input.serializedContext?.[SessionCallbackKey.name];
- if (callback !== undefined) {
- const taskId = await fireTaskUpdateCallbackStep({
- callback,
- callId: input.action.callId,
- updateIndex: input.updateIndex,
- updateEpoch: input.updateEpoch,
- message,
+/** Delivers a task update through the local child adapter or remote callback. */
+export async function deliverTaskUpdate(input: {
+ readonly adapter?: ChannelAdapter;
+ readonly callback: unknown;
+ readonly update: TaskInboundUpdate;
+}): Promise<string | undefined> {
+ const state = input.adapter?.state;
+ if (
+ input.adapter?.kind === SUBAGENT_ADAPTER_KIND &&
+ isSubagentAdapterState(state) &&
+ state.taskId !== undefined
+ ) {
+ await forwardLocalTaskUpdateStep({
+ parentContinuationToken: state.parentContinuationToken,
+ update: input.update,
});
- if (taskId === undefined) {
- return createTaskControlError(input.action, "This session is not owned by a parent task.");
- }
- return createTaskUpdateResult(input.action, taskId);
- }
-
- const adapter = input.adapter;
- if (adapter?.kind !== SUBAGENT_ADAPTER_KIND || !isSubagentAdapterState(adapter.state)) {
- return createTaskControlError(input.action, "This session is not owned by a parent task.");
- }
- const token = adapter.state.parentContinuationToken;
- const taskId = readTaskIdFromInboxToken(token);
- if (taskId === undefined) {
- return createTaskControlError(input.action, "This session is not owned by a parent task.");
+ return state.taskId;
}
- const update: TaskInboundUpdate = {
- callId: input.action.callId,
- updateIndex: input.updateIndex,
- updateEpoch: input.updateEpoch,
- kind: "task-update",
- message,
- };
- await resumeHook(token, update);
- return createTaskUpdateResult(input.action, taskId);
-}
-
-function readUpdateMessage(input: Record<string, unknown>): string | undefined {
- return typeof input.message === "string" && input.message.trim() !== ""
- ? input.message
- : undefined;
-}
-
-function createTaskUpdateResult(
- action: TaskControlInvocation,
- taskId: string,
-): RuntimeActionResult {
- return {
- callId: action.callId,
- kind: "tool-result",
- output: { status: "sent", taskId },
- toolName: action.toolName,
- };
+ return await fireTaskUpdateCallbackStep({
+ callback: input.callback,
+ callId: input.update.callId,
+ message: input.update.message,
+ updateEpoch: input.update.updateEpoch,
+ updateIndex: input.update.updateIndex,
+ });
}
diff --git a/packages/eve/src/execution/tasks/child/workflow.test.ts b/packages/eve/src/execution/tasks/child/workflow.test.ts
index 3af5b84d9..7a7574192 100644
--- a/packages/eve/src/execution/tasks/child/workflow.test.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.test.ts
@@ -1,693 +1,311 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
-import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
-import {
- appendTaskViewStep,
- deliverTaskInputResponsesStep,
- wakeTaskAuthorizationParentStep,
- wakeTaskInputRequestParentStep,
- wakeTaskParentStep,
- wakeTaskUpdateParentStep,
-} from "#execution/tasks/child/steps.js";
+import type { WorkflowToolRunRequestMessage } from "#execution/tools/workflow/messages.js";
import { taskRunWorkflow } from "#execution/tasks/child/workflow.js";
-import type {
- TaskCommandHookPayload,
- TaskInboundAnswerInput,
- TaskRunInboundPayload,
- TaskView,
-} from "#tasks/types.js";
+import type { TaskView } from "#tasks/types.js";
-vi.mock("#compiled/@workflow/core/index.js", () => ({
- createHook: vi.fn(),
- defineHook: () => ({
- create: (options?: { readonly token?: string }) => ({
- [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
- dispose: async () => {},
- getConflict: async () => null,
- token: options?.token ?? "hook",
- }),
- resume: async () => null,
- }),
-}));
-
-vi.mock("#execution/hook-ownership.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/hook-ownership.js")>()),
+const mocks = vi.hoisted(() => ({
+ appendTaskViewStep: vi.fn(),
+ cancelWorkflowToolRunStep: vi.fn(),
claimHookOwnership: vi.fn(),
+ createChannelReader: vi.fn((channel: string) => ({ channel, iterator: [][Symbol.iterator]() })),
+ createHook: vi.fn(() => ({ token: "task-token" })),
+ deliverTaskInputResponsesStep: vi.fn(),
disposeHook: vi.fn(),
+ openWorkflowToolRunOwnerChannels: vi.fn(() => ({ dispose: vi.fn(), readers: [] })),
+ raceChannelReads: vi.fn(),
+ resumeHookStep: vi.fn(),
+ wakeTaskAgentRequestParentStep: vi.fn(),
+ wakeTaskParentStep: vi.fn(),
+ wakeTaskUpdateParentStep: vi.fn(),
+ wakeWorkflowTaskInputRequestParentStep: vi.fn(),
+ executeWorkflowBody: vi.fn(),
+ createWorkflowBodyRef: vi.fn((input) => ({
+ callId: input.callId,
+ execution: input.execution,
+ input: input.input,
+ runId: "task-run",
+ sequence: input.session.turn.sequence,
+ stepIndex: input.stepIndex,
+ toolName: input.toolName,
+ turnId: input.session.turn.id,
+ })),
}));
+vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#compiled/@workflow/core/index.js")>()),
+ createHook: mocks.createHook,
+}));
+vi.mock("#execution/hook-ownership.js", () => ({
+ claimHookOwnership: mocks.claimHookOwnership,
+ disposeHook: mocks.disposeHook,
+ isHookConflictError: () => false,
+}));
vi.mock("#execution/tasks/child/steps.js", () => ({
- appendTaskViewStep: vi.fn(),
- deliverTaskInputResponsesStep: vi.fn(),
+ appendTaskViewStep: mocks.appendTaskViewStep,
+ deliverTaskInputResponsesStep: mocks.deliverTaskInputResponsesStep,
+ wakeTaskAgentRequestParentStep: mocks.wakeTaskAgentRequestParentStep,
wakeTaskAuthorizationParentStep: vi.fn(),
- wakeTaskInputRequestParentStep: vi.fn(),
- wakeTaskParentStep: vi.fn(),
- wakeTaskUpdateParentStep: vi.fn(),
+ wakeTaskParentStep: mocks.wakeTaskParentStep,
+ wakeTaskUpdateParentStep: mocks.wakeTaskUpdateParentStep,
+ wakeWorkflowTaskInputRequestParentStep: mocks.wakeWorkflowTaskInputRequestParentStep,
+}));
+vi.mock("#execution/tools/workflow/cancel.js", () => ({
+ cancelWorkflowToolRunStep: mocks.cancelWorkflowToolRunStep,
+}));
+vi.mock("#execution/tools/workflow/owner-channels.js", () => ({
+ createChannelReader: mocks.createChannelReader,
+ raceChannelReads: mocks.raceChannelReads,
+}));
+vi.mock("#execution/tools/workflow/owner.js", () => ({
+ openWorkflowToolRunOwnerChannels: mocks.openWorkflowToolRunOwnerChannels,
+}));
+vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
+ resumeHookStep: mocks.resumeHookStep,
+}));
+vi.mock("#execution/tools/workflow/body.js", () => ({
+ createWorkflowBodyRef: mocks.createWorkflowBodyRef,
+ executeWorkflowBody: mocks.executeWorkflowBody,
}));
-afterEach(() => {
- vi.resetAllMocks();
-});
-
-function createWorkingView(): TaskView {
- return {
- metadata: {
- agentId: "ag_research:abcdef123456",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
- status: "working",
- taskId: "task_abc123",
- };
-}
-
-function mockCommandHook(
- payloads: readonly (TaskRunInboundPayload | SubagentAuthorizationEventHookPayload)[],
-): void {
- const queue = [...payloads];
- const hook = {
- [Symbol.asyncIterator]: () => ({
- next: async () =>
- queue.length > 0
- ? { done: false as const, value: queue.shift() as TaskCommandHookPayload }
- : { done: true as const, value: undefined },
- }),
- token: "task-token",
- } as Hook<TaskRunInboundPayload | SubagentAuthorizationEventHookPayload>;
- vi.mocked(createHook).mockReturnValue(hook);
-}
-
-function appendedStatuses(): readonly string[] {
- return vi.mocked(appendTaskViewStep).mock.calls.map(([input]) => input.view.status);
-}
+const initialView = {
+ metadata: { kind: "tool", name: "approval-worker" },
+ status: "working",
+ taskId: "task-1",
+} satisfies TaskView;
+
+const bufferedAgentRequest = {
+ from: {
+ callId: "tool-call-1",
+ execution: "background",
+ input: { message: "authorize" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "approval-worker",
+ turnId: "turn-parent",
+ },
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "authorize", target: "approver" },
+ invocationId: "tool-call-1:approver",
+ kind: "agent-invoke",
+ },
+} satisfies WorkflowToolRunRequestMessage;
+
+const workflowAgentRequest = {
+ ...bufferedAgentRequest,
+ request: {
+ input: { message: "authorize", target: "approver" },
+ invocationId: "tool-call-1:approver:2",
+ kind: "agent-invoke",
+ },
+} satisfies WorkflowToolRunRequestMessage;
describe("taskRunWorkflow", () => {
- it("forwards child updates after dispatch acknowledgement without changing the view", async () => {
- const update = {
- callId: "update-call",
- updateIndex: 2,
- updateEpoch: "turn-child",
- kind: "task-update" as const,
- message: "Found three matching records.",
- };
- mockCommandHook([
- update,
- { command: { kind: "ready" }, kind: "task-command" },
- { ...update, callId: "update-call-2" },
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- const view = createWorkingView();
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: view,
- parentContinuationToken: "parent-session-token",
- });
-
- expect(wakeTaskUpdateParentStep).toHaveBeenNthCalledWith(1, {
- token: "parent-session-token",
- update,
- view,
- });
- expect(wakeTaskUpdateParentStep).toHaveBeenNthCalledWith(2, {
- token: "parent-session-token",
- update: { ...update, callId: "update-call-2" },
- view,
- });
- expect(appendedStatuses()).toEqual(["working", "working", "completed"]);
+ beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.createHook.mockReturnValue({ token: "task-token" });
+ mocks.openWorkflowToolRunOwnerChannels.mockReturnValue({ dispose: vi.fn(), readers: [] });
+ mocks.executeWorkflowBody.mockResolvedValue({ output: "done", status: "completed" });
});
- it("forwards a fast child update before its terminal wake", async () => {
- const update = {
- callId: "update-call",
- updateIndex: 2,
- updateEpoch: "turn-child",
- kind: "task-update" as const,
- message: "Final progress update.",
- };
- mockCommandHook([
- update,
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- { command: { kind: "ready" }, kind: "task-command" },
- ]);
+ it("buffers agent requests until task dispatch is acknowledged", async () => {
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({
+ channel: "request",
+ next: { done: false, value: bufferedAgentRequest },
+ })
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ })
+ .mockResolvedValueOnce({ channel: "commands", next: { done: true, value: undefined } });
await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
});
- expect(wakeTaskUpdateParentStep).toHaveBeenCalledWith({
- token: "parent-session-token",
- update,
- view: expect.objectContaining({ status: "completed" }),
+ expect(mocks.wakeTaskAgentRequestParentStep).toHaveBeenCalledWith({
+ request: bufferedAgentRequest,
+ taskId: "task-1",
+ token: "parent-token",
});
- expect(wakeTaskParentStep).toHaveBeenCalledWith({
- token: "parent-session-token",
- view: expect.objectContaining({ status: "completed" }),
- });
- expect(vi.mocked(wakeTaskUpdateParentStep).mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(wakeTaskParentStep).mock.invocationCallOrder[0] ?? 0,
+ expect(mocks.raceChannelReads.mock.invocationCallOrder[1]).toBeLessThan(
+ mocks.wakeTaskAgentRequestParentStep.mock.invocationCallOrder[0]!,
);
});
- it("publishes the initial view, applies commands, and stops at terminal", async () => {
- mockCommandHook([
- { command: { kind: "ready" }, kind: "task-command" },
- {
- command: {
- inputRequests: [{ question: "which?", requestId: "req-1" }],
- kind: "require-input",
- },
- kind: "task-command",
- },
- { command: { kind: "answered", requestIds: ["req-1"] }, kind: "task-command" },
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- // Never consumed: the run stops at the terminal transition.
- { command: { kind: "cancel" }, kind: "task-command" },
- ]);
+ it("forwards admitted agent requests through the task's owner channel", async () => {
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ })
+ .mockResolvedValueOnce({
+ channel: "request",
+ next: { done: false, value: workflowAgentRequest },
+ })
+ .mockResolvedValueOnce({ channel: "commands", next: { done: true, value: undefined } });
await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
});
- expect(appendedStatuses()).toEqual([
- "working",
- "working",
- "input_required",
- "working",
- "completed",
- ]);
- expect(disposeHook).toHaveBeenCalledTimes(1);
- });
-
- it("opens and disposes the run channels only for a background tool's task", async () => {
- mockCommandHook([
- { command: { kind: "ready" }, kind: "task-command" },
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: {
- metadata: { kind: "tool", name: "deploy" },
- status: "working",
- taskId: "task_abc123",
- },
- parentContinuationToken: "parent-session-token",
- });
-
- expect(appendedStatuses()).toEqual(["working", "working", "completed"]);
- expect(disposeHook).toHaveBeenCalledTimes(4);
- });
-
- it("skips views for rejected and noop commands", async () => {
- mockCommandHook([
- { command: { kind: "answered", requestIds: ["req-1"] }, kind: "task-command" }, // noop on working
- { command: { kind: "cancel" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
+ expect(mocks.wakeTaskAgentRequestParentStep).toHaveBeenCalledWith({
+ request: workflowAgentRequest,
+ taskId: "task-1",
+ token: "parent-token",
});
-
- expect(appendedStatuses()).toEqual(["working", "cancelled"]);
});
- it("exits without touching the lifecycle when the hook claim conflicts", async () => {
- mockCommandHook([]);
- vi.mocked(claimHookOwnership).mockRejectedValue(
- Object.assign(new Error("Hook token in use"), { name: "HookConflictError" }),
- );
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
+ it("does not execute a workflow body before task admission", async () => {
+ mocks.raceChannelReads.mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: true, value: undefined },
});
- expect(appendTaskViewStep).not.toHaveBeenCalled();
- expect(disposeHook).not.toHaveBeenCalled();
- });
-
- it("disposes its hook when the command stream closes early", async () => {
- mockCommandHook([
- { command: { inputRequests: [], kind: "require-input" }, kind: "task-command" },
- ]);
-
await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(appendedStatuses()).toEqual(["working"]);
- expect(disposeHook).toHaveBeenCalledTimes(1);
- });
-
- it("translates a settled child turn from the wire and wakes the parent once ready", async () => {
- const ZERO = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };
- mockCommandHook([
- { command: { kind: "ready" }, kind: "task-command" },
- {
- kind: "runtime-action-result",
- results: [
- {
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "answer" },
- usageDelta: ZERO,
- },
- output: "answer",
- },
- ],
- },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: {
- ...createWorkingView(),
- metadata: {
- agentId: "ag_research:abcdef123456",
- kind: "subagent",
- mode: "local",
- name: "research",
+ workflow: {
+ callId: "call-1",
+ input: {},
+ session: {
+ auth: { current: null, initiator: null },
+ id: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
},
+ stepIndex: 0,
+ toolName: "worker",
+ workflowId: "workflow//eve//worker",
},
- parentContinuationToken: "parent-session-token",
});
- expect(appendedStatuses()).toEqual(["working", "working", "completed"]);
- expect(wakeTaskParentStep).toHaveBeenCalledTimes(1);
- expect(vi.mocked(wakeTaskParentStep).mock.calls[0]?.[0]).toMatchObject({
- token: "parent-session-token",
- view: { status: "completed", taskId: "task_abc123" },
- });
+ expect(mocks.executeWorkflowBody).not.toHaveBeenCalled();
});
- it("keeps a fast terminal task hook alive until dispatch acknowledgement", async () => {
- mockCommandHook([
- {
- kind: "runtime-action-result",
- results: [
- {
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "fast" },
- },
- output: "fast",
- },
- ],
- },
- { command: { kind: "ready" }, kind: "task-command" },
- ]);
+ it("starts the workflow body only after ready", async () => {
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ })
+ .mockResolvedValueOnce({ channel: "commands", next: { done: true, value: undefined } });
await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(appendedStatuses()).toEqual(["working", "completed"]);
- expect(wakeTaskParentStep).toHaveBeenCalledTimes(1);
- expect(disposeHook).toHaveBeenCalledTimes(1);
- });
-
- it("silently terminates a dispatch rejected before parent indexing", async () => {
- mockCommandHook([
- {
- command: { data: { code: "START_FAILED" }, kind: "reject-dispatch" },
- kind: "task-command",
- },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(appendedStatuses()).toEqual(["working", "failed"]);
- expect(wakeTaskParentStep).not.toHaveBeenCalled();
- expect(disposeHook).toHaveBeenCalledTimes(1);
- });
-
- it("releases a fast input request when the readiness barrier arrives", async () => {
- mockCommandHook([
- {
- callId: "call-task",
- childContinuationToken: "child-token",
- childSessionId: "child-session",
- event: {
- requests: [
- {
- action: { callId: "call-q", input: {}, kind: "tool-call", toolName: "ask" },
- kind: "question",
- prompt: "Which?",
- requestId: "q1",
- },
- ],
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-child",
+ workflow: {
+ callId: "call-1",
+ input: {},
+ session: {
+ auth: { current: null, initiator: null },
+ id: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
},
- kind: "subagent-input-request",
- subagentName: "research",
+ stepIndex: 0,
+ toolName: "worker",
+ workflowId: "workflow//eve//worker",
},
- { command: { kind: "ready" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
});
- expect(wakeTaskInputRequestParentStep).toHaveBeenCalledTimes(1);
- expect(wakeTaskParentStep).not.toHaveBeenCalled();
+ expect(mocks.executeWorkflowBody).toHaveBeenCalledOnce();
});
- it("normalizes and holds a local authorization event until the readiness barrier", async () => {
- mockCommandHook([
- {
- callId: "call-task",
- childSessionId: "child-session",
- event: {
- data: {
- attemptId: "github-1",
- description: "Authorize GitHub",
- name: "github",
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-child",
- },
- type: "authorization.required",
- },
- kind: "subagent-authorization-event",
- subagentName: "research",
- },
- {
- callId: "call-task",
- childSessionId: "child-session",
- event: {
- data: {
- attemptId: "linear-1",
- description: "Authorize Linear",
- name: "linear",
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-child",
+ it("flushes an update queued before readiness ahead of terminal completion", async () => {
+ const update = {
+ callId: "call-1",
+ kind: "task-update" as const,
+ message: "progress",
+ updateEpoch: "task-1",
+ updateIndex: 0,
+ };
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({ channel: "commands", next: { done: false, value: update } })
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: {
+ done: false,
+ value: {
+ command: { data: "done", kind: "complete" },
+ kind: "task-command",
},
- type: "authorization.required",
},
- kind: "subagent-authorization-event",
- subagentName: "research",
- },
- { command: { kind: "ready" }, kind: "task-command" },
- ]);
+ })
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ });
await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
});
- expect(appendedStatuses()).toEqual([
- "working",
- "input_required",
- "input_required",
- "input_required",
- ]);
- expect(wakeTaskAuthorizationParentStep).toHaveBeenCalledTimes(2);
- expect(wakeTaskAuthorizationParentStep).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- request: expect.objectContaining({
- event: expect.objectContaining({
- data: expect.objectContaining({ name: "github" }),
- }),
- }),
- }),
- );
- expect(wakeTaskAuthorizationParentStep).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- request: expect.objectContaining({
- event: expect.objectContaining({
- data: expect.objectContaining({ name: "linear" }),
- }),
- }),
- }),
- );
- expect(vi.mocked(wakeTaskAuthorizationParentStep).mock.invocationCallOrder[0]).toBeGreaterThan(
- vi.mocked(appendTaskViewStep).mock.invocationCallOrder[2] ?? 0,
- );
- });
-
- it("ignores approval lifecycle events and still wakes on terminal settlement", async () => {
- mockCommandHook([
- { command: { kind: "ready" }, kind: "task-command" },
- {
- callId: "call-task",
- childSessionId: "child-session-1",
- event: {
- data: {
- outcome: "approved",
- requestId: "stale-1",
- responderPrincipalId: "user-1",
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-child",
- },
- type: "approval.settled",
- },
- kind: "subagent-authorization-event",
- subagentName: "research",
- },
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
+ expect(mocks.wakeTaskUpdateParentStep).toHaveBeenCalledWith({
+ token: "parent-token",
+ update,
+ view: expect.objectContaining({ status: "completed" }),
});
-
- expect(wakeTaskAuthorizationParentStep).not.toHaveBeenCalled();
- expect(wakeTaskParentStep).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({ view: expect.objectContaining({ status: "completed" }) }),
+ expect(mocks.wakeTaskUpdateParentStep.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.wakeTaskParentStep.mock.invocationCallOrder[0]!,
);
});
- it("never wakes twice for one blocked child", async () => {
- mockCommandHook([
- { command: { kind: "ready" }, kind: "task-command" },
- {
- command: { inputRequests: [{ q: 1, requestId: "q1" }], kind: "require-input" },
- kind: "task-command",
- },
- {
- command: { inputRequests: [{ q: 2, requestId: "q2" }], kind: "require-input" },
- kind: "task-command",
- },
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
+ it("publishes cancellation after the workflow body observes its abort", async () => {
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ })
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "cancel" }, kind: "task-command" } },
+ })
+ .mockResolvedValueOnce({
+ channel: "body",
+ next: { done: false, value: { reason: "cancelled", status: "cancelled" } },
+ });
+ mocks.executeWorkflowBody.mockImplementation(
+ async (_input, signal: AbortSignal) =>
+ await new Promise((resolve) => {
+ signal.addEventListener(
+ "abort",
+ () => resolve({ reason: "cancelled", status: "cancelled" }),
+ { once: true },
+ );
+ }),
+ );
await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- // input_required wakes once; the second require-input replaces the
- // batch without leaving the ready state, while terminal settlement
- // still wakes independently after direct HITL responses.
- expect(wakeTaskParentStep).toHaveBeenCalledTimes(2);
- });
-
- it("commits and forwards every exact local task HITL batch before terminal wake", async () => {
- const request = (requestId: string) => ({
- action: {
- callId: `call-${requestId}`,
+ workflow: {
+ callId: "call-1",
input: {},
- kind: "tool-call" as const,
- toolName: "ask",
- },
- kind: "question" as const,
- prompt: requestId,
- requestId,
- });
- const inbound = (requestId: string): TaskRunInboundPayload => ({
- callId: "call-task",
- childContinuationToken: "child-token",
- childSessionId: "child-session-1",
- event: { requests: [request(requestId)], sequence: 1, stepIndex: 2, turnId: "turn_child" },
- kind: "subagent-input-request",
- subagentName: "research",
- });
- mockCommandHook([
- { command: { kind: "ready" }, kind: "task-command" },
- inbound("q1"),
- inbound("q2"),
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(wakeTaskInputRequestParentStep).toHaveBeenCalledTimes(2);
- expect(
- vi.mocked(wakeTaskInputRequestParentStep).mock.calls.map(([input]) => {
- const request = input.request.event.requests[0];
- return request !== null && typeof request === "object"
- ? Reflect.get(request, "requestId")
- : undefined;
- }),
- ).toEqual(["q1", "q2"]);
- expect(wakeTaskParentStep).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({ view: expect.objectContaining({ status: "completed" }) }),
- );
- const firstInputWakeOrder =
- vi.mocked(wakeTaskInputRequestParentStep).mock.invocationCallOrder[0] ?? 0;
- const firstInputAppendOrder = vi.mocked(appendTaskViewStep).mock.invocationCallOrder[2] ?? 0;
- expect(firstInputAppendOrder).toBeLessThan(firstInputWakeOrder);
- });
-});
-
-describe("taskRunWorkflow answered input", () => {
- function requireInput(...requestIds: readonly string[]): TaskRunInboundPayload {
- return {
- command: {
- inputRequests: requestIds.map((requestId) => ({ prompt: requestId, requestId })),
- kind: "require-input",
+ session: {
+ auth: { current: null, initiator: null },
+ id: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
+ },
+ stepIndex: 0,
+ toolName: "worker",
+ workflowId: "workflow//eve//worker",
},
- kind: "task-command",
- };
- }
-
- function answer(...requestIds: readonly string[]): TaskInboundAnswerInput {
- return {
- childContinuationToken: "child-token",
- inputResponses: requestIds.map((requestId) => ({ requestId, text: "answer" })),
- kind: "input-response",
- taskId: "task_abc123",
- };
- }
-
- it("forwards the answer to the child before recording it as unblocked", async () => {
- vi.mocked(deliverTaskInputResponsesStep).mockResolvedValue("delivered");
- mockCommandHook([
- requireInput("q1"),
- answer("q1"),
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
});
- expect(deliverTaskInputResponsesStep).toHaveBeenCalledWith({
- answer: answer("q1"),
- requestIds: ["q1"],
+ expect(mocks.wakeTaskParentStep).toHaveBeenCalledWith({
+ token: "parent-token",
+ view: expect.objectContaining({ status: "cancelled" }),
});
- expect(appendedStatuses()).toEqual(["working", "input_required", "working", "completed"]);
- const deliveryOrder = vi.mocked(deliverTaskInputResponsesStep).mock.invocationCallOrder[0] ?? 0;
- const unblockOrder = vi.mocked(appendTaskViewStep).mock.invocationCallOrder[2] ?? 0;
- expect(deliveryOrder).toBeLessThan(unblockOrder);
- });
-
- it("never lets an answer to a superseded batch reach the child", async () => {
- vi.mocked(deliverTaskInputResponsesStep).mockResolvedValue("delivered");
- mockCommandHook([
- requireInput("q1"),
- requireInput("q2"),
- answer("q1"),
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(deliverTaskInputResponsesStep).not.toHaveBeenCalled();
- expect(appendedStatuses()).toEqual([
- "working",
- "input_required",
- "input_required",
- "completed",
- ]);
- });
-
- it("stays blocked on the requests an answer did not cover", async () => {
- vi.mocked(deliverTaskInputResponsesStep).mockResolvedValue("delivered");
- mockCommandHook([
- requireInput("q1", "q2"),
- answer("q1", "unknown"),
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(deliverTaskInputResponsesStep).toHaveBeenCalledWith({
- answer: answer("q1", "unknown"),
- requestIds: ["q1"],
- });
- const blockedAgain = vi.mocked(appendTaskViewStep).mock.calls[2]?.[0].view;
- expect(blockedAgain?.status).toBe("input_required");
- expect(blockedAgain?.inputRequests).toEqual([{ prompt: "q2", requestId: "q2" }]);
- });
-
- it("keeps the task blocked when the child never received the answer", async () => {
- vi.mocked(deliverTaskInputResponsesStep).mockResolvedValue("unreachable");
- mockCommandHook([
- requireInput("q1"),
- answer("q1"),
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(appendedStatuses()).toEqual(["working", "input_required", "completed"]);
- });
-
- it("ignores an answer addressed to a different task", async () => {
- vi.mocked(deliverTaskInputResponsesStep).mockResolvedValue("delivered");
- mockCommandHook([
- requireInput("q1"),
- { ...answer("q1"), taskId: "task_other" },
- { command: { data: "done", kind: "complete" }, kind: "task-command" },
- ]);
-
- await taskRunWorkflow({
- taskInboxToken: "task-token",
- initialView: createWorkingView(),
- parentContinuationToken: "parent-session-token",
- });
-
- expect(deliverTaskInputResponsesStep).not.toHaveBeenCalled();
- expect(appendedStatuses()).toEqual(["working", "input_required", "completed"]);
});
});
diff --git a/packages/eve/src/execution/tasks/child/workflow.ts b/packages/eve/src/execution/tasks/child/workflow.ts
index 61df2a649..76b6a91e3 100644
--- a/packages/eve/src/execution/tasks/child/workflow.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.ts
@@ -1,288 +1,335 @@
-import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
import { createHook } from "#compiled/@workflow/core/index.js";
-import type {
- ActivityObserverConfig,
- SubagentAuthorizationEventHookPayload,
-} from "#channel/types.js";
import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
import {
appendTaskViewStep,
deliverTaskInputResponsesStep,
+ wakeTaskAgentRequestParentStep,
wakeTaskAuthorizationParentStep,
- wakeTaskInputRequestParentStep,
wakeTaskParentStep,
wakeTaskUpdateParentStep,
+ wakeWorkflowTaskInputRequestParentStep,
} from "#execution/tasks/child/steps.js";
-import { applyTaskTransition } from "#tasks/transitions.js";
-import { translateTaskInboundPayload } from "#tasks/wire.js";
-import { createChannelReader, raceChannelReads } from "#execution/tool-run/owner-channels.js";
-import { openRunOwnerChannels } from "#execution/tool-run/owner.js";
import {
- runOutcomeToTaskCommand,
- runReportToTaskUpdate,
- runRequestToInputRequestPayload,
-} from "#execution/tool-run/owner-inbox.js";
+ createWorkflowBodyRef,
+ executeWorkflowBody,
+ type WorkflowBodyDefinition,
+} from "#execution/tools/workflow/body.js";
+import {
+ deriveWorkflowToolRunOwner,
+ type WorkflowToolRunRequestMessage,
+} from "#execution/tools/workflow/messages.js";
+import { createChannelReader, raceChannelReads } from "#execution/tools/workflow/owner-channels.js";
+import { openWorkflowToolRunOwnerChannels } from "#execution/tools/workflow/owner.js";
+import {
+ workflowToolRunOutcomeToTaskCommand,
+ workflowToolRunReportToTaskUpdate,
+ workflowToolRunRequestToTaskInputRequest,
+} from "#execution/tools/workflow/owner-inbox.js";
+import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
+import { applyTaskTransition } from "#tasks/transitions.js";
import {
isReadyTaskStatus,
isTerminalTaskStatus,
readTaskInputRequestId,
- readTaskUsage,
type TaskCommand,
type TaskInboundAnswerInput,
- type TaskInboundAuthorizationEvent,
- type TaskInboundInputRequest,
+ type TaskInputRequest,
type TaskInboundUpdate,
type TaskRunInboundPayload,
type TaskView,
} from "#tasks/types.js";
-/** Input for one durable task run. */
export interface TaskRunWorkflowInput {
- /** Activity sink and work identity for best-effort terminal settlement. */
- readonly activityObserver?: ActivityObserverConfig;
- /** Private task inbox token; a routing credential, never model-visible. */
- readonly taskInboxToken: string;
- /** The creation view, normally `working`. */
readonly initialView: TaskView;
- /** Parent session delivery token used to wake the task's owning parent. */
readonly parentContinuationToken: string;
+ readonly taskInboxToken: string;
+ readonly workflow?: WorkflowBodyDefinition;
}
-type TaskRunHookPayload = TaskRunInboundPayload | SubagentAuthorizationEventHookPayload;
+/** A workflow-body question routed through the task that owns the workflow tool run. */
+interface WorkflowToolRunTaskInputRequestBase {
+ readonly kind: "task-input-request";
+ readonly replyTo: string;
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
+}
-function isTaskRunFinished(view: TaskView, dispatchAcknowledged: boolean): boolean {
- if (!isTerminalTaskStatus(view.status) || !dispatchAcknowledged) return false;
+export type WorkflowToolRunTaskInputRequest = WorkflowToolRunTaskInputRequestBase &
+ (
+ | { readonly request: TaskInputRequest; readonly requests?: never }
+ | { readonly request?: never; readonly requests: readonly TaskInputRequest[] }
+ );
- // Cancellation makes the task terminal before the child executor has
- // necessarily unwound. Keep its hook open until the final result settles it.
- return view.status !== "cancelled" || view.executor?.lifecycle === "terminal";
+interface PendingWorkflowToolTraffic {
+ readonly ownerRequests: WorkflowToolRunRequestMessage[];
}
-/**
- * The durable task run: single writer for one task's lifecycle.
- *
- * Consumes commands and child wire payloads over its private hook,
- * applies the pure transition function, and appends a full `TaskView`
- * per accepted command to its `eve.task` run stream. Competing
- * completion, cancellation, and input transitions serialize here;
- * rejected commands (for example a late child result after `cancelled`)
- * change nothing.
- *
- * Wake policy: a transition into a ready status — terminal or
- * `input_required` — and an explicit child `task_update` deliver a
- * framework notification to the parent session. A parked parent starts
- * a turn; an active turn observes the delivery at its next safe boundary.
- *
- * The run ends when the task reaches a terminal status. Its view
- * stream stays readable, so terminal tasks remain peekable; the
- * disposed hook makes any later command fail loudly instead of queueing
- * against a finished task.
- */
+/** Owns lifecycle for one background task and consumes its executor traffic. */
export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void> {
"use workflow";
- const commands = createHook<TaskRunHookPayload>({ token: input.taskInboxToken });
- // The iterator shares the hook's durable cursor; create it before
- // claiming so conflict replay is consumed by getConflict(), not a
- // later iterator read.
- const commandReader = createChannelReader("commands", commands);
- // Only a background tool's task can own a workflow tool run. Opened before
- // the claim: the parent hands the token to the run as soon as the claim
- // lands, and the run may report at once.
- const runChannels =
- input.initialView.metadata.kind === "tool"
- ? openRunOwnerChannels(input.taskInboxToken)
- : undefined;
- const readers =
- runChannels === undefined
- ? ([commandReader] as const)
- : ([...runChannels.readers, commandReader] as const);
+ const commands = createHook<TaskRunInboundPayload>({ token: input.taskInboxToken });
+ const workflowToolRunChannels = openWorkflowToolRunOwnerChannels(input.taskInboxToken);
+ const readers = [
+ ...workflowToolRunChannels.readers,
+ createChannelReader("commands", commands),
+ ] as const;
let ownsHook = false;
+ let view = input.initialView;
+ let dispatchAcknowledged = false;
+ let dispatchRejected = false;
+ let pendingInputRequest: WorkflowToolRunTaskInputRequest | undefined;
+ let pendingUpdates: TaskInboundUpdate[] = [];
+ let updateIndex = 0;
+ const pendingTraffic: PendingWorkflowToolTraffic = { ownerRequests: [] };
+ const answerHooks = new Map<string, AnswerHookRoute>();
+ const bodyController = new AbortController();
+ let bodyReader:
+ | import("#execution/tools/workflow/owner-channels.js").ChannelReader<
+ "body",
+ import("#execution/tools/workflow/messages.js").WorkflowToolRunOutcome
+ >
+ | undefined;
+ let executorSettled = input.workflow === undefined;
try {
try {
await claimHookOwnership(commands);
ownsHook = true;
} catch (error) {
- // A duplicate start for the same task (crash between the start
- // side effect and its step commit) loses the claim and exits;
- // the surviving run owns the lifecycle.
if (isHookConflictError(error)) return;
throw error;
}
- let view = input.initialView;
- let pendingInputRequest: TaskInboundInputRequest | undefined;
- let pendingAuthorizationEvents: TaskInboundAuthorizationEvent[] = [];
- let pendingUpdates: TaskInboundUpdate[] = [];
- let dispatchAcknowledged = false;
- let runUpdateIndex = 0;
- // The parent answers with the request's token; only this run knows it was a hook.
- const answerHooks = new Map<string, AnswerHookRoute>();
- await appendTaskViewStep({ activityObserver: input.activityObserver, view });
-
- while (!isTaskRunFinished(view, dispatchAcknowledged)) {
- const read = await raceChannelReads(readers);
- if (read.next.done === true) return;
- if (read.channel === "request") {
- answerHooks.set(read.next.value.answerToken, { runId: read.next.value.from.runId });
- }
- const raw: TaskRunHookPayload =
- read.channel === "report"
- ? runReportToTaskUpdate(read.next.value, view.taskId, runUpdateIndex++)
- : read.channel === "request"
- ? runRequestToInputRequestPayload(read.next.value)
- : read.channel === "outcome"
- ? { command: runOutcomeToTaskCommand(read.next.value), kind: "task-command" }
- : read.next.value;
- const payload: TaskRunInboundPayload =
- raw.kind === "subagent-authorization-event" ? { ...raw, kind: "authorization-event" } : raw;
- // Approval lifecycle events (`approval.candidate`/`approval.settled`)
- // are intra-child responder bookkeeping, not task blockers: only
- // `authorization.required`/`authorization.completed` may block or
- // unblock a task. Forwarding them would mint bogus `answered`
- // commands and race the terminal wake.
- if (
- payload.kind === "authorization-event" &&
- (payload.event.type === "approval.candidate" || payload.event.type === "approval.settled")
- ) {
- continue;
- }
- const isReadinessCommand =
- payload.kind === "task-command" && payload.command.kind === "ready";
- const isRejectedDispatch =
- payload.kind === "task-command" && payload.command.kind === "reject-dispatch";
- if (isReadinessCommand || isRejectedDispatch) dispatchAcknowledged = true;
- if (payload.kind === "subagent-input-request") {
- pendingInputRequest = payload;
- }
- if (payload.kind === "authorization-event") {
- pendingAuthorizationEvents.push(payload);
- }
- if (payload.kind === "task-update") {
- if (dispatchAcknowledged && !isTerminalTaskStatus(view.status)) {
- await wakeTaskUpdateParentStep({
- token: input.parentContinuationToken,
- update: payload,
- view,
- });
- } else {
- pendingUpdates.push(payload);
+ await appendTaskViewStep({ view });
+ while (!isFinished()) {
+ const read = await raceChannelReads(
+ bodyReader === undefined ? readers : [...readers, bodyReader],
+ );
+ if (read.channel === "body") {
+ executorSettled = true;
+ bodyReader = undefined;
+ if (read.next.done) continue;
+ await applyPayload({
+ command: workflowToolRunOutcomeToTaskCommand({
+ from: createWorkflowBodyRef({ ...input.workflow!, execution: "background" }),
+ result: read.next.value,
+ }),
+ kind: "task-command",
+ });
+ if (view.status === "cancelled" && dispatchAcknowledged && !dispatchRejected) {
+ await wakeTaskParentStep({ token: input.parentContinuationToken, view });
}
continue;
}
- const isExecutorResultAfterCancellation =
- view.status === "cancelled" && payload.kind === "runtime-action-result";
- const isTaskInputAnswer = payload.kind === "input-response";
- let command: TaskCommand | undefined;
+ if (read.next.done) return;
- if (isExecutorResultAfterCancellation) {
- command = {
- kind: "settle-executor",
- usage: readTaskUsage(payload.results[0]?.outcome?.usageDelta),
- };
- } else if (isTaskInputAnswer) {
- if (view.status !== "input_required") continue;
- command = await resolveAnsweredCommand(
- view,
- payload,
- answerHooks.get(payload.childContinuationToken),
+ if (read.channel === "report") {
+ await applyPayload(
+ workflowToolRunReportToTaskUpdate(read.next.value, view.taskId, updateIndex++),
);
- } else {
- command = translateTaskInboundPayload(payload);
- }
- if (command === undefined) continue;
- if (isReadinessCommand && isTerminalTaskStatus(view.status)) {
- for (const update of pendingUpdates) {
- await wakeTaskUpdateParentStep({
- token: input.parentContinuationToken,
- update,
- view,
- });
- }
- pendingUpdates = [];
- await wakeTaskParentStep({ token: input.parentContinuationToken, view });
continue;
}
- const result = applyTaskTransition(view, command);
- if (result.action !== "accepted") continue;
- const becameTerminal =
- !isTerminalTaskStatus(view.status) && isTerminalTaskStatus(result.view.status);
- const becameReady = !isReadyTaskStatus(view.status) && isReadyTaskStatus(result.view.status);
- view = result.view;
- await appendTaskViewStep({ activityObserver: input.activityObserver, view });
- const routableAuthorizationEvents =
- dispatchAcknowledged && !becameTerminal ? pendingAuthorizationEvents : [];
- for (const request of routableAuthorizationEvents) {
- await wakeTaskAuthorizationParentStep({
- request,
- taskId: view.taskId,
- token: input.parentContinuationToken,
+ if (read.channel === "outcome") {
+ await applyPayload({
+ command: workflowToolRunOutcomeToTaskCommand(read.next.value),
+ kind: "task-command",
});
+ continue;
}
- if (dispatchAcknowledged && pendingUpdates.length > 0 && !isTerminalTaskStatus(view.status)) {
- for (const update of pendingUpdates) {
- await wakeTaskUpdateParentStep({
- token: input.parentContinuationToken,
- update,
- view,
- });
+ if (read.channel === "request") {
+ const request = read.next.value;
+ const kind = request.request.kind;
+ if (
+ kind === "agent-invoke" ||
+ kind === "agent-settled" ||
+ kind === "authorization-request"
+ ) {
+ await handleOwnerRequest(request);
+ continue;
}
- pendingUpdates = [];
- }
- if (becameTerminal || routableAuthorizationEvents.length > 0) pendingAuthorizationEvents = [];
- const routableInputRequest =
- pendingInputRequest !== undefined &&
- dispatchAcknowledged &&
- view.status === "input_required";
- if (routableInputRequest) {
- await wakeTaskInputRequestParentStep({
- request: pendingInputRequest as TaskInboundInputRequest,
- taskId: view.taskId,
- token: input.parentContinuationToken,
- });
- pendingInputRequest = undefined;
- } else if (
- !isRejectedDispatch &&
- routableAuthorizationEvents.length === 0 &&
- dispatchAcknowledged &&
- (becameTerminal || (becameReady && pendingInputRequest === undefined))
- ) {
- await wakeTaskParentStep({ token: input.parentContinuationToken, view });
+ if (request.requestCoordinates === undefined) {
+ answerHooks.set(request.replyTo, { runId: request.from.runId });
+ }
+ await applyPayload(workflowToolRunRequestToTaskInputRequest(request));
+ continue;
}
- // An unrouted request cannot outlive the block it described, or a
- // later block would replay it to the parent as if it were new.
- if (view.status !== "input_required") pendingInputRequest = undefined;
+
+ await applyPayload(read.next.value);
}
} finally {
- // Dispose-only teardown: `iterator.return()` would await a pending
- // durable read that never settles, leaving this run `running`
- // forever and its hook unswept.
if (ownsHook) {
- await runChannels?.dispose();
+ await workflowToolRunChannels.dispose();
await disposeHook(commands);
}
}
+
+ function isFinished(): boolean {
+ return isTerminalTaskStatus(view.status) && dispatchAcknowledged && executorSettled;
+ }
+
+ async function handleUpdate(update: TaskInboundUpdate): Promise<void> {
+ if (dispatchAcknowledged && !isTerminalTaskStatus(view.status)) {
+ await wakeTaskUpdateParentStep({ token: input.parentContinuationToken, update, view });
+ } else {
+ pendingUpdates.push(update);
+ }
+ }
+
+ async function applyPayload(
+ payload: TaskRunInboundPayload | WorkflowToolRunTaskInputRequest,
+ ): Promise<void> {
+ const isReady = payload.kind === "task-command" && payload.command.kind === "ready";
+ const isRejected =
+ payload.kind === "task-command" && payload.command.kind === "reject-dispatch";
+ if (isReady || isRejected) dispatchAcknowledged = true;
+ if (isRejected) dispatchRejected = true;
+ if (isReady || isRejected) {
+ if (isRejected || isTerminalTaskStatus(view.status)) {
+ executorSettled = true;
+ } else if (input.workflow !== undefined && bodyReader === undefined && !executorSettled) {
+ bodyReader = createChannelReader(
+ "body",
+ awaitBodyResult(
+ executeWorkflowBody(
+ {
+ ...input.workflow,
+ execution: "background",
+ owner: deriveWorkflowToolRunOwner(input.taskInboxToken),
+ },
+ bodyController.signal,
+ ),
+ ),
+ );
+ }
+ await flushPendingTraffic();
+ }
+
+ if (payload.kind === "task-input-request") pendingInputRequest = payload;
+ if (payload.kind === "task-update") {
+ await handleUpdate(payload);
+ return;
+ }
+
+ let command: TaskCommand | undefined;
+ if (payload.kind === "input-response") {
+ command =
+ view.status === "input_required"
+ ? await resolveAnsweredCommand(
+ view,
+ payload,
+ answerHooks.get(payload.childContinuationToken),
+ )
+ : undefined;
+ } else if (payload.kind === "task-input-request") {
+ command = {
+ inputRequests: payload.requests ?? [payload.request],
+ kind: "require-input",
+ };
+ } else if (payload.kind === "task-command") {
+ command = payload.command;
+ } else {
+ return;
+ }
+ if (command === undefined) return;
+ if (isReady && isTerminalTaskStatus(view.status)) {
+ await flushUpdates(true);
+ await wakeTaskParentStep({ token: input.parentContinuationToken, view });
+ return;
+ }
+
+ const previous = view;
+ const result = applyTaskTransition(view, command);
+ if (result.action !== "accepted") return;
+ view = result.view;
+ await appendTaskViewStep({ view });
+ if (command.kind === "cancel") {
+ bodyController.abort(new Error(`Task ${view.taskId} was cancelled.`));
+ if (bodyReader === undefined) executorSettled = true;
+ }
+ if (!isTerminalTaskStatus(view.status)) await flushUpdates();
+ if (
+ pendingInputRequest !== undefined &&
+ dispatchAcknowledged &&
+ view.status === "input_required"
+ ) {
+ await wakeWorkflowTaskInputRequestParentStep({
+ request: pendingInputRequest,
+ taskId: view.taskId,
+ token: input.parentContinuationToken,
+ });
+ pendingInputRequest = undefined;
+ } else if (
+ !dispatchRejected &&
+ dispatchAcknowledged &&
+ (command.kind !== "cancel" || executorSettled) &&
+ ((!isTerminalTaskStatus(previous.status) && isTerminalTaskStatus(view.status)) ||
+ (!isReadyTaskStatus(previous.status) &&
+ isReadyTaskStatus(view.status) &&
+ pendingInputRequest === undefined))
+ ) {
+ await wakeTaskParentStep({ token: input.parentContinuationToken, view });
+ }
+ if (view.status !== "input_required") pendingInputRequest = undefined;
+ }
+
+ async function flushUpdates(includeTerminal = false): Promise<void> {
+ if (!dispatchAcknowledged || (isTerminalTaskStatus(view.status) && !includeTerminal)) return;
+ for (const update of pendingUpdates) {
+ await wakeTaskUpdateParentStep({ token: input.parentContinuationToken, update, view });
+ }
+ pendingUpdates = [];
+ }
+
+ // Agent requests and authorization events both target the parent session
+ // directly and must wait until the parent has acknowledged the task dispatch.
+ async function handleOwnerRequest(message: WorkflowToolRunRequestMessage): Promise<void> {
+ if (dispatchRejected || isTerminalTaskStatus(view.status)) return;
+ if (!dispatchAcknowledged) {
+ pendingTraffic.ownerRequests.push(message);
+ return;
+ }
+ await wakeTaskOwnerRequestParent(message);
+ }
+
+ async function flushPendingTraffic(): Promise<void> {
+ if (!dispatchRejected) {
+ for (const request of pendingTraffic.ownerRequests) await wakeTaskOwnerRequestParent(request);
+ }
+ pendingTraffic.ownerRequests.length = 0;
+ }
+
+ async function wakeTaskOwnerRequestParent(message: WorkflowToolRunRequestMessage): Promise<void> {
+ if (message.request.kind === "authorization-request") {
+ await wakeTaskAuthorizationParentStep({
+ request: message.request,
+ taskId: view.taskId,
+ token: input.parentContinuationToken,
+ });
+ return;
+ }
+ await wakeTaskAgentRequestParentStep({
+ request: message,
+ taskId: view.taskId,
+ token: input.parentContinuationToken,
+ });
+ }
+}
+
+async function* awaitBodyResult(
+ result: Promise<import("#execution/tools/workflow/messages.js").WorkflowToolRunOutcome>,
+): AsyncGenerator<import("#execution/tools/workflow/messages.js").WorkflowToolRunOutcome> {
+ yield await result;
}
-/**
- * Forwards one human answer to the blocked child and reports which
- * requests it cleared.
- *
- * Delivery is attempted only for requests the run still lists as
- * outstanding, and the resulting command names exactly those ids. That
- * ordering is the point: answers to a superseded batch never reach the
- * child, and a child whose hook is already gone leaves the task blocked
- * instead of moving to `working` with nothing listening.
- */
async function resolveAnsweredCommand(
view: Extract<TaskView, { status: "input_required" }>,
answer: TaskInboundAnswerInput,
answerHook: AnswerHookRoute | undefined,
): Promise<TaskCommand | undefined> {
if (answer.taskId !== view.taskId) return undefined;
-
const outstanding = new Set(
view.inputRequests.flatMap((request) => {
const requestId = readTaskInputRequestId(request);
@@ -291,9 +338,9 @@ async function resolveAnsweredCommand(
);
const requestIds = answer.inputResponses
.map((response) => response.requestId)
- .filter((requestId) => outstanding.has(requestId));
+ .filter((id) => outstanding.has(id));
if (requestIds.length === 0) return undefined;
-
- const delivery = await deliverTaskInputResponsesStep({ answer, answerHook, requestIds });
- return delivery === "delivered" ? { kind: "answered", requestIds } : undefined;
+ return (await deliverTaskInputResponsesStep({ answer, answerHook, requestIds })) === "delivered"
+ ? { kind: "answered", requestIds }
+ : undefined;
}
diff --git a/packages/eve/src/execution/tasks/parent/agent-identity.ts b/packages/eve/src/execution/tasks/parent/agent-identity.ts
deleted file mode 100644
index 47c826b91..000000000
--- a/packages/eve/src/execution/tasks/parent/agent-identity.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { mintStartOperation } from "#execution/dispatch-start-operation.js";
-import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";
-
-/** Resolves the persistent agent identity attached to one delegated task. */
-export function describeTaskAgent(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly agentId?: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
-}): {
- readonly agentId: string;
- readonly callId: string;
- readonly mode: "local" | "remote";
- readonly name: string;
-} {
- const { action } = input;
- const name = action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;
- const agentId =
- input.agentId ??
- mintStartOperation({
- callId: action.callId,
- name,
- nodeId: action.nodeId,
- parentSessionId: input.parentSessionId,
- parentTurnId: input.parentTurnId,
- }).identity.id;
- return {
- agentId,
- callId: action.callId,
- mode: action.kind === "remote-agent-call" ? "remote" : "local",
- name,
- };
-}
diff --git a/packages/eve/src/execution/tasks/parent/agent-views.test.ts b/packages/eve/src/execution/tasks/parent/agent-views.test.ts
deleted file mode 100644
index 1c5407a70..000000000
--- a/packages/eve/src/execution/tasks/parent/agent-views.test.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- appendTaskAgentAnnouncement,
- readTaskAgentViews,
-} from "#execution/tasks/parent/agent-views.js";
-import { findActiveTaskForAgent } from "#execution/tasks/parent/control-shared.js";
-import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
-import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
-import type { HarnessSession } from "#harness/types.js";
-import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";
-import type { TaskStatus, TaskView } from "#tasks/types.js";
-
-vi.mock("#execution/tasks/parent/run-parent.js", () => ({
- readLatestTaskView: vi.fn(),
-}));
-
-const metadata = {
- agentId: "ag_research:abcdef123456",
- kind: "subagent" as const,
- mode: "local" as const,
- name: "research",
-};
-
-function createSession(taskRunIds: readonly string[]): HarnessSession {
- return {
- agent: { modelReference: { id: "model" }, system: "", tools: [] },
- compaction: { recentWindowSize: 4, threshold: 1_000_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- state: {
- [AGENT_HANDLES_STATE_KEY]: {
- handles: [
- {
- address: {
- continuationToken: "child-token",
- kind: "agent/local",
- sessionId: "child-session",
- },
- identity: { id: metadata.agentId, name: metadata.name, nodeId: "node-research" },
- phase: "addressed",
- },
- ],
- },
- [SESSION_TASKS_STATE_KEY]: {
- tasks: taskRunIds.map((taskRunId, index) => ({
- taskInboxToken: `task-token-${index}`,
- createdByTurnId: `turn-${index}`,
- metadata,
- operationId: `operation-${index}`,
- taskId: `task_${index}`,
- taskRunId,
- })),
- },
- },
- };
-}
-
-function task(taskId: string, status: TaskStatus): TaskView {
- // Cast on purpose: mock views omit the per-status payload fields the
- // TaskView union requires (e.g. lastOutput on completed).
- return { metadata, status, taskId } as TaskView;
-}
-
-describe("task-derived agent availability", () => {
- beforeEach(() => vi.resetAllMocks());
-
- it("renders a nonterminal task as busy and a terminal task as available", async () => {
- vi.mocked(readLatestTaskView)
- .mockResolvedValueOnce(task("task_0", "working"))
- .mockResolvedValueOnce(task("task_0", "completed"));
- const session = createSession(["run-0"]);
-
- await expect(readTaskAgentViews(session)).resolves.toEqual([
- {
- availability: "busy",
- id: metadata.agentId,
- name: metadata.name,
- statusLine: undefined,
- taskId: "task_0",
- taskStatus: "working",
- },
- ]);
- await expect(readTaskAgentViews(session)).resolves.toEqual([
- {
- availability: "available",
- id: metadata.agentId,
- name: metadata.name,
- statusLine: undefined,
- },
- ]);
- });
-
- it("finds the active task used for the continuation availability check", async () => {
- vi.mocked(readLatestTaskView).mockResolvedValue(task("task_0", "input_required"));
-
- await expect(
- findActiveTaskForAgent(createSession(["run-0"]), metadata.agentId),
- ).resolves.toMatchObject({
- view: { status: "input_required", taskId: "task_0" },
- });
- });
-
- it("appends the busy projection without exposing routing coordinates", async () => {
- vi.mocked(readLatestTaskView).mockResolvedValue(task("task_0", "working"));
-
- const next = await appendTaskAgentAnnouncement(createSession(["run-0"]));
- const message = next.history.at(-1);
- const announcement = message?.content;
-
- expect(message?.role).toBe("user");
- expect(announcement).toContain('availability="busy"');
- expect(announcement).toContain('taskId="task_0"');
- expect(announcement).not.toContain("child-token");
- expect(announcement).not.toContain("child-session");
- await expect(appendTaskAgentAnnouncement(next)).resolves.toBe(next);
- });
-
- it("deduplicates task announcements against the prepared history view", async () => {
- vi.mocked(readLatestTaskView).mockResolvedValue(task("task_0", "working"));
- const session = createSession(["run-0"]);
- const withRawAnnouncement = await appendTaskAgentAnnouncement(session);
-
- const next = await appendTaskAgentAnnouncement(withRawAnnouncement, []);
-
- expect(next.history).toHaveLength(withRawAnnouncement.history.length + 1);
- expect(next.history.at(-1)).toEqual(withRawAnnouncement.history.at(-1));
- });
-
- it("rejects two nonterminal tasks bound to one child agent", async () => {
- vi.mocked(readLatestTaskView)
- .mockResolvedValueOnce(task("task_0", "working"))
- .mockResolvedValueOnce(task("task_1", "input_required"));
-
- await expect(readTaskAgentViews(createSession(["run-0", "run-1"]))).rejects.toThrow(
- "more than one nonterminal task",
- );
- });
-});
diff --git a/packages/eve/src/execution/tasks/parent/agent-views.ts b/packages/eve/src/execution/tasks/parent/agent-views.ts
deleted file mode 100644
index 61f1cc606..000000000
--- a/packages/eve/src/execution/tasks/parent/agent-views.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type { ModelMessage } from "ai";
-
-import type { HarnessSession } from "#harness/types.js";
-import { resolveAgentsAnnouncement, type AgentView } from "#harness/handles/prompt.js";
-import { formatAgentStatus, getAgentHandleStore } from "#harness/handles/store.js";
-import { readTaskViews } from "#execution/tasks/parent/control-shared.js";
-import { getSessionTaskIndex } from "#tasks/session-index.js";
-import { readSubagentTaskMetadata } from "#tasks/types.js";
-
-/** Derives model-visible task-agent availability from authoritative task views. */
-export async function readTaskAgentViews(session: HarnessSession): Promise<readonly AgentView[]> {
- const addresses = (getAgentHandleStore(session.state)?.handles ?? []).filter(
- (handle) => handle.phase === "addressed",
- );
- if (addresses.length === 0) return [];
-
- const entries = getSessionTaskIndex(session.state);
- const views = await readTaskViews(entries);
- const byAgent = new Map<string, typeof views>();
- for (const view of views) {
- const metadata = readSubagentTaskMetadata(view);
- if (metadata === undefined) continue;
- const current = byAgent.get(metadata.agentId) ?? [];
- byAgent.set(metadata.agentId, [...current, view]);
- }
-
- return addresses.map((address) => {
- const agentTasks = byAgent.get(address.identity.id) ?? [];
- const active = agentTasks.filter(
- (view) => view.status === "working" || view.status === "input_required",
- );
- if (active.length > 1) {
- throw new Error(`Agent "${address.identity.id}" has more than one nonterminal task.`);
- }
- const task = active[0];
- if (task !== undefined) {
- const taskStatus = task.status === "input_required" ? "input_required" : "working";
- return {
- availability: "busy",
- id: address.identity.id,
- name: address.identity.name,
- taskId: task.taskId,
- taskStatus,
- };
- }
-
- const latest = agentTasks.at(-1);
- return {
- availability: "available",
- id: address.identity.id,
- name: address.identity.name,
- statusLine:
- latest?.lastOutput === undefined ? undefined : formatAgentStatus(latest.lastOutput.data),
- };
- });
-}
-
-/** Appends the changed task-agent projection before the next model call. */
-export async function appendTaskAgentAnnouncement(
- session: HarnessSession,
- messages: readonly ModelMessage[] = session.history,
-): Promise<HarnessSession> {
- const agentViews = await readTaskAgentViews(session);
- const announcement = resolveAgentsAnnouncement({
- agentViews,
- messages,
- store: getAgentHandleStore(session.state),
- });
- return announcement === undefined
- ? session
- : {
- ...session,
- history: [...session.history, { content: announcement, role: "user" }],
- };
-}
diff --git a/packages/eve/src/execution/tasks/parent/continuation-dispatch.test.ts b/packages/eve/src/execution/tasks/parent/continuation-dispatch.test.ts
deleted file mode 100644
index fef89ce1f..000000000
--- a/packages/eve/src/execution/tasks/parent/continuation-dispatch.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { settleTaskDispatchError } from "#execution/tasks/parent/continuation-dispatch.js";
-import {
- failDelegatedDispatch,
- rejectDelegatedDispatch,
-} from "#execution/tasks/parent/delegate.js";
-
-vi.mock("#execution/tasks/parent/delegate.js", () => ({
- failDelegatedDispatch: vi.fn(),
- rejectDelegatedDispatch: vi.fn(),
- settleDelegatedDispatch: vi.fn(),
-}));
-
-const task = {
- taskInboxToken: "task-token",
- createdByTurnId: "turn-parent",
- metadata: {
- agentId: "agent-1",
- kind: "subagent" as const,
- mode: "remote" as const,
- name: "research",
- },
- operationId: "operation-1",
- taskId: "task_1",
- taskRunId: "run-1",
-};
-
-function outcome(deliveryAmbiguous: boolean) {
- return {
- deliveryAmbiguous,
- kind: "error" as const,
- result: {
- callId: "call-1",
- isError: true as const,
- kind: "subagent-result" as const,
- origin: "dispatch" as const,
- output: { code: "AGENT_UNREACHABLE", message: "rejected" },
- subagentName: "research",
- },
- session: {} as never,
- };
-}
-
-describe("settleTaskDispatchError", () => {
- beforeEach(() => vi.resetAllMocks());
-
- it("fails an indexed task after a definitive continuation rejection", async () => {
- const rejected = outcome(false);
-
- await settleTaskDispatchError({
- delegated: task,
- outcome: rejected,
- persisted: { receipt: {} as never, session: rejected.session },
- });
-
- expect(failDelegatedDispatch).toHaveBeenCalledWith({
- error: rejected.result.output,
- task,
- });
- expect(rejectDelegatedDispatch).not.toHaveBeenCalled();
- });
-
- it("leaves an indexed task pending only when delivery was ambiguous", async () => {
- const ambiguous = outcome(true);
-
- await settleTaskDispatchError({
- delegated: task,
- outcome: ambiguous,
- persisted: { receipt: {} as never, session: ambiguous.session },
- });
-
- expect(failDelegatedDispatch).not.toHaveBeenCalled();
- expect(rejectDelegatedDispatch).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts b/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
deleted file mode 100644
index a7bc56c96..000000000
--- a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import {
- createAgentErrorResult,
- type DispatchOutcome,
- type RuntimeAgentHandleAction,
- type RuntimeSession,
-} from "#execution/agent-handle-dispatch.js";
-import {
- findActiveTaskForAgent,
- findTaskAgentAddress,
-} from "#execution/tasks/parent/control-shared.js";
-import {
- failDelegatedDispatch,
- rejectDelegatedDispatch,
- settleDelegatedDispatch,
- type DelegatedTask,
-} from "#execution/tasks/parent/delegate.js";
-import { describeTaskAgent } from "#execution/tasks/parent/agent-identity.js";
-import { AGENT_BUSY } from "#harness/agent-handle-errors.js";
-import type { RuntimeSubagentDispatchFailure } from "#shared/action-types.js";
-import type { JsonValue } from "#shared/json.js";
-
-export type PersistedContinuationTask = Awaited<ReturnType<typeof settleDelegatedDispatch>>;
-
-/** Describes task identity from the stored address when continuing an agent. */
-export function describeTaskDispatch(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly agentId: string | undefined;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
- readonly session: RuntimeSession;
-}): ReturnType<typeof describeTaskAgent> {
- const described = describeTaskAgent(input);
- const handle =
- input.agentId === undefined ? undefined : findTaskAgentAddress(input.session, input.agentId);
- return handle === undefined
- ? described
- : {
- ...described,
- mode: handle.address.kind === "agent/remote" ? "remote" : "local",
- };
-}
-
-export async function checkTaskContinuationAvailability(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly agentId: string;
- readonly parentStepIndex: number;
- readonly parentTurnId: string;
- readonly session: RuntimeSession;
-}): Promise<RuntimeSubagentDispatchFailure | undefined> {
- const active = await findActiveTaskForAgent(
- input.session,
- input.agentId,
- input.parentTurnId,
- input.parentStepIndex,
- );
- return active === undefined
- ? undefined
- : createTaskContinuationBusyResult({
- action: input.action,
- agentId: input.agentId,
- status: active.view.status,
- taskId: active.view.taskId,
- });
-}
-
-export function createTaskContinuationBusyResult(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly agentId: string;
- readonly status: string;
- readonly taskId: string;
-}): RuntimeSubagentDispatchFailure {
- return createAgentErrorResult({
- action: input.action,
- code: AGENT_BUSY,
- message: `Agent "${input.agentId}" is busy with task "${input.taskId}" (${input.status}).`,
- });
-}
-
-/**
- * Persists the task's ownership and routing entry in the parent session's
- * `eve.tasks` index and creates its parked tool-call receipt before dispatch.
- */
-export async function persistContinuationTaskInParentSession(input: {
- readonly action: RuntimeAgentHandleAction;
- readonly agentId: string;
- readonly delegated: DelegatedTask;
- readonly session: RuntimeSession;
-}): Promise<PersistedContinuationTask | undefined> {
- const handle = findTaskAgentAddress(input.session, input.agentId);
- if (handle === undefined) return undefined;
- return settleDelegatedDispatch({
- callId: input.action.callId,
- session: input.session,
- subagentName: handle.identity.name,
- task: input.delegated,
- });
-}
-
-export async function settleTaskDispatchError(input: {
- readonly delegated: DelegatedTask;
- readonly outcome: Extract<DispatchOutcome, { readonly kind: "error" }>;
- readonly persisted: PersistedContinuationTask | undefined;
-}): Promise<RuntimeSubagentDispatchFailure> {
- const ambiguous = input.persisted !== undefined && input.outcome.deliveryAmbiguous === true;
- if (!ambiguous) {
- const settle = input.persisted === undefined ? rejectDelegatedDispatch : failDelegatedDispatch;
- await settle({ error: input.outcome.result.output, task: input.delegated });
- }
- return input.persisted === undefined
- ? input.outcome.result
- : {
- ...input.outcome.result,
- output: attachTaskId(input.outcome.result.output, input.delegated.taskId),
- };
-}
-
-function attachTaskId(output: JsonValue, taskId: string): JsonValue {
- return output !== null && typeof output === "object" && !Array.isArray(output)
- ? { ...output, taskId }
- : { error: output, taskId };
-}
diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.ts
index 9bd407105..f668d4019 100644
--- a/packages/eve/src/execution/tasks/parent/control-shared.ts
+++ b/packages/eve/src/execution/tasks/parent/control-shared.ts
@@ -1,16 +1,10 @@
-import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import type { HarnessSession as RuntimeSession } from "#harness/types.js";
import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
-import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
-import type { RuntimeActionResult } from "#shared/action-types.js";
-import type { TaskControlInvocation } from "#shared/dispatch-action.js";
+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";
import { taskViewsToJson } from "#tasks/json.js";
-import {
- findSessionTaskEntry,
- getSessionTaskIndex,
- type SessionTaskIndexEntry,
-} from "#tasks/session-index.js";
-import { readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";
+import { findSessionTaskEntry, type SessionTaskIndexEntry } from "#tasks/session-index.js";
+import type { TaskView } from "#tasks/types.js";
/**
* Result and lookup helpers shared by the task-control executors
@@ -73,44 +67,9 @@ function createPendingTaskView(entry: SessionTaskIndexEntry): TaskView {
return { ...view, executor: { binding: entry.executor } };
}
-/** Finds the persistent address record for one task-owned agent. */
-export function findTaskAgentAddress(
- session: RuntimeSession,
- agentId: string,
-): Extract<AgentHandle, { phase: "addressed" }> | undefined {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- return handles.find(
- (candidate): candidate is Extract<AgentHandle, { phase: "addressed" }> =>
- candidate.phase === "addressed" && candidate.identity.id === agentId,
- );
-}
-
-/** Returns the one nonterminal task owning an agent, if any. */
-export async function findActiveTaskForAgent(
- session: RuntimeSession,
- agentId: string,
- parentTurnId?: string,
- parentStepIndex?: number,
-): Promise<{ readonly entry: SessionTaskIndexEntry; readonly view: TaskView } | undefined> {
- const entries = getSessionTaskIndex(session.state).filter(
- (entry) => readSubagentTaskMetadata(entry)?.agentId === agentId,
- );
- const views = await readTaskViews(entries);
- const active = entries.flatMap((entry, index) => {
- const view = views[index];
- return view !== undefined &&
- ((entry.createdByTurnId === parentTurnId && entry.createdByStepIndex === parentStepIndex) ||
- view.status === "working" ||
- view.status === "input_required")
- ? [{ entry, view }]
- : [];
- });
- return active[0];
-}
-
/** One successful task-control result carrying full task views. */
export function createTaskViewsResult(
- action: TaskControlInvocation,
+ action: RuntimeToolCallActionRequest,
views: readonly TaskView[],
): RuntimeActionResult {
return {
@@ -123,7 +82,7 @@ export function createTaskViewsResult(
/** One task-control error the model can act on. */
export function createTaskControlError(
- action: TaskControlInvocation,
+ action: RuntimeToolCallActionRequest,
message: string,
): RuntimeActionResult {
return {
@@ -137,7 +96,7 @@ export function createTaskControlError(
/** The ownership error for ids outside this session's task index. */
export function createUnknownTasksError(
- action: TaskControlInvocation,
+ action: RuntimeToolCallActionRequest,
unknown: readonly string[],
): RuntimeActionResult {
return createTaskControlError(
diff --git a/packages/eve/src/execution/tasks/parent/delegate.test.ts b/packages/eve/src/execution/tasks/parent/delegate.test.ts
index 2cba8f0fb..21bf61548 100644
--- a/packages/eve/src/execution/tasks/parent/delegate.test.ts
+++ b/packages/eve/src/execution/tasks/parent/delegate.test.ts
@@ -1,63 +1,25 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
-import {
- acknowledgeDelegatedTasksStep,
- settleDelegatedDispatch,
- type DelegatedTask,
-} from "#execution/tasks/parent/delegate.js";
+import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
import { sendTaskCommandToOwner } from "#execution/tasks/parent/run-parent.js";
-import { getSessionTaskIndex } from "#tasks/session-index.js";
vi.mock("#execution/tasks/parent/run-parent.js", () => ({
readLatestTaskView: vi.fn(),
sendTaskCommandToOwner: vi.fn(),
}));
-describe("delegated task settlement", () => {
+describe("task readiness", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(sendTaskCommandToOwner).mockResolvedValue({ runId: "run-owner" });
});
- it("indexes the resolved command-hook owner before readiness", async () => {
- const session = {
- agent: { modelReference: { id: "model" }, system: "", tools: [] },
- compaction: { recentWindowSize: 4, threshold: 1_000_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- } as RuntimeSession;
- const task: DelegatedTask = {
- taskInboxToken: "task-token",
- createdByTurnId: "turn-parent",
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
- operationId: "operation-1",
- taskId: "task-1",
- taskRunId: "run-candidate",
- };
-
- const result = await settleDelegatedDispatch({
- callId: "call-task",
- session,
- subagentName: "research",
- task,
- });
-
- expect(sendTaskCommandToOwner).not.toHaveBeenCalled();
- expect(getSessionTaskIndex(result.session.state)[0]).toMatchObject({
- taskId: "task-1",
- taskRunId: "run-candidate",
+ it("acknowledges a generic background task after indexing", async () => {
+ await acknowledgeDelegatedTasksStep({
+ tasks: [{ taskId: "task-1", taskInboxToken: "task-token", taskRunId: "run-1" }],
});
-
- await acknowledgeDelegatedTasksStep({ tasks: [task] });
expect(sendTaskCommandToOwner).toHaveBeenCalledWith(
- expect.objectContaining({ command: { kind: "ready" } }),
+ expect.objectContaining({ command: { kind: "ready" }, taskInboxToken: "task-token" }),
);
});
});
diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.ts
index 154aa2f68..df74fd321 100644
--- a/packages/eve/src/execution/tasks/parent/delegate.ts
+++ b/packages/eve/src/execution/tasks/parent/delegate.ts
@@ -1,12 +1,9 @@
/**
- * Delegation policy for the subagent dispatch path: derives task identity,
- * builds metadata and the parked-tool-call receipt, records the session
- * index, and defines failure semantics for an unacknowledged dispatch.
+ * Generic task creation, readiness acknowledgement, and dispatch rejection.
* Task-run transport (start/command/view) lives in `run-parent.ts`, which
- * this module composes and which other non-delegation callers share.
+ * Callers compose these primitives around their own executor policy.
*/
-import type { ActivityObserverConfig } from "#channel/types.js";
-import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import type { HarnessSession } from "#harness/types.js";
import {
readLatestTaskView,
sendTaskCommand,
@@ -15,18 +12,10 @@ import {
waitForTaskCommandOwner,
} from "#execution/tasks/parent/run-parent.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import type { JsonValue } from "#shared/json.js";
import type { TaskExecutorBinding } from "#tools/task.js";
-import { recordSessionTask } from "#tasks/session-index.js";
import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";
-import {
- createSubagentTaskMetadata,
- isTerminalTaskStatus,
- readSubagentTaskMetadata,
- type DurableTaskMetadata,
-} from "#tasks/types.js";
+import { isTerminalTaskStatus, type TaskMetadata } from "#tasks/types.js";
/** A prepared background task: identity plus its started durable run. */
export interface BackgroundTask {
@@ -34,144 +23,56 @@ export interface BackgroundTask {
readonly createdByStepIndex?: number;
readonly createdByTurnId: string;
readonly executor?: TaskExecutorBinding;
- readonly metadata: DurableTaskMetadata;
+ readonly metadata: TaskMetadata;
readonly taskId: string;
readonly taskRunId: string;
}
-/** A subagent task also carries its deterministic agent-handle operation. */
-export interface DelegatedTask extends BackgroundTask {
- readonly operationId: string;
-}
+type BackgroundTaskDraft = Omit<BackgroundTask, "taskRunId">;
-/**
- * Creates the durable task record for one delegated subagent call,
- * before the child dispatch side effect. The task must exist first so
- * a fast child always finds a live command hook; a duplicate replay
- * re-derives the same token and the loser exits on the hook claim.
- */
-export async function beginDelegatedTask(input: {
- readonly activityObserver?: ActivityObserverConfig;
- readonly agentId: string;
+/** Derives the replay-stable task identity before its owning run is started. */
+export function prepareBackgroundTask(input: {
readonly callId: string;
- readonly mode: "local" | "remote";
- readonly name: string;
+ readonly metadata: TaskMetadata;
readonly parentSessionId: string;
readonly parentStepIndex?: number;
readonly parentTurnId: string;
- readonly session: RuntimeSession;
-}): Promise<DelegatedTask> {
- const task = await beginBackgroundTask({
- activityObserver: input.activityObserver,
+ readonly session: HarnessSession;
+}): BackgroundTaskDraft {
+ const taskId = deriveTaskId({
callId: input.callId,
- metadata: createSubagentTaskMetadata({
- agentId: input.agentId,
- mode: input.mode,
- name: input.name,
- }),
parentSessionId: input.parentSessionId,
- parentStepIndex: input.parentStepIndex,
parentTurnId: input.parentTurnId,
- session: input.session,
});
return {
- ...task,
- operationId: deriveAgentOperationId({
- callId: input.callId,
- parentSessionId: input.parentSessionId,
- parentTurnId: input.parentTurnId,
+ taskInboxToken: deriveTaskInboxToken({
+ parentContinuationToken: input.session.continuationToken,
+ taskId,
}),
+ createdByStepIndex: input.parentStepIndex ?? 0,
+ createdByTurnId: input.parentTurnId,
+ metadata: input.metadata,
+ taskId,
};
}
-/** Creates a replay-stable task run before a background tool starts external work. */
+/** Starts a lifecycle-only task run for a non-workflow external executor. */
export async function beginBackgroundTask(input: {
- readonly activityObserver?: ActivityObserverConfig;
readonly callId: string;
- readonly metadata: DurableTaskMetadata;
+ readonly metadata: TaskMetadata;
readonly parentSessionId: string;
readonly parentStepIndex?: number;
readonly parentTurnId: string;
- readonly session: RuntimeSession;
+ readonly session: HarnessSession;
}): Promise<BackgroundTask> {
- const taskId = deriveTaskId({
- callId: input.callId,
- parentSessionId: input.parentSessionId,
- parentTurnId: input.parentTurnId,
- });
- const taskInboxToken = deriveTaskInboxToken({
- parentContinuationToken: input.session.continuationToken,
- taskId,
- });
+ const task = prepareBackgroundTask(input);
await startTaskRun({
- activityObserver: input.activityObserver,
- taskInboxToken,
- initialView: {
- metadata: input.metadata,
- status: "working",
- taskId,
- },
+ taskInboxToken: task.taskInboxToken,
+ initialView: { metadata: task.metadata, status: "working", taskId: task.taskId },
parentContinuationToken: sessionCommandHookToken(input.session.sessionId),
});
- const owner = await waitForTaskCommandOwner({ taskInboxToken });
- return {
- taskInboxToken,
- createdByStepIndex: input.parentStepIndex ?? 0,
- createdByTurnId: input.parentTurnId,
- metadata: input.metadata,
- taskId,
- taskRunId: owner.runId,
- };
-}
-
-/**
- * Settles a delegated dispatch that acknowledged a child: persists the task
- * in the session index and returns the receipt that resolves the originating
- * tool call. Agent identity and routing remain in the persistent address
- * record; task state owns execution availability.
- */
-export async function settleDelegatedDispatch(input: {
- readonly callId: string;
- readonly session: RuntimeSession;
- readonly subagentName: string;
- readonly task: DelegatedTask;
-}): Promise<{ readonly receipt: RuntimeSubagentChildResult; readonly session: RuntimeSession }> {
- const metadata = readSubagentTaskMetadata(input.task);
- if (metadata === undefined) {
- throw new Error(`Task "${input.task.taskId}" is not a subagent task.`);
- }
- const receiptOutput = {
- agentId: metadata.agentId,
- status: "working" as const,
- taskId: input.task.taskId,
- };
- return {
- receipt: {
- backgroundTask: { status: receiptOutput.status, taskId: receiptOutput.taskId },
- callId: input.callId,
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "parked",
- result: {
- kind: "succeeded",
- output: `Delegated as background task ${input.task.taskId} (working).`,
- },
- usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 },
- },
- output: receiptOutput,
- subagentName: input.subagentName,
- },
- session: recordSessionTask(input.session, {
- taskInboxToken: input.task.taskInboxToken,
- createdByStepIndex: input.task.createdByStepIndex,
- createdByTurnId: input.task.createdByTurnId,
- metadata: input.task.metadata,
- operationId: input.task.operationId,
- taskId: input.task.taskId,
- taskRunId: input.task.taskRunId,
- }),
- };
+ const owner = await waitForTaskCommandOwner({ taskInboxToken: task.taskInboxToken });
+ return { ...task, taskRunId: owner.runId };
}
/** Releases task events only after the parent session index committed. */
@@ -197,18 +98,6 @@ export async function acknowledgeDelegatedTasksStep(input: {
}
}
-/** Fails an indexed task whose child dispatch was definitively rejected. */
-export async function failDelegatedDispatch(input: {
- readonly error: JsonValue;
- readonly task: DelegatedTask;
-}): Promise<void> {
- await sendTaskCommand({
- command: { data: input.error, kind: "fail" },
- taskInboxToken: input.task.taskInboxToken,
- retryUnreachable: { attempts: 20, delayMs: 250 },
- });
-}
-
/** Silently terminates a task whose child dispatch failed before parent indexing. */
export async function rejectDelegatedDispatch(input: {
readonly error: JsonValue;
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
deleted file mode 100644
index 425a2f95f..000000000
--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-/**
- * Task-mode sibling of `dispatchRuntimeActionsStep`, selected by the turn
- * workflow when the agent enables `experimental.tasks`.
- *
- * Same plan → dispatch → emit skeleton, but every delegation is wrapped in
- * the durable task lifecycle: the task record and its inbox token
- * exist *before* the child dispatch side effect (`beginDelegatedTask`),
- * continuations pass the availability check and enter the parent session's
- * task index first, and the task settles against the dispatch outcome.
- * Children report through their task's inbox token rather than the
- * parent turn inbox, and every start dispatches a conversation-mode
- * (persistent) child so the background task stays resumable.
- *
- * Task-control calls (`task_cancel` / `task_update`) execute
- * inline in this step, which holds the session ownership index and world
- * access they need.
- */
-
-import {
- type DispatchOutcome,
- dispatchToTaskAgentAddress,
-} from "#execution/agent-handle-dispatch.js";
-import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";
-import {
- emitSubagentCalled,
- prepareRuntimeActionDispatch,
- type RuntimeActionDispatchInput,
- type RuntimeActionDispatchResult,
-} from "#execution/dispatch-runtime-actions-shared.js";
-import { startSubagent } from "#execution/dispatch-runtime-actions-start.js";
-import { startWorkflowTool } from "#execution/tool-run/dispatch.js";
-import { createDurableSessionState } from "#execution/durable-session-store.js";
-import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
-import {
- beginDelegatedTask,
- type DelegatedTask,
- settleDelegatedDispatch,
-} from "#execution/tasks/parent/delegate.js";
-import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
-import {
- checkTaskContinuationAvailability,
- describeTaskDispatch,
- persistContinuationTaskInParentSession,
- settleTaskDispatchError,
- type PersistedContinuationTask,
-} from "#execution/tasks/parent/continuation-dispatch.js";
-import type { RuntimeActionResult } from "#shared/action-types.js";
-
-export async function dispatchTaskStep(
- input: RuntimeActionDispatchInput,
-): Promise<RuntimeActionDispatchResult> {
- "use step";
-
- const prepared = await prepareRuntimeActionDispatch({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- taskControls: true,
- });
- if (prepared === undefined) {
- return { results: [], sessionState: input.sessionState, pendingTasks: [] };
- }
-
- const { batch, bundle, session } = prepared;
- // Acquired only once preflight can no longer throw, so a planning failure
- // never leaks the writer lock.
- const writer = input.parentWritable.getWriter();
-
- let nextSession = session;
- const results: RuntimeActionResult[] = [];
- const pendingTasks: DelegatedTask[] = [];
-
- try {
- for (const entry of prepared.plan) {
- if (entry.kind === "reject") {
- results.push(entry.result);
- continue;
- }
- if (entry.kind === "workflow-tool") {
- const started = await startWorkflowTool({
- action: entry.action,
- batchEvent: batch.event,
- ownerInboxToken: input.parentContinuationToken,
- prepared,
- session: nextSession,
- });
- nextSession = started.session;
- if (started.result !== undefined) results.push(started.result);
- continue;
- }
-
- if (entry.kind === "task-control") {
- const control = await executeTaskControlAction({
- action: entry.action,
- adapter: prepared.adapter,
- bundle,
- parentStepIndex: batch.event.stepIndex,
- parentTurnId: batch.event.turnId,
- serializedContext: prepared.serializedContext,
- session: nextSession,
- });
- nextSession = control.session;
- if (control.pendingTask !== undefined) pendingTasks.push(control.pendingTask);
- results.push(control.result);
- continue;
- }
-
- if (entry.kind === "resume") {
- const busy = await checkTaskContinuationAvailability({
- action: entry.action,
- agentId: entry.agentId,
- parentStepIndex: batch.event.stepIndex,
- parentTurnId: batch.event.turnId,
- session: nextSession,
- });
- if (busy !== undefined) {
- results.push(busy);
- continue;
- }
- }
-
- const action = entry.kind === "resume" ? entry.action : entry.target.action;
- const delegated = await beginDelegatedTask({
- ...describeTaskDispatch({
- action,
- agentId: entry.kind === "resume" ? entry.agentId : undefined,
- parentSessionId: session.sessionId,
- parentTurnId: batch.event.turnId,
- session: nextSession,
- }),
- activityObserver:
- prepared.activityObserver === undefined
- ? undefined
- : deriveChildActivityObserverConfig({
- activityObserver: prepared.activityObserver,
- callId: action.callId,
- kind: "task",
- name: entry.kind === "resume" ? entry.action.name : entry.target.action.name,
- parentSessionId: session.sessionId,
- parentTurnId: batch.event.turnId,
- }),
- parentSessionId: session.sessionId,
- parentStepIndex: batch.event.stepIndex,
- parentTurnId: batch.event.turnId,
- session: nextSession,
- });
- let persistedContinuation: PersistedContinuationTask | undefined;
- if (entry.kind === "resume") {
- persistedContinuation = await persistContinuationTaskInParentSession({
- action: entry.action,
- agentId: entry.agentId,
- delegated,
- session: nextSession,
- });
- nextSession = persistedContinuation?.session ?? nextSession;
- }
-
- let outcome: DispatchOutcome;
- switch (entry.kind) {
- case "resume":
- outcome = await dispatchToTaskAgentAddress({
- action: entry.action,
- activityObserver:
- prepared.activityObserver === undefined
- ? undefined
- : deriveChildActivityObserverConfig({
- activityObserver: prepared.activityObserver,
- callId: entry.action.callId,
- kind: "task",
- name: entry.action.name,
- parentSessionId: session.sessionId,
- parentTurnId: batch.event.turnId,
- }),
- agentId: entry.agentId,
- auth: prepared.auth,
- bundle: createAgentContinuationBundle({
- action: entry.action,
- bundle,
- dynamicRemoteAgent: entry.dynamicRemoteAgent,
- }),
- currentSession: nextSession,
- parentToken: delegated.taskInboxToken,
- });
- break;
- case "start":
- outcome = await startSubagent({
- auth: prepared.auth,
- batchEvent: batch.event,
- bundle,
- callbackBaseUrl: input.callbackBaseUrl,
- capabilities: prepared.capabilities,
- channelMetadata: prepared.channelMetadata,
- currentSession: nextSession,
- fanoutSize: prepared.fanoutSize,
- initiatorAuth: prepared.initiatorAuth,
- localDevRequest: prepared.localDevRequest,
- parentContinuationToken: delegated.taskInboxToken,
- parentTraceContext: prepared.parentTraceContext,
- activityObserver: prepared.activityObserver,
- sandboxSessionId: prepared.sandboxSessionId,
- serializedContext: prepared.serializedContext,
- session,
- taskOwned: true,
- target: entry.target,
- });
- break;
- }
-
- nextSession = outcome.session;
- if (outcome.kind === "error") {
- results.push(
- await settleTaskDispatchError({
- delegated,
- outcome,
- persisted: persistedContinuation,
- }),
- );
- if (persistedContinuation !== undefined) pendingTasks.push(delegated);
- continue;
- }
-
- if (persistedContinuation !== undefined) {
- results.push(persistedContinuation.receipt);
- } else {
- const settled = await settleDelegatedDispatch({
- callId: outcome.callId,
- session: nextSession,
- subagentName: outcome.toolName,
- task: delegated,
- });
- nextSession = settled.session;
- results.push(settled.receipt);
- }
- pendingTasks.push(delegated);
-
- await emitSubagentCalled({
- adapter: prepared.adapter,
- adapterCtx: prepared.adapterCtx,
- batchEvent: batch.event,
- entry,
- outcome,
- sessionId: session.sessionId,
- writer,
- });
- }
- } finally {
- writer.releaseLock();
- }
-
- return {
- results,
- sessionState:
- nextSession === session
- ? prepared.getBaselineSessionState()
- : createDurableSessionState({ session: nextSession }),
- pendingTasks,
- };
-}
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
index a5e28056b..e3c50c84e 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
@@ -1,441 +1,170 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import { deserializeContext } from "#context/serialize.js";
-import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
-import {
- cancelRemoteAgentTurn,
- resolveRemoteAgentForAction,
- resolveRemoteAgentStreamHeaders,
-} from "#execution/remote-agent-dispatch.js";
-import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+import { cancelOwnedTask, executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
import { readLatestTaskView, sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
-import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
-import type { PendingTaskControlAction } from "#shared/dispatch-action.js";
-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
-import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";
+import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";
+
+const { cancelRun, getRun } = vi.hoisted(() => ({
+ cancelRun: vi.fn(),
+ getRun: vi.fn(),
+}));
vi.mock("#execution/tasks/parent/run-parent.js", () => ({
readLatestTaskView: vi.fn(),
sendTaskCommand: vi.fn(),
}));
-vi.mock("#context/serialize.js", () => ({ deserializeContext: vi.fn() }));
-vi.mock("#context/dynamic-subagent-lifecycle.js", () => ({
- getDynamicSubagentSelection: vi.fn(),
-}));
-vi.mock("#execution/workflow-runtime.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/workflow-runtime.js")>()),
- requestWorkflowTurnCancellation: vi.fn(),
-}));
-vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/remote-agent-dispatch.js")>()),
- cancelRemoteAgentTurn: vi.fn(),
- resolveRemoteAgentForAction: vi.fn(),
- resolveRemoteAgentStreamHeaders: vi.fn(),
+vi.mock("#execution/tools/workflow/cancel.js", () => ({ cancelWorkflowToolRun: vi.fn() }));
+vi.mock("#internal/workflow/runtime.js", () => ({
+ cancelRun,
+ getRun,
+ getWorld: vi.fn(() => ({})),
}));
-const action: PendingTaskControlAction = {
- callId: "call-cancel",
- description: "Cancel tasks.",
- input: { taskIds: ["task-1"] },
- target: { kind: "task-cancel" },
- toolName: "task_cancel",
-};
+const entry = {
+ createdByTurnId: "turn-1",
+ executor: { data: { hookToken: "run-hook", runId: "run-1" }, kind: "workflow-tool" },
+ metadata: { kind: "tool", name: "export" },
+ taskId: "task-1",
+ taskInboxToken: "task-token",
+ taskRunId: "task-run",
+} as const;
-function createSession(mode: "local" | "remote"): RuntimeSession {
- const address =
- mode === "local"
- ? { continuationToken: "child-token", kind: "agent/local" as const, sessionId: "child-1" }
- : {
- callbackBaseUrl: "https://parent.example",
- kind: "agent/remote" as const,
- sessionId: "child-1",
- url: "https://child.example",
- };
- return {
- agent: { modelReference: { id: "model" }, system: "", tools: [] },
- compaction: { recentWindowSize: 4, threshold: 1_000_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- state: {
- [AGENT_HANDLES_STATE_KEY]: {
- handles: [
- {
- address,
- identity: { id: "agent-1", name: "research", nodeId: "node-1" },
- phase: "addressed",
- },
- ],
- },
- [SESSION_TASKS_STATE_KEY]: {
- tasks: [
- {
- taskInboxToken: "task-token",
- createdByTurnId: "turn-1",
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode,
- name: "research",
- },
- operationId: "operation-1",
- taskId: "task-1",
- taskRunId: "run-1",
- },
- ],
- },
- },
- } as RuntimeSession;
-}
-
-describe("task cancellation identity", () => {
+describe("task cancellation", () => {
beforeEach(() => {
vi.resetAllMocks();
+ vi.useFakeTimers();
vi.mocked(sendTaskCommand).mockResolvedValue("delivered");
- vi.mocked(readLatestTaskView).mockResolvedValue({
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
- executor: { childSessionId: "child-1", childTurnId: "turn_child_7" },
- status: "cancelled",
- taskId: "task-1",
- });
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue({ name: "research" } as never);
- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({
- sessionId: "child-1",
- status: "accepted",
- });
- vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({
- sessionId: "child-1",
- status: "accepted",
- });
- vi.mocked(resolveRemoteAgentStreamHeaders).mockResolvedValue({ authorization: "Bearer fresh" });
- vi.mocked(deserializeContext).mockResolvedValue("context" as never);
- vi.mocked(getDynamicSubagentSelection).mockReturnValue(undefined);
+ getRun.mockReturnValue({ status: Promise.resolve("completed") });
});
- it.each(["local", "remote"] as const)(
- "guards %s cancellation with the task's child turn",
- async (mode) => {
- const result = await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- session: createSession(mode),
- });
-
- if (mode === "local") {
- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
- sessionId: "child-1",
- taskId: "task-1",
- turnId: "turn_child_7",
- });
- expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
- } else {
- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "child-1",
- taskId: "task-1",
- turnId: "turn_child_7",
- }),
- );
- expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
- }
- expect(result.result).toMatchObject({ output: { tasks: [{ status: "cancelled" }] } });
- expect(result.session.state?.[AGENT_HANDLES_STATE_KEY]).toMatchObject({
- handles: [{ phase: "addressed" }],
- });
- },
- );
+ afterEach(() => {
+ vi.useRealTimers();
+ });
- it("cancels a dynamic remote task with its creation-time credential resolver", async () => {
- const session = createSession("remote");
- const handleStore = session.state?.[AGENT_HANDLES_STATE_KEY] as {
- handles: Array<{ address: { credentialResolver?: { resolverId?: string } } }>;
- };
- handleStore.handles[0]!.address.credentialResolver = {
- resolverId: "dynamic-credentials-step",
- };
+ it("cancels task-owned work after cancellation commits", async () => {
vi.mocked(readLatestTaskView).mockResolvedValue({
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "remote",
- name: "research",
- },
- executor: {
- binding: {
- data: {
- address: handleStore.handles[0]!.address,
- identity: { id: "agent-1", name: "research", nodeId: "node-1" },
- },
- kind: "subagent",
- },
- childSessionId: "child-1",
- childTurnId: "turn_child_7",
- },
+ executor: { binding: entry.executor },
+ metadata: entry.metadata,
status: "cancelled",
- taskId: "task-1",
- });
-
- await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- session,
- });
-
- expect(resolveRemoteAgentForAction).not.toHaveBeenCalled();
- expect(resolveRemoteAgentStreamHeaders).toHaveBeenCalledWith({
- bundle: expect.any(Object),
- name: "research",
- resolverId: "dynamic-credentials-step",
- url: "https://child.example",
- });
- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- headers: { authorization: "Bearer fresh" },
- remote: { name: "research", url: "https://child.example" },
- sessionId: "child-1",
- turnId: "turn_child_7",
- }),
+ taskId: entry.taskId,
+ });
+ const cancelled = cancelOwnedTask({ entry });
+ await vi.runAllTimersAsync();
+ await cancelled;
+ expect(sendTaskCommand).toHaveBeenNthCalledWith(1, {
+ command: { kind: "cancel" },
+ taskInboxToken: "task-token",
+ });
+ expect(cancelWorkflowToolRun).toHaveBeenCalledWith(
+ { hookToken: "run-hook", runId: "run-1" },
+ "Task task-1 was cancelled.",
);
+ expect(cancelRun).not.toHaveBeenCalled();
});
- it("does not resolve authored credentials when creation recorded none", async () => {
- const session = createSession("remote");
- const address = (
- session.state?.[AGENT_HANDLES_STATE_KEY] as {
- handles: Array<{ address: { credentialResolver?: { resolverId?: string } } }>;
- }
- ).handles[0]!.address;
- address.credentialResolver = {};
+ it("does not reinterpret an unknown executor binding", async () => {
+ const external = { data: { id: "external" }, kind: "external" };
vi.mocked(readLatestTaskView).mockResolvedValue({
- metadata: { agentId: "agent-1", kind: "subagent", mode: "remote", name: "research" },
- executor: {
- binding: {
- data: {
- address,
- identity: { id: "agent-1", name: "research", nodeId: "node-1" },
- },
- kind: "subagent",
- },
- childSessionId: "child-1",
- childTurnId: "turn_child_7",
- },
+ executor: { binding: external },
+ metadata: entry.metadata,
status: "cancelled",
- taskId: "task-1",
+ taskId: entry.taskId,
});
-
- await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- session,
- });
-
- expect(resolveRemoteAgentForAction).not.toHaveBeenCalled();
- expect(resolveRemoteAgentStreamHeaders).not.toHaveBeenCalled();
- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- headers: {},
- remote: { name: "research", url: "https://child.example" },
- }),
- );
+ const cancelled = cancelOwnedTask({ entry: { ...entry, executor: external } });
+ await vi.runAllTimersAsync();
+ await cancelled;
+ expect(cancelWorkflowToolRun).not.toHaveBeenCalled();
});
- it("recovers the current dynamic selection for a legacy remote binding", async () => {
- const dynamicRemoteAgent = {
- credentialsStepId: "legacy-dynamic-step",
- description: "Remote research",
- path: "/eve/v1/session",
- url: "https://child.example",
- };
- vi.mocked(getDynamicSubagentSelection).mockReturnValue({
- kind: "remote",
- prepared: {} as never,
- remoteAgent: dynamicRemoteAgent,
- });
-
- await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- serializedContext: { context: "serialized" },
- session: createSession("remote"),
+ it("hard-cancels a task run that does not unwind cooperatively", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: entry.metadata,
+ status: "cancelled",
+ taskId: entry.taskId,
});
+ getRun.mockReturnValue({ status: Promise.resolve("running") });
- expect(deserializeContext).toHaveBeenCalledWith({ context: "serialized" });
- expect(resolveRemoteAgentForAction).toHaveBeenCalledWith(
- expect.objectContaining({ dynamicRemoteAgent }),
- );
- });
-
- it("does not send current credentials to a legacy child's previous URL", async () => {
- vi.mocked(getDynamicSubagentSelection).mockReturnValue({
- kind: "remote",
- prepared: {} as never,
- remoteAgent: {
- credentialsStepId: "new-dynamic-step",
- description: "Remote research",
- path: "/eve/v1/session",
- url: "https://new-child.example",
- },
- });
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue({
- name: "research",
- url: "https://new-child.example",
- } as never);
+ const cancelled = cancelOwnedTask({ entry });
+ await vi.runAllTimersAsync();
+ await cancelled;
- await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- serializedContext: { context: "serialized" },
- session: createSession("remote"),
+ expect(cancelRun).toHaveBeenCalledWith({}, "task-run", {
+ cancelReason: "Task task-1 was cancelled.",
});
-
- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(
- expect.objectContaining({
- headers: {},
- remote: { name: "research", url: "https://child.example" },
- }),
- );
- expect(resolveRemoteAgentStreamHeaders).not.toHaveBeenCalled();
});
+});
+
+describe("task updates", () => {
+ beforeEach(() => vi.resetAllMocks());
- it("uses fresh current credentials when a legacy child's URL still matches", async () => {
- const auth = vi.fn();
- const headers = vi.fn();
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue({
- auth,
- headers,
- name: "research",
- url: "https://child.example",
- } as never);
+ it("forwards a task-owned update and confirms delivery", async () => {
+ const deliverUpdate = vi.fn(async () => "task-1");
- await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- session: createSession("remote"),
+ const result = await executeTaskControlAction({
+ deliverUpdate,
+ action: {
+ callId: "call-update",
+ input: { message: "Working" },
+ kind: "tool-call",
+ toolName: "task_update",
+ },
+ bundle: {} as never,
+ parentStepIndex: 2,
+ parentTurnId: "turn-child",
+ serializedContext: { "eve.sessionCallback": { taskId: "task-1" } },
+ session: {} as never,
});
- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(
+ expect(deliverUpdate).toHaveBeenCalledWith(
expect.objectContaining({
- remote: expect.objectContaining({
- auth,
- headers,
- name: "research",
- url: "https://child.example",
+ update: expect.objectContaining({
+ message: "Working",
+ updateEpoch: "turn-child",
+ updateIndex: 2,
}),
}),
);
- expect(vi.mocked(cancelRemoteAgentTurn).mock.calls[0]?.[0]).not.toHaveProperty("headers");
+ expect(result.result).toMatchObject({ output: { status: "sent", taskId: "task-1" } });
});
- it("preserves resolved headers when retrying an unguarded remote cancel", async () => {
- vi.mocked(cancelRemoteAgentTurn)
- .mockResolvedValueOnce({ status: "no_active_turn" })
- .mockResolvedValueOnce({ sessionId: "child-1", status: "accepted" });
- const session = createSession("remote");
- const address = (
- session.state?.[AGENT_HANDLES_STATE_KEY] as {
- handles: Array<{ address: { credentialResolver?: { resolverId?: string } } }>;
- }
- ).handles[0]!.address;
- address.credentialResolver = { resolverId: "dynamic-credentials-step" };
- vi.mocked(readLatestTaskView).mockResolvedValue({
- metadata: { agentId: "agent-1", kind: "subagent", mode: "remote", name: "research" },
- executor: {
- binding: {
- data: {
- address,
- identity: { id: "agent-1", name: "research", nodeId: "node-1" },
- },
- kind: "subagent",
+ it("forwards a local task-owned child update through the subagent adapter hook", async () => {
+ const deliverUpdate = vi.fn(async () => "task-1");
+ const result = await executeTaskControlAction({
+ deliverUpdate,
+ action: {
+ callId: "call-update",
+ input: { message: "Working" },
+ kind: "tool-call",
+ toolName: "task_update",
+ },
+ adapter: {
+ kind: "subagent",
+ state: {
+ callId: "call-agent",
+ parentContinuationToken: "agent-reply-hook",
+ parentSessionId: "session-parent",
+ subagentName: "worker",
+ taskId: "task-1",
},
- childSessionId: "child-1",
- childTurnId: "turn_child_7",
},
- status: "cancelled",
- taskId: "task-1",
- });
-
- await executeTaskControlAction({
- action,
- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,
- parentTurnId: "turn-parent",
- session,
- });
-
- expect(cancelRemoteAgentTurn).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({ headers: { authorization: "Bearer fresh" } }),
- );
- expect(vi.mocked(cancelRemoteAgentTurn).mock.calls[1]?.[0]).not.toHaveProperty("turnId");
- });
-
- it("uses task-scoped cancellation before child-turn identity arrives", async () => {
- vi.mocked(readLatestTaskView).mockResolvedValue({
- metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },
- status: "cancelled",
- taskId: "task-1",
- });
-
- await executeTaskControlAction({
- action,
- bundle: {} as CompiledBundle,
- parentTurnId: "turn-parent",
- session: createSession("local"),
- });
-
- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
- sessionId: "child-1",
- taskId: "task-1",
- });
- expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
- });
-
- it("does not propagate a repeated cancel after the task hook is disposed", async () => {
- vi.mocked(sendTaskCommand).mockResolvedValue("unreachable");
-
- await executeTaskControlAction({
- action,
- bundle: {} as CompiledBundle,
- parentTurnId: "turn-parent",
- session: createSession("local"),
- });
-
- expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
- expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
- });
-
- it("fails instead of reporting success when cancellation does not commit", async () => {
- vi.useFakeTimers();
- vi.mocked(readLatestTaskView).mockResolvedValue({
- metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },
- status: "working",
- taskId: "task-1",
+ bundle: {} as never,
+ parentStepIndex: 2,
+ parentTurnId: "turn-child",
+ serializedContext: {},
+ session: {} as never,
+ });
+
+ expect(deliverUpdate).toHaveBeenCalledWith({
+ adapter: expect.objectContaining({ kind: "subagent" }),
+ callback: undefined,
+ update: {
+ callId: "call-update",
+ kind: "task-update",
+ message: "Working",
+ updateEpoch: "turn-child",
+ updateIndex: 2,
+ },
});
- try {
- const pending = executeTaskControlAction({
- action,
- bundle: {} as CompiledBundle,
- parentTurnId: "turn-parent",
- session: createSession("local"),
- });
- const rejected = expect(pending).rejects.toThrow("did not commit cancellation");
- await vi.runAllTimersAsync();
- await rejected;
- expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
- } finally {
- vi.useRealTimers();
- }
+ expect(result.result).toMatchObject({ output: { status: "sent", taskId: "task-1" } });
});
});
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.ts
index ff1366f04..34809c8cc 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts
@@ -1,62 +1,46 @@
-import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
-import { deserializeContext } from "#context/serialize.js";
-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
-import {
- cancelRemoteAgentTurn,
- resolveRemoteAgentForAction,
- resolveRemoteAgentStreamHeaders,
-} from "#execution/remote-agent-dispatch.js";
+import type { ChannelAdapter } from "#channel/adapter.js";
+import type { HarnessSession as RuntimeSession } from "#harness/types.js";
import {
createTaskControlError,
createTaskViewsResult,
createUnknownTasksError,
- findTaskAgentAddress,
lookupTaskEntries,
readTaskView,
} from "#execution/tasks/parent/control-shared.js";
-import { executeTaskUpdate } from "#execution/tasks/child/update.js";
-import { readWorkflowToolExecutor } from "#execution/tool-run/background.js";
-import { cancelToolRun } from "#execution/tool-run/cancel.js";
-import type { ChannelAdapter } from "#channel/adapter.js";
-import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";
+import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";
import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
-import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import { createLogger, logError } from "#internal/logging.js";
-import type { RuntimeActionResult } from "#shared/action-types.js";
-import type { PendingDispatchAction, PendingTaskControlAction } from "#shared/dispatch-action.js";
-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import {
+ cancelTaskOwnedWork,
+ type TaskExecutorCancel,
+} from "#execution/tasks/parent/task-cancel.js";
+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";
import type { SessionTaskIndexEntry } from "#tasks/session-index.js";
+import { isTerminalTaskStatus, type TaskInboundUpdate, type TaskView } from "#tasks/types.js";
import {
- isTerminalTaskStatus,
- readSubagentExecutor,
- readSubagentTaskMetadata,
- type SubagentExecutorData,
- type TaskView,
-} from "#tasks/types.js";
-
-const log = createLogger("execution.tasks.dispatch");
+ TASK_CANCEL_TOOL_NAME,
+ TASK_TOOL_NAMES,
+ TASK_UPDATE_TOOL_NAME,
+} from "#tools/framework/task-contract.js";
const CANCEL_COMMIT_POLL_ATTEMPTS = 10;
const CANCEL_COMMIT_POLL_DELAY_MS = 250;
-/** True for task-control calls dispatched outside the model loop. */
-export function isTaskControlAction(
- action: PendingDispatchAction,
-): action is PendingTaskControlAction {
- return action.target.kind === "task-cancel" || action.target.kind === "task-update";
+export type DeliverTaskUpdate = (input: {
+ readonly adapter?: ChannelAdapter;
+ readonly callback: unknown;
+ readonly update: TaskInboundUpdate;
+}) => Promise<string | undefined>;
+
+export function isTaskControlAction(action: RuntimeToolCallActionRequest): boolean {
+ return action.kind === "tool-call" && TASK_TOOL_NAMES.has(action.toolName);
}
-/**
- * Executes one task-control call inside the dispatch step, which holds
- * the durable session state (ownership index) and world access the
- * tools need.
- *
- * Returns the current session alongside the action result.
- */
export async function executeTaskControlAction(input: {
- readonly action: PendingTaskControlAction;
+ readonly action: RuntimeToolCallActionRequest;
readonly adapter?: ChannelAdapter;
- readonly bundle: CompiledBundle;
+ readonly bundle: import("#runtime/sessions/runtime-context-keys.js").CompiledBundle;
+ readonly cancelOwnedWork?: TaskExecutorCancel;
+ readonly deliverUpdate?: DeliverTaskUpdate;
readonly parentStepIndex?: number;
readonly parentTurnId: string;
readonly serializedContext?: Record<string, unknown>;
@@ -64,23 +48,42 @@ export async function executeTaskControlAction(input: {
}): Promise<{
readonly result: RuntimeActionResult;
readonly session: RuntimeSession;
- readonly pendingTask?: DelegatedTask;
+ readonly pendingTask?: BackgroundTask;
}> {
const { action, session } = input;
-
- if (action.target.kind === "task-update") {
+ if (action.toolName === TASK_UPDATE_TOOL_NAME) {
+ const message = action.input.message;
+ if (typeof message !== "string" || message.trim() === "") {
+ return {
+ result: createTaskControlError(action, "Provide a non-empty `message`."),
+ session,
+ };
+ }
+ const update = {
+ callId: action.callId,
+ kind: "task-update",
+ message,
+ updateEpoch: input.parentTurnId,
+ updateIndex: input.parentStepIndex ?? 0,
+ } satisfies TaskInboundUpdate;
+ const taskId = await input.deliverUpdate?.({
+ adapter: input.adapter,
+ callback: input.serializedContext?.["eve.sessionCallback"],
+ update,
+ });
return {
- result: await executeTaskUpdate({
- action,
- adapter: input.adapter,
- updateIndex: input.parentStepIndex ?? 0,
- updateEpoch: input.parentTurnId,
- serializedContext: input.serializedContext,
- }),
+ result:
+ taskId === undefined
+ ? createTaskControlError(action, "task_update requires a task-owned session.")
+ : {
+ callId: action.callId,
+ kind: "tool-result",
+ output: { status: "sent", taskId },
+ toolName: action.toolName,
+ },
session,
};
}
-
const taskIds = readTaskIds(action.input);
if (taskIds === undefined || taskIds.length === 0) {
return {
@@ -88,18 +91,22 @@ export async function executeTaskControlAction(input: {
session,
};
}
-
const lookup = lookupTaskEntries(session, taskIds);
if (lookup.kind === "unknown") {
return { result: createUnknownTasksError(action, lookup.unknown), session };
}
- const entries = lookup.entries;
+ if (action.toolName !== TASK_CANCEL_TOOL_NAME) {
+ return {
+ result: createTaskControlError(action, `Unsupported task control "${action.toolName}".`),
+ session,
+ };
+ }
const views: TaskView[] = [];
- for (const entry of entries) {
+ for (const entry of lookup.entries) {
views.push(
await cancelOwnedTask({
- bundle: input.bundle,
+ cancelOwnedWork: input.cancelOwnedWork,
entry,
serializedContext: input.serializedContext,
session,
@@ -109,200 +116,38 @@ export async function executeTaskControlAction(input: {
return { result: createTaskViewsResult(action, views), session };
}
-/** Commits task cancellation, then propagates it to the addressed executor. */
+/** Commits cancellation, then stops task-owned child work and its lifecycle run. */
export async function cancelOwnedTask(input: {
- readonly bundle: CompiledBundle;
+ readonly cancelOwnedWork?: TaskExecutorCancel;
readonly entry: SessionTaskIndexEntry;
readonly serializedContext?: Record<string, unknown>;
- readonly session: RuntimeSession;
+ readonly session?: RuntimeSession;
}): Promise<TaskView> {
- const { entry } = input;
const delivery = await sendTaskCommand({
command: { kind: "cancel" },
- taskInboxToken: entry.taskInboxToken,
+ taskInboxToken: input.entry.taskInboxToken,
});
-
- // The `cancelled` state must commit before the executor abort
- // propagates, so a late child result can never revive the task.
- let view = await readTaskView(entry);
+ let view = await readTaskView(input.entry);
for (
let attempt = 0;
attempt < CANCEL_COMMIT_POLL_ATTEMPTS && !isTerminalTaskStatus(view.status);
attempt += 1
) {
await new Promise((resolve) => setTimeout(resolve, CANCEL_COMMIT_POLL_DELAY_MS));
- view = await readTaskView(entry);
+ view = await readTaskView(input.entry);
}
if (!isTerminalTaskStatus(view.status)) {
- throw new Error(`Task "${entry.taskId}" did not commit cancellation before timeout.`);
+ throw new Error(`Task "${input.entry.taskId}" did not commit cancellation before timeout.`);
}
- const settledView = view;
+ if (view.status !== "cancelled" || delivery !== "delivered") return view;
- if (settledView.status === "cancelled" && delivery === "delivered") {
- await propagateTaskCancel({
- bundle: input.bundle,
- serializedContext: input.serializedContext,
- entry,
- session: input.session,
- view: settledView,
- });
- }
- return settledView;
-}
-
-/**
- * Best-effort cooperative abort of the cancelled task's child turn. The
- * child address comes from the task's durable executor binding when one
- * was written at delegation, falling back to the agent handle in session
- * state for tasks delegated before an executor binding existed. A task
- * with neither has nothing left to abort.
- */
-async function propagateTaskCancel(input: {
- readonly bundle: CompiledBundle;
- readonly serializedContext?: Record<string, unknown>;
- readonly entry: SessionTaskIndexEntry;
- readonly session: RuntimeSession;
- readonly view: TaskView;
-}): Promise<void> {
- const toolRun = readWorkflowToolExecutor(input.view.executor?.binding);
- if (toolRun !== undefined) {
- // The run reports its own end only after its cancel grace period; settle
- // the executor now so the task run finishes and releases its hook.
- await cancelToolRun(toolRun, `Task ${input.entry.taskId} was cancelled.`);
- await sendTaskCommand({
- command: { kind: "settle-executor" },
- taskInboxToken: input.entry.taskInboxToken,
- });
- return;
- }
-
- const metadata = readSubagentTaskMetadata(input.view);
- if (metadata === undefined) return;
- const executor =
- readSubagentExecutor(input.view.executor) ??
- findTaskAgentAddress(input.session, metadata.agentId);
- if (executor === undefined) return;
- if (
- input.view.executor?.childSessionId !== undefined &&
- input.view.executor.childSessionId !== executor.address.sessionId
- ) {
- return;
- }
- await propagateSubagentExecutorCancel({
- bundle: input.bundle,
- childTurnId: input.view.executor?.childTurnId,
- executor,
+ await cancelTaskOwnedWork({
+ cancelOwnedWork: input.cancelOwnedWork,
+ entry: input.entry,
serializedContext: input.serializedContext,
- taskId: input.view.taskId,
+ session: input.session,
});
-}
-
-/**
- * Sends the cooperative abort to the child identified by a subagent
- * executor binding. Failures are logged, never thrown: the task is already
- * terminal when this runs, so the worst outcome is a child that runs to
- * completion and has its callback refused.
- */
-export async function propagateSubagentExecutorCancel(input: {
- readonly bundle: CompiledBundle | undefined;
- readonly childTurnId?: string;
- readonly executor: SubagentExecutorData;
- readonly serializedContext?: Record<string, unknown>;
- readonly taskId: string;
-}): Promise<void> {
- const { address, identity } = input.executor;
- const childSessionId = address.sessionId;
- const childTurnId = input.childTurnId;
-
- try {
- if (address.kind === "agent/remote") {
- if (input.bundle === undefined) {
- throw new Error("No compiled bundle is available to resolve the remote agent.");
- }
- const credentialResolver = address.credentialResolver;
- let dynamicRemoteAgent;
- if (credentialResolver === undefined && input.serializedContext !== undefined) {
- const ctx = await deserializeContext(input.serializedContext);
- const selection = getDynamicSubagentSelection(ctx, identity.nodeId);
- dynamicRemoteAgent = selection?.kind === "remote" ? selection.remoteAgent : undefined;
- }
- const resolved =
- credentialResolver === undefined
- ? resolveRemoteAgentForAction({
- dynamicRemoteAgent,
- nodeId: identity.nodeId,
- remoteAgentName: identity.name,
- registry: input.bundle.subagentRegistry.subagentsByNodeId,
- })
- : { name: identity.name, url: address.url };
- const legacyUrlMismatch = credentialResolver === undefined && resolved.url !== address.url;
- const headers = legacyUrlMismatch
- ? {}
- : credentialResolver?.resolverId === undefined
- ? credentialResolver === undefined
- ? undefined
- : {}
- : await resolveRemoteAgentStreamHeaders({
- bundle: input.bundle,
- name: identity.name,
- resolverId: credentialResolver.resolverId,
- url: address.url,
- });
- const remote = legacyUrlMismatch
- ? { name: identity.name, url: address.url }
- : { ...resolved, url: address.url };
- const cancelInput: {
- headers?: Record<string, string>;
- readonly remote: typeof resolved & { readonly url: string };
- readonly sessionId: string;
- readonly taskId: string;
- turnId?: string;
- } = {
- remote,
- sessionId: childSessionId,
- taskId: input.taskId,
- };
- if (headers !== undefined) cancelInput.headers = headers;
- if (childTurnId !== undefined) cancelInput.turnId = childTurnId;
- const result = await cancelRemoteAgentTurn(cancelInput);
- if (result.status === "no_active_turn") {
- const retryInput: {
- headers?: Record<string, string>;
- remote: typeof resolved & { readonly url: string };
- sessionId: string;
- taskId: string;
- } = {
- remote,
- sessionId: childSessionId,
- taskId: input.taskId,
- };
- if (headers !== undefined) retryInput.headers = headers;
- await cancelRemoteAgentTurn(retryInput);
- }
- return;
- }
- const cancelInput: {
- readonly sessionId: string;
- readonly taskId: string;
- turnId?: string;
- } = {
- sessionId: childSessionId,
- taskId: input.taskId,
- };
- if (childTurnId !== undefined) cancelInput.turnId = childTurnId;
- const result = await requestWorkflowTurnCancellation(cancelInput);
- if (result.status === "no_active_turn") {
- await requestWorkflowTurnCancellation({
- sessionId: childSessionId,
- taskId: input.taskId,
- });
- }
- } catch (error) {
- logError(log, "task cancel propagation failed; the child may run to completion", error, {
- childSessionId,
- taskId: input.taskId,
- });
- }
+ return view;
}
function readTaskIds(input: Record<string, unknown>): readonly string[] | undefined {
diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts
new file mode 100644
index 000000000..bf577aae9
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.test.ts
@@ -0,0 +1,229 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { readDurableSession } from "#execution/durable-session-store.js";
+import {
+ recordTerminalTaskViewsStep,
+ recordTaskInputRequestStep,
+} from "#execution/tasks/parent/hitl-proxy-steps.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";
+import { getProxyInputRequests } from "#harness/proxy-input-requests.js";
+import { getSessionTaskIndex } from "#tasks/session-index.js";
+
+vi.mock("#execution/durable-session-store.js", () => ({ readDurableSession: vi.fn() }));
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({ readLatestTaskView: vi.fn() }));
+vi.mock("#shared/input.js", () => ({
+ isInputRequest: vi.fn(
+ (value: unknown) =>
+ typeof value === "object" &&
+ value !== null &&
+ !Array.isArray(value) &&
+ Reflect.get(value, "kind") === "question" &&
+ typeof Reflect.get(value, "requestId") === "string",
+ ),
+}));
+
+const request = {
+ replyTo: "eve:workflow-tool-run-answer:run-1:0",
+ request: {
+ action: { callId: "call-1", input: {}, kind: "tool-call" as const, toolName: "export" },
+ kind: "question" as const,
+ prompt: "Continue?",
+ requestId: "req-1",
+ },
+ sequence: 0,
+ stepIndex: 2,
+ taskId: "task-1",
+ turnId: "turn-1",
+};
+
+const sessionState = {
+ continuationToken: "parent-token",
+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
+ hasProxyInputRequests: false,
+ sessionId: "parent-session",
+ version: 1,
+} as const;
+const remoteReplyTo = "eve:eve:op:0123456789abcdef0123456789abcdef";
+
+describe("recordTaskInputRequestStep", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(readDurableSession).mockResolvedValue({
+ agent: { system: "" },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {
+ "eve.tasks": {
+ tasks: [
+ {
+ createdByTurnId: "turn-1",
+ metadata: { kind: "tool", name: "export" },
+ taskId: "task-1",
+ taskInboxToken: "task-token",
+ taskRunId: "task-run",
+ },
+ ],
+ version: 2,
+ },
+ },
+ });
+ });
+
+ it("records a generic workflow answer route after matching the task view", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ inputRequests: [request.request],
+ metadata: { kind: "tool", name: "export" },
+ status: "input_required",
+ taskId: "task-1",
+ });
+
+ const result = await recordTaskInputRequestStep({ request, sessionState });
+
+ expect(result).toMatchObject({
+ accepted: true,
+ request: { request: { requestId: "task-1:req-1" } },
+ sessionState: { hasProxyInputRequests: true },
+ });
+ expect(
+ getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:req-1"),
+ ).toEqual({
+ childContinuationToken: request.replyTo,
+ childRequestId: "req-1",
+ kind: "question",
+ taskId: "task-1",
+ });
+ });
+
+ it("rejects a request that does not match the task's outstanding batch", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ inputRequests: [{ ...request.request, requestId: "other" }],
+ metadata: { kind: "tool", name: "export" },
+ status: "input_required",
+ taskId: "task-1",
+ });
+
+ await expect(recordTaskInputRequestStep({ request, sessionState })).resolves.toEqual({
+ accepted: false,
+ sessionState,
+ });
+ });
+
+ it("records a narrowed remote response route for a claimed remote child", async () => {
+ vi.mocked(readDurableSession).mockResolvedValue({
+ agent: { system: "" },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: setAgentHandleStore(
+ {
+ "eve.tasks": {
+ tasks: [
+ {
+ createdByTurnId: "turn-1",
+ metadata: { kind: "tool", name: "export" },
+ taskId: "task-1",
+ taskInboxToken: "task-token",
+ taskRunId: "task-run",
+ },
+ ],
+ version: 2,
+ },
+ },
+ {
+ handles: [
+ {
+ address: {
+ callbackBaseUrl: "https://parent.example",
+ kind: "agent/remote",
+ sessionId: "remote-session",
+ url: "https://remote.example",
+ },
+ identity: { id: "agent-1", name: "export", nodeId: "node-1" },
+ operationId: "operation-1",
+ phase: "claimed",
+ ownerId: "task-1",
+ },
+ ],
+ },
+ ),
+ });
+ const remoteRequest = {
+ ...request,
+ replyTo: remoteReplyTo,
+ request: { ...request.request, requestId: "remote-req" },
+ };
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ inputRequests: [remoteRequest.request],
+ metadata: { kind: "tool", name: "export" },
+ status: "input_required",
+ taskId: "task-1",
+ });
+
+ const result = await recordTaskInputRequestStep({ request: remoteRequest, sessionState });
+
+ expect(
+ getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:remote-req"),
+ ).toMatchObject({
+ childResponseUrl:
+ "https://remote.example/eve/v1/task-input/eve%3Atask-input%3A0123456789abcdef0123456789abcdef",
+ });
+ });
+});
+
+describe("recordTerminalTaskViewsStep", () => {
+ it("caches an owned terminal view and releases the task's agent lease", async () => {
+ vi.mocked(readDurableSession).mockResolvedValue({
+ agent: { system: "" },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: setAgentHandleStore(
+ {
+ "eve.tasks": {
+ tasks: [
+ {
+ createdByTurnId: "turn-1",
+ metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },
+ taskId: "task-1",
+ taskInboxToken: "task-token",
+ taskRunId: "task-run",
+ },
+ ],
+ version: 2,
+ },
+ },
+ {
+ handles: [
+ {
+ address: {
+ continuationToken: "child-token",
+ kind: "agent/local",
+ sessionId: "child-1",
+ },
+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },
+ operationId: "operation-1",
+ phase: "claimed",
+ ownerId: "task-1",
+ },
+ ],
+ },
+ ),
+ });
+ const view = {
+ lastOutput: { data: "done", type: "result" as const },
+ metadata: { agentId: "agent-1", kind: "subagent", mode: "local" as const, name: "research" },
+ status: "completed" as const,
+ taskId: "task-1",
+ };
+
+ const result = await recordTerminalTaskViewsStep({ sessionState, views: [view] });
+ const state = result.snapshot?.session.state;
+
+ expect(getSessionTaskIndex(state)[0]?.terminalView).toEqual(view);
+ expect(getAgentHandleStore(state)?.handles).toEqual([
+ expect.objectContaining({ phase: "available" }),
+ ]);
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
index 66306d6ec..e67aa1fa3 100644
--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
@@ -1,123 +1,92 @@
-import type { SubagentInputRequestHookPayload } from "#channel/types.js";
-import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
-import {
- type DurableSession,
- type DurableSessionState,
- readDurableSession,
-} from "#execution/durable-session-store.js";
-import { readWorkflowToolExecutor } from "#execution/tool-run/background.js";
-import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";
+import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";
import { createRemoteTaskInputCallbackUrl } from "#execution/workflow-callback-url.js";
import {
createTaskInputRequestId,
- toProxyInputRequestEntries,
upsertProxyInputRequestState,
+ type ProxyInputRequest,
} from "#harness/proxy-input-requests.js";
-import { type AgentHandle, getAgentHandleStore } from "#harness/handles/store.js";
-import { removeTaskAgentAddressFromState } from "#harness/handles/transitions.js";
import { isInputRequest } from "#shared/input.js";
-import {
- cacheTerminalTaskView,
- findSessionTaskEntry,
- type SessionTaskIndexEntry,
-} from "#tasks/session-index.js";
+import { getAgentHandleStore } from "#subagents/handles/store.js";
+import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";
import { createEveTaskInputRoutePath } from "#protocol/routes.js";
-import { isTerminalTaskStatus, readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";
+import { cacheTerminalTaskView, findSessionTaskEntry } from "#tasks/session-index.js";
+import type { TaskInputRequestDelivery, TaskView } from "#tasks/types.js";
-/** Validates and durably records one task-owned child HITL route batch. */
+/** Validates and records a generic task-owned workflow request. */
export async function recordTaskInputRequestStep(input: {
- readonly hookPayload: SubagentInputRequestHookPayload;
- readonly serializedContext: Record<string, unknown>;
+ readonly request: TaskInputRequestDelivery;
readonly sessionState: DurableSessionState;
- readonly taskId: string;
}): Promise<
| { readonly accepted: false; readonly sessionState: DurableSessionState }
| {
readonly accepted: true;
- readonly hookPayload: SubagentInputRequestHookPayload;
+ readonly request: TaskInputRequestDelivery;
readonly sessionState: DurableSessionState;
}
> {
"use step";
const durableSession = await readDurableSession(input.sessionState);
- const entry = findSessionTaskEntry(durableSession.state, input.taskId);
- if (entry === undefined) {
+ const entry = findSessionTaskEntry(durableSession.state, input.request.taskId);
+ const requests = input.request.requests ?? [input.request.request];
+ if (entry === undefined || requests.length === 0 || !requests.every(isInputRequest)) {
return { accepted: false, sessionState: input.sessionState };
}
const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
- const eventRequestIds = input.hookPayload.event.requests.map((request) => request.requestId);
- const viewRequestIds =
- view?.inputRequests?.map((request) =>
- request !== null && typeof request === "object" && !Array.isArray(request)
- ? Reflect.get(request, "requestId")
- : undefined,
- ) ?? [];
+ const requestIds = requests.map((request) => request.requestId);
if (
view?.status !== "input_required" ||
- !input.hookPayload.event.requests.every(isInputRequest) ||
- new Set(eventRequestIds).size !== eventRequestIds.length ||
- eventRequestIds.length !== viewRequestIds.length ||
- eventRequestIds.some((requestId, index) => requestId !== viewRequestIds[index])
+ view.inputRequests.length !== requestIds.length ||
+ !view.inputRequests.every(
+ (request, index) =>
+ request !== null &&
+ typeof request === "object" &&
+ !Array.isArray(request) &&
+ Reflect.get(request, "requestId") === requestIds[index],
+ )
) {
return { accepted: false, sessionState: input.sessionState };
}
- // The child-advertised token is an answer route, not an identity anchor: a
- // tool run is identified by its run id, a subagent child by its addressed handle.
- const toolRun = readWorkflowToolExecutor(view.executor?.binding);
- if (toolRun !== undefined && toolRun.runId !== input.hookPayload.childSessionId) {
- return { accepted: false, sessionState: input.sessionState };
- }
- const handle =
- toolRun === undefined ? findAddressedTaskHandle(durableSession.state, entry) : undefined;
- if (toolRun === undefined) {
- const entryMetadata = readSubagentTaskMetadata(entry);
- const viewMetadata = readSubagentTaskMetadata(view);
- if (
- handle === undefined ||
- handle.address.sessionId !== input.hookPayload.childSessionId ||
- viewMetadata?.mode !== (handle.address.kind === "agent/remote" ? "remote" : "local") ||
- viewMetadata.agentId !== entryMetadata?.agentId ||
- view.executor?.childSessionId !== input.hookPayload.childSessionId
- ) {
- return { accepted: false, sessionState: input.sessionState };
- }
- }
-
- const hookPayload = namespaceTaskInputRequests(input.hookPayload, input.taskId);
- let entries = toProxyInputRequestEntries(hookPayload, input.taskId).map(
- ([requestId, route], index) => {
- const childRequestId = input.hookPayload.event.requests[index]!.requestId;
- return [
- requestId,
- {
- ...route,
- childRequestId,
- },
- ] as const;
- },
+ const parentRequests = requests.map((request) => ({
+ ...request,
+ requestId: createTaskInputRequestId(input.request.taskId, request.requestId),
+ }));
+ const handle = getAgentHandleStore(durableSession.state)?.handles.find(
+ (candidate) => candidate.phase === "claimed" && candidate.ownerId === input.request.taskId,
);
- if (handle?.address.kind === "agent/remote") {
- const childResponseUrl = createRemoteTaskInputCallbackUrl(
- handle.address.url,
- createEveTaskInputRoutePath(
- createTaskInputCapabilityToken(input.hookPayload.childContinuationToken),
- ),
- );
- entries = entries.map(
- ([requestId, route]) => [requestId, { ...route, childResponseUrl }] as const,
- );
- }
+ const remoteResponseUrl =
+ handle?.phase === "claimed" && handle.address.kind === "agent/remote"
+ ? createRemoteTaskInputCallbackUrl(
+ handle.address.url,
+ createEveTaskInputRoutePath(createTaskInputCapabilityToken(input.request.replyTo)),
+ )
+ : undefined;
+ const entries = requests.map((request, index) => {
+ const parentRequest = parentRequests[index]!;
+ const route: { -readonly [K in keyof ProxyInputRequest]: ProxyInputRequest[K] } = {
+ childContinuationToken: input.request.replyTo,
+ childRequestId: request.requestId,
+ kind: request.kind,
+ taskId: input.request.taskId,
+ };
+ if (remoteResponseUrl !== undefined) route.childResponseUrl = remoteResponseUrl;
+ return [parentRequest.requestId, route] as const;
+ });
const state = upsertProxyInputRequestState({
entries,
- forChildContinuationToken: input.hookPayload.childContinuationToken,
+ forChildContinuationToken: input.request.replyTo,
state: durableSession.state,
});
+ const request: TaskInputRequestDelivery =
+ input.request.requests === undefined
+ ? { ...input.request, request: parentRequests[0]! }
+ : { ...input.request, request: undefined, requests: parentRequests };
return {
accepted: true,
- hookPayload,
+ request,
sessionState: {
...input.sessionState,
hasProxyInputRequests: true,
@@ -129,90 +98,28 @@ export async function recordTaskInputRequestStep(input: {
};
}
-function findAddressedTaskHandle(
- state: DurableSession["state"],
- entry: SessionTaskIndexEntry,
-): Extract<AgentHandle, { phase: "addressed" }> | undefined {
- const agentId = readSubagentTaskMetadata(entry)?.agentId;
- if (agentId === undefined) return undefined;
- return (getAgentHandleStore(state)?.handles ?? []).find(
- (candidate): candidate is Extract<AgentHandle, { phase: "addressed" }> =>
- candidate.phase === "addressed" && candidate.identity.id === agentId,
- );
-}
-
-function namespaceTaskInputRequests(
- hookPayload: SubagentInputRequestHookPayload,
- taskId: string,
-): SubagentInputRequestHookPayload {
- return {
- ...hookPayload,
- event: {
- ...hookPayload.event,
- requests: hookPayload.event.requests.map((request) => ({
- ...request,
- requestId: createTaskInputRequestId(taskId, request.requestId),
- })),
- },
- };
-}
-
-/** Validates that one task authorization event came from its owned child address. */
-export async function acceptTaskAuthorizationEventStep(input: {
- readonly hookPayload: SubagentAuthorizationEventHookPayload;
- readonly sessionState: DurableSessionState;
- readonly taskId: string;
-}): Promise<boolean> {
- "use step";
-
- const durableSession = await readDurableSession(input.sessionState);
- const entry = findSessionTaskEntry(durableSession.state, input.taskId);
- if (entry === undefined) return false;
- const entryMetadata = readSubagentTaskMetadata(entry);
- if (entryMetadata === undefined) return false;
- const handle = (getAgentHandleStore(durableSession.state)?.handles ?? []).find(
- (candidate) =>
- candidate.phase === "addressed" && candidate.identity.id === entryMetadata.agentId,
- );
- if (
- handle?.phase !== "addressed" ||
- handle.address.sessionId !== input.hookPayload.childSessionId
- ) {
- return false;
- }
- const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
- const viewMetadata = view === undefined ? undefined : readSubagentTaskMetadata(view);
- return (
- view !== undefined &&
- !isTerminalTaskStatus(view.status) &&
- view.executor?.childSessionId === input.hookPayload.childSessionId &&
- viewMetadata?.agentId === entryMetadata.agentId
- );
-}
-
-/** Caches terminal task views before their workflow runs can expire. */
+/** Caches terminal task views before their workflow runs expire. */
export async function recordTerminalTaskViewsStep(input: {
readonly sessionState: DurableSessionState;
readonly views: readonly TaskView[];
}): Promise<DurableSessionState> {
"use step";
-
const durableSession = await readDurableSession(input.sessionState);
- let state = durableSession.state;
+ let session = durableSession;
for (const view of input.views) {
- state = cacheTerminalTaskView(state, view);
- if (view.executor?.lifecycle === "terminal") {
- const metadata = readSubagentTaskMetadata(view);
- if (metadata !== undefined) {
- state = removeTaskAgentAddressFromState(state, metadata.agentId);
- }
- }
+ if (findSessionTaskEntry(session.state, view.taskId) === undefined) continue;
+ const state = cacheTerminalTaskView(session.state, view);
+ if (state !== session.state) session = { ...session, state };
+ session = applyTaskAgentHandleCommand(session, {
+ kind: "release-owner",
+ ownerId: view.taskId,
+ }).session;
}
- if (state === durableSession.state) return input.sessionState;
+ if (session === durableSession) return input.sessionState;
return {
...input.sessionState,
snapshot: {
- session: { ...durableSession, state },
+ session,
version: input.sessionState.version,
},
};
diff --git a/packages/eve/src/execution/tasks/parent/run-parent.ts b/packages/eve/src/execution/tasks/parent/run-parent.ts
index 1130e6379..6b7bd7300 100644
--- a/packages/eve/src/execution/tasks/parent/run-parent.ts
+++ b/packages/eve/src/execution/tasks/parent/run-parent.ts
@@ -19,8 +19,8 @@ const TASK_VIEW_READ_TIMEOUT_MS = 10_000;
/**
* Node-side controls for durable task runs — the generic transport layer.
* This module only speaks `TaskCommand`/`TaskView`; it knows nothing about
- * subagents, receipts, or the session index. Caller-specific policy (e.g.
- * subagent delegation in `delegate.ts`) composes these primitives.
+ * executor implementations, receipts, or the session index. Caller-specific
+ * policy composes these primitives.
*
* Every export must be called from inside a `"use step"` body; none of
* these are steps themselves so dispatch and tool steps can compose them
diff --git a/packages/eve/src/execution/tasks/parent/task-cancel.ts b/packages/eve/src/execution/tasks/parent/task-cancel.ts
new file mode 100644
index 000000000..f66a4dee9
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/task-cancel.ts
@@ -0,0 +1,43 @@
+import { cancelRun, getRun, getWorld } from "#internal/workflow/runtime.js";
+import type { SessionTaskIndexEntry } from "#tasks/session-index.js";
+import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";
+import { readWorkflowToolExecutorAddress } from "#execution/tools/workflow/types.js";
+
+export interface TaskExecutorCancelContext {
+ readonly entry: SessionTaskIndexEntry;
+ readonly serializedContext?: Record<string, unknown>;
+ readonly session?: unknown;
+}
+
+export type TaskExecutorCancel = (input: TaskExecutorCancelContext) => Promise<void>;
+
+const TASK_RUN_CANCEL_GRACE_MS = 1_000;
+const TASK_RUN_CANCEL_POLL_MS = 50;
+
+/** Cancels policy-specific work associated with one task. */
+export async function cancelTaskOwnedWork(
+ input: TaskExecutorCancelContext & { readonly cancelOwnedWork?: TaskExecutorCancel },
+): Promise<void> {
+ const workflowToolRun = readWorkflowToolExecutorAddress(input.entry.executor);
+ if (workflowToolRun !== undefined) {
+ await cancelWorkflowToolRun(workflowToolRun, `Task ${input.entry.taskId} was cancelled.`);
+ }
+ await input.cancelOwnedWork?.(input);
+ const deadline = Date.now() + TASK_RUN_CANCEL_GRACE_MS;
+ while (Date.now() < deadline) {
+ try {
+ const status = await getRun(input.entry.taskRunId).status;
+ if (status !== "pending" && status !== "running") return;
+ } catch {
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, TASK_RUN_CANCEL_POLL_MS));
+ }
+ try {
+ await cancelRun(await getWorld(), input.entry.taskRunId, {
+ cancelReason: `Task ${input.entry.taskId} was cancelled.`,
+ });
+ } catch {
+ // The merged task run may have completed during its cooperative unwind.
+ }
+}
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
deleted file mode 100644
index e1acaed1b..000000000
--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
+++ /dev/null
@@ -1,359 +0,0 @@
-import { generateText } from "ai";
-import { MockLanguageModelV4 } from "ai/test";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { ContextContainer } from "#context/container.js";
-import {
- AuthKey,
- ContinuationTokenKey,
- HandleEventKey,
- InitiatorAuthKey,
- SessionIdKey,
-} from "#context/keys.js";
-import { runStep } from "#context/run-step.js";
-import { createBackgroundSubagentHarnessDefinition } from "#execution/delegation-tool.js";
-import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
-import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
-import { backgroundToolExecutionProvider } from "#execution/tasks/parent/tool-execution.js";
-import { CallbackBaseUrlKey } from "#harness/authorization.js";
-import { setHarnessEmissionState } from "#harness/emission.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
-import { buildToolSet } from "#harness/tools.js";
-import type { HarnessSession } from "#harness/types.js";
-import { createTestRuntime } from "#internal/testing/app-harness.js";
-import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
-import { getRun } from "#internal/workflow/runtime.js";
-import type {
- SandboxBackend,
- SandboxBackendCreateInput,
-} from "#public/definitions/sandbox-backend.js";
-import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
-import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
-import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-import { readSubagentTaskMetadata } from "#tasks/types.js";
-
-const usage = {
- inputTokens: { cacheRead: undefined, cacheWrite: undefined, noCache: 1, total: 1 },
- outputTokens: { reasoning: undefined, text: 1, total: 1 },
-};
-
-describe("background subagent tool execution", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it("runs concurrent local and remote defineTool calls as independent durable tasks", async () => {
- const runtime = await createTestRuntime({ agent: { name: "background-subagent" } });
-
- await runtime.run(async () => {
- const remoteNode = {
- backing: {
- kind: "resource",
- sourcePath: "/virtual/eve-memory-app/agent/subagents/reviewer.ts",
- },
- binding: runtime.manifest.bindings["subagents/reviewer.ts"] ?? {
- backing: {
- kind: "programmatic",
- moduleId: "subagents/reviewer.ts",
- registryId: "memory:background-subagent",
- revision: "memory:background-subagent",
- },
- logicalPath: "subagents/reviewer.ts",
- owner: { kind: "application" },
- usage: { compile: true, runtimeEntry: true },
- },
- description: "Remote reviewer",
- entryPath: "/virtual/eve-memory-app/agent/subagents/reviewer.ts",
- logicalPath: "subagents/reviewer.ts",
- name: "reviewer",
- nodeId: "remote/reviewer",
- owner: { kind: "application" },
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- path: "/eve/v1/session",
- rootPath: "/virtual/eve-memory-app/agent",
- sourceId: "subagents/reviewer.ts",
- sourceKind: "module",
- url: "https://remote.example.com",
- } as const;
- runtime.session.compiledArtifacts = {
- manifest: { ...runtime.manifest, remoteAgents: [remoteNode] },
- moduleMap: {
- nodes: {
- ...runtime.moduleMap.nodes,
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- ...runtime.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules,
- [remoteNode.sourceId]: { default: { url: remoteNode.url } },
- },
- },
- },
- },
- };
- const bundle = await getCompiledRuntimeAgentBundle({
- compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
- });
- const sandbox = mockSandbox({ id: "background-subagent-sandbox" });
- const createSandbox = vi.fn(async (input: SandboxBackendCreateInput) => ({
- captureState: async () => ({
- backendName: "test",
- metadata: {},
- sessionKey: input.sessionKey,
- }),
- delete: async () => {},
- session: sandbox.session,
- shutdown: async () => {},
- stop: async () => {},
- useSessionFn: async () => sandbox.session,
- }));
- const backend: SandboxBackend = {
- create: createSandbox,
- name: "test",
- prewarm: async () => ({ reused: false }),
- };
- (
- bundle.graph.root.sandboxRegistry.sandbox.definition as {
- backend: SandboxBackend;
- }
- ).backend = backend;
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- Response.json(
- { ok: true, sessionId: "remote-child", status: "accepted" },
- { headers: { "x-eve-session-id": "remote-child" }, status: 202 },
- ),
- );
- vi.stubGlobal("fetch", fetchMock);
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(BundleKey, bundle);
- ctx.set(CallbackBaseUrlKey, "https://caller.example.com");
- ctx.set(ChannelKey, { kind: "http", state: {} });
- ctx.set(ContinuationTokenKey, "http:background-subagent");
- ctx.set(InitiatorAuthKey, null);
- ctx.set(SessionIdKey, "parent-background-subagent");
-
- const session: HarnessSession = setHarnessEmissionState(
- {
- agent: { modelReference: { id: "openai/gpt-5.4" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "http:background-subagent",
- history: [],
- sessionId: "parent-background-subagent",
- },
- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-background" },
- );
- const localTool = createBackgroundSubagentHarnessDefinition({
- behavior: {
- availability: ["root-session"],
- handling: {
- kind: "dispatch",
- target: {
- kind: "self-agent-call",
- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- subagentName: "agent",
- },
- },
- },
- description: "General-purpose agent",
- name: "agent",
- });
- const remoteTool = createBackgroundSubagentHarnessDefinition({
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "remote-agent-call",
- nodeId: remoteNode.nodeId,
- remoteAgentName: remoteNode.name,
- },
- },
- },
- description: remoteNode.description,
- name: remoteNode.name,
- });
- const model = new MockLanguageModelV4({
- doGenerate: {
- content: [
- {
- input: JSON.stringify({ message: "Reply with exactly `background-child-a`." }),
- toolCallId: "call-background-child-a",
- toolName: "agent",
- type: "tool-call",
- },
- {
- input: JSON.stringify({ message: "Reply with exactly `background-child-b`." }),
- toolCallId: "call-background-child-b",
- toolName: "agent",
- type: "tool-call",
- },
- {
- input: JSON.stringify({ message: "Review the result." }),
- toolCallId: "call-background-remote",
- toolName: "reviewer",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- });
-
- let generated: Awaited<ReturnType<typeof generateText>> | undefined;
- const calledEvents: unknown[] = [];
- const result = await runStep(
- ctx,
- session,
- async (current) => {
- ctx.setVirtualContext(HandleEventKey, async (event) => {
- calledEvents.push(event);
- });
- generated = await generateText({
- model,
- prompt: "Delegate the work.",
- tools: buildToolSet({
- tools: new Map([
- [localTool.name, localTool],
- [remoteTool.name, remoteTool],
- ]),
- }),
- });
- return { next: null, session: current };
- },
- [backgroundToolExecutionProvider],
- );
-
- const pendingTasks = result.backgroundTasks ?? [];
- const handles = getAgentHandleStore(result.session.state)?.handles ?? [];
- expect(createSandbox).toHaveBeenCalledTimes(2);
- for (const [input] of createSandbox.mock.calls) {
- expect(input).toEqual(
- expect.objectContaining({
- tags: expect.objectContaining({ sessionId: "parent-background-subagent" }),
- }),
- );
- }
- if (pendingTasks.length !== 3) throw new Error("Three durable tasks were not committed.");
- if (handles.some((handle) => handle.phase !== "addressed") || handles.length !== 3) {
- throw new Error("Three child addresses were not committed.");
- }
-
- try {
- expect(generated?.toolResults).toHaveLength(3);
- expect(generated?.toolResults.map((toolResult) => toolResult.output)).toEqual(
- expect.arrayContaining(
- pendingTasks.map((task) =>
- expect.objectContaining({ status: "working", taskId: task.taskId }),
- ),
- ),
- );
- expect(new Set(handles.map((handle) => handle.identity.id)).size).toBe(3);
- expect(calledEvents).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- data: expect.objectContaining({ name: "agent" }),
- type: "subagent.called",
- }),
- expect.objectContaining({
- data: expect.objectContaining({
- childSessionId: "remote-child",
- name: "reviewer",
- remote: {
- resolverId: remoteNode.nodeId,
- url: remoteNode.url,
- },
- }),
- type: "subagent.called",
- }),
- ...pendingTasks.map((task) =>
- expect.objectContaining({
- data: expect.objectContaining({
- backgroundTask: { status: "working", taskId: task.taskId },
- }),
- type: "subagent.completed",
- }),
- ),
- ]),
- );
- expect(calledEvents).toHaveLength(6);
- expect(handles).toContainEqual(
- expect.objectContaining({
- address: expect.objectContaining({ kind: "agent/remote", sessionId: "remote-child" }),
- }),
- );
- const remoteReceipt = generated?.toolResults.find(
- (toolResult) => toolResult.toolName === "reviewer",
- )?.output;
- const remoteTaskId =
- typeof remoteReceipt === "object" &&
- remoteReceipt !== null &&
- "taskId" in remoteReceipt &&
- typeof remoteReceipt.taskId === "string"
- ? remoteReceipt.taskId
- : undefined;
- const remoteTaskIndex = pendingTasks.findIndex((task) => task.taskId === remoteTaskId);
- expect(remoteTaskIndex).toBeGreaterThanOrEqual(0);
-
- await acknowledgeDelegatedTasksStep({ tasks: pendingTasks });
- const localTasks = pendingTasks.filter((_task, index) => index !== remoteTaskIndex);
- await Promise.all(localTasks.map((task) => getRun(task.taskRunId).returnValue));
- const views = await Promise.all(
- pendingTasks.map((task) => readLatestTaskView({ taskRunId: task.taskRunId })),
- );
- expect(views).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- lastOutput: {
- data: expect.stringContaining("background-child-a"),
- type: "result",
- },
- status: "completed",
- }),
- expect.objectContaining({
- lastOutput: {
- data: expect.stringContaining("background-child-b"),
- type: "result",
- },
- status: "completed",
- }),
- expect.objectContaining({
- status: "working",
- }),
- ]),
- );
- const remoteTask = pendingTasks[remoteTaskIndex];
- const remoteView = views[remoteTaskIndex];
- expect(remoteTask).toBeDefined();
- expect(
- remoteView === undefined ? undefined : readSubagentTaskMetadata(remoteView),
- ).toMatchObject({ mode: "remote", name: "reviewer" });
- expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
- callback: { token: remoteTask?.taskInboxToken },
- });
- } finally {
- await Promise.all(
- handles.flatMap((handle) =>
- handle.phase === "addressed"
- ? [
- getRun(handle.address.sessionId)
- .cancel()
- .catch(() => {}),
- ]
- : [],
- ),
- );
- await Promise.all(
- pendingTasks.map((task) =>
- getRun(task.taskRunId)
- .cancel()
- .catch(() => {}),
- ),
- );
- }
- });
- }, 60_000);
-});
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts
deleted file mode 100644
index c68a592f5..000000000
--- a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts
+++ /dev/null
@@ -1,667 +0,0 @@
-import { generateText } from "ai";
-import { MockLanguageModelV4 } from "ai/test";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { z } from "#compiled/zod/index.js";
-import { ContextContainer } from "#context/container.js";
-import { AuthKey, SessionIdKey } from "#context/keys.js";
-import { runStep } from "#context/run-step.js";
-import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
-import { backgroundToolExecutionProvider } from "#execution/tasks/parent/tool-execution.js";
-import { setHarnessEmissionState } from "#harness/emission.js";
-import { isAuthorizationPendingModelOutput, requestAuthorization } from "#harness/authorization.js";
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { buildToolSet } from "#harness/tools.js";
-import type { HarnessSession } from "#harness/types.js";
-import {
- getAgentHandleStore,
- type AgentAddress,
- type AgentIdentity,
-} from "#harness/handles/store.js";
-import { defineTool, type TaskExec, type ToolContext } from "#tools/definition.js";
-import { toInputSchema } from "#tools/schema.js";
-import { getSessionTaskIndex } from "#tasks/session-index.js";
-import { createSubagentExecutorBinding } from "#tasks/types.js";
-
-const mocks = vi.hoisted(() => ({
- beginBackgroundTask: vi.fn(),
- propagateSubagentExecutorCancel: vi.fn(),
- rejectDelegatedDispatch: vi.fn(),
- sendTaskCommand: vi.fn(),
- sendTaskInboundPayload: vi.fn(),
-}));
-
-vi.mock("#execution/tasks/parent/delegate.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/tasks/parent/delegate.js")>()),
- beginBackgroundTask: mocks.beginBackgroundTask,
- rejectDelegatedDispatch: mocks.rejectDelegatedDispatch,
-}));
-vi.mock("#execution/tasks/parent/dispatch.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/tasks/parent/dispatch.js")>()),
- propagateSubagentExecutorCancel: mocks.propagateSubagentExecutorCancel,
-}));
-vi.mock("#execution/tasks/parent/run-parent.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#execution/tasks/parent/run-parent.js")>()),
- sendTaskCommand: mocks.sendTaskCommand,
- sendTaskInboundPayload: mocks.sendTaskInboundPayload,
-}));
-
-const usage = {
- inputTokens: { cacheRead: undefined, cacheWrite: undefined, noCache: 1, total: 1 },
- outputTokens: { reasoning: undefined, text: 1, total: 1 },
-};
-
-const childIdentity: AgentIdentity = {
- id: "ag_research:operation1",
- name: "research",
- nodeId: "node_research",
-};
-const childAddress: AgentAddress = {
- continuationToken: "continuation_child",
- kind: "agent/local",
- sessionId: "session_child",
-};
-
-function createParentSession(): HarnessSession {
- return setHarnessEmissionState(
- {
- agent: { modelReference: { id: "mock" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- },
- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
- );
-}
-
-function createSubagentTool(): HarnessToolDefinition {
- const definition = defineTool({
- description: "Spawn a research subagent.",
- execution: "background",
- inputSchema: z.strictObject({}),
- execute(_input: Record<string, never>, _ctx: ToolContext, background: TaskExec) {
- return background.delegated({
- executor: createSubagentExecutorBinding({
- address: childAddress,
- identity: childIdentity,
- }),
- receipt: { agentId: childIdentity.id },
- });
- },
- });
- return {
- description: definition.description,
- execute: createToolExecuteWithAuth({
- execute: definition.execute,
- execution: definition.execution,
- scope: "research",
- }),
- execution: definition.execution,
- inputSchema: toInputSchema(definition.inputSchema),
- name: "research",
- };
-}
-
-const subagentToolCallModel = () =>
- new MockLanguageModelV4({
- doGenerate: {
- content: [
- {
- input: "{}",
- toolCallId: "call-research",
- toolName: "research",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- });
-
-describe("background tool execution", () => {
- beforeEach(() => {
- mocks.beginBackgroundTask.mockReset();
- mocks.propagateSubagentExecutorCancel.mockReset();
- mocks.rejectDelegatedDispatch.mockReset();
- mocks.sendTaskCommand.mockReset();
- mocks.sendTaskInboundPayload.mockReset();
- });
-
- it("runs a non-subagent defineTool through the generic durable task lifecycle", async () => {
- mocks.beginBackgroundTask.mockImplementation(
- async ({ callId }: { readonly callId: string }) => ({
- createdByStepIndex: 0,
- createdByTurnId: "turn-1",
- metadata: { kind: "tool", name: "export" },
- taskId: `task-${callId}`,
- taskInboxToken: `inbox-${callId}`,
- taskRunId: `run-${callId}`,
- }),
- );
- mocks.sendTaskCommand.mockResolvedValue("delivered");
- let releaseSiblingExecutors: (() => void) | undefined;
- const siblingExecutorsStarted = new Promise<void>((resolve) => {
- releaseSiblingExecutors = resolve;
- });
- const startedQueries: string[] = [];
- const observedBatchSizes: number[] = [];
-
- const definition = defineTool({
- description: "Start an external export.",
- execution: "background",
- inputSchema: z.strictObject({ query: z.string() }),
- async execute(input: { readonly query: string }, _ctx: ToolContext, background: TaskExec) {
- startedQueries.push(input.query);
- observedBatchSizes.push(background.batch.length);
- if (startedQueries.length === 2) releaseSiblingExecutors?.();
- await siblingExecutorsStarted;
- return background.delegated({
- executor: { data: { exportId: input.query }, kind: "export" },
- receipt: { exportId: input.query },
- });
- },
- });
- const tool: HarnessToolDefinition = {
- description: definition.description,
- execute: createToolExecuteWithAuth({
- execute: definition.execute,
- execution: definition.execution,
- scope: "export",
- }),
- execution: definition.execution,
- inputSchema: toInputSchema(definition.inputSchema),
- name: "export",
- };
- const model = new MockLanguageModelV4({
- doGenerate: [
- {
- content: [
- {
- input: JSON.stringify({ query: "export-1" }),
- toolCallId: "call-export-1",
- toolName: "export",
- type: "tool-call",
- },
- {
- input: JSON.stringify({ query: "export-2" }),
- toolCallId: "call-export-2",
- toolName: "export",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- {
- content: [
- {
- input: JSON.stringify({ query: "export-3" }),
- toolCallId: "call-export-3",
- toolName: "export",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- ],
- });
- const session: HarnessSession = setHarnessEmissionState(
- {
- agent: { modelReference: { id: "mock" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- },
- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
- );
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(SessionIdKey, session.sessionId);
-
- const generated: Awaited<ReturnType<typeof generateText>>[] = [];
- const result = await runStep(
- ctx,
- session,
- async (current) => {
- generated.push(
- await generateText({
- model,
- prompt: "Start two exports.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- }),
- await generateText({
- model,
- prompt: "Start one more export.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- }),
- );
- return { next: null, session: current };
- },
- [backgroundToolExecutionProvider],
- );
-
- expect(startedQueries).toEqual(["export-1", "export-2", "export-3"]);
- expect(observedBatchSizes).toEqual([2, 2, 1]);
- expect(generated.flatMap((result) => result.toolResults)).toEqual(
- expect.arrayContaining(
- ["export-1", "export-2", "export-3"].map((exportId, index) =>
- expect.objectContaining({
- output: {
- exportId,
- status: "working",
- taskId: `task-call-export-${index + 1}`,
- },
- toolName: "export",
- }),
- ),
- ),
- );
- expect(result.backgroundTasks).toHaveLength(3);
- expect(getSessionTaskIndex(result.session.state)).toEqual(
- expect.arrayContaining(
- ["export-1", "export-2", "export-3"].map((exportId, index) =>
- expect.objectContaining({
- executor: { data: { exportId }, kind: "export" },
- metadata: { kind: "tool", name: "export" },
- taskId: `task-call-export-${index + 1}`,
- }),
- ),
- ),
- );
- expect(mocks.sendTaskCommand).toHaveBeenCalledTimes(3);
- expect(mocks.rejectDelegatedDispatch).not.toHaveBeenCalled();
- });
-
- it("send delivers progress and terminal commands after delegation", async () => {
- const task = {
- createdByStepIndex: 0,
- createdByTurnId: "turn-1",
- metadata: { kind: "tool", name: "export" },
- taskId: "task-export",
- taskInboxToken: "inbox-export",
- taskRunId: "run-export",
- } as const;
- mocks.beginBackgroundTask.mockResolvedValue(task);
- mocks.sendTaskCommand.mockResolvedValue("delivered");
- mocks.sendTaskInboundPayload.mockResolvedValue("delivered");
- let background: TaskExec | undefined;
- const definition = defineTool({
- description: "Start an external export.",
- execution: "background",
- inputSchema: z.strictObject({ query: z.string() }),
- execute(input: { readonly query: string }, _ctx: ToolContext, taskExec: TaskExec) {
- background = taskExec;
- return taskExec.delegated({
- executor: { data: { exportId: input.query }, kind: "export" },
- receipt: { exportId: input.query },
- });
- },
- });
- const tool: HarnessToolDefinition = {
- description: definition.description,
- execute: createToolExecuteWithAuth({
- execute: definition.execute,
- execution: definition.execution,
- scope: "export",
- }),
- execution: definition.execution,
- inputSchema: toInputSchema(definition.inputSchema),
- name: "export",
- };
- const model = new MockLanguageModelV4({
- doGenerate: {
- content: [
- {
- input: JSON.stringify({ query: "customers" }),
- toolCallId: "call-export",
- toolName: "export",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- });
- const session: HarnessSession = setHarnessEmissionState(
- {
- agent: { modelReference: { id: "mock" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- },
- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
- );
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(SessionIdKey, session.sessionId);
-
- await runStep(
- ctx,
- session,
- async (current) => {
- await generateText({
- model,
- prompt: "Start the export.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- });
- return { next: null, session: current };
- },
- [backgroundToolExecutionProvider],
- );
-
- expect(background).toBeDefined();
- await background!.send({
- kind: "update",
- message: "Exported 10 rows.",
- });
- await background!.send({
- kind: "update",
- message: "Exported 20 rows.",
- });
- expect(mocks.sendTaskInboundPayload).toHaveBeenNthCalledWith(1, {
- payload: {
- callId: "call-export",
- kind: "task-update",
- message: "Exported 10 rows.",
- updateEpoch: "task-export",
- updateIndex: 0,
- },
- taskInboxToken: "inbox-export",
- });
- expect(mocks.sendTaskInboundPayload).toHaveBeenNthCalledWith(2, {
- payload: {
- callId: "call-export",
- kind: "task-update",
- message: "Exported 20 rows.",
- updateEpoch: "task-export",
- updateIndex: 1,
- },
- taskInboxToken: "inbox-export",
- });
-
- await background!.send({ data: { rows: 10 }, kind: "complete" });
- expect(mocks.sendTaskCommand).toHaveBeenLastCalledWith({
- command: { data: { rows: 10 }, kind: "complete" },
- taskInboxToken: "inbox-export",
- });
-
- mocks.sendTaskCommand.mockResolvedValue("unreachable");
- await expect(background!.send({ kind: "cancel" })).rejects.toThrow(
- 'Task run "task-export" did not accept "cancel".',
- );
- });
-
- it("rejects a delegated generic executor without cancel propagation when the parent step fails", async () => {
- const task = {
- createdByStepIndex: 0,
- createdByTurnId: "turn-1",
- metadata: { kind: "tool", name: "export" },
- taskId: "task-export",
- taskInboxToken: "inbox-export",
- taskRunId: "run-export",
- } as const;
- mocks.beginBackgroundTask.mockResolvedValue(task);
- mocks.sendTaskCommand.mockResolvedValue("delivered");
- const definition = defineTool({
- description: "Start an external export.",
- execution: "background",
- inputSchema: z.strictObject({ query: z.string() }),
- execute(input: { readonly query: string }, _ctx: ToolContext, background: TaskExec) {
- return background.delegated({
- executor: { data: { exportId: input.query }, kind: "export" },
- receipt: { exportId: input.query },
- });
- },
- });
- const tool: HarnessToolDefinition = {
- description: definition.description,
- execute: createToolExecuteWithAuth({
- execute: definition.execute,
- execution: definition.execution,
- scope: "export",
- }),
- execution: definition.execution,
- inputSchema: toInputSchema(definition.inputSchema),
- name: "export",
- };
- const model = new MockLanguageModelV4({
- doGenerate: {
- content: [
- {
- input: JSON.stringify({ query: "customers" }),
- toolCallId: "call-export",
- toolName: "export",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- });
- const session = createParentSession();
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(SessionIdKey, session.sessionId);
-
- await expect(
- runStep(
- ctx,
- session,
- async () => {
- await generateText({
- model,
- prompt: "Start the export.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- });
- throw new Error("parent step failed");
- },
- [backgroundToolExecutionProvider],
- ),
- ).rejects.toThrow("parent step failed");
-
- expect(mocks.rejectDelegatedDispatch).toHaveBeenCalledWith({
- error: { code: "PARENT_STEP_FAILED", message: "parent step failed" },
- task: {
- ...task,
- executor: { data: { exportId: "customers" }, kind: "export" },
- },
- });
- expect(mocks.propagateSubagentExecutorCancel).not.toHaveBeenCalled();
- expect(getSessionTaskIndex(session.state)).toEqual([]);
- });
-
- it("commits the subagent executor's addressed handle with the step", async () => {
- const task = {
- createdByStepIndex: 0,
- createdByTurnId: "turn-1",
- metadata: { kind: "tool", name: "research" },
- taskId: "task-research",
- taskInboxToken: "inbox-research",
- taskRunId: "run-research",
- } as const;
- mocks.beginBackgroundTask.mockResolvedValue(task);
- mocks.sendTaskCommand.mockResolvedValue("delivered");
- const tool = createSubagentTool();
- const session = createParentSession();
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(SessionIdKey, session.sessionId);
-
- const result = await runStep(
- ctx,
- session,
- async (current) => {
- await generateText({
- model: subagentToolCallModel(),
- prompt: "Spawn the researcher.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- });
- return { next: null, session: current };
- },
- [backgroundToolExecutionProvider],
- );
-
- expect(getAgentHandleStore(result.session.state)?.handles).toEqual([
- { address: childAddress, identity: childIdentity, phase: "addressed" },
- ]);
- expect(getSessionTaskIndex(result.session.state)).toEqual([
- expect.objectContaining({
- executor: createSubagentExecutorBinding({
- address: childAddress,
- identity: childIdentity,
- }),
- taskId: task.taskId,
- }),
- ]);
- expect(mocks.rejectDelegatedDispatch).not.toHaveBeenCalled();
- expect(mocks.propagateSubagentExecutorCancel).not.toHaveBeenCalled();
- });
-
- it("rejects the task first and then cancels the dispatched subagent child when the parent step fails", async () => {
- const task = {
- createdByStepIndex: 0,
- createdByTurnId: "turn-1",
- metadata: { kind: "tool", name: "research" },
- taskId: "task-research",
- taskInboxToken: "inbox-research",
- taskRunId: "run-research",
- } as const;
- mocks.beginBackgroundTask.mockResolvedValue(task);
- mocks.sendTaskCommand.mockResolvedValue("delivered");
- mocks.rejectDelegatedDispatch.mockResolvedValue(undefined);
- mocks.propagateSubagentExecutorCancel.mockResolvedValue(undefined);
- const tool = createSubagentTool();
- const session = createParentSession();
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(SessionIdKey, session.sessionId);
-
- await expect(
- runStep(
- ctx,
- session,
- async () => {
- await generateText({
- model: subagentToolCallModel(),
- prompt: "Spawn the researcher.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- });
- throw new Error("parent step failed");
- },
- [backgroundToolExecutionProvider],
- ),
- ).rejects.toThrow("parent step failed");
-
- const executor = createSubagentExecutorBinding({
- address: childAddress,
- identity: childIdentity,
- });
- expect(mocks.rejectDelegatedDispatch).toHaveBeenCalledWith({
- error: { code: "PARENT_STEP_FAILED", message: "parent step failed" },
- task: { ...task, executor },
- });
- expect(mocks.propagateSubagentExecutorCancel).toHaveBeenCalledWith({
- bundle: undefined,
- executor: { address: childAddress, identity: childIdentity },
- taskId: task.taskId,
- });
- // The task must be terminal before the child learns anything: a late
- // child result then bounces instead of reviving the rejected task.
- expect(mocks.rejectDelegatedDispatch.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.propagateSubagentExecutorCancel.mock.invocationCallOrder[0] ?? 0,
- );
- expect(getSessionTaskIndex(session.state)).toEqual([]);
- });
-
- it("parks authorization without committing the provisional task", async () => {
- const task = {
- createdByStepIndex: 0,
- createdByTurnId: "turn-1",
- metadata: { kind: "tool", name: "export" },
- taskId: "task-export",
- taskInboxToken: "inbox-export",
- taskRunId: "run-export",
- } as const;
- mocks.beginBackgroundTask.mockResolvedValue(task);
- mocks.rejectDelegatedDispatch.mockResolvedValue(undefined);
- const signal = requestAuthorization([
- {
- challenge: { url: "https://idp.example/authorize" },
- hookUrl: "https://app.example/callback",
- name: "exports",
- },
- ]);
- const tool: HarnessToolDefinition = {
- description: "Start an authorized export.",
- execute: async () => signal,
- execution: "background",
- inputSchema: z.strictObject({}),
- name: "export",
- };
- const model = new MockLanguageModelV4({
- doGenerate: {
- content: [
- {
- input: "{}",
- toolCallId: "call-export",
- toolName: "export",
- type: "tool-call",
- },
- ],
- finishReason: { raw: undefined, unified: "tool-calls" },
- usage,
- warnings: [],
- },
- });
- const session: HarnessSession = setHarnessEmissionState(
- {
- agent: { modelReference: { id: "mock" }, system: "", tools: [] },
- compaction: { recentWindowSize: 10, threshold: 100_000 },
- continuationToken: "parent-token",
- history: [],
- sessionId: "parent-session",
- },
- { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
- );
- const ctx = new ContextContainer();
- ctx.set(AuthKey, null);
- ctx.set(SessionIdKey, session.sessionId);
- let output: unknown;
-
- const result = await runStep(
- ctx,
- session,
- async (current) => {
- const generated = await generateText({
- model,
- prompt: "Start the export.",
- tools: buildToolSet({ tools: new Map([[tool.name, tool]]) }),
- });
- output = generated.toolResults[0]?.output;
- return { next: null, session: current };
- },
- [backgroundToolExecutionProvider],
- );
-
- expect(isAuthorizationPendingModelOutput(output)).toBe(true);
- expect(result.backgroundTasks).toBeUndefined();
- expect(getSessionTaskIndex(result.session.state)).toEqual([]);
- expect(mocks.sendTaskCommand).not.toHaveBeenCalled();
- expect(mocks.rejectDelegatedDispatch).toHaveBeenCalledWith({
- error: {
- code: "PARENT_STEP_FAILED",
- message: "Background tool execution did not delegate or complete its task.",
- },
- task,
- });
- });
-});
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.ts
index 735d0f3a3..aed53a183 100644
--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts
@@ -2,12 +2,14 @@ import type { ContextContainer } from "#context/container.js";
import { loadContext } from "#context/container.js";
import type { FrameworkContextProvider } from "#context/provider.js";
import { runStep } from "#context/run-step.js";
+import { buildCallbackContext } from "#context/build-callback-context.js";
import { CallbackBaseUrlKey } from "#harness/authorization.js";
import { isAuthorizationSignal } from "#harness/authorization.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getHarnessEmissionState } from "#harness/emission.js";
import { isTurnCancellation } from "#harness/turn-cancellation.js";
import type { HarnessSession, StepResult } from "#harness/types.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import {
BackgroundToolExecutorKey,
type BackgroundExecutableTool,
@@ -24,22 +26,62 @@ import {
type TaskExec,
type TaskSendCommand,
} from "#tools/task.js";
-import { recordTaskAgentAddress } from "#harness/handles/transitions.js";
-import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { recordSessionTask } from "#tasks/session-index.js";
-import { readSubagentExecutor, type TaskInboundUpdate } from "#tasks/types.js";
+import type { TaskInboundUpdate } from "#tasks/types.js";
+import type { AgentView } from "#subagents/handles/prompt.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import {
beginBackgroundTask,
+ prepareBackgroundTask,
rejectDelegatedDispatch,
type BackgroundTask,
} from "#execution/tasks/parent/delegate.js";
-import { propagateSubagentExecutorCancel } from "#execution/tasks/parent/dispatch.js";
-import { readWorkflowToolExecutor } from "#execution/tool-run/background.js";
-import { cancelToolRun } from "#execution/tool-run/cancel.js";
-import { sendTaskCommand, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
+import { parseWorkflowToolInput } from "#execution/tools/workflow/background.js";
+import {
+ sendTaskCommand,
+ sendTaskInboundPayload,
+ startTaskRun,
+ waitForTaskCommandOwner,
+} from "#execution/tasks/parent/run-parent.js";
+import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import { createSubagentReceiptIdentity } from "#execution/tools/subagent/receipt-identity.js";
+import { parseJsonObject } from "#shared/json.js";
+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
+import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#subagents/agent-handle-errors.js";
+import { formatAgentBusyMessage } from "#subagents/agent-handle-errors.js";
+import {
+ getAgentHandleStore,
+ writeHandles,
+ type AgentHandleStoreCommand,
+ type AgentHandleStoreCommandResult,
+} from "#subagents/handles/store.js";
+import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";
+
+type SubagentReceiptIdentity = ReturnType<typeof createSubagentReceiptIdentity>;
+
+const IN_PROCESS_WORKFLOW_EXECUTOR = { data: {}, kind: "workflow-task" } as const;
+
+interface SubagentTaskProjection {
+ readonly identity?: SubagentReceiptIdentity;
+ readonly metadata: {
+ readonly agentId: string;
+ readonly kind: "subagent";
+ readonly mode: "local" | "remote";
+ readonly name: string;
+ };
+ readonly receipt: { readonly agentId: string };
+}
interface BackgroundToolExecutionRecord {
+ claim?: {
+ readonly operationId: string;
+ readonly taskId: string;
+ };
+ reservation?: {
+ readonly agentId: string;
+ readonly operationId: string;
+ };
settled: boolean;
task?: BackgroundTask;
}
@@ -60,7 +102,7 @@ export function runBackgroundStep(
/**
* Makes background tool work transactional with the harness step.
*
- * Concretely: when the model calls a background tool (e.g. a subagent spawn),
+ * Concretely: when the model calls a background tool,
* the tool does real external work mid-step — it creates a task run and
* delivers commands to its inbox — while the step itself can still fail. This
* provider scopes that work to the step so it either lands with the step or
@@ -73,8 +115,7 @@ export function runBackgroundStep(
*
* - `commit` — step succeeded. Compensates executions that never settled
* (the tool neither delegated nor completed its task), then records the
- * task entries and executor-owned session writes onto the session being
- * persisted.
+ * task entries onto the session being persisted.
* - `rollback` — step failed. Compensates incomplete executions, and settled
* ones too — unless the cause is turn cancellation: those tasks are already
* running, so they are retained for {@link readRetainedBackgroundToolResult}
@@ -85,8 +126,8 @@ export function runBackgroundStep(
*/
export const backgroundToolExecutionProvider: FrameworkContextProvider<BackgroundToolExecutor> = {
key: BackgroundToolExecutorKey,
- create(ctx, session) {
- return { value: new BackgroundToolExecutionScope(session, ctx.get(BundleKey)) };
+ create(_ctx, session) {
+ return { value: new BackgroundToolExecutionScope(session) };
},
async commit(executor, session) {
return await requireExecutionScope(executor).commit(session);
@@ -115,16 +156,17 @@ export function readRetainedBackgroundToolResult(
}
class BackgroundToolExecutionScope implements BackgroundToolExecutor {
- private readonly bundle: CompiledBundle | undefined;
private readonly executions = new Map<string, Promise<unknown>>();
private readonly records: BackgroundToolExecutionRecord[] = [];
+ private agentHandleSession: HarnessSession;
+ private agentHandlesChanged = false;
private retained = false;
private readonly initialSession: HarnessSession;
- constructor(initialSession: HarnessSession, bundle: CompiledBundle | undefined) {
- this.bundle = bundle;
+ constructor(initialSession: HarnessSession) {
this.initialSession = initialSession;
+ this.agentHandleSession = initialSession;
}
execute(input: {
@@ -145,13 +187,38 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
return execution;
}
+ async readAgentViews(): Promise<readonly AgentView[]> {
+ const handles = getAgentHandleStore(this.agentHandleSession.state)?.handles ?? [];
+ return handles.flatMap<AgentView>((handle) => {
+ if (handle.phase === "reserved") return [];
+ if (handle.phase === "available") {
+ return [
+ {
+ availability: "available" as const,
+ id: handle.identity.id,
+ name: handle.identity.name,
+ },
+ ];
+ }
+ if (handle.phase !== "claimed") return [];
+ return [
+ {
+ availability: "busy" as const,
+ id: handle.identity.id,
+ name: handle.identity.name,
+ taskId: handle.ownerId,
+ taskStatus: "working" as const,
+ },
+ ];
+ });
+ }
+
async commit(session: HarnessSession): Promise<HarnessSession> {
const incomplete = this.records.filter((record) => !record.settled);
if (incomplete.length > 0) {
- await compensateBackgroundToolExecution(
+ await this.compensate(
incomplete,
new Error("Background tool execution did not delegate or complete its task."),
- this.bundle,
);
}
return this.apply(session);
@@ -166,7 +233,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
const settled = this.records.filter((record) => record.settled);
const incomplete = this.records.filter((record) => !record.settled);
if (incomplete.length > 0) {
- await compensateBackgroundToolExecution(incomplete, cause, this.bundle);
+ await this.compensate(incomplete, cause);
}
if (settled.length === 0) return;
// Cancellation must not compensate settled records: their tasks are
@@ -175,7 +242,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
this.retained = true;
return;
}
- await compensateBackgroundToolExecution(settled, cause, this.bundle);
+ await this.compensate(settled, cause);
}
retainedResult(): BackgroundToolStepResult | undefined {
@@ -186,14 +253,11 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
let next = session;
for (const record of this.records) {
if (!record.settled || record.task === undefined) continue;
- // Framework-owned executor commits, matched by executor kind. The
- // subagent binding is the durable copy of the child's addressed
- // handle; committing the task also commits that address into the
- // parent's handle store.
- const subagent = readSubagentExecutor(record.task.executor);
- if (subagent !== undefined) next = recordTaskAgentAddress(next, subagent);
next = recordSessionTask(next, record.task);
}
+ if (this.agentHandlesChanged) {
+ next = writeHandles(next, getAgentHandleStore(this.agentHandleSession.state)?.handles ?? []);
+ }
return next;
}
@@ -221,17 +285,12 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
const record: BackgroundToolExecutionRecord = { settled: false };
this.records.push(record);
const emission = getHarnessEmissionState(this.initialSession.state);
- const task = await beginBackgroundTask({
- callId: input.options.toolCallId,
- metadata: { kind: "tool", name: input.definition.name },
- parentSessionId: this.initialSession.sessionId,
- parentStepIndex: emission.stepIndex,
- parentTurnId: activeTurnId(emission),
- session: this.initialSession,
- });
+ const ctx = loadContext();
+ const started = await this.startTask({ ctx, emission, input, record });
+ const task = started.task;
record.task = task;
- const callbackBaseUrl = loadContext().get(CallbackBaseUrlKey);
+ const callbackBaseUrl = ctx.get(CallbackBaseUrlKey);
const binding = {
taskId: task.taskId,
token: task.taskInboxToken,
@@ -252,7 +311,14 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
session: this.initialSession,
task,
};
-
+ if (input.definition.workflowId !== undefined) {
+ record.settled = true;
+ return {
+ ...started.receipt,
+ status: "working",
+ taskId: task.taskId,
+ };
+ }
const output = input.definition.execute(input.toolInput, input.options, taskExec);
if (isAsyncIterable(output)) {
throw new Error("Background tools cannot return AsyncIterable output.");
@@ -260,19 +326,296 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
const settled = await output;
if (isAuthorizationSignal(settled)) return settled;
if (isTaskDelegated(settled)) {
- await deliverTaskCommand(task, {
- executor: settled.executor,
- kind: "bind",
- });
- record.task = { ...task, executor: settled.executor };
+ if (settled.executor !== undefined) {
+ await deliverTaskCommand(task, {
+ executor: settled.executor,
+ kind: "bind",
+ });
+ record.task = { ...task, executor: settled.executor };
+ }
record.settled = true;
- return settled.receipt;
+ return started.receipt === undefined
+ ? settled.receipt
+ : { ...settled.receipt, ...started.receipt };
}
await deliverTaskCommand(task, { data: parseJsonValue(settled), kind: "complete" });
record.settled = true;
return settled;
}
+
+ private async startTask(input: {
+ readonly ctx: ReturnType<typeof loadContext>;
+ readonly emission: ReturnType<typeof getHarnessEmissionState>;
+ readonly input: {
+ readonly batch: BackgroundToolCallBatch;
+ readonly definition: BackgroundExecutableTool;
+ readonly options: ToolExecuteOptions;
+ readonly toolInput: unknown;
+ };
+ readonly record: BackgroundToolExecutionRecord;
+ }): Promise<{ readonly receipt?: { readonly agentId: string }; readonly task: BackgroundTask }> {
+ const workflow =
+ input.input.definition.workflowId === undefined
+ ? undefined
+ : {
+ ...input.input.definition,
+ workflowId: input.input.definition.workflowId,
+ };
+ let workflowInput =
+ workflow === undefined
+ ? undefined
+ : parseWorkflowToolInput(input.input.toolInput, input.input.definition.name);
+ const parentTurnId = activeTurnId(input.emission);
+ let subagentProjection =
+ workflow?.resultKind === "subagent" && workflowInput !== undefined
+ ? projectSubagentTask({
+ ctx: input.ctx,
+ input: workflowInput,
+ name: input.input.definition.name,
+ nodeId: workflow.nodeId ?? input.input.definition.name,
+ taskInput: {
+ callId: input.input.options.toolCallId,
+ parentSessionId: this.initialSession.sessionId,
+ parentTurnId,
+ },
+ })
+ : undefined;
+ if (
+ subagentProjection !== undefined &&
+ subagentProjection.identity === undefined &&
+ !hasAgentHandle(this.agentHandleSession, subagentProjection.metadata.agentId)
+ ) {
+ const { agentId: _unknownAgentId, ...freshWorkflowInput } = workflowInput!;
+ workflowInput = freshWorkflowInput;
+ subagentProjection = projectSubagentTask({
+ ctx: input.ctx,
+ input: freshWorkflowInput,
+ name: input.input.definition.name,
+ nodeId: workflow!.nodeId ?? input.input.definition.name,
+ taskInput: {
+ callId: input.input.options.toolCallId,
+ parentSessionId: this.initialSession.sessionId,
+ parentTurnId,
+ },
+ });
+ }
+ const taskInput = {
+ callId: input.input.options.toolCallId,
+ metadata: subagentProjection?.metadata ?? { kind: "tool", name: input.input.definition.name },
+ parentSessionId: this.initialSession.sessionId,
+ parentStepIndex: input.emission.stepIndex,
+ parentTurnId,
+ session: this.initialSession,
+ };
+ if (workflow === undefined) {
+ return {
+ task: await beginBackgroundTask({
+ callId: taskInput.callId,
+ metadata: taskInput.metadata,
+ parentSessionId: taskInput.parentSessionId,
+ parentStepIndex: taskInput.parentStepIndex,
+ parentTurnId: taskInput.parentTurnId,
+ session: taskInput.session,
+ }),
+ };
+ }
+ if (workflowInput === undefined) {
+ throw new Error(`Background workflow tool "${input.input.definition.name}" has no input.`);
+ }
+
+ const task = prepareBackgroundTask(taskInput);
+ if (
+ workflow.resultKind === "subagent" &&
+ subagentProjection !== undefined &&
+ subagentProjection.identity !== undefined
+ ) {
+ const identity = subagentProjection.identity;
+ const reservation = this.applyAgentHandleCommand({
+ identity: identity.identity,
+ callId: taskInput.callId,
+ kind: "reserve",
+ operationId: identity.operation.id,
+ ownerId: task.taskId,
+ });
+ if (reservation.kind !== "ready") {
+ throw new Error(`Agent handle store rejected start operation "${identity.operation.id}".`);
+ }
+ input.record.reservation = {
+ agentId: identity.identity.id,
+ operationId: identity.operation.id,
+ };
+ }
+ if (
+ workflow.resultKind === "subagent" &&
+ subagentProjection !== undefined &&
+ subagentProjection.identity === undefined
+ ) {
+ const operationId = deriveAgentOperationId({
+ callId: taskInput.callId,
+ parentSessionId: taskInput.parentSessionId,
+ parentTurnId,
+ });
+ const claim = this.applyAgentHandleCommand({
+ agentId: subagentProjection.metadata.agentId,
+ callId: taskInput.callId,
+ expectedTarget: subagentProjection.metadata.mode,
+ invokedName: subagentProjection.metadata.name,
+ kind: "claim",
+ operationId,
+ ownerId: task.taskId,
+ });
+ if (!readClaimedHandle(claim)) {
+ throwAgentClaimError(subagentProjection.metadata.agentId, claim);
+ } else {
+ input.record.claim = {
+ operationId,
+ taskId: task.taskId,
+ };
+ }
+ }
+ await startTaskRun({
+ initialView: { metadata: task.metadata, status: "working", taskId: task.taskId },
+ parentContinuationToken: sessionCommandHookToken(this.initialSession.sessionId),
+ taskInboxToken: task.taskInboxToken,
+ workflow: {
+ callId: taskInput.callId,
+ executeInput: workflow.executeInput?.(workflowInput),
+ input: workflowInput,
+ resultKind: workflow.resultKind,
+ session: buildCallbackContext().session,
+ stepIndex: input.emission.stepIndex,
+ toolName: input.input.definition.name,
+ workflowId: workflow.workflowId,
+ },
+ });
+ const owner = await waitForTaskCommandOwner({ taskInboxToken: task.taskInboxToken });
+ const backgroundTask = {
+ ...task,
+ executor: IN_PROCESS_WORKFLOW_EXECUTOR,
+ taskRunId: owner.runId,
+ };
+ input.record.task = backgroundTask;
+ if (workflow.resultKind !== "subagent") {
+ return { task: backgroundTask };
+ }
+
+ if (subagentProjection === undefined) {
+ return { task: backgroundTask };
+ }
+ if (subagentProjection.identity === undefined) {
+ return { receipt: subagentProjection.receipt, task: backgroundTask };
+ }
+ return { receipt: subagentProjection.receipt, task: backgroundTask };
+ }
+
+ private applyAgentHandleCommand(command: AgentHandleStoreCommand): AgentHandleStoreCommandResult {
+ const applied = applyTaskAgentHandleCommand(this.agentHandleSession, command);
+ if (applied.session !== this.agentHandleSession) {
+ this.agentHandleSession = applied.session;
+ this.agentHandlesChanged = true;
+ }
+ return applied.result;
+ }
+
+ private async compensate(
+ records: readonly BackgroundToolExecutionRecord[],
+ cause: unknown,
+ ): Promise<void> {
+ const failures: unknown[] = [];
+ for (const record of records.toReversed()) {
+ if (record.task !== undefined) {
+ try {
+ await rejectDelegatedDispatch({
+ error: {
+ code: "PARENT_STEP_FAILED",
+ message: cause instanceof Error ? cause.message : String(cause),
+ },
+ task: record.task,
+ });
+ } catch (error) {
+ failures.push(error);
+ }
+ }
+ if (record.claim !== undefined) {
+ this.applyAgentHandleCommand({ kind: "release-owner", ownerId: record.claim.taskId });
+ }
+ if (record.reservation !== undefined && record.task !== undefined) {
+ this.applyAgentHandleCommand({
+ agentId: record.reservation.agentId,
+ kind: "remove",
+ ownerId: record.task.taskId,
+ });
+ }
+ }
+ if (failures.length > 0) {
+ throw new AggregateError(
+ [cause, ...failures],
+ "Background tool execution failed and its tasks could not all be rejected.",
+ { cause },
+ );
+ }
+ }
+}
+
+function hasAgentHandle(session: HarnessSession, agentId: string): boolean {
+ return (
+ getAgentHandleStore(session.state)?.handles.some((handle) => handle.identity.id === agentId) ===
+ true
+ );
+}
+
+function projectSubagentTask(input: {
+ readonly ctx: ReturnType<typeof loadContext>;
+ readonly input: ReturnType<typeof parseJsonObject>;
+ readonly name: string;
+ readonly nodeId: string;
+ readonly taskInput: {
+ readonly callId: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+ };
+}): SubagentTaskProjection {
+ const continuation = input.input.agentId;
+ if (typeof continuation === "string" && continuation.trim() !== "") {
+ return {
+ metadata: {
+ agentId: continuation,
+ kind: "subagent",
+ mode: readSubagentTaskMode(input.ctx, input.nodeId),
+ name: input.name,
+ },
+ receipt: { agentId: continuation },
+ };
+ }
+ const identity = createSubagentReceiptIdentity({
+ callId: input.taskInput.callId,
+ nodeId: input.nodeId,
+ parentSessionId: input.taskInput.parentSessionId,
+ parentTurnId: input.taskInput.parentTurnId,
+ subagentName: input.name,
+ });
+ return {
+ identity,
+ metadata: {
+ agentId: identity.identity.id,
+ kind: "subagent",
+ mode: readSubagentTaskMode(input.ctx, input.nodeId),
+ name: input.name,
+ },
+ receipt: { agentId: identity.identity.id },
+ };
+}
+
+function readSubagentTaskMode(
+ ctx: ReturnType<typeof loadContext>,
+ nodeId: string,
+): "local" | "remote" {
+ const dynamic = getDynamicSubagentSelection(ctx, nodeId);
+ if (dynamic !== undefined) return dynamic.kind === "remote" ? "remote" : "local";
+
+ const registered = ctx.get(BundleKey)?.subagentRegistry.subagentsByNodeId.get(nodeId);
+ return registered?.definition.kind === "remote" ? "remote" : "local";
}
function requireExecutionScope(executor: BackgroundToolExecutor): BackgroundToolExecutionScope {
@@ -320,46 +663,35 @@ function createTaskSender(
};
}
-async function compensateBackgroundToolExecution(
- records: readonly BackgroundToolExecutionRecord[],
- cause: unknown,
- bundle: CompiledBundle | undefined,
-): Promise<void> {
- const failures: unknown[] = [];
- for (const record of records.toReversed()) {
- if (record.task === undefined) continue;
- try {
- await rejectDelegatedDispatch({
- error: {
- code: "PARENT_STEP_FAILED",
- message: cause instanceof Error ? cause.message : String(cause),
- },
- task: record.task,
- });
- } catch (error) {
- failures.push(error);
- }
- // Reject first so the task is terminal and a late child result cannot
- // revive it, then best-effort abort the already-dispatched executor using
- // the address carried on its durable executor binding.
- const subagent = readSubagentExecutor(record.task.executor);
- if (subagent !== undefined) {
- await propagateSubagentExecutorCancel({
- bundle,
- executor: subagent,
- taskId: record.task.taskId,
- });
- }
- const toolRun = readWorkflowToolExecutor(record.task.executor);
- if (toolRun !== undefined) {
- await cancelToolRun(toolRun, "The step that started the tool failed.");
- }
+function readClaimedHandle(result: AgentHandleStoreCommandResult): boolean {
+ return result.kind === "ready" && result.handle?.phase === "claimed";
+}
+
+function throwAgentClaimError(agentId: string, result: AgentHandleStoreCommandResult): never {
+ if (result.kind === "mismatch") {
+ throw new Error(
+ JSON.stringify({
+ code: AGENT_MISMATCH,
+ message: `Agent "${agentId}" no longer matches this subagent definition. Start a new agent instead.`,
+ }),
+ );
}
- if (failures.length > 0) {
- throw new AggregateError(
- [cause, ...failures],
- "Background tool execution failed and its tasks could not all be rejected.",
- { cause },
+ if (result.kind === "busy") {
+ throw new Error(
+ JSON.stringify({
+ code: AGENT_BUSY,
+ message: formatAgentBusyMessage({
+ agentId,
+ agentName: result.handle.identity.name,
+ ownerId: "ownerId" in result.handle ? result.handle.ownerId : undefined,
+ }),
+ }),
);
}
+ throw new Error(
+ JSON.stringify({
+ code: AGENT_UNREACHABLE,
+ message: `Agent with id "${agentId}" is no longer reachable.`,
+ }),
+ );
}
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
index c50f8c610..4b7399a59 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#harness/handles/store.js";
+import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#subagents/handles/store.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
import { SESSION_TASKS_STATE_KEY, type SessionTaskIndexEntry } from "#tasks/session-index.js";
@@ -45,7 +45,7 @@ vi.mock("#execution/effective-agent-config.js", () => ({
vi.mock("#execution/session.js", () => ({
hydrateDurableSession: hydrateDurableSessionMock,
}));
-vi.mock("#execution/remote-agent-dispatch.js", () => ({
+vi.mock("#subagents/remote-dispatch.js", () => ({
resetRemoteAgentSession: resetRemoteAgentSessionMock,
resolveRemoteAgentForAction: resolveRemoteAgentForActionMock,
resolveRemoteAgentStreamHeaders: resolveRemoteAgentStreamHeadersMock,
@@ -432,12 +432,9 @@ function indexedTask(taskId: string): SessionTaskIndexEntry {
taskInboxToken: `${taskId}:inbox`,
createdByTurnId: "turn-1",
metadata: {
- agentId: "ag_local:1",
- kind: "subagent",
- mode: "local",
+ kind: "tool",
name: "research",
},
- operationId: `op-${taskId}`,
taskId,
taskRunId: `run-${taskId}`,
};
@@ -466,7 +463,10 @@ function makeSessionState(
state:
tasks.length === 0
? { [AGENT_HANDLES_STATE_KEY]: { handles } }
- : { [AGENT_HANDLES_STATE_KEY]: { handles }, [SESSION_TASKS_STATE_KEY]: { tasks } },
+ : {
+ [AGENT_HANDLES_STATE_KEY]: { handles },
+ [SESSION_TASKS_STATE_KEY]: { tasks, version: 2 },
+ },
},
version: 1,
},
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.ts
index f825a5004..1c920cb80 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts
@@ -8,9 +8,10 @@ import {
resetRemoteAgentSession,
resolveRemoteAgentForAction,
resolveRemoteAgentStreamHeaders,
-} from "#execution/remote-agent-dispatch.js";
+} from "#subagents/remote-dispatch.js";
import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
+import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
+import { getAgentHandleStore } from "#subagents/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
import { getSessionTaskIndex } from "#tasks/session-index.js";
@@ -52,7 +53,7 @@ export async function terminateChildSessionsStep(input: {
const taskEntries = readSessionTaskIndex(session.state, session.sessionId);
const handles = getAgentHandleStore(session.state)?.handles ?? [];
const hasRemoteHandle = handles.some(
- (handle) => handle.phase !== "starting" && handle.address.kind === "agent/remote",
+ (handle) => "address" in handle && handle.address.kind === "agent/remote",
);
let runtimeContext:
| {
@@ -77,7 +78,7 @@ export async function terminateChildSessionsStep(input: {
for (const entry of taskEntries) {
try {
await cancelOwnedTask({
- bundle,
+ cancelOwnedWork: cancelBackgroundAgentTask,
entry,
serializedContext: input.serializedContext,
session: runtimeSession,
@@ -96,10 +97,9 @@ export async function terminateChildSessionsStep(input: {
}
for (const handle of handles) {
- if (handle.phase === "starting") {
- log.debug("skipping starting child without a session id", {
+ if (!("address" in handle)) {
+ log.debug("skipping unaddressed child", {
agentId: handle.identity.id,
- kind: handle.target.kind,
parentSessionId: session.sessionId,
});
continue;
diff --git a/packages/eve/src/execution/tool-run/background.test.ts b/packages/eve/src/execution/tool-run/background.test.ts
deleted file mode 100644
index 376f23d69..000000000
--- a/packages/eve/src/execution/tool-run/background.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { parseWorkflowToolInput } from "./background.js";
-
-describe("parseWorkflowToolInput", () => {
- it("passes a JSON object through", () => {
- expect(parseWorkflowToolInput({ service: "api" }, "deploy")).toEqual({ service: "api" });
- });
-
- it("rejects an input that cannot cross the run boundary, naming the tool", () => {
- for (const input of [new Date(0), "api", 42, null, undefined, ["api"]]) {
- expect(() => parseWorkflowToolInput(input, "deploy")).toThrow(
- /Tool "deploy" is a workflow, so its parsed input must be a JSON object/u,
- );
- }
- });
-});
diff --git a/packages/eve/src/execution/tool-run/background.ts b/packages/eve/src/execution/tool-run/background.ts
deleted file mode 100644
index 3d0dc9933..000000000
--- a/packages/eve/src/execution/tool-run/background.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { buildCallbackContext } from "#context/build-callback-context.js";
-import { deriveRunOwner } from "#execution/tool-run/messages.js";
-import { startToolRun } from "#execution/tool-run/start.js";
-import { WORKFLOW_TOOL_EXECUTOR_KIND, type ToolRunAddress } from "#execution/tool-run/types.js";
-import { getHarnessEmissionState } from "#harness/emission.js";
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { type JsonObject, parseJsonObject } from "#shared/json.js";
-import type { ToolExecuteOptions } from "#tools/definition.js";
-import type { TaskDelegated, TaskExec, TaskExecutorBinding } from "#tools/task.js";
-
-/** Harness `execute` for a background workflow tool: starts the run as the task's executor. */
-export function createWorkflowToolBackgroundExecute(input: {
- readonly toolName: string;
- readonly workflowId: string;
-}): NonNullable<HarnessToolDefinition["execute"]> {
- return async (
- toolInput: unknown,
- options: ToolExecuteOptions,
- task?: TaskExec,
- ): Promise<TaskDelegated> => {
- if (task === undefined) {
- throw new Error(`Background tool "${input.toolName}" requires a task runtime.`);
- }
-
- const started = await startToolRun({
- callId: options.toolCallId,
- input: parseWorkflowToolInput(toolInput, input.toolName),
- owner: deriveRunOwner(task.task.taskInboxToken),
- session: buildCallbackContext().session,
- stepIndex: getHarnessEmissionState(task.session.state).stepIndex,
- toolName: input.toolName,
- workflowId: input.workflowId,
- });
-
- return task.delegated({
- executor: createWorkflowToolExecutorBinding(started),
- receipt: {},
- });
- };
-}
-
-export function createWorkflowToolExecutorBinding(data: ToolRunAddress): TaskExecutorBinding {
- return {
- data: { hookToken: data.hookToken, runId: data.runId },
- kind: WORKFLOW_TOOL_EXECUTOR_KIND,
- };
-}
-
-/** Reads the tool run recorded on a task's executor binding, if that is what runs it. */
-export function readWorkflowToolExecutor(
- binding: TaskExecutorBinding | undefined,
-): ToolRunAddress | undefined {
- if (binding?.kind !== WORKFLOW_TOOL_EXECUTOR_KIND) return undefined;
- const { hookToken, runId } = binding.data;
- return typeof hookToken === "string" && typeof runId === "string"
- ? { hookToken, runId }
- : undefined;
-}
-
-/** The input crosses the run's serialization boundary; a schema may emit a `Date`, which cannot. */
-export function parseWorkflowToolInput(toolInput: unknown, toolName: string): JsonObject {
- try {
- return parseJsonObject(toolInput);
- } catch (error) {
- throw new TypeError(
- `Tool "${toolName}" is a workflow, so its parsed input must be a JSON object.`,
- { cause: error },
- );
- }
-}
diff --git a/packages/eve/src/execution/tool-run/dispatch.ts b/packages/eve/src/execution/tool-run/dispatch.ts
deleted file mode 100644
index dda43edbe..000000000
--- a/packages/eve/src/execution/tool-run/dispatch.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import type { PreparedRuntimeActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";
-import { deriveRunOwner } from "#execution/tool-run/messages.js";
-import { startToolRun } from "#execution/tool-run/start.js";
-import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
-import { recordToolRun } from "#harness/tool-runs.js";
-import { createLogger, logError } from "#internal/logging.js";
-import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
-import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
-import type { PendingDispatchAction, PendingWorkflowToolAction } from "#shared/dispatch-action.js";
-import { toError } from "#shared/errors.js";
-
-const log = createLogger("execution.tool-run");
-
-export function isWorkflowToolAction(
- action: PendingDispatchAction,
-): action is PendingWorkflowToolAction {
- return action.target.kind === "workflow-tool-call";
-}
-
-/**
- * Starts the run and records it on the session so the turn can bind its
- * result, route its requests, and cancel it. A start failure settles the call
- * with an error and records nothing, so nothing is left to cancel.
- */
-export async function startWorkflowTool(input: {
- readonly action: PendingWorkflowToolAction;
- readonly batchEvent: {
- readonly sequence: number;
- readonly stepIndex: number;
- readonly turnId: string;
- };
- readonly ownerInboxToken: string | undefined;
- readonly prepared: Pick<
- PreparedRuntimeActionDispatch,
- "auth" | "initiatorAuth" | "parentSession"
- >;
- readonly session: RuntimeSession;
-}): Promise<{ readonly result?: RuntimeToolResultActionResult; readonly session: RuntimeSession }> {
- const { action, batchEvent, prepared, session } = input;
- if (input.ownerInboxToken === undefined) {
- throw new Error(
- `Workflow tool "${action.toolName}" was dispatched without the turn inbox its run reports to.`,
- );
- }
- try {
- const started = await startToolRun({
- callId: action.callId,
- input: action.input,
- owner: deriveRunOwner(input.ownerInboxToken),
- session: {
- auth: { current: prepared.auth, initiator: prepared.initiatorAuth },
- id: session.sessionId,
- parent: prepared.parentSession,
- turn: { id: batchEvent.turnId, sequence: batchEvent.sequence },
- },
- stepIndex: batchEvent.stepIndex,
- toolName: action.toolName,
- workflowId: action.target.workflowId,
- });
- return {
- session: recordToolRun(session, {
- callId: action.callId,
- hookToken: started.hookToken,
- runId: started.runId,
- toolName: action.toolName,
- }),
- };
- } catch (error) {
- logError(log, "workflow tool run failed to start", error, {
- callId: action.callId,
- toolName: action.toolName,
- });
- return {
- result: createRuntimeToolResultFromValue({
- callId: action.callId,
- isError: true,
- output: toError(error),
- toolName: action.toolName,
- }),
- session,
- };
- }
-}
diff --git a/packages/eve/src/execution/tool-run/messages.ts b/packages/eve/src/execution/tool-run/messages.ts
deleted file mode 100644
index daca198b8..000000000
--- a/packages/eve/src/execution/tool-run/messages.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { createHook, defineHook, type Hook } from "#compiled/@workflow/core/index.js";
-
-import { resumeHookStep } from "#execution/tool-run/resume-hook-step.js";
-import { toolRunAnswerToken } from "#harness/tool-runs.js";
-
-import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
-import type { JsonObject, JsonValue } from "#shared/json.js";
-
-export interface ToolRunOwner {
- readonly outcome: string;
- readonly report: string;
- readonly request: string;
-}
-
-/** Identifies the sending run to an owner that shares its channels across many runs. */
-export interface RunRef {
- readonly callId: string;
- /** The tool's parsed input, shown as the request's action when the run asks. */
- readonly input: JsonObject;
- readonly runId: string;
- /** Stream coordinates of the model call that made the tool call. */
- readonly sequence: number;
- readonly stepIndex: number;
- readonly toolName: string;
- readonly turnId: string;
-}
-
-export type RunOutcome =
- | { readonly status: "completed"; readonly output: JsonValue }
- | { readonly status: "failed"; readonly error: unknown }
- | { readonly status: "cancelled"; readonly reason?: string };
-
-/** Progress sent up from a run; the owner streams it as a turn partial or a task update. */
-export interface RunReport {
- readonly from: RunRef;
- readonly update: JsonValue;
-}
-
-/** A question sent up from a run; the owner puts it to the human and resumes `answerToken` with the reply. */
-export interface RunRequestMessage {
- readonly answerToken: string;
- readonly from: RunRef;
- readonly request: ToolInputRequest;
-}
-
-/** The end of a run, sent up once; the owner settles the tool call or the task with it. */
-export interface RunOutcomeMessage {
- readonly from: RunRef;
- readonly result: RunOutcome;
-}
-
-export const reportHook = defineHook<RunReport>();
-export const requestHook = defineHook<RunRequestMessage>();
-export const outcomeHook = defineHook<RunOutcomeMessage>();
-
-/** Derived from the owner's inbox token so owner and run agree without exchanging tokens. */
-export function deriveRunOwner(inboxToken: string): ToolRunOwner {
- return {
- outcome: `${inboxToken}:outcome`,
- report: `${inboxToken}:report`,
- request: `${inboxToken}:request`,
- };
-}
-
-export type RunControlMessage = { readonly kind: "cancel"; readonly reason: string };
-
-// Not a zod schema: this runs in the replayed body, and zod would ship in every function bundle.
-export function isRunControlMessage(value: unknown): value is RunControlMessage {
- if (typeof value !== "object" || value === null) return false;
- const { kind, reason } = value as { kind?: unknown; reason?: unknown };
- return kind === "cancel" && typeof reason === "string";
-}
-
-// Carried on `ctx` under a global-registry symbol: the framework and application
-// driver layers are separate bundles and share only the objects they pass around.
-const RUN_CONTEXT = Symbol.for("eve.tool-run.context");
-
-interface RunContext {
- answerSeq: number;
- readonly from: RunRef;
- readonly owner: ToolRunOwner;
-}
-
-export function attachRunContext(ctx: ToolContext, context: Omit<RunContext, "answerSeq">): void {
- Object.defineProperty(ctx, RUN_CONTEXT, {
- enumerable: false,
- value: { ...context, answerSeq: 0 },
- });
-}
-
-function readRunContext(ctx: ToolContext): RunContext {
- const context = (ctx as { [RUN_CONTEXT]?: RunContext })[RUN_CONTEXT];
- if (context === undefined) {
- throw new Error(
- 'ask() must be called with the context of a workflow tool body ("use workflow").',
- );
- }
- return context;
-}
-
-/**
- * Asks the human on the session's channel and returns the hook the answer
- * resumes, as `createHook` would: await it for the answer, or race it against
- * a `sleep` for a deadline. Synchronous because a `Hook` is thenable: an async
- * `ask` would resolve to the answer, never the hook.
- */
-export function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> {
- const context = readRunContext(ctx);
- const answer = createHook<ToolInputResponse>({
- token: toolRunAnswerToken(context.from.runId, context.answerSeq++),
- });
- const message: RunRequestMessage = { answerToken: answer.token, from: context.from, request };
- void resumeHookStep(context.owner.request, message);
- return answer;
-}
diff --git a/packages/eve/src/execution/tool-run/owner-inbox.ts b/packages/eve/src/execution/tool-run/owner-inbox.ts
deleted file mode 100644
index e7c13c8c4..000000000
--- a/packages/eve/src/execution/tool-run/owner-inbox.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import type { SubagentInputRequestHookPayload } from "#channel/types.js";
-import type {
- RunOutcomeMessage,
- RunRef,
- RunReport,
- RunRequestMessage,
-} from "#execution/tool-run/messages.js";
-import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
-import type { InputRequest } from "#shared/input.js";
-import type { JsonValue } from "#shared/json.js";
-import type { TaskCommand, TaskInboundUpdate } from "#tasks/types.js";
-import type { ToolInputRequest } from "#tools/definition.js";
-
-// Type-only imports: these run in the turn and task driver bodies.
-
-/** A cancelled run settles the call as an error so the owner never waits on it. */
-export function runOutcomeToToolResult(message: RunOutcomeMessage): RuntimeToolResultActionResult {
- const { from, result } = message;
- if (result.status === "completed") {
- return {
- callId: from.callId,
- kind: "tool-result",
- output: result.output,
- toolName: from.toolName,
- };
- }
- const output: JsonValue =
- result.status === "failed"
- ? errorMessage(result.error)
- : (result.reason ?? "The tool run was cancelled.");
- return {
- callId: from.callId,
- isError: true,
- kind: "tool-result",
- output,
- toolName: from.toolName,
- };
-}
-
-function errorMessage(error: unknown): string {
- if (typeof error === "object" && error !== null && "message" in error) {
- const message = (error as { message?: unknown }).message;
- if (typeof message === "string") return message;
- }
- return String(error);
-}
-
-/** The answer hook token is both the request id and the route, so one resume reaches the body. */
-export function runRequestToInputRequestPayload(
- message: RunRequestMessage,
-): SubagentInputRequestHookPayload {
- const { answerToken, from, request } = message;
- return {
- callId: from.callId,
- childContinuationToken: answerToken,
- childSessionId: from.runId,
- event: {
- requests: [toInputRequest(request, from, answerToken)],
- sequence: from.sequence,
- stepIndex: from.stepIndex,
- turnId: from.turnId,
- },
- kind: "subagent-input-request",
- subagentName: from.toolName,
- };
-}
-
-function toInputRequest(request: ToolInputRequest, from: RunRef, requestId: string): InputRequest {
- if (typeof request.prompt !== "string" || request.prompt.length === 0) {
- throw new TypeError("A tool run request needs a non-empty `prompt`.");
- }
- const normalized: InputRequest = {
- action: { callId: from.callId, input: from.input, kind: "tool-call", toolName: from.toolName },
- kind: "question",
- prompt: request.prompt,
- requestId,
- };
- if (request.allowFreeform !== undefined) normalized.allowFreeform = request.allowFreeform;
- if (request.display !== undefined) normalized.display = request.display;
- if (request.options !== undefined) normalized.options = [...request.options];
- return normalized;
-}
-
-export function runReportToTaskUpdate(
- message: RunReport,
- taskId: string,
- updateIndex: number,
-): TaskInboundUpdate {
- return {
- callId: message.from.callId,
- kind: "task-update",
- message: typeof message.update === "string" ? message.update : JSON.stringify(message.update),
- updateEpoch: taskId,
- updateIndex,
- };
-}
-
-/** A cancelled run only settles the executor: the task itself was already cancelled. */
-export function runOutcomeToTaskCommand(message: RunOutcomeMessage): TaskCommand {
- const { result } = message;
- if (result.status === "completed") {
- return { data: result.output, kind: "complete", lifecycle: "terminal" };
- }
- if (result.status === "failed") {
- return { data: errorMessage(result.error), kind: "fail", lifecycle: "terminal" };
- }
- return { kind: "settle-executor" };
-}
diff --git a/packages/eve/src/execution/tool-run/owner.ts b/packages/eve/src/execution/tool-run/owner.ts
deleted file mode 100644
index ab4f23506..000000000
--- a/packages/eve/src/execution/tool-run/owner.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { disposeHook } from "#execution/hook-ownership.js";
-import {
- deriveRunOwner,
- outcomeHook,
- reportHook,
- requestHook,
- type RunOutcomeMessage,
- type RunReport,
- type RunRequestMessage,
-} from "#execution/tool-run/messages.js";
-import { type ChannelReader, createChannelReader } from "#execution/tool-run/owner-channels.js";
-
-/** In read priority: what a run said before its outcome lands first. */
-export type RunOwnerReaders = readonly [
- ChannelReader<"report", RunReport>,
- ChannelReader<"request", RunRequestMessage>,
- ChannelReader<"outcome", RunOutcomeMessage>,
-];
-
-export interface RunOwnerChannels {
- readonly readers: RunOwnerReaders;
- dispose(): Promise<void>;
-}
-
-export function openRunOwnerChannels(inboxToken: string): RunOwnerChannels {
- const owner = deriveRunOwner(inboxToken);
- const report = reportHook.create({ token: owner.report });
- const request = requestHook.create({ token: owner.request });
- const outcome = outcomeHook.create({ token: owner.outcome });
- return {
- readers: [
- createChannelReader("report", report),
- createChannelReader("request", request),
- createChannelReader("outcome", outcome),
- ],
- async dispose() {
- await Promise.all([disposeHook(report), disposeHook(request), disposeHook(outcome)]);
- },
- };
-}
diff --git a/packages/eve/src/execution/tool-run/start.ts b/packages/eve/src/execution/tool-run/start.ts
deleted file mode 100644
index 4caea61c1..000000000
--- a/packages/eve/src/execution/tool-run/start.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { ToolRunWorkflowInput } from "#execution/tool-run/types.js";
-import {
- startWorkflowOnCurrentDeployment,
- toolRunWorkflowReference,
- waitForCommandHookOwner,
-} from "#execution/workflow-runtime.js";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-
-// Derived from the call alone so a replayed dispatch starts a duplicate that
-// loses the claim and still resolves to the run that owns the call.
-export function deriveToolRunHookToken(input: {
- readonly callId: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
-}): string {
- return `eve:tool-run:${deriveAgentOperationId(input)}`;
-}
-
-/** Resolves once the run owns its hook. Call from inside a `"use step"` body. */
-export async function startToolRun(
- input: Omit<ToolRunWorkflowInput, "hookToken">,
-): Promise<{ readonly hookToken: string; readonly runId: string }> {
- const hookToken = deriveToolRunHookToken({
- callId: input.callId,
- parentSessionId: input.session.id,
- parentTurnId: input.session.turn.id,
- });
- const workflowInput: ToolRunWorkflowInput = { ...input, hookToken };
- await startWorkflowOnCurrentDeployment(toolRunWorkflowReference, [workflowInput]);
- const owner = await waitForCommandHookOwner(hookToken);
- return { hookToken, runId: owner.runId };
-}
diff --git a/packages/eve/src/execution/tool-run/types.ts b/packages/eve/src/execution/tool-run/types.ts
deleted file mode 100644
index 1da635aef..000000000
--- a/packages/eve/src/execution/tool-run/types.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { SessionContext } from "#context/session-context.js";
-import type { ToolRunOwner } from "#execution/tool-run/messages.js";
-import type { JsonObject } from "#shared/json.js";
-
-export type ToolRunSessionContext = SessionContext["session"];
-
-export interface ToolRunWorkflowInput {
- readonly callId: string;
- /** Deterministic per call: a replayed start re-derives it, loses the claim, and exits. */
- readonly hookToken: string;
- readonly input: JsonObject;
- readonly owner: ToolRunOwner;
- readonly session: ToolRunSessionContext;
- /** Harness step index of the model call that made this tool call. */
- readonly stepIndex: number;
- readonly toolName: string;
- readonly workflowId: string;
-}
-
-export interface ToolRunAddress {
- readonly hookToken: string;
- readonly runId: string;
-}
-
-export const WORKFLOW_TOOL_EXECUTOR_KIND = "workflow-tool";
diff --git a/packages/eve/src/execution/tool-run/workflow.ts b/packages/eve/src/execution/tool-run/workflow.ts
deleted file mode 100644
index fadebda86..000000000
--- a/packages/eve/src/execution/tool-run/workflow.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { getWorkflowMetadata, sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
-
-import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
-import {
- attachRunContext,
- type RunOutcome,
- type RunOutcomeMessage,
- type RunRef,
- type RunReport,
-} from "#execution/tool-run/messages.js";
-import { openRunControlInbox } from "#execution/tool-run/run-control.js";
-import type { ToolRunWorkflowInput } from "#execution/tool-run/types.js";
-import { resumeHookStep } from "#execution/tool-run/resume-hook-step.js";
-import { normalizeSerializableError } from "#execution/workflow-errors.js";
-import { readRegisteredWorkflow } from "#execution/workflow-registry.js";
-import type { ToolContext } from "#tools/definition.js";
-import type { JsonValue } from "#shared/json.js";
-
-/** How long a cancelled run waits for its body to unwind before it ends. */
-const CANCEL_GRACE = "30s";
-
-function noop(): void {}
-
-type WorkflowToolStream = AsyncIterable<JsonValue, JsonValue | undefined, void>;
-type WorkflowToolExecute = (
- input: unknown,
- ctx: ToolContext,
-) => Promise<JsonValue> | WorkflowToolStream;
-
-/**
- * Runs one authored workflow tool call. The run's own hook is its identity
- * claim and its control inbox: a duplicate start loses the claim and exits; a
- * `cancel` message aborts `ctx.abortSignal`, and the run waits up to
- * {@link CANCEL_GRACE} for the body to unwind before ending as cancelled, so a
- * body parked on a hook or sleep cannot keep a cancelled run alive.
- */
-export async function toolRunWorkflow(input: ToolRunWorkflowInput): Promise<void> {
- "use workflow";
-
- const control = openRunControlInbox(input.hookToken);
- let ownsInbox = false;
-
- try {
- try {
- await claimHookOwnership(control.hook);
- ownsInbox = true;
- } catch (error) {
- if (isHookConflictError(error)) return;
- throw error;
- }
-
- const runId = readRunId();
- const from: RunRef = {
- callId: input.callId,
- input: input.input,
- runId,
- sequence: input.session.turn.sequence,
- stepIndex: input.stepIndex,
- toolName: input.toolName,
- turnId: input.session.turn.id,
- };
- const ctx = createWorkflowToolContext(input, control.signal);
- attachRunContext(ctx, { from, owner: input.owner });
-
- const body = runBody(input, ctx, from);
- // A body abandoned by a lost race must not surface as an unhandled rejection.
- const settled = body.catch(noop);
-
- let outcome: RunOutcome;
- try {
- // Racing the control read is what drives it; an unawaited durable read
- // is not scheduled under replay, so a cancel would never be observed.
- outcome = { output: await Promise.race([body, control.cancelled]), status: "completed" };
- } catch (error) {
- if (!control.signal.aborted) {
- outcome = { error: normalizeSerializableError(error), status: "failed" };
- } else {
- await Promise.race([settled, workflowSleep(CANCEL_GRACE)]);
- outcome = { reason: control.reason(), status: "cancelled" };
- }
- }
-
- const message: RunOutcomeMessage = { from, result: outcome };
- // An owner that cancelled the run may have finished before the grace
- // period ended; a cancelled outcome has nobody left to reach.
- await resumeHookStep(input.owner.outcome, message, {
- ifPresent: outcome.status === "cancelled",
- });
- } finally {
- if (ownsInbox) await disposeHook(control.hook);
- }
-}
-
-async function runBody(
- input: ToolRunWorkflowInput,
- ctx: ToolContext,
- from: RunRef,
-): Promise<JsonValue> {
- const execute = resolveWorkflowToolExecute(input);
- const result = execute(input.input, ctx);
- if (!isAsyncIterable(result)) return await result;
-
- // `for await` discards a generator's return value; it is the tool result.
- const iterator = result[Symbol.asyncIterator]();
- let last: JsonValue | undefined;
- let next = await iterator.next();
- while (next.done !== true) {
- last = next.value;
- const report: RunReport = { from, update: next.value };
- await resumeHookStep(input.owner.report, report);
- next = await iterator.next();
- }
- return next.value ?? last ?? null;
-}
-
-function isAsyncIterable(value: unknown): value is WorkflowToolStream {
- return (
- typeof value === "object" &&
- value !== null &&
- typeof (value as WorkflowToolStream)[Symbol.asyncIterator] === "function"
- );
-}
-
-function readRunId(): string {
- const runId = getWorkflowMetadata().workflowRunId;
- if (typeof runId !== "string") {
- throw new Error("The tool run has no workflow run id.");
- }
- return runId;
-}
-
-function resolveWorkflowToolExecute(input: ToolRunWorkflowInput): WorkflowToolExecute {
- const execute = readRegisteredWorkflow(input.workflowId);
- if (typeof execute !== "function") {
- throw new Error(
- `Tool "${input.toolName}" is not registered as a workflow in this deployment (${input.workflowId}). ` +
- "The tool was renamed or removed after this run started.",
- );
- }
- return execute as WorkflowToolExecute;
-}
-
-function createWorkflowToolContext(input: ToolRunWorkflowInput, signal: AbortSignal): ToolContext {
- const { callId, session, toolName } = input;
- const unavailable = (member: string, hint: string): never => {
- throw new Error(
- `ctx.${member} is not available inside a workflow tool; ${hint}. ` +
- `Tool "${toolName}" runs as a durable workflow body, which only replays deterministic code.`,
- );
- };
-
- return {
- abortSignal: signal,
- callId,
- getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),
- getSkill: () => unavailable("getSkill()", "skills are read through the session sandbox"),
- getToken: () =>
- unavailable("getToken()", 'read credentials from the environment inside a "use step" helper'),
- requireAuth: () => unavailable("requireAuth()", "a workflow body cannot park on authorization"),
- session,
- toolName,
- };
-}
diff --git a/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts b/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts
new file mode 100644
index 000000000..67be307c1
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/accept-event-step.test.ts
@@ -0,0 +1,138 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { readDurableSession } from "#execution/durable-session-store.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { acceptTaskAuthorizationEventStep } from "#execution/tools/subagent/accept-event-step.js";
+import { setAgentHandleStore } from "#subagents/handles/store.js";
+
+vi.mock("#execution/durable-session-store.js", () => ({ readDurableSession: vi.fn() }));
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({ readLatestTaskView: vi.fn() }));
+
+const sessionState = {
+ continuationToken: "parent-token",
+ emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
+ hasProxyInputRequests: false,
+ sessionId: "parent-session",
+ version: 1,
+} as const;
+const hookPayload = {
+ callId: "call-1",
+ childSessionId: "child-1",
+ event: {
+ data: {
+ description: "Authorize Linear",
+ name: "linear",
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn-child",
+ },
+ type: "authorization.required" as const,
+ },
+ kind: "subagent-authorization-event" as const,
+ subagentName: "research",
+};
+const taskIndex = {
+ "eve.tasks": {
+ tasks: [
+ {
+ createdByTurnId: "turn-1",
+ metadata: { kind: "tool", name: "export" },
+ taskId: "task-1",
+ taskInboxToken: "task-token",
+ taskRunId: "task-run",
+ },
+ ],
+ version: 2,
+ },
+};
+
+function mockSession(handles: readonly unknown[]): void {
+ vi.mocked(readDurableSession).mockResolvedValue({
+ agent: { system: "" },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: setAgentHandleStore(taskIndex, { handles: handles as never }),
+ });
+}
+
+describe("acceptTaskAuthorizationEventStep", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ mockSession([
+ {
+ address: {
+ callbackBaseUrl: "https://parent.example",
+ kind: "agent/remote",
+ sessionId: "child-1",
+ url: "https://remote.example",
+ },
+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },
+ operationId: "operation-1",
+ phase: "claimed",
+ ownerId: "task-1",
+ },
+ ]);
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: { kind: "tool", name: "export" },
+ status: "working",
+ taskId: "task-1",
+ });
+ });
+
+ it("accepts an authorization event from the task's claimed child agent", async () => {
+ await expect(
+ acceptTaskAuthorizationEventStep({
+ delivery: { hookPayload, taskId: "task-1" },
+ sessionState,
+ }),
+ ).resolves.toBe(true);
+ expect(readLatestTaskView).toHaveBeenCalledWith({ taskRunId: "task-run" });
+ });
+
+ it("accepts the first authorization event while the task child start is still reserved", async () => {
+ mockSession([
+ {
+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },
+ operationId: "operation-1",
+ phase: "reserved",
+ ownerId: "task-1",
+ },
+ ]);
+
+ await expect(
+ acceptTaskAuthorizationEventStep({
+ delivery: { hookPayload, taskId: "task-1" },
+ sessionState,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it("rejects an authorization event from a child session not claimed by the task", async () => {
+ await expect(
+ acceptTaskAuthorizationEventStep({
+ delivery: {
+ hookPayload: { ...hookPayload, childSessionId: "other-child" },
+ taskId: "task-1",
+ },
+ sessionState,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it("rejects an authorization event once the task is terminal", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ lastOutput: { data: "done", type: "result" },
+ metadata: { kind: "tool", name: "export" },
+ status: "completed",
+ taskId: "task-1",
+ });
+
+ await expect(
+ acceptTaskAuthorizationEventStep({
+ delivery: { hookPayload, taskId: "task-1" },
+ sessionState,
+ }),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/packages/eve/src/execution/tools/subagent/accept-event-step.ts b/packages/eve/src/execution/tools/subagent/accept-event-step.ts
new file mode 100644
index 000000000..17d621646
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/accept-event-step.ts
@@ -0,0 +1,40 @@
+import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import { getAgentHandleStore } from "#subagents/handles/store.js";
+import { findSessionTaskEntry } from "#tasks/session-index.js";
+import { isTerminalTaskStatus, type TaskAuthorizationEventDelivery } from "#tasks/types.js";
+
+/** Validates that a task child's authorization event came from an agent the task owns. */
+export async function acceptTaskAuthorizationEventStep(input: {
+ readonly delivery: TaskAuthorizationEventDelivery;
+ readonly sessionState: DurableSessionState;
+}): Promise<boolean> {
+ "use step";
+
+ const { hookPayload, taskId } = input.delivery;
+ const durableSession = await readDurableSession(input.sessionState);
+ const entry = findSessionTaskEntry(durableSession.state, taskId);
+ if (entry === undefined) return false;
+
+ const handles = getAgentHandleStore(durableSession.state)?.handles ?? [];
+ const claimed = handles.find(
+ (candidate) =>
+ candidate.phase === "claimed" &&
+ candidate.ownerId === taskId &&
+ candidate.identity.name === hookPayload.subagentName &&
+ candidate.address.sessionId === hookPayload.childSessionId,
+ );
+ // A just-started task child can emit authorization before the parent session
+ // has processed the matching confirm command. Accept only an unambiguous
+ // reservation; confirmed children still bind by child session id.
+ const reserved = handles.filter(
+ (candidate) =>
+ candidate.phase === "reserved" &&
+ candidate.ownerId === taskId &&
+ candidate.identity.name === hookPayload.subagentName,
+ );
+ if (claimed === undefined && reserved.length !== 1) return false;
+
+ const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
+ return view !== undefined && !isTerminalTaskStatus(view.status);
+}
diff --git a/packages/eve/src/execution/tools/subagent/emit-called-step.ts b/packages/eve/src/execution/tools/subagent/emit-called-step.ts
new file mode 100644
index 000000000..c96975fc1
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/emit-called-step.ts
@@ -0,0 +1,33 @@
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import { callAdapterEventHandler } from "#channel/adapter.js";
+import { deserializeContext, serializeContext } from "#context/serialize.js";
+import {
+ encodeMessageStreamEvent,
+ stampMessageStreamEvent,
+ type UnstampedMessageStreamEvent,
+} from "#protocol/message.js";
+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+
+/** Emits an already-projected task-owned `subagent.called` event on the parent stream. */
+export async function emitTaskSubagentCalledStep(input: {
+ readonly event: UnstampedMessageStreamEvent;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+}): Promise<{ readonly serializedContext: Record<string, unknown> }> {
+ "use step";
+
+ const ctx = await deserializeContext(input.serializedContext);
+ const adapter = ctx.require(ChannelKey);
+ const emitted = await callAdapterEventHandler(
+ adapter,
+ input.event,
+ buildAdapterContext(adapter, ctx),
+ );
+ const writer = input.parentWritable.getWriter();
+ try {
+ await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(emitted)));
+ } finally {
+ writer.releaseLock();
+ }
+ return { serializedContext: serializeContext(ctx) };
+}
diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
new file mode 100644
index 000000000..5487fe46c
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
@@ -0,0 +1,552 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
+import { agent, type AgentInvocationReply } from "#execution/tools/subagent/invoke-agent.js";
+import type { ToolContext } from "#tools/definition.js";
+
+const mocks = vi.hoisted(() => ({
+ claimHookOwnership: vi.fn(),
+ createHook: vi.fn(),
+ disposeHook: vi.fn(),
+ resumeHook: vi.fn(),
+}));
+
+vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
+ ...(await importOriginal()),
+ createHook: mocks.createHook,
+}));
+vi.mock("#execution/hook-ownership.js", () => ({
+ claimHookOwnership: mocks.claimHookOwnership,
+ disposeHook: mocks.disposeHook,
+}));
+vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
+ resumeHookStep: (...args: unknown[]) => mocks.resumeHook(...args),
+}));
+beforeEach(() => vi.resetAllMocks());
+
+describe("background agent invocation routing", () => {
+ it("stops waiting when the workflow body is cancelled", async () => {
+ const controller = new AbortController();
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
+ token: "agent-reply",
+ });
+ const ctx = { abortSignal: controller.signal, callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ admission: Promise.resolve({ status: "accepted" }),
+ from: {
+ callId: "call-1",
+ execution: "background",
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ const result = agent(ctx, { key: "research", message: "Find it", target: "research" });
+ await vi.waitFor(() => expect(mocks.resumeHook).toHaveBeenCalledOnce());
+ controller.abort(new Error("task cancelled"));
+
+ await expect(result).rejects.toThrow("task cancelled");
+ expect(mocks.disposeHook).toHaveBeenCalledOnce();
+ });
+
+ it("sends the invocation through the task owner after admission", async () => {
+ const result = {
+ callId: "call-1:research",
+ kind: "subagent-result" as const,
+ origin: "child" as const,
+ outcome: {
+ kind: "parked" as const,
+ result: { kind: "succeeded" as const, output: "available" },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ output: "available",
+ subagentName: "research",
+ };
+ const replies: AgentInvocationReply[] = [{ kind: "runtime-action-result", results: [result] }];
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: async () =>
+ replies.length > 0
+ ? { done: false as const, value: replies.shift()! }
+ : { done: true as const, value: undefined },
+ }),
+ token: "agent-reply",
+ });
+ mocks.resumeHook.mockImplementation(async () => undefined);
+ const from: WorkflowToolRunRef = {
+ callId: "call-1",
+ execution: "background",
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ };
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ admission: Promise.resolve({ status: "accepted" }),
+ from,
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ await expect(
+ agent(ctx, { key: "research", message: "Find it", target: "research" }),
+ ).resolves.toBe("available");
+
+ expect(mocks.claimHookOwnership).toHaveBeenCalledWith(
+ expect.objectContaining({ token: "agent-reply" }),
+ );
+ expect(mocks.claimHookOwnership.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.resumeHook.mock.invocationCallOrder[0]!,
+ );
+ expect(mocks.resumeHook).toHaveBeenCalledWith("owner-request", {
+ from,
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke",
+ },
+ });
+ });
+
+ it("does not send the invocation before the owning task is admitted", async () => {
+ const admission = Promise.withResolvers<{ readonly status: "accepted" }>();
+ const replies: AgentInvocationReply[] = [
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1:research",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "research",
+ } as never,
+ ],
+ },
+ ];
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: async () =>
+ replies.length > 0
+ ? { done: false as const, value: replies.shift()! }
+ : { done: true as const, value: undefined },
+ }),
+ token: "agent-reply",
+ });
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ admission: admission.promise,
+ from: {
+ callId: "call-1",
+ execution: "background",
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ const result = agent(ctx, { key: "research", message: "Find it", target: "research" });
+ await Promise.resolve();
+ expect(mocks.resumeHook).not.toHaveBeenCalled();
+
+ admission.resolve({ status: "accepted" });
+ await expect(result).resolves.toBe("done");
+ expect(mocks.resumeHook).toHaveBeenCalledTimes(2);
+ });
+
+ it("waits for agent calls inside a blocking workflow tool", async () => {
+ const result = {
+ callId: "call-1:research",
+ kind: "subagent-result" as const,
+ origin: "child" as const,
+ outcome: {
+ kind: "parked" as const,
+ result: { kind: "succeeded" as const, output: "inline" },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ output: "inline",
+ subagentName: "research",
+ };
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: vi
+ .fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: { kind: "runtime-action-result", results: [result] },
+ })
+ .mockResolvedValue({ done: true }),
+ }),
+ token: "agent-reply",
+ });
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ from: {
+ callId: "call-1",
+ execution: "blocking",
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ await expect(
+ agent(ctx, { key: "research", message: "Find it", target: "research" }),
+ ).resolves.toBe("inline");
+ expect(mocks.resumeHook).toHaveBeenCalledTimes(2);
+ expect(mocks.resumeHook).toHaveBeenNthCalledWith(1, "owner-request", {
+ from: expect.objectContaining({ execution: "blocking", runId: "run-1" }),
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke",
+ },
+ });
+ });
+
+ it("rejects dispatch failures without reporting a child settlement", async () => {
+ const failure = {
+ callId: "call-1:research",
+ isError: true as const,
+ kind: "subagent-result" as const,
+ origin: "dispatch" as const,
+ output: {
+ code: "REMOTE_AGENT_START_FAILED",
+ message: "The remote agent could not be started.",
+ },
+ subagentName: "research",
+ };
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: vi
+ .fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: { kind: "runtime-action-result", results: [failure] },
+ })
+ .mockResolvedValue({ done: true }),
+ }),
+ token: "agent-reply",
+ });
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ from: {
+ callId: "call-1",
+ execution: "blocking",
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+ },
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ await expect(
+ agent(ctx, { key: "research", message: "Find it", target: "research" }),
+ ).rejects.toEqual(failure.output);
+ expect(mocks.resumeHook).toHaveBeenCalledTimes(1);
+ expect(mocks.resumeHook).not.toHaveBeenCalledWith(
+ "owner-request",
+ expect.objectContaining({ request: expect.objectContaining({ kind: "agent-settled" }) }),
+ );
+ });
+
+ it("preserves each child HITL event's coordinates when relaying repeated requests", async () => {
+ const childRequest = (input: {
+ readonly requestId: string;
+ readonly stepIndex: number;
+ }): AgentInvocationReply => ({
+ callId: "call-1",
+ childContinuationToken: "child-continuation",
+ childSessionId: "child-1",
+ event: {
+ requests: [
+ {
+ action: {
+ callId: input.requestId,
+ input: {},
+ kind: "tool-call",
+ toolName: "approval_gate",
+ },
+ kind: "tool-approval",
+ prompt: "Approve?",
+ requestId: input.requestId,
+ },
+ ],
+ sequence: 3,
+ stepIndex: input.stepIndex,
+ turnId: "turn-child",
+ },
+ kind: "subagent-input-request",
+ subagentName: "research",
+ });
+ const replies: AgentInvocationReply[] = [
+ childRequest({ requestId: "approval-1", stepIndex: 1 }),
+ childRequest({ requestId: "approval-2", stepIndex: 2 }),
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1:research",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "research",
+ } as never,
+ ],
+ },
+ ];
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: async () =>
+ replies.length > 0
+ ? { done: false as const, value: replies.shift()! }
+ : { done: true as const, value: undefined },
+ }),
+ token: "agent-reply",
+ });
+ mocks.resumeHook.mockImplementation(async () => undefined);
+ const from: WorkflowToolRunRef = {
+ callId: "call-1",
+ execution: "background",
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-parent",
+ };
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ admission: Promise.resolve({ status: "accepted" }),
+ from,
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ await expect(
+ agent(ctx, { key: "research", message: "Find it", target: "research" }),
+ ).resolves.toBe("done");
+
+ expect(mocks.resumeHook).toHaveBeenNthCalledWith(2, "owner-request", {
+ from,
+ replyTo: "child-continuation",
+ request: {
+ kind: "input-batch",
+ requests: [expect.objectContaining({ requestId: "approval-1" })],
+ },
+ requestCoordinates: { sequence: 3, stepIndex: 1, turnId: "turn-child" },
+ });
+ expect(mocks.resumeHook).toHaveBeenNthCalledWith(3, "owner-request", {
+ from,
+ replyTo: "child-continuation",
+ request: {
+ kind: "input-batch",
+ requests: [expect.objectContaining({ requestId: "approval-2" })],
+ },
+ requestCoordinates: { sequence: 3, stepIndex: 2, turnId: "turn-child" },
+ });
+ });
+
+ it("forwards background authorization as an owner authorization request", async () => {
+ const replies: AgentInvocationReply[] = [
+ {
+ callId: "call-1",
+ childSessionId: "child-1",
+ event: {
+ data: {
+ description: "Authorize Linear",
+ name: "linear",
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn-child",
+ },
+ type: "authorization.required",
+ },
+ kind: "subagent-authorization-event",
+ subagentName: "research",
+ },
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1:research",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "research",
+ } as never,
+ ],
+ },
+ ];
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: async () =>
+ replies.length > 0
+ ? { done: false as const, value: replies.shift()! }
+ : { done: true as const, value: undefined },
+ }),
+ token: "agent-reply",
+ });
+ mocks.resumeHook.mockImplementation(async () => undefined);
+ const from: WorkflowToolRunRef = {
+ callId: "call-1",
+ execution: "background",
+ input: { message: "Find it", target: "research" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 2,
+ toolName: "research",
+ turnId: "turn-1",
+ };
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ admission: Promise.resolve({ status: "accepted" }),
+ from,
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ await expect(
+ agent(ctx, { key: "research", message: "Find it", target: "research" }),
+ ).resolves.toBe("done");
+
+ expect(mocks.resumeHook).toHaveBeenCalledWith("owner-request", {
+ from,
+ replyTo: "agent-reply",
+ request: {
+ event: expect.objectContaining({ kind: "subagent-authorization-event" }),
+ kind: "authorization-request",
+ },
+ });
+ expect(mocks.resumeHook).not.toHaveBeenCalledWith("owner-report", expect.anything());
+ });
+
+ it("forwards task-owned child updates to the workflow tool report channel", async () => {
+ const replies: AgentInvocationReply[] = [
+ {
+ callId: "task-update-call",
+ kind: "task-update",
+ message: "Still working",
+ updateEpoch: "turn-child",
+ updateIndex: 0,
+ },
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1:research",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "research",
+ } as never,
+ ],
+ },
+ ];
+ mocks.createHook.mockReturnValue({
+ [Symbol.asyncIterator]: () => ({
+ next: async () =>
+ replies.length > 0
+ ? { done: false as const, value: replies.shift()! }
+ : { done: true as const, value: undefined },
+ }),
+ token: "agent-reply",
+ });
+ mocks.resumeHook.mockImplementation(async () => undefined);
+ const from: WorkflowToolRunRef = {
+ callId: "call-1",
+ execution: "background",
+ input: { message: "Find it", target: "research" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 2,
+ toolName: "research",
+ turnId: "turn-1",
+ };
+ const ctx = { callId: "call-1" } as ToolContext;
+ attachWorkflowToolRunContext(ctx, {
+ admission: Promise.resolve({ status: "accepted" }),
+ from,
+ owner: {
+ admission: "owner-admission",
+ outcome: "owner-outcome",
+ report: "owner-report",
+ request: "owner-request",
+ },
+ });
+
+ await expect(
+ agent(ctx, { key: "research", message: "Find it", target: "research" }),
+ ).resolves.toBe("done");
+
+ expect(mocks.resumeHook).toHaveBeenCalledWith("owner-report", {
+ from,
+ update: "Still working",
+ });
+ });
+});
diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.ts
new file mode 100644
index 000000000..3abdceac1
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.ts
@@ -0,0 +1,234 @@
+import { createHook } from "#compiled/@workflow/core/index.js";
+
+import type {
+ RuntimeActionResultHookPayload,
+ SubagentAuthorizationEventHookPayload,
+ SubagentInputRequestHookPayload,
+} from "#channel/types.js";
+import {
+ readWorkflowToolRunAdmission,
+ readWorkflowToolRunOwner,
+ readWorkflowToolRunRef,
+} from "#execution/tools/workflow/ask.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import type { RuntimeSubagentChildResult, RuntimeSubagentResult } from "#shared/action-types.js";
+import type { JsonValue } from "#shared/json.js";
+import type { JsonObject } from "#shared/json.js";
+import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
+import type { ToolContext } from "#tools/definition.js";
+import type { TaskInboundUpdate } from "#tasks/types.js";
+
+export type InternalAgentInput = {
+ readonly agentId?: string;
+ readonly message: string;
+ readonly outputSchema?: JsonObject;
+ readonly target: string;
+};
+
+export interface AgentInput {
+ readonly agentId?: string;
+ readonly key: string;
+ readonly message: string;
+ readonly outputSchema?: JsonObject;
+ readonly target: string;
+}
+
+/**
+ * Asks the owning session to spawn an agent for a workflow tool run. Spawning
+ * needs owner-held material (auth, capabilities, admission, the agent handle
+ * store) that a workflow tool body never has.
+ */
+export interface AgentInvocationRequest {
+ readonly input: InternalAgentInput;
+ readonly invocationId: string;
+ readonly kind: "agent-invoke";
+}
+
+/**
+ * Tells the owning session that an owner-spawned agent replied to the run, so
+ * the owner can release the handle it reserved for `agent-invoke`.
+ */
+export interface AgentSettlementRequest {
+ readonly kind: "agent-settled";
+ readonly result: RuntimeSubagentChildResult;
+}
+
+export type AgentInvocationEvent =
+ | SubagentAuthorizationEventHookPayload
+ | SubagentInputRequestHookPayload;
+
+export type AgentInvocationReply =
+ | AgentInvocationEvent
+ | RuntimeActionResultHookPayload
+ | TaskInboundUpdate;
+
+const AGENT_INVOCATION_IDS = Symbol.for("eve.workflow-tool-run.agent-invocation-ids");
+
+/** Invokes an agent from a task-owned background workflow tool. */
+export async function agent(ctx: ToolContext, input: AgentInput): Promise<JsonValue> {
+ validateAgentInput(input, true);
+ return await invokeAgent(
+ ctx,
+ {
+ agentId: input.agentId,
+ message: input.message,
+ outputSchema: input.outputSchema,
+ target: input.target,
+ },
+ { invocationId: `${ctx.callId}:${input.key}` },
+ );
+}
+
+/** Invokes an agent with a framework-selected replay-stable invocation id. */
+export async function invokeAgent(
+ ctx: ToolContext,
+ input: InternalAgentInput,
+ options: { readonly invocationId: string; readonly returnResult: true },
+): Promise<JsonValue | RuntimeSubagentResult>;
+export async function invokeAgent(
+ ctx: ToolContext,
+ input: InternalAgentInput,
+ options: { readonly invocationId: string; readonly returnResult?: false },
+): Promise<JsonValue>;
+export async function invokeAgent(
+ ctx: ToolContext,
+ input: InternalAgentInput,
+ options: { readonly invocationId: string; readonly returnResult?: boolean },
+): Promise<JsonValue | RuntimeSubagentResult> {
+ validateAgentInput(input, false);
+ const run = readWorkflowToolRunRef(ctx);
+ const owner = readWorkflowToolRunOwner(ctx);
+ const admission = readWorkflowToolRunAdmission(ctx);
+ claimInvocationId(ctx, options.invocationId);
+ const replies = createHook<AgentInvocationReply>();
+ let ownsReplies = false;
+ try {
+ await claimHookOwnership(replies);
+ ownsReplies = true;
+ if (admission !== undefined) {
+ const admitted = await admission;
+ if (admitted.status === "rejected") throw new Error(admitted.reason);
+ }
+ await resumeHookStep(owner.request, {
+ from: run,
+ replyTo: replies.token,
+ request: { input, invocationId: options.invocationId, kind: "agent-invoke" },
+ });
+
+ const iterator = replies[Symbol.asyncIterator]();
+ while (true) {
+ const next = await nextAgentReply(iterator, ctx.abortSignal);
+ if (next.done) break;
+ const reply = next.value;
+ if (reply.kind === "runtime-action-result") {
+ const result = reply.results.find(
+ (candidate): candidate is RuntimeSubagentResult =>
+ candidate.kind === "subagent-result" && candidate.callId === options.invocationId,
+ );
+ if (result !== undefined) {
+ if (result.origin === "child") {
+ await resumeHookStep(owner.request, {
+ from: run,
+ replyTo: replies.token,
+ request: { kind: "agent-settled", result },
+ });
+ }
+ if (options.returnResult === true && run.execution === "blocking") return result;
+ if (result.isError === true) throw result.output;
+ return result.output;
+ }
+ continue;
+ }
+ if (reply.kind === "subagent-input-request") {
+ await resumeHookStep(owner.request, {
+ from: run,
+ replyTo: reply.childContinuationToken,
+ request: {
+ kind: "input-batch",
+ requests: reply.event.requests,
+ },
+ requestCoordinates: {
+ sequence: reply.event.sequence,
+ stepIndex: reply.event.stepIndex,
+ turnId: reply.event.turnId,
+ },
+ });
+ continue;
+ }
+ if (reply.kind === "task-update") {
+ await resumeHookStep(owner.report, {
+ from: run,
+ update: reply.message,
+ });
+ continue;
+ }
+ await resumeHookStep(owner.request, {
+ from: run,
+ replyTo: replies.token,
+ request: { event: reply, kind: "authorization-request" },
+ });
+ }
+ } finally {
+ if (ownsReplies) {
+ try {
+ await disposeHook(replies);
+ } catch {
+ // A result or invocation error is authoritative; reply-hook cleanup is best effort.
+ }
+ }
+ }
+ throw new Error(`Agent "${input.target}" closed without a result.`);
+}
+
+async function nextAgentReply(
+ iterator: AsyncIterator<AgentInvocationReply>,
+ signal: AbortSignal | undefined,
+): Promise<IteratorResult<AgentInvocationReply>> {
+ if (signal === undefined) return await iterator.next();
+ if (signal.aborted) throw signal.reason;
+ let rejectAbort: ((reason: unknown) => void) | undefined;
+ const aborted = new Promise<never>((_resolve, reject) => {
+ rejectAbort = reject;
+ });
+ const abort = (): void => rejectAbort?.(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ try {
+ return await Promise.race([iterator.next(), aborted]);
+ } finally {
+ signal.removeEventListener("abort", abort);
+ }
+}
+
+export function validateAgentInput(
+ input: InternalAgentInput | AgentInput,
+ requireKey: boolean,
+): void {
+ if (
+ requireKey &&
+ (typeof (input as AgentInput).key !== "string" || (input as AgentInput).key.trim() === "")
+ ) {
+ throw new TypeError("agent() requires a non-empty `key`.");
+ }
+ if (typeof input.target !== "string" || input.target.trim() === "") {
+ throw new TypeError("agent() requires a non-empty `target`.");
+ }
+ if (typeof input.message !== "string" || input.message.trim() === "") {
+ throw new TypeError("agent() requires a non-empty `message`.");
+ }
+}
+
+function claimInvocationId(ctx: ToolContext, invocationId: string): void {
+ const holder = ctx as ToolContext & { [AGENT_INVOCATION_IDS]?: Set<string> };
+ const ids = holder[AGENT_INVOCATION_IDS] ?? new Set<string>();
+ if (ids.has(invocationId)) {
+ const separator = invocationId.lastIndexOf(":");
+ const key = separator < 0 ? invocationId : invocationId.slice(separator + 1);
+ throw new TypeError(
+ `agent() invocation key "${key}" was already used in this run; keys must be unique per run.`,
+ );
+ }
+ ids.add(invocationId);
+ if (holder[AGENT_INVOCATION_IDS] === undefined) {
+ Object.defineProperty(holder, AGENT_INVOCATION_IDS, { enumerable: false, value: ids });
+ }
+}
diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts
new file mode 100644
index 000000000..521491ca4
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest";
+
+import { planAgentDispatch } from "#execution/tools/subagent/invoke-preparation.js";
+
+const localAction = {
+ callId: "call-1",
+ description: "Research",
+ input: { message: "Find it" },
+ kind: "subagent-call" as const,
+ name: "research",
+ nodeId: "subagents/research",
+ subagentName: "research",
+};
+
+function session(rootSessionId?: string) {
+ return {
+ agent: { dynamicModel: true as const, system: "", tools: [] },
+ compaction: { recentWindowSize: 5, threshold: 10_000 },
+ continuationToken: "parent-token",
+ history: [],
+ rootSessionId,
+ sessionId: "parent",
+ };
+}
+
+describe("planAgentDispatch", () => {
+ it("rejects recursive self-agent starts outside the root session", () => {
+ expect(
+ planAgentDispatch({
+ action: { ...localAction, name: "agent", nodeId: "__root__", subagentName: "agent" },
+ bundle: {
+ subagentRegistry: { subagentsByNodeId: new Map() },
+ turnAgent: {},
+ } as never,
+ ctx: {} as never,
+ session: session("root") as never,
+ }),
+ ).toMatchObject({
+ kind: "reject",
+ result: { output: { code: "RECURSIVE_AGENT_ROOT_ONLY" } },
+ });
+ });
+
+ it("rejects a dynamic target omitted from the current selection", () => {
+ expect(
+ planAgentDispatch({
+ action: localAction,
+ bundle: {
+ subagentRegistry: {
+ dynamicNodeIds: new Set([localAction.nodeId]),
+ subagentsByNodeId: new Map(),
+ },
+ turnAgent: {},
+ } as never,
+ ctx: { get: () => undefined } as never,
+ session: session() as never,
+ }),
+ ).toMatchObject({ kind: "reject", result: { output: { code: "SUBAGENT_UNAVAILABLE" } } });
+ });
+
+ it("falls back to a fresh start for an unknown agentId", () => {
+ expect(
+ planAgentDispatch({
+ action: { ...localAction, input: { agentId: "unknown", message: "Find it" } },
+ bundle: {
+ subagentRegistry: {
+ subagentsByNodeId: new Map([
+ [localAction.nodeId, { definition: { description: "Research", kind: "subagent" } }],
+ ]),
+ },
+ turnAgent: {},
+ } as never,
+ ctx: {} as never,
+ knownAgentIds: [],
+ session: session() as never,
+ }),
+ ).toMatchObject({ kind: "start", target: { action: localAction, kind: "local" } });
+ });
+});
diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
new file mode 100644
index 000000000..c01824848
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-preparation.ts
@@ -0,0 +1,279 @@
+import type { ContextReader } from "#context/key.js";
+import { deserializeContext } from "#context/serialize.js";
+import {
+ prepareActionDispatch,
+ type PreparedCoordinationDispatch,
+} from "#execution/coordination-dispatch-shared.js";
+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
+import { activeTurnId } from "#harness/active-turn-id.js";
+import { getHarnessEmissionState } from "#harness/emission.js";
+import type { RuntimeAgentDispatchRequest } from "#shared/action-types.js";
+import type {
+ RuntimeSubagentDispatchFailure,
+ RuntimeSubagentDispatchRequest,
+} from "#shared/action-types.js";
+import type { JsonObject } from "#shared/json.js";
+import type { AgentInvocationRequest } from "#execution/tools/subagent/invoke-agent.js";
+import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
+import { AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";
+import {
+ SessionDynamicSubagentSelectionsKey,
+ TurnDynamicSubagentSelectionsKey,
+ type DurableDynamicSubagentSelection,
+} from "#context/keys.js";
+import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
+import {
+ isAgentHandleAction,
+ type RuntimeAgentHandleAction,
+ type RuntimeSession,
+} from "#subagents/handle-dispatch.js";
+import { getAgentHandleStore } from "#subagents/handles/store.js";
+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
+import {
+ createRecursiveAgentRootOnlyResult,
+ createUnavailableDynamicSubagentResult,
+ getSubagentName,
+} from "#execution/dispatch-action-failures.js";
+import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";
+import type { SubagentInputSource } from "#subagents/tool.js";
+import { createLogger } from "#internal/logging.js";
+
+const log = createLogger("execution.agent-invocation");
+
+export type OwnerAgentDispatchPlanEntry =
+ | {
+ readonly kind: "resume";
+ readonly action: RuntimeAgentHandleAction;
+ readonly agentId: string;
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
+ }
+ | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
+ | { readonly kind: "start"; readonly target: SubagentStartTarget };
+
+/** Prepares one workflow-owner agent invocation from durable inputs. */
+export async function prepareOwnerAgentInvocation(input: {
+ readonly invocation: AgentInvocationRequest["input"];
+ readonly invocationId: string;
+ readonly knownAgentIds?: readonly string[];
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<Omit<PreparedCoordinationDispatch<OwnerAgentDispatchPlanEntry>, "sessionState">> {
+ const durableSession = await readDurableSession(input.sessionState);
+ const ctx = await deserializeContext(input.serializedContext);
+ const event = getHarnessEmissionState(durableSession.state);
+ const action = resolveAgentInvocationAction({
+ ctx,
+ input: input.invocation,
+ invocationId: input.invocationId,
+ });
+ return await prepareActionDispatch({
+ batch: {
+ requests: [action],
+ event: { ...event, turnId: activeTurnId(event) },
+ },
+ ctx,
+ durableSession,
+ fanoutSize: 1,
+ plan: ({ bundle, ctx: planContext, session }) => [
+ planAgentDispatch({
+ action,
+ bundle,
+ ctx: planContext,
+ knownAgentIds: input.knownAgentIds,
+ session,
+ }),
+ ],
+ planSharesSandbox: ({ bundle, plan }) => ownerPlanSharesSandbox({ bundle, plan }),
+ serializedContext: input.serializedContext,
+ });
+}
+
+export function planAgentDispatch(input: {
+ readonly action: RuntimeAgentDispatchRequest;
+ readonly bundle: CompiledBundle;
+ readonly ctx: ContextReader;
+ readonly knownAgentIds?: readonly string[];
+ readonly session: RuntimeSession;
+}): OwnerAgentDispatchPlanEntry {
+ const knownAgentIds = new Set(
+ input.knownAgentIds ??
+ (getAgentHandleStore(input.session.state)?.handles ?? []).map((handle) => handle.identity.id),
+ );
+ const rawAgentId = input.action.input.agentId;
+ const agentId =
+ typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;
+ if (agentId !== undefined && isAgentHandleAction(input.action)) {
+ if (knownAgentIds.has(agentId)) {
+ const dynamicSubagentSelection =
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(input.action.nodeId) === true
+ ? getDynamicSubagentSelection(input.ctx, input.action.nodeId)
+ : undefined;
+ return {
+ action: input.action,
+ agentId,
+ dynamicRemoteAgent:
+ input.action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
+ kind: "resume",
+ };
+ }
+ log.warn("unknown agentId on subagent call; starting a new agent", {
+ agentId,
+ callId: input.action.callId,
+ });
+ }
+ return classifyFreshStart(input);
+}
+
+function classifyFreshStart(input: {
+ readonly action: RuntimeAgentDispatchRequest;
+ readonly bundle: CompiledBundle;
+ readonly ctx: ContextReader;
+ readonly session: RuntimeSession;
+}): Extract<OwnerAgentDispatchPlanEntry, { kind: "reject" | "start" }> {
+ const { action } = input;
+ const registry = input.bundle.subagentRegistry.subagentsByNodeId;
+ const isDynamicSubagent =
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
+ const dynamicSubagentSelection = isDynamicSubagent
+ ? getDynamicSubagentSelection(input.ctx, action.nodeId)
+ : undefined;
+ if (
+ isDynamicSubagent &&
+ (dynamicSubagentSelection === undefined ||
+ (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
+ (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
+ ) {
+ log.warn("dynamic subagent call blocked after availability changed", {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName: getSubagentName(action),
+ });
+ return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };
+ }
+ if (isRecursiveAgentAction(action, registry) && input.session.rootSessionId !== undefined) {
+ log.warn("recursive agent call blocked outside the root session", {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ rootSessionId: input.session.rootSessionId,
+ subagentName: action.subagentName,
+ });
+ return { kind: "reject", result: createRecursiveAgentRootOnlyResult(action) };
+ }
+ if (action.kind === "remote-agent-call") {
+ return {
+ kind: "start",
+ target: {
+ action,
+ dynamicRemoteAgent:
+ dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
+ kind: "remote",
+ },
+ };
+ }
+ const dynamicAgentConfig =
+ dynamicSubagentSelection?.kind === "subagent"
+ ? dynamicSubagentSelection.agentConfig
+ : undefined;
+ const registered = registry.get(action.nodeId);
+ const description =
+ dynamicAgentConfig?.description ??
+ (registered?.definition.kind === "subagent" ? registered.definition.description : undefined);
+ const source: SubagentInputSource =
+ description === undefined
+ ? { outputSchema: input.bundle.turnAgent.outputSchema, type: "runtime" }
+ : {
+ description,
+ outputSchema:
+ dynamicAgentConfig?.outputSchema ??
+ input.bundle.graph?.nodesByNodeId.get(action.nodeId)?.turnAgent?.outputSchema,
+ type: "local",
+ };
+ return {
+ kind: "start",
+ target: { action, dynamicSubagentAgentConfig: dynamicAgentConfig, kind: "local", source },
+ };
+}
+
+function ownerPlanSharesSandbox(input: {
+ readonly bundle: CompiledBundle;
+ readonly plan: readonly OwnerAgentDispatchPlanEntry[];
+}): boolean {
+ return input.plan.some((entry) => {
+ if (entry.kind !== "start" || entry.target.kind !== "local") return false;
+ const action = entry.target.action;
+ const isSelfDelegation =
+ action.subagentName === "agent" &&
+ !input.bundle.subagentRegistry.subagentsByNodeId.has(action.nodeId);
+ return (
+ isSelfDelegation ||
+ input.bundle.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox.definition
+ .inheritsParent === true
+ );
+ });
+}
+
+function isRecursiveAgentAction(
+ action: RuntimeAgentDispatchRequest,
+ subagentsByNodeId: ReadonlyMap<string, unknown>,
+): action is RuntimeSubagentDispatchRequest {
+ return (
+ action.kind === "subagent-call" &&
+ action.subagentName === "agent" &&
+ !subagentsByNodeId.has(action.nodeId)
+ );
+}
+
+function resolveAgentInvocationAction(input: {
+ readonly ctx: Awaited<ReturnType<typeof deserializeContext>>;
+ readonly input: AgentInvocationRequest["input"];
+ readonly invocationId: string;
+}): RuntimeAgentDispatchRequest {
+ const bundle = input.ctx.require(BundleKey);
+ const registered = bundle.subagentRegistry.subagentsByName.get(input.input.target);
+ const dynamicSelection =
+ registered === undefined
+ ? Object.values({
+ ...input.ctx.get(SessionDynamicSubagentSelectionsKey),
+ ...input.ctx.get(TurnDynamicSubagentSelectionsKey),
+ }).find(
+ (selection: DurableDynamicSubagentSelection) =>
+ selection !== null && selection.prepared?.name === input.input.target,
+ )
+ : undefined;
+ const definition =
+ registered?.definition ??
+ dynamicSelection?.prepared ??
+ (input.input.target === AGENT_TOOL_NAME && bundle.nodeId === undefined
+ ? {
+ description: AGENT_TOOL_DESCRIPTION,
+ kind: "subagent" as const,
+ name: AGENT_TOOL_NAME,
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ }
+ : undefined);
+ if (definition === undefined) {
+ throw new Error(`Agent target "${input.input.target}" is not available to this agent.`);
+ }
+ const actionInput: {
+ agentId?: string;
+ message: string;
+ outputSchema?: JsonObject;
+ } = { message: input.input.message };
+ if (input.input.agentId !== undefined) actionInput.agentId = input.input.agentId;
+ if (input.input.outputSchema !== undefined) actionInput.outputSchema = input.input.outputSchema;
+ const common = {
+ callId: input.invocationId,
+ description: definition.description ?? "",
+ input: actionInput,
+ name: definition.name,
+ nodeId: definition.nodeId,
+ };
+ return definition.kind === "remote"
+ ? { ...common, kind: "remote-agent-call", remoteAgentName: definition.name }
+ : { ...common, kind: "subagent-call", subagentName: definition.name };
+}
diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts
new file mode 100644
index 000000000..fd0755aba
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import {
+ dispatchAgentInvocation,
+ settleTaskAgentInvocationStep,
+} from "#execution/tools/subagent/invoke-step.js";
+import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";
+import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";
+import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";
+
+vi.mock("#execution/tools/subagent/invoke-preparation.js", () => ({
+ prepareOwnerAgentInvocation: vi.fn(),
+}));
+vi.mock("#subagents/handle-dispatch.js", async (importOriginal) => ({
+ ...(await importOriginal()),
+ dispatchToClaimedAgentAddress: vi.fn(),
+}));
+
+const address = {
+ continuationToken: "child-token",
+ kind: "agent/local" as const,
+ sessionId: "child-session",
+};
+const identity = { id: "agent-1", name: "research", nodeId: "subagents/research" };
+
+describe("blocking workflow agent continuation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(prepareOwnerAgentInvocation).mockImplementation(async (input) => {
+ const session = await readDurableSession(input.sessionState);
+ return {
+ adapter: {},
+ adapterCtx: {},
+ auth: null,
+ batch: { event: { sequence: 1, stepIndex: 0, turnId: "turn-1" } },
+ bundle: {},
+ capabilities: undefined,
+ channelMetadata: undefined,
+ fanoutSize: 1,
+ initiatorAuth: null,
+ parentTraceContext: undefined,
+ plan: [
+ {
+ action: {
+ callId: input.invocationId,
+ description: "Research",
+ input: input.invocation,
+ kind: "subagent-call",
+ name: "research",
+ nodeId: identity.nodeId,
+ subagentName: identity.name,
+ },
+ agentId: identity.id,
+ kind: "resume",
+ },
+ ],
+ sandboxSessionId: "parent",
+ serializedContext: {},
+ session: {
+ ...session,
+ compaction: { recentWindowSize: 5, threshold: 10_000 },
+ },
+ } as never;
+ });
+ vi.mocked(dispatchToClaimedAgentAddress).mockImplementation(async (input) => ({
+ address,
+ callId: input.action.callId,
+ kind: "called",
+ name: "research",
+ session: input.currentSession,
+ toolName: "research",
+ }));
+ });
+
+ it("reuses one handle for two calls from the same workflow run", async () => {
+ const session = {
+ agent: { dynamicModel: true as const, system: "", tools: [] },
+ compaction: { recentWindowSize: 5, threshold: 10_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent",
+ state: setAgentHandleStore(undefined, {
+ handles: [{ address, identity, phase: "available" }],
+ }),
+ };
+ let sessionState = createDurableSessionState({ session });
+
+ for (const [index, message] of ["first", "second"].entries()) {
+ const callId = `workflow-call:${String(index)}`;
+ const dispatched = await dispatchAgentInvocation({
+ callbackBaseUrl: "https://parent.example",
+ ownerId: "workflow-run-1",
+ replyTo: `reply-${String(index)}`,
+ request: {
+ input: { agentId: identity.id, message, target: identity.name },
+ invocationId: callId,
+ kind: "agent-invoke",
+ },
+ serializedContext: {},
+ sessionState,
+ });
+ expect(dispatched).toMatchObject({ agentId: identity.id, kind: "dispatched" });
+ if (dispatched.kind !== "dispatched") throw new Error("Expected dispatch.");
+ const claimed = getAgentHandleStore(dispatched.sessionState.snapshot?.session.state)?.handles;
+ expect(claimed).toEqual([
+ expect.objectContaining({ identity, ownerId: "workflow-run-1", phase: "claimed" }),
+ ]);
+
+ const settled = await settleTaskAgentInvocationStep({
+ ownerId: "workflow-run-1",
+ result: {
+ callId,
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind: "parked",
+ result: { kind: "succeeded", output: message },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ output: message,
+ subagentName: identity.name,
+ },
+ sessionState: dispatched.sessionState,
+ });
+ sessionState = settled.sessionState;
+ expect(getAgentHandleStore(sessionState.snapshot?.session.state)?.handles).toEqual([
+ { address, identity, phase: "available" },
+ ]);
+ }
+
+ expect(dispatchToClaimedAgentAddress).toHaveBeenCalledTimes(2);
+ expect(
+ vi.mocked(dispatchToClaimedAgentAddress).mock.calls.map(([input]) => input.handle.address),
+ ).toEqual([address, address]);
+ });
+});
diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts
new file mode 100644
index 000000000..52dc0e63f
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts
@@ -0,0 +1,394 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ dispatchAgentInvocation,
+ releaseAgentInvocationOwnerStep,
+ settleTaskAgentInvocationStep,
+} from "#execution/tools/subagent/invoke-step.js";
+import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";
+import { startSubagent } from "#execution/tools/subagent/start.js";
+import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";
+import { readDurableSession } from "#execution/durable-session-store.js";
+import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";
+
+vi.mock("#subagents/handle-dispatch.js", async (importOriginal) => ({
+ ...(await importOriginal()),
+ dispatchToClaimedAgentAddress: vi.fn(),
+}));
+vi.mock("#subagents/continuation-bundle.js", () => ({
+ createAgentContinuationBundle: vi.fn(() => ({ nodeId: "child" })),
+}));
+vi.mock("#execution/tools/subagent/start.js", () => ({
+ startSubagent: vi.fn(),
+}));
+vi.mock("#execution/tools/subagent/invoke-preparation.js", () => ({
+ prepareOwnerAgentInvocation: vi.fn(),
+}));
+vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({
+ ...(await importOriginal()),
+ readDurableSession: vi.fn(),
+}));
+const action = {
+ callId: "call-1",
+ description: "Research",
+ input: { message: "Find it" },
+ kind: "subagent-call" as const,
+ name: "research",
+ nodeId: "subagents/research",
+ subagentName: "research",
+};
+const availableRecord = {
+ address: { continuationToken: "child", kind: "agent/local" as const, sessionId: "child" },
+ identity: { id: "agent-1", name: "research", nodeId: "subagents/research" },
+ phase: "available" as const,
+};
+const session = {
+ agent: { system: "" },
+ compaction: {},
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent",
+ state: setAgentHandleStore(undefined, { handles: [availableRecord] }),
+};
+const prepared = {
+ adapter: {},
+ adapterCtx: {},
+ auth: null,
+ batch: { event: { sequence: 1, stepIndex: 2, turnId: "turn-1" } },
+ bundle: {},
+ capabilities: undefined,
+ channelMetadata: undefined,
+ fanoutSize: 1,
+ initiatorAuth: null,
+ parentTraceContext: undefined,
+ sandboxSessionId: "parent",
+ serializedContext: {},
+ session,
+};
+const called = {
+ address: { continuationToken: "child", kind: "agent/local" as const, sessionId: "child" },
+ callId: "call-1",
+ kind: "called" as const,
+ name: "research",
+ session: session as never,
+ toolName: "research",
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(readDurableSession).mockResolvedValue(session as never);
+});
+
+describe("owner agent invocation dispatch", () => {
+ it("resumes an addressed agent through its owning task", async () => {
+ vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({
+ ...prepared,
+ plan: [{ action, agentId: "agent-1", kind: "resume" }],
+ } as never);
+ vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);
+
+ const dispatched = await dispatch();
+
+ expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(
+ expect.objectContaining({
+ handle: expect.objectContaining({
+ identity: availableRecord.identity,
+ phase: "claimed",
+ ownerId: "task-1",
+ }),
+ parentToken: "agent-reply",
+ taskId: "task-1",
+ }),
+ );
+ expect(dispatched).toMatchObject({ agentId: "agent-1", kind: "dispatched" });
+ expect(getAgentHandleStore(dispatched.sessionState.snapshot?.session.state)?.handles).toEqual([
+ expect.objectContaining({
+ identity: availableRecord.identity,
+ phase: "claimed",
+ ownerId: "task-1",
+ }),
+ ]);
+ });
+
+ it("reuses a continuation claim admitted before the workflow body starts", async () => {
+ const claimed = {
+ ...availableRecord,
+ callId: "call-1",
+ operationId: "admission-operation",
+ phase: "claimed" as const,
+ ownerId: "task-1",
+ };
+ const claimedSession = {
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [claimed] }),
+ };
+ vi.mocked(readDurableSession).mockResolvedValue(claimedSession as never);
+ vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({
+ ...prepared,
+ session: claimedSession,
+ plan: [{ action, agentId: "agent-1", kind: "resume" }],
+ } as never);
+ vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);
+
+ await dispatch();
+
+ expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(
+ expect.objectContaining({ handle: claimed }),
+ );
+ });
+
+ it("reuses one handle across blocking invocations with the same agentId", async () => {
+ vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({
+ ...prepared,
+ plan: [{ action, agentId: "agent-1", kind: "resume" }],
+ } as never);
+ vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);
+
+ const first = await dispatchAgentInvocation({
+ callbackBaseUrl: "https://parent.example",
+ replyTo: "first-reply",
+ request: {
+ input: { agentId: "agent-1", message: "First", target: "research" },
+ invocationId: "call-1:first",
+ kind: "agent-invoke",
+ },
+ ownerId: "workflow-run-1",
+ serializedContext: {},
+ sessionState: {} as never,
+ });
+ expect(first.kind).toBe("dispatched");
+ const firstHandle =
+ first.kind === "dispatched"
+ ? getAgentHandleStore(first.sessionState.snapshot?.session.state)?.handles[0]
+ : undefined;
+ expect(firstHandle).toMatchObject({
+ identity: { id: "agent-1" },
+ ownerId: "workflow-run-1",
+ phase: "claimed",
+ });
+
+ vi.mocked(readDurableSession).mockResolvedValue({
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [availableRecord] }),
+ } as never);
+ const second = await dispatchAgentInvocation({
+ callbackBaseUrl: "https://parent.example",
+ replyTo: "second-reply",
+ request: {
+ input: { agentId: "agent-1", message: "Second", target: "research" },
+ invocationId: "call-1:second",
+ kind: "agent-invoke",
+ },
+ ownerId: "workflow-run-1",
+ serializedContext: {},
+ sessionState: {} as never,
+ });
+
+ expect(second).toMatchObject({ agentId: "agent-1", kind: "dispatched" });
+ expect(dispatchToClaimedAgentAddress).toHaveBeenCalledTimes(2);
+ expect(
+ vi
+ .mocked(dispatchToClaimedAgentAddress)
+ .mock.calls.map(([input]) => input.handle.identity.id),
+ ).toEqual(["agent-1", "agent-1"]);
+ });
+
+ it("starts a fresh agent with task-owned handle semantics", async () => {
+ const reserved = {
+ callId: "call-1",
+ identity: { id: "agent-receipt", name: "research", nodeId: "subagents/research" },
+ operationId: "receipt-operation",
+ phase: "reserved" as const,
+ ownerId: "task-1",
+ };
+ vi.mocked(readDurableSession).mockResolvedValue({
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [reserved] }),
+ } as never);
+ vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({
+ ...prepared,
+ session: {
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [reserved] }),
+ },
+ plan: [{ kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }],
+ } as never);
+ vi.mocked(startSubagent).mockResolvedValue(called);
+
+ const dispatched = await dispatch();
+
+ expect(startSubagent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentContinuationToken: "agent-reply",
+ taskId: "task-1",
+ }),
+ );
+ expect(dispatched).toMatchObject({ agentId: "agent-receipt", kind: "dispatched" });
+ expect(startSubagent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ currentSession: expect.objectContaining({
+ state: expect.objectContaining({
+ "eve.agent.handles": { handles: [reserved] },
+ }),
+ }),
+ }),
+ );
+ expect(getAgentHandleStore(dispatched.sessionState.snapshot?.session.state)?.handles).toEqual(
+ expect.arrayContaining([expect.objectContaining({ ownerId: "task-1", phase: "claimed" })]),
+ );
+ });
+});
+
+describe("task-owned agent settlement", () => {
+ it.each(["parked", "terminal"] as const)("applies a %s child outcome", async (kind) => {
+ const claimed = {
+ ...availableRecord,
+ operationId: "operation-1",
+ phase: "claimed" as const,
+ ownerId: "task-1",
+ };
+ vi.mocked(readDurableSession).mockResolvedValue({
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [claimed] }),
+ } as never);
+
+ const settled = await settleTaskAgentInvocationStep({
+ result: {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind,
+ result: { kind: "succeeded", output: "done" },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 2,
+ outputTokens: 1,
+ },
+ },
+ output: "done",
+ subagentName: "research",
+ },
+ ownerId: "task-1",
+ sessionState: {} as never,
+ taskId: "task-1",
+ });
+
+ const handles =
+ getAgentHandleStore(settled.sessionState.snapshot?.session.state)?.handles ?? [];
+ expect(handles).toEqual(
+ kind === "parked" ? [expect.objectContaining({ phase: "available" })] : [],
+ );
+ });
+
+ it("releases every remaining claim for a completed workflow run", async () => {
+ const claimed = {
+ ...availableRecord,
+ operationId: "operation-1",
+ ownerId: "workflow-run-1",
+ phase: "claimed" as const,
+ };
+ vi.mocked(readDurableSession).mockResolvedValue({
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [claimed] }),
+ } as never);
+
+ const released = await releaseAgentInvocationOwnerStep({
+ ownerId: "workflow-run-1",
+ sessionState: {} as never,
+ });
+
+ expect(getAgentHandleStore(released.sessionState.snapshot?.session.state)?.handles).toEqual([
+ availableRecord,
+ ]);
+ });
+
+ it("parks every remaining claim for a cancelled workflow run", async () => {
+ const claimed = {
+ ...availableRecord,
+ operationId: "operation-1",
+ ownerId: "workflow-run-1",
+ phase: "claimed" as const,
+ };
+ vi.mocked(readDurableSession).mockResolvedValue({
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [claimed] }),
+ } as never);
+
+ const released = await releaseAgentInvocationOwnerStep({
+ cancelled: true,
+ ownerId: "workflow-run-1",
+ sessionState: {} as never,
+ });
+
+ expect(getAgentHandleStore(released.sessionState.snapshot?.session.state)?.handles).toEqual([
+ {
+ address: availableRecord.address,
+ identity: availableRecord.identity,
+ lastStatus: "(cancelled)",
+ phase: "parked",
+ },
+ ]);
+ });
+
+ it("keeps a cancelled parked child resumable after settlement", async () => {
+ const claimed = {
+ ...availableRecord,
+ operationId: "operation-1",
+ phase: "claimed" as const,
+ ownerId: "workflow-run-1",
+ };
+ vi.mocked(readDurableSession).mockResolvedValue({
+ ...session,
+ state: setAgentHandleStore(undefined, { handles: [claimed] }),
+ } as never);
+
+ const settled = await settleTaskAgentInvocationStep({
+ ownerId: "workflow-run-1",
+ result: {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind: "parked",
+ result: { kind: "cancelled" },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ output: "cancelled",
+ subagentName: "research",
+ },
+ sessionState: {} as never,
+ });
+
+ expect(getAgentHandleStore(settled.sessionState.snapshot?.session.state)?.handles).toEqual([
+ {
+ address: availableRecord.address,
+ identity: availableRecord.identity,
+ lastStatus: "(cancelled)",
+ phase: "parked",
+ },
+ ]);
+ });
+});
+
+async function dispatch() {
+ return await dispatchAgentInvocation({
+ callbackBaseUrl: "https://parent.example",
+ emit: vi.fn(),
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1",
+ kind: "agent-invoke",
+ },
+ ownerId: "task-1",
+ serializedContext: {},
+ sessionState: {} as never,
+ taskId: "task-1",
+ });
+}
diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.ts
new file mode 100644
index 000000000..f4b731824
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts
@@ -0,0 +1,435 @@
+import {
+ createAgentErrorResult,
+ dispatchToClaimedAgentAddress,
+ type DispatchOutcome,
+} from "#subagents/handle-dispatch.js";
+import { createAgentContinuationBundle } from "#subagents/continuation-bundle.js";
+import { startSubagent } from "#execution/tools/subagent/start.js";
+import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";
+import type { AgentInvocationRequest } from "#execution/tools/subagent/invoke-agent.js";
+import type { RuntimeSubagentResult } from "#shared/action-types.js";
+import type { HandleEventFn } from "#harness/types.js";
+import { createSubagentCalledEvent, type SubagentCalledStreamEvent } from "#protocol/message.js";
+import { workflowEntryReference } from "#execution/workflow-runtime.js";
+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
+import { createSubagentReceiptIdentity } from "#execution/tools/subagent/receipt-identity.js";
+import {
+ readDurableSession,
+ replaceDurableSessionSnapshot,
+ type DurableSessionState,
+} from "#execution/durable-session-store.js";
+import { projectToDurableSession } from "#execution/session.js";
+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
+import {
+ getAgentHandleStore,
+ writeHandles,
+ type AgentHandle,
+ type AgentHandleStoreCommand,
+ type AgentHandleStoreCommandResult,
+ type TaskOwnedAgentHandle,
+} from "#subagents/handles/store.js";
+import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";
+import { abandonAgentInvocationOwners } from "#subagents/handles/transitions.js";
+import {
+ AGENT_BUSY,
+ AGENT_MISMATCH,
+ AGENT_UNREACHABLE,
+ formatAgentBusyMessage,
+} from "#subagents/agent-handle-errors.js";
+import { findSessionTaskEntry } from "#tasks/session-index.js";
+import { isTerminalTaskStatus } from "#tasks/types.js";
+import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
+import {
+ clearProxyInputRequestsForChild,
+ clearProxyInputRequestsForTask,
+} from "#harness/proxy-input-requests.js";
+import {
+ accumulateSessionUsage,
+ getTurnUsageState,
+ setTurnUsageState,
+} from "#harness/turn-tag-state.js";
+
+export type AgentInvocationDispatchResult =
+ | {
+ readonly kind: "dispatched";
+ readonly agentId: string;
+ readonly event: SubagentCalledStreamEvent;
+ readonly sessionState: DurableSessionState;
+ }
+ | {
+ readonly kind: "failed";
+ readonly result: RuntimeSubagentResult;
+ readonly sessionState: DurableSessionState;
+ };
+
+export type TaskAgentInvocationDispatchResult =
+ | { readonly kind: "not-admitted"; readonly sessionState: DurableSessionState }
+ | AgentInvocationDispatchResult;
+
+/** Dispatches one owner-scoped local or remote agent invocation. */
+export async function dispatchAgentInvocation(input: {
+ readonly callbackBaseUrl: string;
+ readonly emit?: HandleEventFn;
+ readonly replyTo: string;
+ readonly request: AgentInvocationRequest;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+ readonly ownerId: string;
+ readonly taskId?: string | undefined;
+}): Promise<AgentInvocationDispatchResult> {
+ const durableSession = await readDurableSession(input.sessionState);
+ const agentHandles = getAgentHandleStore(durableSession.state)?.handles ?? [];
+ const prepared = await prepareOwnerAgentInvocation({
+ invocation: input.request.input,
+ invocationId: input.request.invocationId,
+ knownAgentIds: agentHandles.map((handle) => handle.identity.id),
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
+ const entry = prepared.plan[0];
+ if (entry === undefined) {
+ throw new Error("Agent invocation produced no executable plan entry.");
+ }
+ let session = prepared.session;
+ const currentAgentHandles = (): readonly AgentHandle[] =>
+ getAgentHandleStore(session.state)?.handles ?? [];
+ const sessionState = (): DurableSessionState =>
+ replaceDurableSessionSnapshot({
+ session: projectToDurableSession(session),
+ state: input.sessionState,
+ });
+ const applyHandleCommand = (command: AgentHandleStoreCommand): AgentHandleStoreCommandResult => {
+ const applied = applyTaskAgentHandleCommand(session, command);
+ session = applied.session;
+ return applied.result;
+ };
+ if (entry.kind === "reject") {
+ return { kind: "failed", result: entry.result, sessionState: sessionState() };
+ }
+
+ let outcome: DispatchOutcome;
+ let agentId: string;
+ if (entry.kind === "resume") {
+ const existingClaims = currentAgentHandles().filter(
+ (handle): handle is Extract<TaskOwnedAgentHandle, { readonly phase: "claimed" }> =>
+ handle.phase === "claimed" &&
+ handle.ownerId === input.ownerId &&
+ handle.callId === entry.action.callId &&
+ handle.identity.id === entry.agentId,
+ );
+ if (existingClaims.length > 1) {
+ throw new Error(
+ `Invocation owner "${input.ownerId}" has multiple claims for "${entry.action.callId}".`,
+ );
+ }
+ let claimed = existingClaims[0];
+ if (claimed === undefined) {
+ const operationId = deriveAgentOperationId({
+ callId: entry.action.callId,
+ parentSessionId: prepared.session.sessionId,
+ parentTurnId: prepared.batch.event.turnId,
+ });
+ const claim = applyHandleCommand({
+ agentId: entry.agentId,
+ callId: entry.action.callId,
+ expectedTarget: entry.action.kind === "remote-agent-call" ? "remote" : "local",
+ invokedName:
+ entry.action.kind === "remote-agent-call"
+ ? entry.action.remoteAgentName
+ : entry.action.subagentName,
+ kind: "claim",
+ operationId,
+ ownerId: input.ownerId,
+ });
+ claimed = readClaimedHandle(claim);
+ if (claimed === undefined) {
+ return {
+ kind: "failed",
+ result: createTaskClaimError(entry.action, entry.agentId, claim),
+ sessionState: sessionState(),
+ };
+ }
+ }
+ const bundle = createAgentContinuationBundle({
+ action: entry.action,
+ bundle: prepared.bundle,
+ dynamicRemoteAgent: entry.dynamicRemoteAgent,
+ });
+ outcome = await dispatchToClaimedAgentAddress({
+ action: entry.action,
+ auth: prepared.auth,
+ bundle,
+ currentSession: session,
+ parentToken: input.replyTo,
+ handle: claimed,
+ taskId: input.taskId,
+ });
+ if (outcome.kind === "error" && outcome.deliveryPermanent === true) {
+ applyHandleCommand({ agentId: entry.agentId, kind: "remove", ownerId: input.ownerId });
+ }
+ agentId = claimed.identity.id;
+ } else {
+ const action = entry.target.action;
+ const reserved = currentAgentHandles().filter(
+ (handle): handle is Extract<TaskOwnedAgentHandle, { readonly phase: "reserved" }> =>
+ handle.phase === "reserved" &&
+ handle.ownerId === input.ownerId &&
+ handle.callId === action.callId &&
+ handle.identity.name === action.name &&
+ handle.identity.nodeId === action.nodeId,
+ );
+ const start =
+ reserved.length === 1
+ ? { identity: reserved[0]!.identity, operation: { id: reserved[0]!.operationId } }
+ : createSubagentReceiptIdentity({
+ callId: action.callId,
+ subagentName:
+ action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName,
+ nodeId: action.nodeId,
+ parentSessionId: prepared.session.sessionId,
+ parentTurnId: prepared.batch.event.turnId,
+ });
+ if (reserved.length > 1) {
+ throw new Error(
+ `Invocation owner "${input.ownerId}" has multiple reservations for "${action.callId}".`,
+ );
+ }
+ if (reserved.length === 0) {
+ const reservation = applyHandleCommand({
+ identity: start.identity,
+ callId: action.callId,
+ kind: "reserve",
+ operationId: start.operation.id,
+ ownerId: input.ownerId,
+ });
+ if (reservation.kind !== "ready") {
+ throw new Error(`Agent handle store rejected start operation "${start.operation.id}".`);
+ }
+ }
+ outcome = await startSubagent({
+ auth: prepared.auth,
+ batchEvent: prepared.batch.event,
+ bundle: prepared.bundle,
+ callbackBaseUrl: input.callbackBaseUrl,
+ capabilities: prepared.capabilities,
+ channelMetadata: prepared.channelMetadata,
+ currentSession: session,
+ fanoutSize: prepared.fanoutSize,
+ initiatorAuth: prepared.initiatorAuth,
+ localDevRequest: prepared.localDevRequest,
+ parentContinuationToken: input.replyTo,
+ parentTraceContext: prepared.parentTraceContext,
+ sandboxSessionId: prepared.sandboxSessionId,
+ serializedContext: prepared.serializedContext,
+ session,
+ taskId: input.taskId,
+ target: entry.target,
+ });
+ agentId = start.identity.id;
+ if (outcome.kind === "error") {
+ applyHandleCommand({ agentId, kind: "remove", ownerId: input.ownerId });
+ } else {
+ const confirmed = applyHandleCommand({
+ address: outcome.address,
+ kind: "confirm",
+ operationId: start.operation.id,
+ ownerId: input.ownerId,
+ });
+ if (readClaimedHandle(confirmed) === undefined) {
+ throw new Error(
+ `Agent handle store could not confirm start operation "${start.operation.id}".`,
+ );
+ }
+ }
+ }
+
+ if (outcome.kind === "error") {
+ return { kind: "failed", result: outcome.result, sessionState: sessionState() };
+ }
+
+ const action = entry.kind === "resume" ? entry.action : entry.target.action;
+ const dynamicRemoteAgent =
+ entry.kind === "resume"
+ ? entry.dynamicRemoteAgent
+ : entry.target.kind === "remote"
+ ? entry.target.dynamicRemoteAgent
+ : undefined;
+ const event = createSubagentCalledEvent({
+ agentId,
+ callId: outcome.callId,
+ childSessionId: outcome.address.sessionId,
+ name: outcome.name,
+ remote:
+ outcome.address.kind === "agent/remote"
+ ? {
+ resolverId:
+ dynamicRemoteAgent === undefined
+ ? action.nodeId
+ : dynamicRemoteAgent.credentialsStepId,
+ url: outcome.address.url,
+ }
+ : undefined,
+ sequence: prepared.batch.event.sequence,
+ sessionId: prepared.session.sessionId,
+ toolName: outcome.toolName,
+ turnId: prepared.batch.event.turnId,
+ workflowId: workflowEntryReference.workflowId,
+ });
+ if (input.emit !== undefined) {
+ await input.emit(event);
+ }
+ return { kind: "dispatched", agentId, event, sessionState: sessionState() };
+}
+
+/**
+ * Dispatches one agent request after any task-owned invocation is admitted.
+ * The callback origin is parent-owned, so it is derived from this workflow's
+ * own metadata rather than accepted from the inbound request.
+ */
+export async function dispatchTaskAgentInvocationStep(
+ input: Omit<Parameters<typeof dispatchAgentInvocation>[0], "callbackBaseUrl" | "emit">,
+): Promise<TaskAgentInvocationDispatchResult> {
+ "use step";
+
+ if (input.taskId !== undefined) {
+ const session = await readDurableSession(input.sessionState);
+ const entry = findSessionTaskEntry(session.state, input.taskId);
+ if (entry === undefined) return { kind: "not-admitted", sessionState: input.sessionState };
+ const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
+ if (view === undefined || isTerminalTaskStatus(view.status)) {
+ return { kind: "not-admitted", sessionState: input.sessionState };
+ }
+ }
+ return await dispatchAgentInvocation({
+ ...input,
+ callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),
+ });
+}
+
+/** Applies an owner-scoped child settlement to the parent session's canonical state. */
+export async function settleTaskAgentInvocationStep(input: {
+ readonly accumulateUsage?: boolean;
+ readonly ownerId: string;
+ readonly result: RuntimeSubagentChildResult;
+ readonly sessionState: DurableSessionState;
+ readonly taskId?: string | undefined;
+}): Promise<{ readonly sessionState: DurableSessionState }> {
+ "use step";
+
+ const durable = await readDurableSession(input.sessionState);
+ const handles = getAgentHandleStore(durable.state)?.handles ?? [];
+ const candidates = handles.filter(
+ (candidate) => candidate.phase === "claimed" && candidate.ownerId === input.ownerId,
+ );
+ const handle =
+ candidates.find(
+ (candidate) => candidate.phase === "claimed" && candidate.callId === input.result.callId,
+ ) ?? (candidates.length === 1 ? candidates[0] : undefined);
+ if (handle?.phase !== "claimed") return { sessionState: input.sessionState };
+
+ const nextHandles =
+ input.result.outcome.kind === "terminal"
+ ? handles.filter((candidate) => candidate !== handle)
+ : handles.map((candidate) =>
+ candidate === handle
+ ? input.result.outcome.result.kind === "cancelled"
+ ? {
+ address: handle.address,
+ identity: handle.identity,
+ lastStatus: "(cancelled)",
+ phase: "parked" as const,
+ }
+ : {
+ address: handle.address,
+ identity: handle.identity,
+ phase: "available" as const,
+ }
+ : candidate,
+ );
+ let session = writeHandles(durable, nextHandles);
+ if (input.result.outcome.kind === "terminal") {
+ session =
+ input.taskId === undefined
+ ? "continuationToken" in handle.address
+ ? clearProxyInputRequestsForChild(
+ session as Parameters<typeof clearProxyInputRequestsForChild>[0],
+ handle.address.continuationToken,
+ )
+ : session
+ : clearProxyInputRequestsForTask(session, input.taskId);
+ }
+ if (input.accumulateUsage !== false) {
+ session = setTurnUsageState(
+ session,
+ accumulateSessionUsage({
+ previous: getTurnUsageState(session.state),
+ usage: input.result.outcome.usageDelta,
+ }),
+ );
+ }
+ return {
+ sessionState: replaceDurableSessionSnapshot({ session, state: input.sessionState }),
+ };
+}
+
+/** Releases any child leases still owned by a completed workflow-tool run. */
+export async function releaseAgentInvocationOwnerStep(input: {
+ readonly cancelled?: boolean;
+ readonly ownerId: string;
+ readonly sessionState: DurableSessionState;
+}): Promise<{ readonly sessionState: DurableSessionState }> {
+ "use step";
+
+ const durable = await readDurableSession(input.sessionState);
+ const session = input.cancelled
+ ? abandonAgentInvocationOwners(durable, new Set([input.ownerId]))
+ : applyTaskAgentHandleCommand(durable, {
+ kind: "release-owner",
+ ownerId: input.ownerId,
+ }).session;
+ return {
+ sessionState:
+ session === durable
+ ? input.sessionState
+ : replaceDurableSessionSnapshot({ session, state: input.sessionState }),
+ };
+}
+
+function readClaimedHandle(
+ result: AgentHandleStoreCommandResult,
+): Extract<TaskOwnedAgentHandle, { phase: "claimed" }> | undefined {
+ const handle = result.kind === "ready" ? result.handle : undefined;
+ return handle?.phase === "claimed" ? handle : undefined;
+}
+
+function createTaskClaimError(
+ action: Parameters<typeof createAgentErrorResult>[0]["action"],
+ agentId: string,
+ result: AgentHandleStoreCommandResult,
+): RuntimeSubagentResult {
+ if (result.kind === "mismatch") {
+ return createAgentErrorResult({
+ action,
+ code: AGENT_MISMATCH,
+ message: `Agent "${agentId}" no longer matches this subagent definition. Start a new agent instead.`,
+ });
+ }
+ if (result.kind === "busy") {
+ return createAgentErrorResult({
+ action,
+ code: AGENT_BUSY,
+ message: formatAgentBusyMessage({
+ agentId,
+ agentName: result.handle.identity.name,
+ ownerId: "ownerId" in result.handle ? result.handle.ownerId : undefined,
+ }),
+ });
+ }
+ return createAgentErrorResult({
+ action,
+ code: AGENT_UNREACHABLE,
+ message: `Agent with id "${agentId}" is no longer reachable.`,
+ });
+}
diff --git a/packages/eve/src/execution/tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.ts
deleted file mode 100644
index 31e08101a..000000000
--- a/packages/eve/src/execution/tools/subagent/local.ts
+++ /dev/null
@@ -1,361 +0,0 @@
-import { type AlsContext, loadContext } from "#context/container.js";
-import { HandleEventKey } from "#context/keys.js";
-import { serializeContext } from "#context/serialize.js";
-import {
- dispatchToTaskAgentAddress,
- type DispatchOutcome,
- type RuntimeSession,
-} from "#execution/agent-handle-dispatch.js";
-import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";
-import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
-import { prepareAgentActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";
-import { startSubagent } from "#execution/dispatch-runtime-actions-start.js";
-import { createDurableSessionState } from "#execution/durable-session-store.js";
-import {
- checkTaskContinuationAvailability,
- createTaskContinuationBusyResult,
- describeTaskDispatch,
-} from "#execution/tasks/parent/continuation-dispatch.js";
-import { findTaskAgentAddress } from "#execution/tasks/parent/control-shared.js";
-import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";
-import { CallbackBaseUrlKey } from "#harness/authorization.js";
-import { getHarnessEmissionState } from "#harness/emission.js";
-import { defineTool, type TaskExec, type ToolContext } from "#tools/definition.js";
-import type {
- RuntimeRemoteAgentCallActionRequest,
- RuntimeSubagentCallActionRequest,
-} from "#shared/action-types.js";
-import type { PendingAgentDispatchAction } from "#shared/dispatch-action.js";
-import { resolvePreparedAgentAction } from "#execution/prepared-agent-action.js";
-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";
-import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";
-import { parseJsonObject } from "#shared/json.js";
-import { createSubagentExecutorBinding } from "#tasks/types.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
-import { createSubagentCalledEvent } from "#protocol/message.js";
-import { workflowEntryReference } from "#execution/workflow-runtime.js";
-import { createLogger, logError } from "#internal/logging.js";
-
-type SubagentCallAction = RuntimeRemoteAgentCallActionRequest | RuntimeSubagentCallActionRequest;
-
-interface SubagentDefinitionInput {
- readonly description: string;
- readonly name: string;
- readonly target: PendingAgentDispatchAction["target"];
-}
-
-interface SubagentDispatchInput {
- readonly action: SubagentCallAction;
- readonly dispatchAction: PendingAgentDispatchAction;
- readonly batch: TaskExec["batch"];
- readonly callbackBaseUrl?: string;
- readonly ctx: AlsContext;
- readonly event: {
- readonly sequence: number;
- readonly stepIndex: number;
- readonly turnId: string;
- };
- readonly localFanoutSize: number;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: ReturnType<typeof createDurableSessionState>;
- readonly task: BackgroundTask;
-}
-
-interface SubagentDispatchResult {
- readonly address: Extract<DispatchOutcome, { readonly kind: "called" }>["address"];
- readonly agentId: string;
- readonly mode: "local" | "remote";
- readonly name: string;
- readonly remote?: { readonly resolverId: string; readonly url: string };
- readonly session: RuntimeSession;
-}
-
-const batchAgentClaims = new WeakMap<TaskExec["batch"], Map<string, string>>();
-const log = createLogger("runtime.framework-tools.subagent");
-
-export function defineSubagent(input: SubagentDefinitionInput) {
- const definition = defineTool({
- description: input.description,
- execution: "background",
- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,
- execute: (toolInput, ctx, task) =>
- executeSubagentTool({ definition: input, task, toolContext: ctx, toolInput }),
- });
- return definition;
-}
-
-export function countLocalSubagentCalls(
- calls: readonly {
- readonly definition: { readonly behavior?: import("#tools/behavior.js").PreparedToolBehavior };
- }[],
-): number {
- return calls.filter((call) => {
- const handling = call.definition.behavior?.handling;
- return (
- handling?.kind === "dispatch" &&
- (handling.target.kind === "self-agent-call" || handling.target.kind === "subagent-call")
- );
- }).length;
-}
-
-export async function executeSubagentTool(input: {
- readonly definition: SubagentDefinitionInput;
- readonly task: TaskExec;
- readonly toolContext: ToolContext;
- readonly toolInput: unknown;
-}) {
- const ctx = loadContext();
- const { batch, session, task } = input.task;
- const emission = getHarnessEmissionState(session.state);
- const dispatchAction: PendingAgentDispatchAction = {
- callId: input.toolContext.callId,
- description: input.definition.description,
- input: parseJsonObject(SUBAGENT_TOOL_INPUT_SCHEMA.parse(input.toolInput)),
- target: input.definition.target,
- toolName: input.definition.name,
- };
- const action: SubagentCallAction = resolvePreparedAgentAction(dispatchAction).action;
- const dispatched = await dispatchSubagent({
- action,
- batch,
- callbackBaseUrl: ctx.get(CallbackBaseUrlKey),
- ctx,
- dispatchAction,
- event: { ...emission, turnId: activeTurnId(emission) },
- localFanoutSize: countLocalSubagentCalls(batch),
- serializedContext: serializeContext(ctx),
- sessionState: createDurableSessionState({ session }),
- task,
- });
- // The executor binding is the durable copy of the child's addressed
- // handle, read back from the post-dispatch session so it is exactly what
- // the handle store recorded (fresh start) or already held (resume). It is
- // deep-equal on replay — identity and address derive from the originating
- // call — and it is the only channel the task layer needs: commit writes
- // the address into the parent handle store, and compensation or a later
- // turn cancels the child through it.
- const record = findTaskAgentAddress(dispatched.session, dispatched.agentId);
- if (record === undefined) {
- throw new Error(
- `Subagent dispatch for "${dispatched.agentId}" recorded no task agent address.`,
- );
- }
- const executor = createSubagentExecutorBinding({
- address: record.address,
- identity: record.identity,
- });
- await emitSubagentCalled({
- callId: input.toolContext.callId,
- childSessionId: dispatched.address.sessionId,
- event: { ...emission, turnId: activeTurnId(emission) },
- name: dispatched.name,
- remote: dispatched.remote,
- sessionId: session.sessionId,
- toolName: input.definition.name,
- });
-
- const delegated = input.task.delegated({
- executor,
- receipt: { agentId: dispatched.agentId },
- });
- await emitSubagentCompleted({
- callId: input.toolContext.callId,
- output: JSON.stringify(delegated.receipt),
- subagentName: dispatched.name,
- taskId: delegated.receipt.taskId,
- });
- return delegated;
-}
-
-async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentDispatchResult> {
- const prepared = await prepareAgentActionDispatch({
- action: input.dispatchAction,
- ctx: input.ctx,
- event: input.event,
- localFanoutSize: input.localFanoutSize,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
- const entry = prepared.plan[0];
- if (entry === undefined || entry.kind === "task-control" || entry.kind === "workflow-tool") {
- throw new Error("Subagent tool dispatch produced no executable plan entry.");
- }
- if (entry.kind === "reject") {
- throw new Error(JSON.stringify(entry.result.output));
- }
-
- if (entry.kind === "resume") {
- const busy = await checkTaskContinuationAvailability({
- action: entry.action,
- agentId: entry.agentId,
- parentStepIndex: input.event.stepIndex,
- parentTurnId: input.event.turnId,
- session: prepared.session,
- });
- if (busy !== undefined) throw new Error(JSON.stringify(busy.output));
-
- const claimedTaskId = claimBatchAgent(input.batch, entry.agentId, input.task.taskId);
- if (claimedTaskId !== undefined) {
- const busy = createTaskContinuationBusyResult({
- action: entry.action,
- agentId: entry.agentId,
- status: "working",
- taskId: claimedTaskId,
- });
- throw new Error(JSON.stringify(busy.output));
- }
- }
-
- const outcome =
- entry.kind === "resume"
- ? await dispatchToTaskAgentAddress({
- action: entry.action,
- activityObserver:
- prepared.activityObserver === undefined
- ? undefined
- : deriveChildActivityObserverConfig({
- activityObserver: prepared.activityObserver,
- callId: entry.action.callId,
- kind: "task",
- name: entry.action.name,
- parentSessionId: prepared.session.sessionId,
- parentTurnId: input.event.turnId,
- }),
- agentId: entry.agentId,
- auth: prepared.auth,
- bundle: createAgentContinuationBundle({
- action: entry.action,
- bundle: prepared.bundle,
- dynamicRemoteAgent: entry.dynamicRemoteAgent,
- }),
- currentSession: prepared.session,
- parentToken: input.task.taskInboxToken,
- })
- : await startSubagent({
- auth: prepared.auth,
- batchEvent: input.event,
- bundle: prepared.bundle,
- callbackBaseUrl: input.callbackBaseUrl,
- capabilities: prepared.capabilities,
- channelMetadata: prepared.channelMetadata,
- currentSession: prepared.session,
- fanoutSize: prepared.fanoutSize,
- initiatorAuth: prepared.initiatorAuth,
- localDevRequest: prepared.localDevRequest,
- parentContinuationToken: input.task.taskInboxToken,
- parentTraceContext: prepared.parentTraceContext,
- activityObserver: prepared.activityObserver,
- sandboxSessionId: prepared.sandboxSessionId,
- serializedContext: prepared.serializedContext,
- session: prepared.session,
- taskOwned: true,
- target: entry.target,
- });
- if (outcome.kind === "error") throw new Error(JSON.stringify(outcome.result.output));
-
- const described = describeTaskDispatch({
- action: input.action,
- agentId: entry.kind === "resume" ? entry.agentId : undefined,
- parentSessionId: prepared.session.sessionId,
- parentTurnId: input.event.turnId,
- session: outcome.session,
- });
- const dynamicRemoteAgent =
- entry.kind === "resume"
- ? entry.dynamicRemoteAgent
- : entry.target.kind === "remote"
- ? entry.target.dynamicRemoteAgent
- : undefined;
- return {
- address: outcome.address,
- agentId: described.agentId,
- mode: described.mode,
- name: described.name,
- ...(outcome.address.kind === "agent/remote"
- ? {
- remote: {
- resolverId: dynamicRemoteAgent?.credentialsStepId ?? input.action.nodeId,
- url: outcome.address.url,
- },
- }
- : {}),
- session: outcome.session,
- };
-}
-
-function claimBatchAgent(
- batch: TaskExec["batch"],
- agentId: string,
- taskId: string,
-): string | undefined {
- let claims = batchAgentClaims.get(batch);
- if (claims === undefined) {
- claims = new Map();
- batchAgentClaims.set(batch, claims);
- }
- const claimedTaskId = claims.get(agentId);
- if (claimedTaskId !== undefined) return claimedTaskId;
- claims.set(agentId, taskId);
- return undefined;
-}
-
-async function emitSubagentCalled(input: {
- readonly callId: string;
- readonly childSessionId: string;
- readonly event: { readonly sequence: number; readonly turnId: string };
- readonly name: string;
- readonly remote?: { readonly resolverId: string; readonly url: string };
- readonly sessionId: string;
- readonly toolName: string;
-}): Promise<void> {
- const handleEvent = loadContext().get(HandleEventKey);
- if (handleEvent === undefined) return;
- try {
- await handleEvent(
- createSubagentCalledEvent({
- callId: input.callId,
- childSessionId: input.childSessionId,
- name: input.name,
- remote: input.remote,
- sequence: input.event.sequence,
- sessionId: input.sessionId,
- toolName: input.toolName,
- turnId: input.event.turnId,
- workflowId: workflowEntryReference.workflowId,
- }),
- );
- } catch (error) {
- logError(log, "subagent.called emission failed", error, {
- callId: input.callId,
- childSessionId: input.childSessionId,
- toolName: input.toolName,
- });
- }
-}
-
-async function emitSubagentCompleted(input: {
- readonly callId: string;
- readonly output: string;
- readonly subagentName: string;
- readonly taskId: string;
-}): Promise<void> {
- const handleEvent = loadContext().get(HandleEventKey);
- if (handleEvent === undefined) return;
- try {
- await handleEvent({
- data: {
- backgroundTask: { status: "working", taskId: input.taskId },
- callId: input.callId,
- output: input.output,
- subagentName: input.subagentName,
- },
- type: "subagent.completed",
- });
- } catch (error) {
- logError(log, "subagent.completed emission failed", error, {
- callId: input.callId,
- taskId: input.taskId,
- });
- }
-}
diff --git a/packages/eve/src/execution/tools/subagent/receipt-identity.ts b/packages/eve/src/execution/tools/subagent/receipt-identity.ts
new file mode 100644
index 000000000..dab16e9b7
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/receipt-identity.ts
@@ -0,0 +1,18 @@
+import { mintStartOperation } from "#execution/dispatch-start-operation.js";
+
+/** Derives the one deterministic identity shared by subagent receipts and dispatch. */
+export function createSubagentReceiptIdentity(input: {
+ readonly callId: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+ readonly subagentName: string;
+ readonly nodeId: string;
+}) {
+ return mintStartOperation({
+ callId: input.callId,
+ name: input.subagentName,
+ nodeId: input.nodeId,
+ parentSessionId: input.parentSessionId,
+ parentTurnId: input.parentTurnId,
+ });
+}
diff --git a/packages/eve/src/execution/tools/subagent/remote.ts b/packages/eve/src/execution/tools/subagent/remote.ts
deleted file mode 100644
index b53274190..000000000
--- a/packages/eve/src/execution/tools/subagent/remote.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { defineTool } from "#tools/definition.js";
-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";
-import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";
-import { executeSubagentTool } from "#execution/tools/subagent/local.js";
-import type { PendingAgentDispatchAction } from "#shared/dispatch-action.js";
-
-export function defineRemoteSubagent(input: {
- readonly description: string;
- readonly name: string;
- readonly target: Extract<
- PendingAgentDispatchAction["target"],
- { readonly kind: "remote-agent-call" }
- >;
-}) {
- return defineTool({
- description: input.description,
- execution: "background",
- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,
- execute: (toolInput, ctx, task) =>
- executeSubagentTool({ definition: input, task, toolContext: ctx, toolInput }),
- });
-}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-start.ts b/packages/eve/src/execution/tools/subagent/start.ts
similarity index 77%
rename from packages/eve/src/execution/dispatch-runtime-actions-start.ts
rename to packages/eve/src/execution/tools/subagent/start.ts
index 6342531f8..02d7dd46e 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-start.ts
+++ b/packages/eve/src/execution/tools/subagent/start.ts
@@ -1,19 +1,37 @@
import type { ActivityObserverConfig } from "#channel/types.js";
import type { LocalDevRequestProvenance } from "#context/keys.js";
-import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
-import type { DispatchStartTarget } from "#execution/dispatch-runtime-actions-shared.js";
-import { startLocalSubagent } from "#execution/subagent-start-local.js";
-import { startRemoteSubagent } from "#execution/subagent-start-remote.js";
-import { buildSubagentRunInput } from "#execution/subagent-tool.js";
import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
+import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
+import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import type {
+ RuntimeRemoteAgentDispatchRequest,
+ RuntimeSubagentDispatchRequest,
+} from "#shared/action-types.js";
import { normalizeChannelAudience } from "#shared/channel-audience.js";
import {
applyLiveDeliveryAudienceCeiling,
readForwardedTraceAssertion,
} from "#shared/forwarded-trace-policy.js";
+import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";
+import { startLocalSubagent } from "#subagents/start-local.js";
+import { startRemoteSubagent } from "#subagents/start-remote.js";
+import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";
import { readActionTraceContext } from "#tracing/agent-trace-context-store.js";
+export type SubagentStartTarget =
+ | {
+ readonly kind: "local";
+ readonly action: RuntimeSubagentDispatchRequest;
+ readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
+ readonly source: SubagentInputSource;
+ }
+ | {
+ readonly kind: "remote";
+ readonly action: RuntimeRemoteAgentDispatchRequest;
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
+ };
+
/** Starts one planned fresh child against its local or remote target. */
export async function startSubagent(input: {
readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
@@ -34,8 +52,8 @@ export async function startSubagent(input: {
readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly session: RuntimeSession;
- readonly taskOwned: boolean;
- readonly target: DispatchStartTarget;
+ readonly taskId?: string;
+ readonly target: SubagentStartTarget;
}): Promise<DispatchOutcome> {
const storedParentTraceContext =
readActionTraceContext(
@@ -78,10 +96,9 @@ export async function startSubagent(input: {
parentTraceContext,
activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
- selfAgent: input.target.selfAgent,
session: input.session,
source: input.target.source,
- taskOwned: input.taskOwned,
+ taskId: input.taskId,
});
case "remote":
return startRemoteSubagent({
@@ -98,7 +115,7 @@ export async function startSubagent(input: {
parentTraceContext,
activityObserver: input.activityObserver,
session: input.session,
- taskOwned: input.taskOwned,
+ taskId: input.taskId,
});
default: {
const _exhaustive: never = input.target;
diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
new file mode 100644
index 000000000..61fb43651
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
@@ -0,0 +1,88 @@
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { emitTaskSubagentCalledStep } from "#execution/tools/subagent/emit-called-step.js";
+import {
+ dispatchTaskAgentInvocationStep,
+ settleTaskAgentInvocationStep,
+} from "#execution/tools/subagent/invoke-step.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import type { TaskAgentRequestDelivery } from "#tasks/types.js";
+
+export interface AgentRequestDelivery {
+ readonly accumulateUsage?: boolean;
+ readonly ownerId: string;
+ readonly replyTo: TaskAgentRequestDelivery["replyTo"];
+ readonly request: TaskAgentRequestDelivery["request"];
+ readonly taskId?: string;
+}
+
+export interface TaskAgentRequestContext {
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+export interface AppliedTaskAgentRequest {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+/**
+ * Applies one workflow-owned agent request to the parent session: `agent-invoke`
+ * spawns the child with parent-owned material and `agent-settled` releases the
+ * handle. Child authorization and HITL ride their own task envelope arms.
+ */
+export async function applyTaskAgentRequest(
+ delivery: AgentRequestDelivery,
+ ctx: TaskAgentRequestContext,
+): Promise<AppliedTaskAgentRequest> {
+ const { request } = delivery;
+ switch (request.kind) {
+ case "agent-settled": {
+ const settled = await settleTaskAgentInvocationStep({
+ accumulateUsage: delivery.accumulateUsage,
+ ownerId: delivery.ownerId,
+ result: request.result,
+ sessionState: ctx.sessionState,
+ taskId: delivery.taskId,
+ });
+ return { serializedContext: ctx.serializedContext, sessionState: settled.sessionState };
+ }
+ case "agent-invoke": {
+ const dispatched = await dispatchTaskAgentInvocationStep({
+ ownerId: delivery.ownerId,
+ replyTo: delivery.replyTo,
+ request,
+ serializedContext: ctx.serializedContext,
+ sessionState: ctx.sessionState,
+ taskId: delivery.taskId,
+ });
+ switch (dispatched.kind) {
+ case "dispatched": {
+ const emitted = await emitTaskSubagentCalledStep({
+ event: dispatched.event,
+ parentWritable: ctx.parentWritable,
+ serializedContext: ctx.serializedContext,
+ });
+ return {
+ serializedContext: emitted.serializedContext,
+ sessionState: dispatched.sessionState,
+ };
+ }
+ case "failed":
+ await resumeHookStep(delivery.replyTo, {
+ kind: "runtime-action-result",
+ results: [dispatched.result],
+ });
+ return {
+ serializedContext: ctx.serializedContext,
+ sessionState: dispatched.sessionState,
+ };
+ case "not-admitted":
+ return {
+ serializedContext: ctx.serializedContext,
+ sessionState: dispatched.sessionState,
+ };
+ }
+ }
+ }
+}
diff --git a/packages/eve/src/execution/tools/subagent/task-cancel.ts b/packages/eve/src/execution/tools/subagent/task-cancel.ts
new file mode 100644
index 000000000..c34753aec
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/task-cancel.ts
@@ -0,0 +1,86 @@
+import type { RuntimeSession } from "#subagents/handle-dispatch.js";
+import type { TaskExecutorCancel } from "#execution/tasks/parent/task-cancel.js";
+import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
+import { cancelRemoteAgentTurn, resolveRemoteAgentForAction } from "#subagents/remote-dispatch.js";
+import { deserializeContext } from "#context/serialize.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import { getAgentHandleStore, type AgentHandle } from "#subagents/handles/store.js";
+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
+import { createLogger, logError } from "#internal/logging.js";
+
+const log = createLogger("execution.agent-invocation-cancel");
+
+/** Cancels the active child turn owned by a background subagent task. */
+export const cancelBackgroundAgentTask: TaskExecutorCancel = async (input) => {
+ if (input.session === undefined || input.serializedContext === undefined) return;
+ const session = input.session as RuntimeSession;
+ const handle = getAgentHandleStore(session.state)?.handles.find(
+ (candidate) => candidate.phase === "claimed" && candidate.ownerId === input.entry.taskId,
+ );
+ if (handle === undefined || handle.phase !== "claimed") return;
+ if (handle.address.kind !== "agent/remote") {
+ await requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId });
+ return;
+ }
+ const ctx = await deserializeContext(input.serializedContext);
+ const bundle = ctx.require(BundleKey);
+ const selection = getDynamicSubagentSelection(ctx, handle.identity.nodeId);
+ const remote = resolveRemoteAgentForAction({
+ dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,
+ nodeId: handle.identity.nodeId,
+ registry: bundle.subagentRegistry.subagentsByNodeId,
+ remoteAgentName: handle.identity.name,
+ });
+ await cancelRemoteAgentTurn({
+ remote: { ...remote, url: handle.address.url },
+ sessionId: handle.address.sessionId,
+ });
+};
+
+/** Cancels a child turn still claimed by a completed workflow-tool run. */
+export async function cancelAgentInvocationOwnerStep(input: {
+ readonly ownerId: string;
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}): Promise<void> {
+ "use step";
+
+ const session = await readDurableSession(input.sessionState);
+ const handles = (getAgentHandleStore(session.state)?.handles ?? []).filter(
+ (candidate): candidate is Extract<AgentHandle, { phase: "claimed" }> =>
+ candidate.phase === "claimed" && candidate.ownerId === input.ownerId,
+ );
+ if (handles.length === 0) return;
+ const remoteContext = handles.some((handle) => handle.address.kind === "agent/remote")
+ ? await deserializeContext(input.serializedContext)
+ : undefined;
+ await Promise.all(
+ handles.map(async (handle) => {
+ try {
+ if (handle.address.kind !== "agent/remote") {
+ await requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId });
+ return;
+ }
+ const bundle = remoteContext!.require(BundleKey);
+ const selection = getDynamicSubagentSelection(remoteContext!, handle.identity.nodeId);
+ const remote = resolveRemoteAgentForAction({
+ dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,
+ nodeId: handle.identity.nodeId,
+ registry: bundle.subagentRegistry.subagentsByNodeId,
+ remoteAgentName: handle.identity.name,
+ });
+ await cancelRemoteAgentTurn({
+ remote: { ...remote, url: handle.address.url },
+ sessionId: handle.address.sessionId,
+ });
+ } catch (error) {
+ logError(log, "failed to cancel workflow-owned agent turn", error, {
+ agentId: handle.identity.id,
+ childSessionId: handle.address.sessionId,
+ ownerId: input.ownerId,
+ });
+ }
+ }),
+ );
+}
diff --git a/packages/eve/src/execution/tools/tasks.ts b/packages/eve/src/execution/tools/tasks.ts
new file mode 100644
index 000000000..1d936a72f
--- /dev/null
+++ b/packages/eve/src/execution/tools/tasks.ts
@@ -0,0 +1,45 @@
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import {
+ TASK_CANCEL_INPUT_SCHEMA,
+ TASK_CANCEL_TOOL_NAME,
+ TASK_UPDATE_INPUT_SCHEMA,
+ TASK_UPDATE_TOOL_NAME,
+ TASK_VIEWS_OUTPUT_SCHEMA,
+} from "#tools/framework/task-contract.js";
+
+/** Framework controls for durable background tasks. */
+
+const TASK_CANCEL_DESCRIPTION =
+ "Request cooperative cancellation of one or more background tasks. " +
+ "Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.";
+
+const TASK_UPDATE_DESCRIPTION =
+ "Briefly tell the parent agent what this background task is currently doing. " +
+ "Report activity, not preliminary findings or results.";
+
+/**
+ * Builds harness definitions for the compiled framework task tools.
+ */
+export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinition[] {
+ return [
+ {
+ description: TASK_CANCEL_DESCRIPTION,
+ inputSchema: TASK_CANCEL_INPUT_SCHEMA,
+ name: TASK_CANCEL_TOOL_NAME,
+ outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
+ runtimeAction: { kind: "task-control" },
+ },
+ {
+ description: TASK_UPDATE_DESCRIPTION,
+ inputSchema: TASK_UPDATE_INPUT_SCHEMA,
+ name: TASK_UPDATE_TOOL_NAME,
+ runtimeAction: { kind: "task-control" },
+ },
+ ];
+}
+
+/**
+ * Authored tools with the same name shadow these framework definitions,
+ * and `disableTool(name)` removes individual controls. advertised-tools
+ * evaluates their selected availability against persisted session metadata.
+ */
diff --git a/packages/eve/src/execution/tool-run/answer.ts b/packages/eve/src/execution/tools/workflow/answer.ts
similarity index 91%
rename from packages/eve/src/execution/tool-run/answer.ts
rename to packages/eve/src/execution/tools/workflow/answer.ts
index 7417721d0..f1f60ac92 100644
--- a/packages/eve/src/execution/tool-run/answer.ts
+++ b/packages/eve/src/execution/tools/workflow/answer.ts
@@ -3,7 +3,7 @@ import type { InputResponse } from "#shared/input.js";
import type { ToolInputResponse } from "#tools/definition.js";
/** Resumed with the bare response, not a session-inbox delivery, so the body can race the hook. */
-export async function resumeToolRunAnswers(
+export async function resumeWorkflowToolRunAnswers(
answerToken: string,
responses: readonly InputResponse[] | undefined,
): Promise<void> {
diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.ts
new file mode 100644
index 000000000..e7f3adbcd
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/ask.ts
@@ -0,0 +1,76 @@
+import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+
+import type {
+ WorkflowToolRunOwner,
+ WorkflowToolRunRef,
+} from "#execution/tools/workflow/messages.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import { workflowToolRunAnswerToken } from "#harness/workflow-tool-runs.js";
+import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
+
+// `Symbol.for`, not a module-local WeakMap: `ask()` ships via the `eve/workflow`
+// entry while `attachWorkflowToolRunContext` runs from `body.ts`, and those may
+// be different bundled copies of this module.
+const WORKFLOW_TOOL_RUN_CONTEXT = Symbol.for("eve.workflow-tool-run.context");
+
+interface WorkflowToolRunContext {
+ /** Compatibility for already-started two-run background workflows. */
+ readonly admission?: Promise<
+ { readonly status: "accepted" } | { readonly status: "rejected"; readonly reason: string }
+ >;
+ answerSeq: number;
+ readonly from: WorkflowToolRunRef;
+ readonly owner: WorkflowToolRunOwner;
+}
+
+type WorkflowToolRunContextCarrier = {
+ readonly [WORKFLOW_TOOL_RUN_CONTEXT]?: WorkflowToolRunContext;
+};
+
+export function attachWorkflowToolRunContext(
+ ctx: ToolContext,
+ context: Omit<WorkflowToolRunContext, "answerSeq">,
+): void {
+ Object.defineProperty(ctx, WORKFLOW_TOOL_RUN_CONTEXT, {
+ enumerable: false,
+ value: { ...context, answerSeq: 0 },
+ });
+}
+
+function readWorkflowToolRunContext(ctx: ToolContext): WorkflowToolRunContext {
+ const context = (ctx as WorkflowToolRunContextCarrier)[WORKFLOW_TOOL_RUN_CONTEXT];
+ if (context === undefined) {
+ throw new Error(
+ 'This function must be called with the context of a workflow tool body ("use workflow").',
+ );
+ }
+ return context;
+}
+
+export function readWorkflowToolRunRef(ctx: ToolContext): WorkflowToolRunRef {
+ return readWorkflowToolRunContext(ctx).from;
+}
+
+export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwner {
+ return readWorkflowToolRunContext(ctx).owner;
+}
+
+export function readWorkflowToolRunAdmission(
+ ctx: ToolContext,
+): WorkflowToolRunContext["admission"] {
+ return readWorkflowToolRunContext(ctx).admission;
+}
+
+/** Returns an answer hook which may be awaited or raced with another workflow operation. */
+export function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> {
+ const context = readWorkflowToolRunContext(ctx);
+ const answer = createHook<ToolInputResponse>({
+ token: workflowToolRunAnswerToken(context.from.runId, context.answerSeq++),
+ });
+ void resumeHookStep(context.owner.request, {
+ from: context.from,
+ replyTo: answer.token,
+ request: { kind: "ask", request },
+ });
+ return answer;
+}
diff --git a/packages/eve/src/execution/tools/workflow/background.test.ts b/packages/eve/src/execution/tools/workflow/background.test.ts
new file mode 100644
index 000000000..110537d6d
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/background.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+
+import { jsonSchema } from "ai";
+import { createWorkflowToolHarnessDefinition, parseWorkflowToolInput } from "./background.js";
+
+describe("createWorkflowToolHarnessDefinition", () => {
+ it("preserves subagent resultKind on workflow-backed tools", () => {
+ expect(
+ createWorkflowToolHarnessDefinition({
+ definition: {
+ description: "Delegate research.",
+ execution: "background",
+ execute: () => undefined,
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "research",
+ },
+ resultKind: "subagent",
+ workflowId: "workflow//eve//subagentToolExecuteWorkflow",
+ }),
+ ).toMatchObject({ resultKind: "subagent" });
+ });
+});
+
+describe("parseWorkflowToolInput", () => {
+ it("passes a JSON object through", () => {
+ expect(parseWorkflowToolInput({ service: "api" }, "deploy")).toEqual({ service: "api" });
+ });
+
+ it("rejects an input that cannot cross the run boundary, naming the tool", () => {
+ for (const input of [new Date(0), "api", 42, null, undefined, ["api"]]) {
+ expect(() => parseWorkflowToolInput(input, "deploy")).toThrow(
+ /Tool "deploy" is a workflow, so its parsed input must be a JSON object/u,
+ );
+ }
+ });
+});
diff --git a/packages/eve/src/execution/tools/workflow/background.ts b/packages/eve/src/execution/tools/workflow/background.ts
new file mode 100644
index 000000000..d046fb8b7
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/background.ts
@@ -0,0 +1,90 @@
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
+import { parseJsonObject, type JsonValue } from "#shared/json.js";
+import type { ToolExecuteOptions } from "#tools/definition.js";
+import type { TaskExec } from "#tools/task.js";
+import { UNSPECIFIED_INPUT_SCHEMA, toInputSchema, toOutputSchema } from "#tools/schema.js";
+
+export interface WorkflowToolHarnessDefinitionInput {
+ readonly definition: HarnessToolDefinition;
+ readonly executeInput?: (input: unknown) => JsonValue;
+ readonly nodeId?: string;
+ readonly resultKind?: "subagent" | "tool";
+ readonly workflowId: string;
+}
+
+export function createWorkflowToolHarnessDefinition(
+ input: WorkflowToolHarnessDefinitionInput,
+): HarnessToolDefinition {
+ const definition = input.definition;
+ const workflow = {
+ executeInput: input.executeInput,
+ nodeId: input.nodeId,
+ resultKind: input.resultKind,
+ workflowId: input.workflowId,
+ };
+ if (definition.execution !== "background") {
+ return { ...definition, ...workflow, execute: undefined };
+ }
+ return {
+ ...definition,
+ ...workflow,
+ execute: createWorkflowToolBackgroundExecute({
+ toolName: definition.name,
+ workflowId: input.workflowId,
+ }),
+ };
+}
+
+export function createPreparedWorkflowToolHarnessDefinition(
+ tool: PreparedRuntimeTool,
+): HarnessToolDefinition {
+ if (tool.task === undefined) {
+ throw new Error(`Prepared tool "${tool.name}" is not backed by a workflow task.`);
+ }
+ const input: {
+ -readonly [
+ K in keyof WorkflowToolHarnessDefinitionInput
+ ]: WorkflowToolHarnessDefinitionInput[K];
+ } = {
+ definition: {
+ behavior: tool.behavior,
+ description: tool.description,
+ execution: tool.execution,
+ inputSchema: toInputSchema(tool.inputSchema) ?? UNSPECIFIED_INPUT_SCHEMA,
+ name: tool.name,
+ outputSchema: toOutputSchema(tool.outputSchema),
+ rootOnly: tool.rootOnly,
+ },
+ nodeId: tool.task.nodeId,
+ resultKind: tool.task.resultKind,
+ workflowId: tool.task.workflowId,
+ };
+ return createWorkflowToolHarnessDefinition(input);
+}
+
+/** Returns a task receipt after the background scope starts the owning run. */
+export function createWorkflowToolBackgroundExecute(input: {
+ readonly toolName: string;
+ readonly workflowId: string;
+}): NonNullable<HarnessToolDefinition["execute"]> {
+ return (_toolInput: unknown, _options: ToolExecuteOptions, _task?: TaskExec): never => {
+ throw new Error(
+ `Background workflow tool "${input.toolName}" must be started by the task runtime (${input.workflowId}).`,
+ );
+ };
+}
+
+export function parseWorkflowToolInput(
+ toolInput: unknown,
+ toolName: string,
+): ReturnType<typeof parseJsonObject> {
+ try {
+ return parseJsonObject(toolInput);
+ } catch (error) {
+ throw new TypeError(
+ `Tool "${toolName}" is a workflow, so its parsed input must be a JSON object.`,
+ { cause: error },
+ );
+ }
+}
diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.ts
new file mode 100644
index 000000000..52810eb1b
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/body.ts
@@ -0,0 +1,134 @@
+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
+
+import type { SessionContext } from "#context/session-context.js";
+import { attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import {
+ type WorkflowToolRunOutcome,
+ type WorkflowToolRunOwner,
+ type WorkflowToolRunRef,
+ type WorkflowToolRunReport,
+} from "#execution/tools/workflow/messages.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import { normalizeSerializableError } from "#execution/workflow-errors.js";
+import { readRegisteredWorkflow } from "#execution/workflow-registry.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
+import type { ToolContext } from "#tools/definition.js";
+
+export interface WorkflowBodyDefinition {
+ readonly callId: string;
+ readonly executeInput?: JsonValue;
+ readonly input: JsonObject;
+ readonly resultKind?: "subagent" | "tool";
+ readonly session: SessionContext["session"];
+ readonly stepIndex: number;
+ readonly toolName: string;
+ readonly workflowId: string;
+}
+
+export interface WorkflowBodyInput extends WorkflowBodyDefinition {
+ readonly owner: WorkflowToolRunOwner;
+}
+
+type WorkflowToolExecute = (
+ input: unknown,
+ ctx: ToolContext,
+) => Promise<JsonValue> | AsyncIterable<JsonValue>;
+
+/** Executes one registered workflow body and reports progress to its owner. */
+export async function executeWorkflowBody(
+ input: WorkflowBodyInput & {
+ readonly execution: "background" | "blocking";
+ readonly runId?: string;
+ },
+ signal: AbortSignal,
+): Promise<WorkflowToolRunOutcome> {
+ const from = createWorkflowBodyRef(input);
+ const ctx = createWorkflowBodyContext(input, signal);
+ attachWorkflowToolRunContext(ctx, { from, owner: input.owner });
+
+ try {
+ const execute = resolveWorkflowToolExecute(input);
+ const result = execute(input.executeInput ?? input.input, ctx);
+ let output: JsonValue;
+ if (!isAsyncIterable(result)) {
+ output = await result;
+ } else {
+ const iterator = result[Symbol.asyncIterator]();
+ let last: JsonValue | undefined;
+ let next = await iterator.next();
+ while (next.done !== true) {
+ last = next.value;
+ const report: WorkflowToolRunReport = { from, update: next.value };
+ await resumeHookStep(input.owner.report, report);
+ next = await iterator.next();
+ }
+ output = (next.value as JsonValue | undefined) ?? last ?? null;
+ }
+ return { output, status: "completed" };
+ } catch (error) {
+ if (signal.aborted) {
+ return {
+ reason:
+ signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? ""),
+ status: "cancelled",
+ };
+ }
+ return { error: normalizeSerializableError(error), status: "failed" };
+ }
+}
+
+export function createWorkflowBodyRef(
+ input: WorkflowBodyDefinition & {
+ readonly execution: "background" | "blocking";
+ readonly runId?: string;
+ },
+): WorkflowToolRunRef {
+ return {
+ callId: input.callId,
+ execution: input.execution,
+ input: input.input,
+ resultKind: input.resultKind,
+ runId: input.runId ?? getWorkflowMetadata().workflowRunId,
+ sequence: input.session.turn.sequence,
+ stepIndex: input.stepIndex,
+ toolName: input.toolName,
+ turnId: input.session.turn.id,
+ };
+}
+
+function resolveWorkflowToolExecute(input: WorkflowBodyInput): WorkflowToolExecute {
+ const execute = readRegisteredWorkflow(input.workflowId);
+ if (typeof execute !== "function") {
+ throw new Error(
+ `Tool "${input.toolName}" is not registered as a workflow in this deployment (${input.workflowId}). The tool was renamed or removed after this run started.`,
+ );
+ }
+ return execute as WorkflowToolExecute;
+}
+
+function createWorkflowBodyContext(input: WorkflowBodyInput, signal: AbortSignal): ToolContext {
+ const unavailable = (member: string, hint: string): never => {
+ throw new Error(
+ `ctx.${member} is not available inside a workflow tool; ${hint}. Tool "${input.toolName}" runs as a durable workflow body, which only replays deterministic code.`,
+ );
+ };
+ return {
+ abortSignal: signal,
+ callId: input.callId,
+ getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),
+ getSkill: () => unavailable("getSkill()", "skills are read through the session sandbox"),
+ getToken: () =>
+ unavailable("getToken()", 'read credentials from the environment inside a "use step" helper'),
+ requireAuth: () => unavailable("requireAuth()", "a workflow body cannot park on authorization"),
+ session: input.session,
+ toolName: input.toolName,
+ };
+}
+
+function isAsyncIterable(value: unknown): value is AsyncIterable<JsonValue> {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ typeof (value as AsyncIterable<JsonValue>)[Symbol.asyncIterator] === "function"
+ );
+}
diff --git a/packages/eve/src/execution/tool-run/cancel.ts b/packages/eve/src/execution/tools/workflow/cancel.ts
similarity index 60%
rename from packages/eve/src/execution/tool-run/cancel.ts
rename to packages/eve/src/execution/tools/workflow/cancel.ts
index 13e5482fd..058f45f42 100644
--- a/packages/eve/src/execution/tool-run/cancel.ts
+++ b/packages/eve/src/execution/tools/workflow/cancel.ts
@@ -1,18 +1,21 @@
-import type { RunControlMessage } from "#execution/tool-run/messages.js";
-import type { ToolRunAddress } from "#execution/tool-run/types.js";
+import type { WorkflowToolRunControlMessage } from "#execution/tools/workflow/messages.js";
+import type { WorkflowToolRunAddress } from "#execution/tools/workflow/types.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import { cancelRun, getWorld, resumeHook } from "#internal/workflow/runtime.js";
import { createLogger, logError } from "#internal/logging.js";
-const log = createLogger("execution.tool-run");
+const log = createLogger("execution.workflow-tool-run");
/**
* Asks the run to cancel itself; cancels it outright only if the message cannot
* be delivered. Failures are logged, not thrown: the caller has already
* committed the cancellation the run was serving.
*/
-export async function cancelToolRun(run: ToolRunAddress, reason: string): Promise<void> {
- const cancel: RunControlMessage = { kind: "cancel", reason };
+export async function cancelWorkflowToolRun(
+ run: WorkflowToolRunAddress,
+ reason: string,
+): Promise<void> {
+ const cancel: WorkflowToolRunControlMessage = { kind: "cancel", reason };
try {
await resumeHook(run.hookToken, cancel);
return;
@@ -32,3 +35,12 @@ export async function cancelToolRun(run: ToolRunAddress, reason: string): Promis
});
}
}
+
+export async function cancelWorkflowToolRunStep(input: {
+ readonly reason: string;
+ readonly run: WorkflowToolRunAddress;
+}): Promise<void> {
+ "use step";
+
+ await cancelWorkflowToolRun(input.run, input.reason);
+}
diff --git a/packages/eve/src/execution/tool-run/emit-run-report-step.ts b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
similarity index 82%
rename from packages/eve/src/execution/tool-run/emit-run-report-step.ts
rename to packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
index 6bad715d4..ac9b832c4 100644
--- a/packages/eve/src/execution/tool-run/emit-run-report-step.ts
+++ b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts
@@ -1,4 +1,4 @@
-import type { RunRef } from "#execution/tool-run/messages.js";
+import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import {
createActionPartialEvent,
@@ -7,8 +7,8 @@ import {
} from "#protocol/message.js";
import type { JsonValue } from "#shared/json.js";
-export async function emitRunReportStep(input: {
- readonly from: RunRef;
+export async function emitWorkflowToolRunReportStep(input: {
+ readonly from: WorkflowToolRunRef;
readonly parentWritable: WritableStream<Uint8Array>;
readonly update: JsonValue;
}): Promise<void> {
diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.ts
new file mode 100644
index 000000000..b2657fdac
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/messages.ts
@@ -0,0 +1,117 @@
+import { defineHook } from "#compiled/@workflow/core/index.js";
+
+import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
+import type {
+ AgentInvocationRequest,
+ AgentSettlementRequest,
+} from "#execution/tools/subagent/invoke-agent.js";
+import type { InputRequest } from "#shared/input.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
+import type { ToolInputRequest } from "#tools/definition.js";
+
+export interface WorkflowToolRunOwner {
+ readonly admission: string;
+ readonly outcome: string;
+ readonly report: string;
+ readonly request: string;
+}
+
+/**
+ * Requests the owner must apply on the run's behalf because they touch
+ * owner-held state: spawning an agent and releasing its handle afterwards.
+ */
+export type WorkflowToolAgentRequest = AgentInvocationRequest | AgentSettlementRequest;
+
+/**
+ * A child authorization event the owner should display. Unlike input requests
+ * it has no answer: the authorization callback completes against the child
+ * directly, so the owner only re-emits it.
+ */
+export interface WorkflowToolAuthorizationRequest {
+ readonly event: SubagentAuthorizationEventHookPayload;
+ readonly kind: "authorization-request";
+}
+
+/** A question authored with `ask()` from `eve/workflow`, before owner normalization. */
+export interface WorkflowToolAskRequest {
+ readonly kind: "ask";
+ readonly request: ToolInputRequest;
+}
+
+/**
+ * A child subagent's pending input requests for one step, forwarded as a unit
+ * so the owner resolves them against the same child step they came from.
+ */
+export interface WorkflowToolInputRequestBatch {
+ readonly kind: "input-batch";
+ readonly requests: readonly InputRequest[];
+}
+
+export type WorkflowToolRequest =
+ | WorkflowToolAgentRequest
+ | WorkflowToolAuthorizationRequest
+ | WorkflowToolAskRequest
+ | InputRequest
+ | WorkflowToolInputRequestBatch;
+
+/** Identifies the sending workflow tool run to an owner shared by many runs. */
+export interface WorkflowToolRunRef {
+ readonly callId: string;
+ readonly execution: "background" | "blocking";
+ readonly input: JsonObject;
+ readonly resultKind?: "subagent" | "tool";
+ readonly runId: string;
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly toolName: string;
+ readonly turnId: string;
+}
+
+export type WorkflowToolRunOutcome =
+ | { readonly status: "completed"; readonly output: JsonValue }
+ | { readonly status: "failed"; readonly error: unknown }
+ | { readonly status: "cancelled"; readonly reason?: string };
+
+export interface WorkflowToolRunReport {
+ readonly from: WorkflowToolRunRef;
+ readonly update: JsonValue;
+}
+
+export interface WorkflowToolRunRequestMessage {
+ readonly from: WorkflowToolRunRef;
+ readonly replyTo: string;
+ readonly request: WorkflowToolRequest;
+ readonly requestCoordinates?: {
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
+ };
+}
+
+export interface WorkflowToolRunOutcomeMessage {
+ readonly from: WorkflowToolRunRef;
+ readonly result: WorkflowToolRunOutcome;
+}
+
+export const workflowToolRunReportHook = defineHook<WorkflowToolRunReport>();
+export const workflowToolRunRequestHook = defineHook<WorkflowToolRunRequestMessage>();
+export const workflowToolRunOutcomeHook = defineHook<WorkflowToolRunOutcomeMessage>();
+
+export function deriveWorkflowToolRunOwner(inboxToken: string): WorkflowToolRunOwner {
+ return {
+ admission: `${inboxToken}:admission`,
+ outcome: `${inboxToken}:outcome`,
+ report: `${inboxToken}:report`,
+ request: `${inboxToken}:request`,
+ };
+}
+
+export type WorkflowToolRunControlMessage = { readonly kind: "cancel"; readonly reason: string };
+
+export function isWorkflowToolRunControlMessage(
+ value: unknown,
+): value is WorkflowToolRunControlMessage {
+ if (typeof value !== "object" || value === null) return false;
+ const { kind, reason } = value as { kind?: unknown; reason?: unknown };
+ return kind === "cancel" && typeof reason === "string";
+}
diff --git a/packages/eve/src/execution/tool-run/owner-channels.test.ts b/packages/eve/src/execution/tools/workflow/owner-channels.test.ts
similarity index 100%
rename from packages/eve/src/execution/tool-run/owner-channels.test.ts
rename to packages/eve/src/execution/tools/workflow/owner-channels.test.ts
diff --git a/packages/eve/src/execution/tool-run/owner-channels.ts b/packages/eve/src/execution/tools/workflow/owner-channels.ts
similarity index 100%
rename from packages/eve/src/execution/tool-run/owner-channels.ts
rename to packages/eve/src/execution/tools/workflow/owner-channels.ts
diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
new file mode 100644
index 000000000..365623d0e
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ workflowToolRunOutcomeToTaskCommand,
+ workflowToolRunRequestToTaskInputRequest,
+} from "#execution/tools/workflow/owner-inbox.js";
+
+const from = {
+ callId: "call-1",
+ execution: "background" as const,
+ input: { message: "Find it" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn-1",
+};
+
+describe("workflow-tool task input", () => {
+ it("preserves a forwarded child request id independently of its session route", () => {
+ const request = {
+ action: {
+ callId: "child-call",
+ input: { ticker: "GOOG" },
+ kind: "tool-call" as const,
+ toolName: "get_stock_price",
+ },
+ kind: "tool-approval" as const,
+ prompt: "Approve tool call: get_stock_price",
+ requestId: "approval-1",
+ };
+
+ expect(
+ workflowToolRunRequestToTaskInputRequest({
+ from,
+ replyTo: "subagent:parent:call-1",
+ request,
+ }),
+ ).toEqual({
+ kind: "task-input-request",
+ replyTo: "subagent:parent:call-1",
+ request,
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn-1",
+ });
+ });
+
+ it("uses child event coordinates for repeated forwarded requests", () => {
+ const request = {
+ action: {
+ callId: "child-call",
+ input: {},
+ kind: "tool-call" as const,
+ toolName: "approval_gate",
+ },
+ kind: "tool-approval" as const,
+ prompt: "Approve?",
+ requestId: "approval-2",
+ };
+
+ expect(
+ workflowToolRunRequestToTaskInputRequest({
+ from,
+ replyTo: "subagent:parent:call-1",
+ request,
+ requestCoordinates: { sequence: 4, stepIndex: 2, turnId: "turn-child" },
+ }),
+ ).toEqual({
+ kind: "task-input-request",
+ replyTo: "subagent:parent:call-1",
+ request,
+ sequence: 4,
+ stepIndex: 2,
+ turnId: "turn-child",
+ });
+ });
+
+ it("does not normalize workflow agent requests as human input", () => {
+ expect(() =>
+ workflowToolRunRequestToTaskInputRequest({
+ from,
+ replyTo: "subagent:parent:call-1",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1",
+ kind: "agent-invoke",
+ },
+ }),
+ ).toThrow("A workflow agent request cannot be normalized as human input.");
+ });
+});
+
+describe("workflow-tool task outcomes", () => {
+ it("keeps a subagent failure object as task failure data", () => {
+ expect(
+ workflowToolRunOutcomeToTaskCommand({
+ from: { ...from, resultKind: "subagent" },
+ result: {
+ error: {
+ code: "SUBAGENT_EXECUTION_FAILED",
+ message: "child crashed",
+ },
+ status: "failed",
+ },
+ }),
+ ).toEqual({
+ data: {
+ code: "SUBAGENT_EXECUTION_FAILED",
+ message: "child crashed",
+ },
+ kind: "fail",
+ });
+ });
+
+ it("keeps ordinary workflow-tool task failures as message strings", () => {
+ expect(
+ workflowToolRunOutcomeToTaskCommand({
+ from,
+ result: {
+ error: {
+ message: "export failed",
+ },
+ status: "failed",
+ },
+ }),
+ ).toEqual({
+ data: "export failed",
+ kind: "fail",
+ });
+ });
+});
diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.ts
new file mode 100644
index 000000000..3ea4465fd
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.ts
@@ -0,0 +1,214 @@
+import type { SubagentInputRequestHookPayload } from "#channel/types.js";
+import type {
+ WorkflowToolRunOutcomeMessage,
+ WorkflowToolRunReport,
+ WorkflowToolRunRef,
+ WorkflowToolInputRequestBatch,
+ WorkflowToolRequest,
+ WorkflowToolRunRequestMessage,
+} from "#execution/tools/workflow/messages.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+import type { RuntimeSubagentResult } from "#shared/action-types.js";
+import type { InputRequest } from "#shared/input.js";
+import type { ToolInputRequest } from "#tools/definition.js";
+import type { WorkflowToolRunTaskInputRequest } from "#execution/tasks/child/workflow.js";
+import type { TaskCommand, TaskInboundUpdate } from "#tasks/types.js";
+import { SUBAGENT_EXECUTION_FAILED } from "#subagents/agent-handle-errors.js";
+import { parseJsonValue, type JsonValue } from "#shared/json.js";
+
+export function workflowToolRunOutcomeToToolResult(
+ message: WorkflowToolRunOutcomeMessage,
+): RuntimeToolResultActionResult {
+ const { from, result } = message;
+ if (result.status === "completed") {
+ return {
+ callId: from.callId,
+ kind: "tool-result",
+ output: result.output,
+ toolName: from.toolName,
+ };
+ }
+ return {
+ callId: from.callId,
+ isError: true,
+ kind: "tool-result",
+ output:
+ result.status === "failed"
+ ? errorMessage(result.error)
+ : (result.reason ?? "The workflow tool run was cancelled."),
+ toolName: from.toolName,
+ };
+}
+
+/** Reads a blocking agent result returned through an ordinary run outcome. */
+export function workflowToolRunOutcomeToSubagentResult(
+ message: WorkflowToolRunOutcomeMessage,
+): RuntimeSubagentResult {
+ if (message.result.status === "completed" && isRuntimeSubagentResult(message.result.output)) {
+ return message.result.output;
+ }
+ const output =
+ message.result.status === "failed"
+ ? errorMessage(message.result.error)
+ : message.result.status === "cancelled"
+ ? (message.result.reason ?? "The agent invocation was cancelled.")
+ : "The agent invocation returned an invalid result.";
+ return {
+ callId: message.from.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output,
+ subagentName: message.from.toolName,
+ };
+}
+
+export function workflowToolRunOutcomeToTaskCommand(
+ message: WorkflowToolRunOutcomeMessage,
+): TaskCommand {
+ if (message.result.status === "completed") {
+ return { data: message.result.output, kind: "complete" };
+ }
+ if (message.result.status === "failed") {
+ return {
+ data:
+ message.from.resultKind === "subagent"
+ ? subagentFailureOutput(message.result.error)
+ : errorMessage(message.result.error),
+ kind: "fail",
+ };
+ }
+ return { kind: "cancel" };
+}
+
+function subagentFailureOutput(error: unknown): JsonValue {
+ const parsed = parseJsonValueOrUndefined(error);
+ if (
+ parsed !== undefined &&
+ typeof parsed === "object" &&
+ parsed !== null &&
+ !Array.isArray(parsed) &&
+ typeof Reflect.get(parsed, "code") === "string"
+ ) {
+ return parsed;
+ }
+ return {
+ code: SUBAGENT_EXECUTION_FAILED,
+ message: errorMessage(error),
+ };
+}
+
+export function workflowToolRunReportToTaskUpdate(
+ report: WorkflowToolRunReport,
+ taskId: string,
+ updateIndex: number,
+): TaskInboundUpdate {
+ return {
+ callId: report.from.callId,
+ kind: "task-update",
+ message: typeof report.update === "string" ? report.update : JSON.stringify(report.update),
+ updateEpoch: taskId,
+ updateIndex,
+ };
+}
+
+function isRuntimeSubagentResult(value: unknown): value is RuntimeSubagentResult {
+ if (typeof value !== "object" || value === null) return false;
+ const origin = Reflect.get(value, "origin");
+ return (
+ Reflect.get(value, "kind") === "subagent-result" &&
+ (origin === "child" || origin === "dispatch")
+ );
+}
+
+function errorMessage(error: unknown): string {
+ if (typeof error === "object" && error !== null && "message" in error) {
+ const message = (error as { readonly message?: unknown }).message;
+ if (typeof message === "string") return message;
+ }
+ return String(error);
+}
+
+function parseJsonValueOrUndefined(value: unknown): JsonValue | undefined {
+ try {
+ return parseJsonValue(value);
+ } catch {
+ return undefined;
+ }
+}
+
+export function workflowToolRunRequestToInputRequestPayload(
+ message: WorkflowToolRunRequestMessage,
+): SubagentInputRequestHookPayload {
+ const { from, replyTo, request, requestCoordinates } = message;
+ return {
+ callId: from.callId,
+ childContinuationToken: replyTo,
+ childSessionId: from.runId,
+ event: {
+ requests:
+ request.kind === "input-batch"
+ ? request.requests
+ : [normalizeInputRequest(request, from, replyTo)],
+ sequence: requestCoordinates?.sequence ?? from.sequence,
+ stepIndex: requestCoordinates?.stepIndex ?? from.stepIndex,
+ turnId: requestCoordinates?.turnId ?? from.turnId,
+ },
+ kind: "subagent-input-request",
+ subagentName: from.toolName,
+ };
+}
+
+export function workflowToolRunRequestToTaskInputRequest(
+ message: WorkflowToolRunRequestMessage,
+): WorkflowToolRunTaskInputRequest {
+ const { from, replyTo, request, requestCoordinates } = message;
+ const base = {
+ kind: "task-input-request" as const,
+ replyTo,
+ sequence: requestCoordinates?.sequence ?? from.sequence,
+ stepIndex: requestCoordinates?.stepIndex ?? from.stepIndex,
+ turnId: requestCoordinates?.turnId ?? from.turnId,
+ };
+ return request.kind === "input-batch"
+ ? { ...base, requests: request.requests }
+ : { ...base, request: normalizeInputRequest(request, from, replyTo) };
+}
+
+function normalizeInputRequest(
+ request: Exclude<WorkflowToolRequest, WorkflowToolInputRequestBatch>,
+ from: WorkflowToolRunRef,
+ requestId: string,
+): InputRequest {
+ switch (request.kind) {
+ case "agent-invoke":
+ case "agent-settled":
+ throw new TypeError("A workflow agent request cannot be normalized as human input.");
+ case "authorization-request":
+ throw new TypeError("A workflow authorization event cannot be normalized as human input.");
+ case "ask":
+ return normalizeAskRequest(request.request, from, requestId);
+ default:
+ return request;
+ }
+}
+
+function normalizeAskRequest(
+ authored: ToolInputRequest,
+ from: WorkflowToolRunRef,
+ requestId: string,
+): InputRequest {
+ if (typeof authored.prompt !== "string" || authored.prompt.length === 0) {
+ throw new TypeError("A workflow tool run request needs a non-empty `prompt`.");
+ }
+ const normalized: InputRequest = {
+ action: { callId: from.callId, input: from.input, kind: "tool-call", toolName: from.toolName },
+ kind: "question",
+ prompt: authored.prompt,
+ requestId,
+ };
+ if (authored.allowFreeform !== undefined) normalized.allowFreeform = authored.allowFreeform;
+ if (authored.display !== undefined) normalized.display = authored.display;
+ if (authored.options !== undefined) normalized.options = [...authored.options];
+ return normalized;
+}
diff --git a/packages/eve/src/execution/tools/workflow/owner.ts b/packages/eve/src/execution/tools/workflow/owner.ts
new file mode 100644
index 000000000..93f7833fe
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/owner.ts
@@ -0,0 +1,45 @@
+import { disposeHook } from "#execution/hook-ownership.js";
+import {
+ deriveWorkflowToolRunOwner,
+ workflowToolRunOutcomeHook,
+ workflowToolRunReportHook,
+ workflowToolRunRequestHook,
+ type WorkflowToolRunOutcomeMessage,
+ type WorkflowToolRunReport,
+ type WorkflowToolRunRequestMessage,
+} from "#execution/tools/workflow/messages.js";
+import {
+ type ChannelReader,
+ createChannelReader,
+} from "#execution/tools/workflow/owner-channels.js";
+
+/** In read priority: what a workflow tool run said before its outcome lands first. */
+export type WorkflowToolRunOwnerReaders = readonly [
+ ChannelReader<"report", WorkflowToolRunReport>,
+ ChannelReader<"request", WorkflowToolRunRequestMessage>,
+ ChannelReader<"outcome", WorkflowToolRunOutcomeMessage>,
+];
+
+export interface WorkflowToolRunOwnerChannels {
+ readonly readers: WorkflowToolRunOwnerReaders;
+ dispose(): Promise<void>;
+}
+
+export function openWorkflowToolRunOwnerChannels(inboxToken: string): WorkflowToolRunOwnerChannels {
+ const owner = deriveWorkflowToolRunOwner(inboxToken);
+ const report = workflowToolRunReportHook.create({ token: owner.report });
+ const request = workflowToolRunRequestHook.create({ token: owner.request });
+ const outcome = workflowToolRunOutcomeHook.create({ token: owner.outcome });
+ return {
+ readers: [
+ createChannelReader("report", report),
+ createChannelReader("request", request),
+ createChannelReader("outcome", outcome),
+ ],
+ async dispose() {
+ await disposeHook(report);
+ await disposeHook(request);
+ await disposeHook(outcome);
+ },
+ };
+}
diff --git a/packages/eve/src/execution/tool-run/resume-hook-step.ts b/packages/eve/src/execution/tools/workflow/resume-hook-step.ts
similarity index 100%
rename from packages/eve/src/execution/tool-run/resume-hook-step.ts
rename to packages/eve/src/execution/tools/workflow/resume-hook-step.ts
diff --git a/packages/eve/src/execution/tool-run/run-control.ts b/packages/eve/src/execution/tools/workflow/run-control.ts
similarity index 61%
rename from packages/eve/src/execution/tool-run/run-control.ts
rename to packages/eve/src/execution/tools/workflow/run-control.ts
index c190fefab..a60b45d80 100644
--- a/packages/eve/src/execution/tool-run/run-control.ts
+++ b/packages/eve/src/execution/tools/workflow/run-control.ts
@@ -1,22 +1,25 @@
import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
-import { isRunControlMessage, type RunControlMessage } from "#execution/tool-run/messages.js";
+import {
+ isWorkflowToolRunControlMessage,
+ type WorkflowToolRunControlMessage,
+} from "#execution/tools/workflow/messages.js";
/**
* The run's control inbox. An unawaited hook read is not scheduled under
* replay, so `cancelled` must be raced for a cancel to be observed at all.
*/
-export interface RunControlInbox {
- readonly hook: Hook<RunControlMessage>;
+export interface WorkflowToolRunControlInbox {
+ readonly hook: Hook<WorkflowToolRunControlMessage>;
readonly signal: AbortSignal;
- /** Rejects with {@link RunCancelledError} when a cancel message arrives; never resolves. */
+ /** Rejects with {@link WorkflowToolRunCancelledError} when a cancel message arrives; never resolves. */
readonly cancelled: Promise<never>;
reason(): string | undefined;
}
/** Opens without claiming, so a losing duplicate start never trips the signal. */
-export function openRunControlInbox(hookToken: string): RunControlInbox {
- const hook = createHook<RunControlMessage>({ token: hookToken });
+export function openWorkflowToolRunControlInbox(hookToken: string): WorkflowToolRunControlInbox {
+ const hook = createHook<WorkflowToolRunControlMessage>({ token: hookToken });
// Hook promises and iterators share one durable cursor. Create the iterator
// before the caller claims so conflict replay is consumed by getConflict().
const iterator = hook[Symbol.asyncIterator]();
@@ -25,7 +28,7 @@ export function openRunControlInbox(hookToken: string): RunControlInbox {
const cancelled = consumeCancel(iterator, (reason) => {
cancelReason = reason;
- controller.abort(new RunCancelledError(reason));
+ controller.abort(new WorkflowToolRunCancelledError(reason));
});
// Racing drives the read; a lone reference must not surface as unhandled.
cancelled.catch(() => {});
@@ -40,26 +43,26 @@ export function openRunControlInbox(hookToken: string): RunControlInbox {
// End-of-stream parks forever so the race is simply never won.
async function consumeCancel(
- iterator: AsyncIterator<RunControlMessage>,
+ iterator: AsyncIterator<WorkflowToolRunControlMessage>,
onCancel: (reason: string) => void,
): Promise<never> {
while (true) {
- let next: IteratorResult<RunControlMessage>;
+ let next: IteratorResult<WorkflowToolRunControlMessage>;
try {
next = await iterator.next();
} catch {
return await new Promise<never>(() => {});
}
if (next.done === true) return await new Promise<never>(() => {});
- if (!isRunControlMessage(next.value)) continue;
+ if (!isWorkflowToolRunControlMessage(next.value)) continue;
onCancel(next.value.reason);
- throw new RunCancelledError(next.value.reason);
+ throw new WorkflowToolRunCancelledError(next.value.reason);
}
}
-export class RunCancelledError extends Error {
+export class WorkflowToolRunCancelledError extends Error {
constructor(reason: string) {
super(reason);
- this.name = "RunCancelledError";
+ this.name = "WorkflowToolRunCancelledError";
}
}
diff --git a/packages/eve/src/execution/tools/workflow/start.ts b/packages/eve/src/execution/tools/workflow/start.ts
new file mode 100644
index 000000000..d6d5f83af
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/start.ts
@@ -0,0 +1,105 @@
+import type { SessionAuth, SessionParent } from "#context/session-context.js";
+import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import { recordWorkflowToolRun } from "#harness/workflow-tool-runs.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { RuntimeSession } from "#subagents/handle-dispatch.js";
+import type {
+ RuntimeToolResultActionResult,
+ RuntimeWorkflowTaskRequest,
+} from "#shared/action-types.js";
+import { toError } from "#shared/errors.js";
+import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";
+import { deriveWorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
+import {
+ startWorkflowOnCurrentDeployment,
+ workflowToolRunWorkflowReference,
+ waitForCommandHookOwner,
+} from "#execution/workflow-runtime.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
+
+const log = createLogger("execution.workflow-tool-run");
+
+// Derived from the call alone so a replayed dispatch starts a duplicate that
+// loses the claim and still resolves to the workflow tool run that owns the call.
+export function deriveWorkflowToolRunHookToken(input: {
+ readonly callId: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+}): string {
+ return `eve:workflow-tool-run:${deriveAgentOperationId(input)}`;
+}
+
+/** Resolves once the workflow tool run owns its hook. Call from a `"use step"` body. */
+export async function startWorkflowToolRun(
+ input: Omit<WorkflowToolRunInput, "hookToken"> & { readonly hookToken?: string },
+): Promise<{ readonly hookToken: string; readonly runId: string }> {
+ const hookToken =
+ input.hookToken ??
+ deriveWorkflowToolRunHookToken({
+ callId: input.callId,
+ parentSessionId: input.session.id,
+ parentTurnId: input.session.turn.id,
+ });
+ const workflowToolRunInput = { ...input, hookToken } as WorkflowToolRunInput;
+ await startWorkflowOnCurrentDeployment(workflowToolRunWorkflowReference, [workflowToolRunInput]);
+ const owner = await waitForCommandHookOwner(hookToken);
+ return { hookToken, runId: owner.runId };
+}
+
+/** Starts one durable workflow task and records it on the owning session. */
+export async function startWorkflowTask(input: {
+ readonly auth: SessionAuth["current"];
+ readonly batchEvent: {
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
+ };
+ readonly initiatorAuth: SessionAuth["initiator"];
+ readonly parentContinuationToken: string;
+ readonly parentSession: SessionParent | undefined;
+ readonly session: RuntimeSession;
+ readonly task: RuntimeWorkflowTaskRequest;
+}): Promise<{ readonly result?: RuntimeToolResultActionResult; readonly session: RuntimeSession }> {
+ const { task, batchEvent, session } = input;
+ try {
+ const started = await startWorkflowToolRun({
+ callId: task.callId,
+ executeInput: task.executeInput,
+ input: task.input,
+ owner: deriveWorkflowToolRunOwner(input.parentContinuationToken),
+ resultKind: task.resultKind,
+ session: {
+ auth: { current: input.auth, initiator: input.initiatorAuth },
+ id: session.sessionId,
+ parent: input.parentSession,
+ turn: { id: batchEvent.turnId, sequence: batchEvent.sequence },
+ },
+ stepIndex: batchEvent.stepIndex,
+ toolName: task.toolName,
+ workflowId: task.workflowId,
+ });
+ return {
+ session: recordWorkflowToolRun(session, {
+ callId: task.callId,
+ hookToken: started.hookToken,
+ resultKind: task.resultKind ?? "tool",
+ runId: started.runId,
+ toolName: task.toolName,
+ }),
+ };
+ } catch (error) {
+ logError(log, "workflow tool run failed to start", error, {
+ callId: task.callId,
+ toolName: task.toolName,
+ });
+ return {
+ result: createRuntimeToolResultFromValue({
+ callId: task.callId,
+ isError: true,
+ output: toError(error),
+ toolName: task.toolName,
+ }),
+ session,
+ };
+ }
+}
diff --git a/packages/eve/src/execution/tools/workflow/types.ts b/packages/eve/src/execution/tools/workflow/types.ts
new file mode 100644
index 000000000..e68a68346
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/types.ts
@@ -0,0 +1,48 @@
+import type { SessionContext } from "#context/session-context.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
+import type { TaskExecutorBinding } from "#tools/task.js";
+import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
+
+export type WorkflowToolRunSessionContext = SessionContext["session"];
+
+export const WORKFLOW_TOOL_EXECUTOR_KIND = "workflow-tool";
+
+/** Private task executor binding for the workflow tool run doing the task's work. */
+export function createWorkflowToolExecutorBinding(
+ input: WorkflowToolRunAddress,
+): TaskExecutorBinding {
+ return {
+ data: { hookToken: input.hookToken, runId: input.runId },
+ kind: WORKFLOW_TOOL_EXECUTOR_KIND,
+ };
+}
+
+export function readWorkflowToolExecutorAddress(
+ executor: TaskExecutorBinding | undefined,
+): WorkflowToolRunAddress | undefined {
+ if (executor?.kind !== WORKFLOW_TOOL_EXECUTOR_KIND) return undefined;
+ const hookToken = executor.data.hookToken;
+ const runId = executor.data.runId;
+ return typeof hookToken === "string" && typeof runId === "string"
+ ? { hookToken, runId }
+ : undefined;
+}
+
+export interface WorkflowToolRunInput {
+ readonly callId: string;
+ readonly execution?: "background" | "blocking";
+ readonly executeInput?: JsonValue;
+ readonly hookToken: string;
+ readonly input: JsonObject;
+ readonly owner: WorkflowToolRunOwner;
+ readonly resultKind?: "subagent" | "tool";
+ readonly session: WorkflowToolRunSessionContext;
+ readonly stepIndex: number;
+ readonly toolName: string;
+ readonly workflowId: string;
+}
+
+export interface WorkflowToolRunAddress {
+ readonly hookToken: string;
+ readonly runId: string;
+}
diff --git a/packages/eve/src/execution/tool-run/tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
similarity index 94%
rename from packages/eve/src/execution/tool-run/tool-run.integration.test.ts
rename to packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index fc9f62079..d4f34ac0e 100644
--- a/packages/eve/src/execution/tool-run/tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -17,7 +17,7 @@ import {
} from "#internal/testing/workflow-tool-fixtures.js";
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
import { getRun, getWorld, start } from "#internal/workflow/runtime.js";
-import { toolRunWorkflowReference } from "#execution/workflow-runtime.js";
+import { workflowToolRunWorkflowReference } from "#execution/workflow-runtime.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { InputRequestedStreamEvent } from "#protocol/message.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
@@ -83,34 +83,38 @@ async function createWorkflowToolRuntime(input: {
return runtime;
}
-/** Ids of every tool run in the shared world, so a test can spot the one it started. */
-async function listToolRunIds(): Promise<Set<string>> {
+/** Ids of every workflow tool run in the shared world, so a test can spot the one it started. */
+async function listWorkflowToolRunIds(): Promise<Set<string>> {
const world = await getWorld();
const page = await world.runs.list({ pagination: { limit: 100 } });
return new Set(
page.data
.filter(
(entry: { readonly workflowName?: string }) =>
- entry.workflowName === toolRunWorkflowReference.workflowId,
+ entry.workflowName === workflowToolRunWorkflowReference.workflowId,
)
.map((entry: { readonly runId: string }) => entry.runId),
);
}
-/** Polls until exactly one tool run exists that was not in `before`. */
-async function waitForNewToolRun(before: ReadonlySet<string>, timeout = 15_000): Promise<string> {
+/** Polls until exactly one workflow tool run exists that was not in `before`. */
+async function waitForNewWorkflowToolRun(
+ before: ReadonlySet<string>,
+ timeout = 15_000,
+): Promise<string> {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
- const started = [...(await listToolRunIds())].filter((runId) => !before.has(runId));
+ const started = [...(await listWorkflowToolRunIds())].filter((runId) => !before.has(runId));
if (started.length === 1) return started[0]!;
- if (started.length > 1) throw new Error(`Expected one new tool run, found ${started.length}.`);
+ if (started.length > 1)
+ throw new Error(`Expected one new workflow tool run, found ${started.length}.`);
await new Promise((resolve) => setTimeout(resolve, 50));
}
- throw new Error("Timed out waiting for a tool run to start.");
+ throw new Error("Timed out waiting for a workflow tool run to start.");
}
/** Polls one run until it reaches a terminal status, returning that status. */
-async function waitForRunTerminal(runId: string, timeout = 15_000): Promise<string> {
+async function waitForWorkflowToolRunTerminal(runId: string, timeout = 15_000): Promise<string> {
const terminal = new Set(["completed", "failed", "cancelled"]);
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
@@ -305,7 +309,7 @@ describe("workflow tools", () => {
});
await runtime.run(async () => {
- const before = await listToolRunIds();
+ const before = await listWorkflowToolRunIds();
const run = await start(workflowEntry, [
{
input: { message: 'Run deploy_service with service "api"' },
@@ -318,7 +322,7 @@ describe("workflow tools", () => {
const stream = captureTurnEvents(run);
try {
- const toolRunId = await waitForNewToolRun(before);
+ const workflowToolRunId = await waitForNewWorkflowToolRun(before);
const commandToken = sessionCommandHookToken(run.runId);
await waitForHook(run, { token: commandToken });
await resumeSessionInbox(commandToken, { kind: "cancel", turnId: "turn_0" });
@@ -326,7 +330,7 @@ describe("workflow tools", () => {
// The body is holding in a step that received ctx.abortSignal, so the
// run ends well inside its grace period once the step rejects and
// `finally` runs; a run that ignored the signal would still be running.
- expect(await waitForRunTerminal(toolRunId)).toBe("completed");
+ expect(await waitForWorkflowToolRunTerminal(workflowToolRunId)).toBe("completed");
await resumeSessionInbox(commandToken, {
kind: "send",
@@ -556,7 +560,7 @@ function enableBackgroundTool(runtime: TestRuntime, toolName: string): void {
...artifacts,
manifest: {
...artifacts.manifest,
- config: { ...artifacts.manifest.config, experimental: { tasks: true } },
+ config: artifacts.manifest.config,
tools: artifacts.manifest.tools.map((tool) =>
tool.name === toolName ? { ...tool, execution: "background" as const } : tool,
),
diff --git a/packages/eve/src/execution/tools/workflow/workflow.ts b/packages/eve/src/execution/tools/workflow/workflow.ts
new file mode 100644
index 000000000..7befeb48a
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/workflow.ts
@@ -0,0 +1,58 @@
+import { sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
+
+import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
+import type {
+ WorkflowToolRunOutcome,
+ WorkflowToolRunOutcomeMessage,
+} from "#execution/tools/workflow/messages.js";
+import { createWorkflowBodyRef, executeWorkflowBody } from "#execution/tools/workflow/body.js";
+import { openWorkflowToolRunControlInbox } from "#execution/tools/workflow/run-control.js";
+import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import { normalizeSerializableError } from "#execution/workflow-errors.js";
+
+const CANCEL_GRACE = "30s";
+
+/** Runs one authored workflow tool call and reports to its declared owner hooks. */
+export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Promise<void> {
+ "use workflow";
+
+ const control = openWorkflowToolRunControlInbox(input.hookToken);
+ let ownsInbox = false;
+ try {
+ try {
+ await claimHookOwnership(control.hook);
+ ownsInbox = true;
+ } catch (error) {
+ if (isHookConflictError(error)) return;
+ throw error;
+ }
+
+ const bodyInput = { ...input, execution: input.execution ?? "blocking" } as const;
+ const from = createWorkflowBodyRef(bodyInput);
+ const body = executeWorkflowBody(bodyInput, control.signal).then((outcome) => {
+ if (outcome.status === "completed") return outcome.output;
+ if (outcome.status === "failed") throw outcome.error;
+ throw control.signal.reason ?? new Error(outcome.reason ?? "Workflow tool run cancelled.");
+ });
+ const settled = body.catch(() => {});
+ let outcome: WorkflowToolRunOutcome;
+ try {
+ outcome = { output: await Promise.race([body, control.cancelled]), status: "completed" };
+ } catch (error) {
+ if (!control.signal.aborted) {
+ outcome = { error: normalizeSerializableError(error), status: "failed" };
+ } else {
+ await Promise.race([settled, workflowSleep(CANCEL_GRACE)]);
+ outcome = { reason: control.reason(), status: "cancelled" };
+ }
+ }
+
+ const message: WorkflowToolRunOutcomeMessage = { from, result: outcome };
+ await resumeHookStep(input.owner.outcome, message, {
+ ifPresent: outcome.status === "cancelled",
+ });
+ } finally {
+ if (ownsInbox) await disposeHook(control.hook);
+ }
+}
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 65a503eeb..a79c50daf 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -25,6 +25,7 @@ import { eveChannel } from "#public/channels/eve.js";
import type { ToolContext } from "#tools/definition.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { toInputSchema } from "#tools/schema.js";
+import { experimental_workflow } from "#tools/workflow.js";
/**
* Turn cancellation settles as `turn.cancelled` → `session.waiting` with
@@ -106,7 +107,16 @@ async function createWaitToolRuntime(agentName: string): Promise<WaitToolFixture
aborts += 1;
},
);
- const runtime = await createTestRuntime({ agent: { name: agentName }, tools: [waitTool] });
+ const runtime = await createTestRuntime({
+ agent: { name: agentName },
+ modules: [
+ {
+ loadNamespace: async () => ({ default: experimental_workflow() }),
+ logicalPath: "tools/workflow.ts",
+ },
+ ],
+ tools: [waitTool],
+ });
const manifestTool = runtime.manifest.tools.find((tool) => tool.name === WAIT_TOOL_NAME);
if (manifestTool === undefined) {
throw new Error(`Expected ${WAIT_TOOL_NAME} to be present in the test manifest.`);
@@ -580,7 +590,9 @@ describe("turn cancellation integration", () => {
await fixture.runtime.run(async () => {
const run = await start(workflowEntry, [
{
- input: { message: `Delegate to a subagent: use the ${WAIT_TOOL_NAME} tool.` },
+ input: {
+ message: `Delegate through Workflow to a subagent: use the ${WAIT_TOOL_NAME} tool.`,
+ },
serializedContext: buildSerializedContext({
channelKind: "http",
continuationToken,
@@ -640,13 +652,24 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("cancels a turn parked on a child HITL request without corrupting the stream", async () => {
- const runtime = await createTestRuntime({ agent: { name: "turn-cancel-hitl" } });
+ const runtime = await createTestRuntime({
+ agent: { name: "turn-cancel-hitl" },
+ modules: [
+ {
+ loadNamespace: async () => ({ default: experimental_workflow() }),
+ logicalPath: "tools/workflow.ts",
+ },
+ ],
+ });
const continuationToken = "http:turn-cancel-hitl";
await runtime.run(async () => {
const run = await start(workflowEntry, [
{
- input: { message: "Delegate to a subagent: Use the ask_question tool exactly once." },
+ input: {
+ message:
+ "Delegate through Workflow to a subagent: Use the ask_question tool exactly once.",
+ },
serializedContext: {
...buildSerializedContext({
channelKind: "http",
diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.ts
index c82fe7c19..d0ed8926d 100644
--- a/packages/eve/src/execution/turn-dispatch.test.ts
+++ b/packages/eve/src/execution/turn-dispatch.test.ts
@@ -305,7 +305,7 @@ describe("dispatchAndAwaitTurn", () => {
action: "park" as const,
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "pending" },
sessionState: state,
};
diff --git a/packages/eve/src/execution/turn-workflow-tool-run.ts b/packages/eve/src/execution/turn-workflow-tool-run.ts
new file mode 100644
index 000000000..b62b18a38
--- /dev/null
+++ b/packages/eve/src/execution/turn-workflow-tool-run.ts
@@ -0,0 +1,175 @@
+import type {
+ WorkflowToolRunOutcomeMessage,
+ WorkflowToolRunRequestMessage,
+} from "#execution/tools/workflow/messages.js";
+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import type { TurnExecutionCursor } from "#execution/turn-execution-cursor.js";
+import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";
+import { cancelAgentInvocationOwnerStep } from "#execution/tools/subagent/task-cancel.js";
+import { releaseAgentInvocationOwnerStep } from "#execution/tools/subagent/invoke-step.js";
+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
+import {
+ workflowToolRunOutcomeToSubagentResult,
+ workflowToolRunOutcomeToToolResult,
+ workflowToolRunRequestToInputRequestPayload,
+} from "#execution/tools/workflow/owner-inbox.js";
+import {
+ findWorkflowToolRun,
+ isInboxSubagentResultFromRecordedWorkflowToolRun,
+ isInboxToolResultFromRecordedWorkflowToolRun,
+} from "#harness/workflow-tool-runs.js";
+import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
+import type {
+ RuntimeActionResult,
+ RuntimeSubagentResult,
+ RuntimeToolResultActionResult,
+} from "#shared/action-types.js";
+
+interface HandlerInput<T> {
+ readonly callbackMetadataUrl: string;
+ readonly cursor: TurnExecutionCursor;
+ readonly message: T;
+}
+
+/**
+ * Settles a workflow tool run outcome against the turn's recorded runs and
+ * returns the runtime action result the turn should accept, or `undefined`
+ * when the outcome does not bind to a run this turn owns.
+ */
+export async function handleWorkflowToolRunOutcome(
+ input: HandlerInput<WorkflowToolRunOutcomeMessage>,
+): Promise<RuntimeActionResult | undefined> {
+ const { cursor, message } = input;
+ const recorded = findWorkflowToolRun(
+ cursor.sessionState.snapshot?.session.state,
+ message.from.callId,
+ );
+ if (recorded?.runId !== message.from.runId) return undefined;
+
+ const result: RuntimeSubagentResult | RuntimeToolResultActionResult =
+ recorded.resultKind === "subagent"
+ ? await settleSubagentOutcome(input)
+ : workflowToolRunOutcomeToToolResult(message);
+
+ // Any workflow tool run may have invoked agents through its request channel,
+ // so leases are released regardless of the run's result kind.
+ await cancelAgentInvocationOwnerStep({
+ ownerId: message.from.runId,
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ });
+ const released = await releaseAgentInvocationOwnerStep({
+ cancelled: message.result.status === "cancelled",
+ ownerId: message.from.runId,
+ sessionState: cursor.sessionState,
+ });
+ await cursor.adopt({
+ serializedContext: cursor.serializedContext,
+ sessionState: released.sessionState,
+ });
+
+ const sessionSnapshotState = cursor.sessionState.snapshot?.session.state;
+ const accepted =
+ result.kind === "subagent-result"
+ ? result.callId === message.from.callId &&
+ isInboxSubagentResultFromRecordedWorkflowToolRun(sessionSnapshotState, result)
+ : isInboxToolResultFromRecordedWorkflowToolRun(sessionSnapshotState, result);
+ return accepted ? result : undefined;
+}
+
+async function settleSubagentOutcome(
+ input: HandlerInput<WorkflowToolRunOutcomeMessage>,
+): Promise<RuntimeSubagentResult> {
+ const { cursor, message } = input;
+ const result = workflowToolRunOutcomeToSubagentResult(message);
+ if (result.origin === "child") {
+ await cursor.adopt(
+ await applyTaskAgentRequest(
+ {
+ accumulateUsage: false,
+ ownerId: message.from.runId,
+ replyTo: message.from.runId,
+ request: { kind: "agent-settled", result },
+ },
+ requestContext(input),
+ ),
+ );
+ }
+ return result;
+}
+
+export async function handleWorkflowToolRunRequest(
+ input: HandlerInput<WorkflowToolRunRequestMessage>,
+): Promise<void> {
+ const { cursor, message } = input;
+ if (message.request.kind === "agent-invoke" || message.request.kind === "agent-settled") {
+ const recorded = findWorkflowToolRun(
+ cursor.sessionState.snapshot?.session.state,
+ message.from.callId,
+ );
+ if (recorded?.runId !== message.from.runId) {
+ if (message.request.kind === "agent-invoke") {
+ await resumeHookStep(message.replyTo, {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: message.request.invocationId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: "AGENT_INVOCATION_NOT_ADMITTED",
+ message: "The workflow tool run no longer owns this agent invocation.",
+ },
+ subagentName: message.request.input.target,
+ },
+ ],
+ });
+ }
+ return;
+ }
+ await cursor.adopt(
+ await applyTaskAgentRequest(
+ {
+ accumulateUsage: message.from.resultKind !== "subagent",
+ ownerId: message.from.runId,
+ replyTo: message.replyTo,
+ request: message.request,
+ },
+ requestContext(input),
+ ),
+ );
+ return;
+ }
+ if (message.request.kind === "authorization-request") {
+ await cursor.adopt(
+ await runProxySubagentEventStep({
+ hookPayload: message.request.event,
+ parentWritable: cursor.parentWritable,
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ }),
+ );
+ return;
+ }
+ await cursor.adopt(
+ await runProxySubagentEventStep({
+ ...(message.requestCoordinates === undefined
+ ? { answerHook: { runId: message.from.runId } }
+ : {}),
+ hookPayload: workflowToolRunRequestToInputRequestPayload(message),
+ parentWritable: cursor.parentWritable,
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ }),
+ );
+}
+
+function requestContext(input: HandlerInput<unknown>) {
+ return {
+ callbackBaseUrl: resolveWorkflowCallbackBaseUrl(input.callbackMetadataUrl),
+ parentWritable: input.cursor.parentWritable,
+ serializedContext: input.cursor.serializedContext,
+ sessionState: input.cursor.sessionState,
+ };
+}
diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.ts
index 9172d9db8..406d93cea 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -3,11 +3,13 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { HookPayload } from "#channel/types.js";
import { SessionDynamicModelReferenceKey } from "#context/keys.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
-import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
+import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
-import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";
+import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";
+import { releaseAgentInvocationOwnerStep } from "#execution/tools/subagent/invoke-step.js";
+import { cancelAgentInvocationOwnerStep } from "#execution/tools/subagent/task-cancel.js";
+import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
import { turnWorkflow } from "#execution/turn-workflow.js";
import {
TURN_WORKFLOW_INPUT_VERSION,
@@ -15,24 +17,39 @@ import {
} from "#execution/durable-session-migrations/turn-workflow.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { turnStep } from "#execution/workflow-steps.js";
-import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
+import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/store.js";
+import type { HarnessSession } from "#harness/types.js";
+import { recordWorkflowToolRun } from "#harness/workflow-tool-runs.js";
const resumeHookMock = vi.fn();
const createHookMock = vi.fn();
-const createOwnerHookMock = vi.fn();
const sleepMock = vi.fn(async (_duration: unknown) => {});
+const definedHookPayloads = new Map<string, readonly unknown[]>();
+
+function createDefinedHookMock(token: string, values: readonly unknown[]): unknown {
+ const queue = [...values];
+ return {
+ token,
+ getConflict: vi.fn(async () => null),
+ dispose: vi.fn(),
+ [Symbol.asyncIterator](): AsyncIterator<unknown> {
+ return {
+ next: vi.fn(async () => {
+ const value = queue.shift();
+ return value === undefined ? await new Promise<never>(() => {}) : { done: false, value };
+ }),
+ return: vi.fn(async () => ({ done: true, value: undefined })),
+ };
+ },
+ };
+}
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: (...args: unknown[]) => createHookMock(...args),
defineHook: () => ({
create: (options?: { readonly token?: string }) => {
- createOwnerHookMock(options?.token);
- return {
- [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
- dispose: async () => {},
- getConflict: async () => null,
- token: options?.token ?? "hook",
- };
+ const token = options?.token ?? "hook";
+ return createDefinedHookMock(token, definedHookPayloads.get(token) ?? []);
},
resume: async () => null,
}),
@@ -48,7 +65,7 @@ vi.mock("./route-child-delivery.js", () => ({
routeDeliverToChildren: vi.fn(),
}));
-vi.mock("./subagent-event-proxy-step.js", () => ({
+vi.mock("../subagents/event-proxy-step.js", () => ({
runProxySubagentEventStep: vi.fn(),
}));
@@ -56,12 +73,8 @@ vi.mock("./workflow-steps.js", () => ({
turnStep: vi.fn(),
}));
-vi.mock("./dispatch-runtime-actions-step.js", () => ({
- dispatchRuntimeActionsStep: vi.fn(),
-}));
-
-vi.mock("./dispatch-workflow-runtime-actions-step.js", () => ({
- dispatchWorkflowRuntimeActionsStep: vi.fn(),
+vi.mock("#execution/coordination-dispatch-step.js", () => ({
+ dispatchCoordinationStep: vi.fn(),
}));
vi.mock("./cancel-descendant-turns-step.js", () => ({
@@ -72,6 +85,18 @@ vi.mock("./tasks/parent/delegate.js", () => ({
acknowledgeDelegatedTasksStep: vi.fn(),
}));
+vi.mock("./tools/subagent/task-agent-requests.js", () => ({
+ applyTaskAgentRequest: vi.fn(),
+}));
+
+vi.mock("./tools/subagent/invoke-step.js", () => ({
+ releaseAgentInvocationOwnerStep: vi.fn(),
+}));
+
+vi.mock("./tools/subagent/task-cancel.js", () => ({
+ cancelAgentInvocationOwnerStep: vi.fn(),
+}));
+
vi.mock("./workflow-callback-url.js", () => ({
resolveWorkflowCallbackBaseUrl: vi.fn((metadataUrl: string) => metadataUrl),
}));
@@ -81,8 +106,11 @@ describe("turnWorkflow", () => {
vi.clearAllMocks();
resumeHookMock.mockReset();
createHookMock.mockReset();
- createOwnerHookMock.mockReset();
sleepMock.mockClear();
+ vi.mocked(applyTaskAgentRequest).mockReset();
+ vi.mocked(releaseAgentInvocationOwnerStep).mockReset();
+ vi.mocked(cancelAgentInvocationOwnerStep).mockReset();
+ definedHookPayloads.clear();
});
it("notifies the driver when a turn completes", async () => {
@@ -112,8 +140,6 @@ describe("turnWorkflow", () => {
},
kind: "turn-result",
});
- // A turn that starts no workflow tool run never opens run channels.
- expect(createOwnerHookMock).not.toHaveBeenCalled();
});
it("continues from an inline step result without executing it twice", async () => {
@@ -348,7 +374,7 @@ describe("turnWorkflow", () => {
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "pending-runtime-action" },
sessionState,
});
@@ -358,8 +384,8 @@ describe("turnWorkflow", () => {
expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {
action: {
- kind: "dispatch-runtime-actions",
- pendingActionKeys: ["subagent-call:delegate:call-1"],
+ kind: "dispatch-coordination",
+ pendingCallIds: ["call-1"],
serializedContext: { state: "pending-runtime-action" },
sessionState,
},
@@ -696,98 +722,6 @@ describe("turnWorkflow", () => {
expect(inbox.createIterator).toHaveBeenCalledOnce();
});
- it("keeps a local subagent result inside one turn workflow", async () => {
- const now = vi.spyOn(Date, "now").mockReturnValue(1_234);
- const initialState = createSessionState({ continuationToken: "slack:C1:" });
- const pendingState = createSessionState({ continuationToken: "slack:C1:T1" });
- const completedState = createSessionState({ continuationToken: "slack:C1:T1" });
- installInbox([
- {
- kind: "runtime-action-result",
- results: [
- {
- callId: "call-1",
- kind: "subagent-result",
- origin: "child",
- output: "child output",
- subagentName: "delegate",
- },
- ],
- },
- ]);
- vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
- results: [],
- sessionState: withRunningChildren(pendingState, [
- { callId: "call-1", sessionId: "child-session" },
- ]),
- pendingTasks: [],
- });
- vi.mocked(turnStep)
- .mockResolvedValueOnce({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
- serializedContext: { state: "pending" },
- sessionState: pendingState,
- })
- .mockResolvedValueOnce({
- action: "done",
- output: "parent output",
- serializedContext: { state: "done" },
- sessionState: completedState,
- });
-
- const { input, parentWritable } = createInput({
- driverCapabilities: { turnInbox: true },
- mode: "task",
- sessionState: initialState,
- });
- await turnWorkflow(input);
-
- expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {
- continuationToken: "slack:C1:T1",
- kind: "turn-continuation-token",
- });
- expect(resumeHookMock.mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(dispatchRuntimeActionsStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
- expect(dispatchRuntimeActionsStep).toHaveBeenCalledWith({
- callbackBaseUrl: "https://eve.example.com",
- parentContinuationToken: "turn-token:inbox",
- parentWritable,
- serializedContext: { state: "pending" },
- sessionState: pendingState,
- });
- expect(vi.mocked(turnStep).mock.calls[1]?.[0]).toMatchObject({
- input: {
- acceptedAtMsByCallId: { "call-1": 1_234 },
- kind: "runtime-action-result",
- results: [
- expect.objectContaining({
- callId: "call-1",
- output: "child output",
- }),
- ],
- },
- });
- expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result")).toEqual([
- [
- "turn-token",
- expect.objectContaining({
- action: expect.objectContaining({ kind: "done", output: "parent output" }),
- }),
- ],
- ]);
- expect(resumeHookMock).not.toHaveBeenCalledWith(
- "turn-token",
- expect.objectContaining({
- action: expect.objectContaining({ kind: "dispatch-runtime-actions" }),
- }),
- );
- now.mockRestore();
- });
-
it("waits for dispatch adoption before cascading a cancellation", async () => {
const initialState = createSessionState({ continuationToken: "http:parent" });
const pendingState = createSessionState({ continuationToken: "http:parent:turn" });
@@ -807,13 +741,13 @@ describe("turnWorkflow", () => {
finishDispatch = resolve;
});
installInbox([], { cancelPayloads: [{}], stayOpen: true });
- vi.mocked(dispatchRuntimeActionsStep).mockReturnValue(dispatchResult);
+ vi.mocked(dispatchCoordinationStep).mockReturnValue(dispatchResult);
vi.mocked(turnStep)
.mockResolvedValueOnce({
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "pending" },
sessionState: pendingState,
})
@@ -829,7 +763,7 @@ describe("turnWorkflow", () => {
sessionState: initialState,
});
const workflow = turnWorkflow(input);
- await vi.waitFor(() => expect(dispatchRuntimeActionsStep).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(dispatchCoordinationStep).toHaveBeenCalledOnce());
expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();
finishDispatch?.({ results: [], sessionState: adoptedState, pendingTasks: [] });
@@ -840,7 +774,7 @@ describe("turnWorkflow", () => {
serializedContext: { state: "cancelled" },
sessionState: adoptedState,
});
- expect(vi.mocked(dispatchRuntimeActionsStep).mock.invocationCallOrder[0]).toBeLessThan(
+ expect(vi.mocked(dispatchCoordinationStep).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(cancelDescendantTurnsStep).mock.invocationCallOrder[0]!,
);
});
@@ -850,7 +784,7 @@ describe("turnWorkflow", () => {
const pendingState = createSessionState();
const completedState = createSessionState();
installInbox([]);
- vi.mocked(dispatchWorkflowRuntimeActionsStep).mockResolvedValue({
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
results: [
{
callId: "call-1",
@@ -866,8 +800,8 @@ describe("turnWorkflow", () => {
});
vi.mocked(turnStep)
.mockResolvedValueOnce({
- action: "dispatch-workflow-runtime-actions",
- pendingRuntimeActionKeys: ["subagent-call:research:call-1"],
+ action: "dispatch-workflow-tasks",
+ pendingTaskCallIds: ["call-1"],
serializedContext: { state: "pending" },
sessionState: pendingState,
})
@@ -885,7 +819,8 @@ describe("turnWorkflow", () => {
});
await turnWorkflow(input);
- expect(dispatchWorkflowRuntimeActionsStep).toHaveBeenCalledWith({
+ expect(dispatchCoordinationStep).toHaveBeenCalledWith({
+ action: "dispatch-workflow-tasks",
callbackBaseUrl: "https://eve.example.com",
parentContinuationToken: "turn-token:inbox",
parentWritable,
@@ -943,7 +878,7 @@ describe("turnWorkflow", () => {
],
},
]);
- vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
results: [],
sessionState: withRunningChildren(pendingState, runningChildren),
pendingTasks: [],
@@ -963,7 +898,7 @@ describe("turnWorkflow", () => {
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "pending" },
sessionState: pendingState,
})
@@ -1004,8 +939,309 @@ describe("turnWorkflow", () => {
expect(vi.mocked(turnStep).mock.calls[1]?.[0].sessionState).toBe(retiredProxyState);
});
- it("lets the parent cancel after a descendant consumes a session-limit Stop response", async () => {
+ it("marks workflow-tool owner-channel input requests as answer hooks", async () => {
const pendingState = createSessionState();
+ const dispatchedState = withWorkflowToolRun(createSessionState());
+ const proxyState = withWorkflowToolRun(createSessionState({ hasProxyInputRequests: true }));
+ const retiredProxyState = withWorkflowToolRun(createSessionState());
+ const completedState = createSessionState();
+ const answerToken = "eve:workflow-tool-run-answer:run-1:0";
+ const requestId = "turn-token:inbox:delivery:0";
+ const workflowRequest = {
+ from: {
+ callId: "call-1",
+ execution: "blocking" as const,
+ input: { service: "api" },
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 1,
+ toolName: "confirm_deploy",
+ turnId: "turn_0",
+ },
+ replyTo: answerToken,
+ request: {
+ options: [
+ { id: "approve", label: "Approve" },
+ { id: "reject", label: "Reject" },
+ ],
+ prompt: "Approve deploy?",
+ },
+ };
+ definedHookPayloads.set("turn-token:inbox:request", [workflowRequest]);
+ installInbox([
+ {
+ delivery: {
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: answerToken }] }],
+ },
+ kind: "driver-delivery",
+ requestId,
+ },
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1",
+ kind: "tool-result",
+ output: { approved: true, service: "api" },
+ toolName: "confirm_deploy",
+ },
+ ],
+ },
+ ]);
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
+ results: [],
+ sessionState: dispatchedState,
+ pendingTasks: [],
+ });
+ vi.mocked(runProxySubagentEventStep).mockResolvedValue({
+ serializedContext: { state: "proxied" },
+ sessionState: proxyState,
+ });
+ vi.mocked(routeDeliverToChildren).mockResolvedValue({
+ kind: "continue",
+ remainder: undefined,
+ serializedContext: { state: "proxied" },
+ sessionState: retiredProxyState,
+ });
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["call-1"],
+ serializedContext: { state: "pending" },
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "done",
+ serializedContext: { state: "done" },
+ sessionState: completedState,
+ });
+
+ const { input, parentWritable } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: pendingState,
+ });
+ await turnWorkflow(input);
+
+ expect(runProxySubagentEventStep).toHaveBeenCalledWith({
+ answerHook: { runId: "run-1" },
+ hookPayload: expect.objectContaining({
+ childContinuationToken: answerToken,
+ childSessionId: "run-1",
+ kind: "subagent-input-request",
+ }),
+ parentWritable,
+ serializedContext: { state: "pending" },
+ sessionState: dispatchedState,
+ });
+ expect(routeDeliverToChildren).toHaveBeenCalledWith(
+ expect.objectContaining({
+ delivery: {
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: answerToken }] }],
+ },
+ sessionState: proxyState,
+ }),
+ );
+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({
+ acceptedAtMsByCallId: { "call-1": expect.any(Number) },
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1",
+ kind: "tool-result",
+ output: { approved: true, service: "api" },
+ toolName: "confirm_deploy",
+ },
+ ],
+ });
+ });
+
+ it("routes blocking workflow agent lifecycle requests through the recorded run owner", async () => {
+ const pendingState = createSessionState();
+ const dispatchedState = withWorkflowToolRun(createSessionState(), "research");
+ const invokedState = withWorkflowToolRun(createSessionState(), "research");
+ const settledState = withWorkflowToolRun(createSessionState(), "research");
+ const completedState = createSessionState();
+ const childResult = {
+ callId: "call-1",
+ kind: "subagent-result" as const,
+ origin: "child" as const,
+ outcome: {
+ kind: "parked" as const,
+ result: { kind: "succeeded" as const, output: "done" },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ output: "done",
+ subagentName: "research",
+ };
+ definedHookPayloads.set("turn-token:inbox:request", [
+ {
+ from: {
+ callId: "call-1",
+ execution: "blocking",
+ input: {},
+ resultKind: "subagent",
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn_0",
+ },
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1",
+ kind: "agent-invoke",
+ },
+ },
+ {
+ from: {
+ callId: "call-1",
+ execution: "blocking",
+ input: {},
+ resultKind: "subagent",
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn_0",
+ },
+ replyTo: "agent-reply",
+ request: { kind: "agent-settled", result: childResult },
+ },
+ ]);
+ definedHookPayloads.set("turn-token:inbox:outcome", [
+ {
+ from: {
+ callId: "call-1",
+ execution: "blocking",
+ input: {},
+ resultKind: "subagent",
+ runId: "run-1",
+ sequence: 0,
+ stepIndex: 0,
+ toolName: "research",
+ turnId: "turn_0",
+ },
+ result: { output: childResult, status: "completed" },
+ },
+ ]);
+ installInbox([]);
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
+ results: [],
+ sessionState: dispatchedState,
+ pendingTasks: [],
+ });
+ vi.mocked(applyTaskAgentRequest)
+ .mockResolvedValueOnce({ serializedContext: {}, sessionState: invokedState })
+ .mockResolvedValueOnce({ serializedContext: {}, sessionState: settledState });
+ vi.mocked(releaseAgentInvocationOwnerStep).mockResolvedValue({ sessionState: settledState });
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["call-1"],
+ serializedContext: {},
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "done",
+ serializedContext: {},
+ sessionState: completedState,
+ });
+
+ const { input } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: pendingState,
+ });
+ await turnWorkflow(input);
+
+ expect(vi.mocked(applyTaskAgentRequest).mock.calls.map(([delivery]) => delivery)).toEqual([
+ expect.objectContaining({
+ ownerId: "run-1",
+ request: { kind: "agent-invoke", invocationId: "call-1", input: expect.any(Object) },
+ }),
+ expect.objectContaining({
+ ownerId: "run-1",
+ request: { kind: "agent-settled", result: childResult },
+ }),
+ ]);
+ });
+
+ it("drops an unbound legacy child event before proxying it", async () => {
+ const pendingState = createSessionState();
+ installInbox([
+ {
+ callId: "call-1",
+ childContinuationToken: "child-token",
+ childSessionId: "wrong-child",
+ event: { requests: [], sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ kind: "subagent-input-request",
+ subagentName: "delegate",
+ },
+ {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ output: "child output",
+ subagentName: "delegate",
+ },
+ ],
+ },
+ ]);
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
+ results: [],
+ sessionState: withRunningChildren(pendingState, [
+ { callId: "call-1", sessionId: "child-session" },
+ ]),
+ pendingTasks: [],
+ });
+ vi.mocked(turnStep)
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["call-1"],
+ serializedContext: {},
+ sessionState: pendingState,
+ })
+ .mockResolvedValueOnce({
+ action: "done",
+ output: "done",
+ serializedContext: {},
+ sessionState: createSessionState(),
+ });
+
+ const { input } = createInput({
+ driverCapabilities: { turnInbox: true },
+ mode: "task",
+ sessionState: pendingState,
+ });
+ await turnWorkflow(input);
+
+ expect(runProxySubagentEventStep).not.toHaveBeenCalled();
+ });
+
+ it("lets the parent cancel after a descendant consumes a session-limit Stop response", async () => {
+ const pendingState = withRunningChildren(createSessionState(), [
+ { callId: "call-1", sessionId: "child-session" },
+ ]);
const proxyState = createSessionState({ hasProxyInputRequests: true });
const retiredProxyState = createSessionState();
const requestId = "child-limit-request";
@@ -1027,7 +1263,7 @@ describe("turnWorkflow", () => {
requestId: "turn-token:inbox:delivery:0",
},
]);
- vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
results: [],
sessionState: pendingState,
pendingTasks: [],
@@ -1045,7 +1281,7 @@ describe("turnWorkflow", () => {
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "pending" },
sessionState: pendingState,
});
@@ -1131,7 +1367,7 @@ describe("turnWorkflow", () => {
},
]);
const dispatchedState = withRunningChildren(pendingState, runningChildren);
- vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
results: [],
sessionState: dispatchedState,
pendingTasks: [],
@@ -1150,7 +1386,7 @@ describe("turnWorkflow", () => {
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "pending" },
sessionState: pendingState,
})
@@ -1244,7 +1480,7 @@ describe("turnWorkflow", () => {
],
},
]);
- vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({
results: [],
sessionState: withRunningChildren(pendingState, [
{ callId: "call-1", sessionId: "child-session-1" },
@@ -1263,7 +1499,7 @@ describe("turnWorkflow", () => {
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-1"],
+ pendingCoordinationCallIds: ["call-1"],
serializedContext: { state: "batch-1" },
sessionState: pendingState,
})
@@ -1271,7 +1507,7 @@ describe("turnWorkflow", () => {
action: "park",
hasPendingAuthorization: false,
hasPendingInputBatch: false,
- pendingRuntimeActionKeys: ["subagent-call:delegate:call-2"],
+ pendingCoordinationCallIds: ["call-2"],
serializedContext: { state: "batch-2" },
sessionState: pendingState,
})
@@ -1498,3 +1734,30 @@ function withRunningChildren(
},
};
}
+
+function withWorkflowToolRun(
+ state: DurableSessionState,
+ toolName = "confirm_deploy",
+): DurableSessionState {
+ const baseSession: HarnessSession = {
+ agent: { dynamicModel: true, system: "", tools: [] },
+ compaction: { recentWindowSize: 5, threshold: 10_000 },
+ continuationToken: state.continuationToken,
+ history: [],
+ sessionId: state.sessionId,
+ };
+ const session = recordWorkflowToolRun(baseSession, {
+ callId: "call-1",
+ hookToken: "eve:workflow-tool-run:run-1",
+ runId: "run-1",
+ resultKind: toolName === "research" ? "subagent" : undefined,
+ toolName,
+ });
+ return {
+ ...state,
+ snapshot: {
+ session,
+ version: 1,
+ },
+ };
+}
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index da97c4132..cd8b9ee5c 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -1,5 +1,11 @@
-import { isInboxSubagentResultFromRunningHandle } from "#harness/handles/query.js";
-import { isInboxToolResultFromRecordedRun } from "#harness/tool-runs.js";
+import {
+ findRunningAgentHandle,
+ isInboxSubagentResultFromRunningHandle,
+} from "#subagents/handles/query.js";
+import {
+ isInboxSubagentResultFromRecordedWorkflowToolRun,
+ isInboxToolResultFromRecordedWorkflowToolRun,
+} from "#harness/workflow-tool-runs.js";
import {
createHook,
getWorkflowMetadata,
@@ -10,10 +16,8 @@ import type { DeliverHookPayload } from "#channel/types.js";
import { preserveSerializedSessionDynamicModelSelection } from "#context/serialized-dynamic-model-selection.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { sendTurnControlStep, type TurnInboxPayload } from "#execution/turn-control-protocol.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import { acknowledgeDelegatedTasksStep } from "#execution/tasks/parent/delegate.js";
-import { dispatchTaskStep } from "#execution/tasks/parent/dispatch-task-step.js";
-import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
import {
migrateTurnWorkflowInput,
type TurnStepInput,
@@ -22,22 +26,18 @@ import {
import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
-import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";
-import { emitRunReportStep } from "#execution/tool-run/emit-run-report-step.js";
+import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
+import { emitWorkflowToolRunReportStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";
import {
type ChannelReader,
createChannelReader,
raceChannelReads,
-} from "#execution/tool-run/owner-channels.js";
-import {
- openRunOwnerChannels,
- type RunOwnerChannels,
- type RunOwnerReaders,
-} from "#execution/tool-run/owner.js";
+} from "#execution/tools/workflow/owner-channels.js";
import {
- runOutcomeToToolResult,
- runRequestToInputRequestPayload,
-} from "#execution/tool-run/owner-inbox.js";
+ openWorkflowToolRunOwnerChannels,
+ type WorkflowToolRunOwnerChannels,
+ type WorkflowToolRunOwnerReaders,
+} from "#execution/tools/workflow/owner.js";
import {
createTurnCancellationControl,
type TurnCancellationControl,
@@ -47,9 +47,12 @@ import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url
import { normalizeSerializableError } from "#execution/workflow-errors.js";
import { turnStep } from "#execution/workflow-steps.js";
import { activeTurnId } from "#harness/active-turn-id.js";
-import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";
-import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";
+import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
+import {
+ handleWorkflowToolRunOutcome,
+ handleWorkflowToolRunRequest,
+} from "#execution/turn-workflow-tool-run.js";
const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";
@@ -98,7 +101,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
const bufferedDeliveries: DeliverHookPayload[] = [];
let nextStepInput = input.stepInput.input;
let ownsInbox = false;
- let runChannels: RunOwnerChannels | undefined;
+ let workflowToolRunChannels: WorkflowToolRunOwnerChannels | undefined;
let cancellation: TurnCancellationControl | undefined;
try {
@@ -110,6 +113,11 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
throw error;
}
+ // Opened after the inbox claim so a losing duplicate never contends for
+ // them; the turn starts no run before this point.
+ workflowToolRunChannels = openWorkflowToolRunOwnerChannels(inbox.token);
+ const readers: TurnReaders = [...workflowToolRunChannels.readers, inboxReader];
+
// Claimed after the inbox claim so a losing duplicate run never
// contends for the session cancel token.
if (input.driverCapabilities?.cancelledTurnSettle === true) {
@@ -129,10 +137,12 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
initialStep?.result ??
(await turnStep(cursor.createStepInput(nextStepInput, cancellation?.signal)));
initialStep = undefined;
- const pendingActionKeys =
- result.action === "dispatch-workflow-runtime-actions" || result.action === "park"
- ? result.pendingRuntimeActionKeys
- : undefined;
+ const pendingCallIds =
+ result.action === "dispatch-workflow-tasks"
+ ? result.pendingTaskCallIds
+ : result.action === "park"
+ ? result.pendingCoordinationCallIds
+ : undefined;
const hasBackgroundTasks = (result.backgroundTasks?.length ?? 0) > 0;
if (hasBackgroundTasks) {
@@ -164,7 +174,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
if (
cancellation?.signal.aborted === true &&
- (pendingActionKeys === undefined || hasBackgroundTasks)
+ (pendingCallIds === undefined || hasBackgroundTasks)
) {
// Some worlds cannot interrupt a running step, so it can complete
// normally after the workflow observes cancellation. Roll that result
@@ -209,28 +219,16 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
return;
}
- // A pending runtime-action batch (model-driven `park` or dynamic-workflow
- // interrupt) is resolved in-line so the turn stays alive across the wait;
- // the arms differ only in their dispatch path: the workflow adapter for
- // interrupt-sourced batches, and the task-mode sibling when the agent
- // runs `experimental.tasks`.
- if (pendingActionKeys !== undefined) {
+ // Both sources converge on coordination dispatch. Model-driven `park`
+ // already carries a coordination batch; a dynamic Workflow interrupt is
+ // normalized into that shape inside the dispatch step.
+ if (
+ pendingCallIds !== undefined &&
+ (result.action === "park" || result.action === "dispatch-workflow-tasks")
+ ) {
await cursor.adopt(result);
- // Opened before the dispatch step suspends, so the hooks exist when
- // the first run reports; a turn that starts no run never pays for them.
- if (result.action === "park" && result.startsWorkflowToolRuns === true) {
- runChannels ??= openRunOwnerChannels(inbox.token);
- }
- const hasPendingTasks = result.action === "park" && result.tasksEnabled;
- let dispatch;
- if (result.action === "dispatch-workflow-runtime-actions") {
- dispatch = dispatchWorkflowRuntimeActionsStep;
- } else if (hasPendingTasks) {
- dispatch = dispatchTaskStep;
- } else {
- dispatch = dispatchRuntimeActionsStep;
- }
- const dispatchResult = await dispatch({
+ const dispatchResult = await dispatchCoordinationStep({
+ action: result.action,
callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),
parentContinuationToken: inbox.token,
parentWritable: cursor.parentWritable,
@@ -249,9 +247,8 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
initialAcceptedAtMs,
initialResults: dispatchResult.results,
nextDeliveryRequestId,
- readers:
- runChannels === undefined ? [inboxReader] : [...runChannels.readers, inboxReader],
- pendingActionKeys,
+ readers,
+ pendingCallIds,
});
if (results === "cancelled") {
// The next turnStep observes the aborted signal and settles
@@ -302,14 +299,15 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
// terminal result publishes so the next turn's claim never races this
// run's teardown; this backstop covers the error path.
if (cancellation !== undefined) await cancellation.dispose();
- if (runChannels !== undefined) await runChannels.dispose();
+ if (workflowToolRunChannels !== undefined) await workflowToolRunChannels.dispose();
if (ownsInbox) await disposeHook(inbox);
}
}
-type TurnReaders =
- | readonly [...RunOwnerReaders, ChannelReader<"inbox", TurnInboxPayload>]
- | readonly [ChannelReader<"inbox", TurnInboxPayload>];
+type TurnReaders = readonly [
+ ...WorkflowToolRunOwnerReaders,
+ ChannelReader<"inbox", TurnInboxPayload>,
+];
async function finishCancelledTurn(input: {
readonly bufferedDeliveries: readonly DeliverHookPayload[];
@@ -353,21 +351,21 @@ async function waitForRuntimeActionResults(input: {
readonly initialAcceptedAtMs: number | undefined;
readonly initialResults: readonly RuntimeActionResult[];
readonly nextDeliveryRequestId: () => string;
- readonly pendingActionKeys: readonly string[];
+ readonly pendingCallIds: readonly string[];
readonly readers: TurnReaders;
}): Promise<AcceptedRuntimeActionBatch | "cancelled" | "cancel-turn"> {
let pendingDeliveryRequest: string | undefined;
const results: RuntimeActionResult[] = [...input.initialResults];
- const acceptedAtMsByKey = new Map<string, number>();
+ const acceptedAtMsByCallId = new Map<string, number>();
if (input.initialAcceptedAtMs !== undefined) {
for (const result of input.initialResults) {
- acceptedAtMsByKey.set(getRuntimeActionResultKey(result), input.initialAcceptedAtMs);
+ acceptedAtMsByCallId.set(result.callId, input.initialAcceptedAtMs);
}
}
while (true) {
- const ready = resolveRuntimeActionResultsForKeys({
- pendingKeys: input.pendingActionKeys,
+ const ready = resolveRuntimeActionResultsForCallIds({
+ pendingCallIds: input.pendingCallIds,
results,
});
if (ready !== undefined) {
@@ -381,10 +379,7 @@ async function waitForRuntimeActionResults(input: {
}
return {
acceptedAtMsByCallId: Object.fromEntries(
- ready.map((result) => [
- result.callId,
- acceptedAtMsByKey.get(getRuntimeActionResultKey(result))!,
- ]),
+ ready.map((result) => [result.callId, acceptedAtMsByCallId.get(result.callId)!]),
),
results: ready,
};
@@ -417,28 +412,27 @@ async function waitForRuntimeActionResults(input: {
if (read.next.done) throw new Error("Turn inbox closed before runtime actions completed.");
if (read.channel === "outcome") {
- const result = runOutcomeToToolResult(read.next.value);
- const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;
- if (isInboxToolResultFromRecordedRun(sessionSnapshotState, result)) {
- const acceptedAtMs = Date.now();
+ const result = await handleWorkflowToolRunOutcome({
+ callbackMetadataUrl: getWorkflowMetadata().url,
+ cursor: input.cursor,
+ message: read.next.value,
+ });
+ if (result !== undefined) {
results.push(result);
- acceptedAtMsByKey.set(getRuntimeActionResultKey(result), acceptedAtMs);
+ acceptedAtMsByCallId.set(result.callId, Date.now());
}
continue;
}
if (read.channel === "request") {
- const proxyResult = await runProxySubagentEventStep({
- answerHook: { runId: read.next.value.from.runId },
- hookPayload: runRequestToInputRequestPayload(read.next.value),
- parentWritable: input.cursor.parentWritable,
- serializedContext: input.cursor.serializedContext,
- sessionState: input.cursor.sessionState,
+ await handleWorkflowToolRunRequest({
+ callbackMetadataUrl: getWorkflowMetadata().url,
+ cursor: input.cursor,
+ message: read.next.value,
});
- await input.cursor.adopt(proxyResult);
continue;
}
if (read.channel === "report") {
- await emitRunReportStep({
+ await emitWorkflowToolRunReportStep({
from: read.next.value.from,
parentWritable: input.cursor.parentWritable,
update: read.next.value.update,
@@ -451,27 +445,38 @@ async function waitForRuntimeActionResults(input: {
// The inbox token is shared by every callee in the batch, so an inbox
// result must bind to the adopted session snapshot: a subagent result
// to a running agent handle carrying its callId, a tool result to the
- // tool run recorded for its callId. Anything else — a callee settling a
+ // workflow tool run recorded for its callId. Anything else — a callee settling a
// sibling's call, or a result for a callId whose dispatch failed — is
// dropped; the genuine result (or the dispatch error already in
// `results`) still resolves the wait.
const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;
const accepted = value.results.filter((result) =>
result.kind === "tool-result"
- ? isInboxToolResultFromRecordedRun(sessionSnapshotState, result)
- : isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result),
+ ? isInboxToolResultFromRecordedWorkflowToolRun(sessionSnapshotState, result)
+ : (result.origin === "child" &&
+ isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result)) ||
+ isInboxSubagentResultFromRecordedWorkflowToolRun(sessionSnapshotState, result),
);
if (accepted.length > 0) {
const acceptedAtMs = Date.now();
results.push(...accepted);
for (const result of accepted) {
- acceptedAtMsByKey.set(getRuntimeActionResultKey(result), acceptedAtMs);
+ acceptedAtMsByCallId.set(result.callId, acceptedAtMs);
}
}
continue;
}
if (value.kind === "subagent-input-request" || value.kind === "subagent-authorization-event") {
+ const handle = findRunningAgentHandle(input.cursor.sessionState.snapshot?.session.state, {
+ callId: value.callId,
+ });
+ if (
+ handle?.identity.name !== value.subagentName ||
+ handle.address.sessionId !== value.childSessionId
+ ) {
+ continue;
+ }
const proxyResult = await runProxySubagentEventStep({
hookPayload: value,
parentWritable: input.cursor.parentWritable,
@@ -540,13 +545,13 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {
return;
}
- if (result.action === "dispatch-workflow-runtime-actions") {
+ if (result.action === "dispatch-workflow-tasks") {
await sendTurnControlStep({
controlToken: input.completionToken,
payload: {
action: {
- kind: "dispatch-workflow-runtime-actions",
- pendingActionKeys: result.pendingRuntimeActionKeys,
+ kind: "dispatch-workflow-tasks",
+ pendingCallIds: result.pendingTaskCallIds,
serializedContext: result.serializedContext,
sessionState: result.sessionState,
},
@@ -557,9 +562,9 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {
}
if (result.action === "park") {
- const pendingActionKeys = result.pendingRuntimeActionKeys;
+ const pendingCallIds = result.pendingCoordinationCallIds;
const canPark =
- pendingActionKeys !== undefined ||
+ pendingCallIds !== undefined ||
result.hasPendingAuthorization ||
(result.hasPendingInputBatch && input.capabilities?.requestInput === true) ||
input.mode === "conversation";
@@ -567,10 +572,10 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {
if (!canPark) throw new Error(TASK_MODE_WAIT_ERROR_MESSAGE);
const action: NextDriverAction =
- pendingActionKeys !== undefined
+ pendingCallIds !== undefined
? {
- kind: "dispatch-runtime-actions",
- pendingActionKeys,
+ kind: "dispatch-coordination",
+ pendingCallIds,
serializedContext: result.serializedContext,
sessionState: result.sessionState,
}
diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v4.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v4.test.ts.snap
new file mode 100644
index 000000000..577ab11cb
--- /dev/null
+++ b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v4.test.ts.snap
@@ -0,0 +1,3 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`session inbox wire v4 > pins the complete schema byte for byte 1`] = `"{"$defs":{"__schema0":{"anyOf":[{"type":"null"},{"type":"boolean"},{"type":"number"},{"type":"string"},{"items":{"$ref":"#/$defs/__schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/__schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"acceptedDeploymentId":{"type":"string"},"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"agentRequests":{"items":{"additionalProperties":false,"properties":{"replyTo":{"type":"string"},"request":{"oneOf":[{"additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"message":{"type":"string"},"outputSchema":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"target":{"type":"string"}},"required":["message","target"],"type":"object"},"invocationId":{"type":"string"},"kind":{"const":"agent-invoke","type":"string"}},"required":["input","invocationId","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"agent-settled","type":"string"},"result":{"additionalProperties":false,"properties":{"backgroundTask":{"additionalProperties":false,"properties":{"status":{"const":"working","type":"string"},"taskId":{"type":"string"}},"required":["status","taskId"],"type":"object"},"callId":{"type":"string"},"isError":{"type":"boolean"},"kind":{"const":"subagent-result","type":"string"},"origin":{"const":"child","type":"string"},"outcome":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"parked","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"terminal","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"}]},"output":{},"subagentName":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["callId","kind","origin","outcome","output","subagentName"],"type":"object"}},"required":["kind","result"],"type":"object"}]},"taskId":{"type":"string"}},"required":["replyTo","request","taskId"],"type":"object"},"type":"array"},"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"anyOf":[{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"request":{},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","request"],"type":"object"},{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"requests":{"items":{},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","requests"],"type":"object"}]},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"agentRequests":{"items":{"additionalProperties":false,"properties":{"replyTo":{"type":"string"},"request":{"oneOf":[{"additionalProperties":false,"properties":{"input":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"message":{"type":"string"},"outputSchema":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"target":{"type":"string"}},"required":["message","target"],"type":"object"},"invocationId":{"type":"string"},"kind":{"const":"agent-invoke","type":"string"}},"required":["input","invocationId","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"agent-settled","type":"string"},"result":{"additionalProperties":false,"properties":{"backgroundTask":{"additionalProperties":false,"properties":{"status":{"const":"working","type":"string"},"taskId":{"type":"string"}},"required":["status","taskId"],"type":"object"},"callId":{"type":"string"},"isError":{"type":"boolean"},"kind":{"const":"subagent-result","type":"string"},"origin":{"const":"child","type":"string"},"outcome":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"parked","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"terminal","type":"string"},"result":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"succeeded","type":"string"},"output":{"$ref":"#/$defs/__schema0"}},"required":["kind","output"],"type":"object"},{"additionalProperties":false,"properties":{"error":{"$ref":"#/$defs/__schema0"},"kind":{"const":"failed","type":"string"}},"required":["error","kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancelled","type":"string"}},"required":["kind"],"type":"object"}]},"usageDelta":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["kind","result","usageDelta"],"type":"object"}]},"output":{},"subagentName":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["callId","kind","origin","outcome","output","subagentName"],"type":"object"}},"required":["kind","result"],"type":"object"}]},"taskId":{"type":"string"}},"required":["replyTo","request","taskId"],"type":"object"},"type":"array"},"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"anyOf":[{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"request":{},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","request"],"type":"object"},{"additionalProperties":{},"properties":{"replyTo":{"type":"string"},"requests":{"items":{},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"taskId":{"type":"string"},"turnId":{"type":"string"}},"required":["replyTo","sequence","stepIndex","taskId","turnId","requests"],"type":"object"}]},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"}},"type":"object"},"metadata":{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":4,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;
diff --git a/packages/eve/src/execution/wire/session-inbox-contract.ts b/packages/eve/src/execution/wire/session-inbox-contract.ts
index a570b9645..c8b03cedd 100644
--- a/packages/eve/src/execution/wire/session-inbox-contract.ts
+++ b/packages/eve/src/execution/wire/session-inbox-contract.ts
@@ -1,5 +1,5 @@
/** Every explicit session-inbox wire version still supported by producers. */
-export const SESSION_INBOX_WIRE_VERSIONS = [1, 2, 3] as const;
+export const SESSION_INBOX_WIRE_VERSIONS = [1, 2, 3, 4] as const;
export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[number];
diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.ts b/packages/eve/src/execution/wire/session-inbox-encoder.ts
index 0c1aac606..ea1153667 100644
--- a/packages/eve/src/execution/wire/session-inbox-encoder.ts
+++ b/packages/eve/src/execution/wire/session-inbox-encoder.ts
@@ -22,11 +22,15 @@ import {
type SessionInboxWireVersion,
} from "#execution/wire/session-inbox-contract.js";
import { encodeSessionCommandV0 } from "#execution/wire/session-inbox-wire.v0.js";
+import {
+ encodeSessionCommandV4,
+ type SessionInboxWireV4,
+} from "#execution/wire/session-inbox-wire.v4.js";
type SessionInboxCommand = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;
/** Current wire type consumed after migration. */
-export type SessionInboxWire = SessionInboxWireV3;
+export type SessionInboxWire = SessionInboxWireV4;
type LegacySessionInboxWireTarget = Extract<SessionInboxWireTarget, { readonly version: 0 }>;
type VersionedSessionInboxEncoder = (command: SessionInboxCommand) => unknown;
@@ -35,12 +39,14 @@ const versionedEncoders = {
1: (command: SessionInboxCommand) => encodeSessionCommandV1(withoutAcceptedDeployment(command)),
2: (command: SessionInboxCommand) => encodeSessionCommandV2(withoutAcceptedDeployment(command)),
3: encodeSessionCommandV3,
+ 4: encodeSessionCommandV4,
} satisfies Record<SessionInboxWireVersion, VersionedSessionInboxEncoder>;
/** Encodes a command for the selected session-inbox consumer. */
function encode(command: SessionInboxCommand, target: { readonly version: 1 }): SessionInboxWireV1;
function encode(command: SessionInboxCommand, target: { readonly version: 2 }): SessionInboxWireV2;
function encode(command: SessionInboxCommand, target: { readonly version: 3 }): SessionInboxWireV3;
+function encode(command: SessionInboxCommand, target: { readonly version: 4 }): SessionInboxWireV4;
function encode(
command: SessionInboxCommand,
target: { readonly version: SessionInboxWireVersion },
@@ -52,16 +58,33 @@ function encode(
function encode(
command: SessionInboxCommand,
target: SessionInboxWireTarget,
-): SessionInboxWireV1 | SessionInboxWireV2 | SessionInboxWireV3 | Record<string, unknown>;
+):
+ | SessionInboxWireV1
+ | SessionInboxWireV2
+ | SessionInboxWireV3
+ | SessionInboxWireV4
+ | Record<string, unknown>;
function encode(
command: SessionInboxCommand,
target: SessionInboxWireTarget,
-): SessionInboxWireV1 | SessionInboxWireV2 | SessionInboxWireV3 | Record<string, unknown> {
+):
+ | SessionInboxWireV1
+ | SessionInboxWireV2
+ | SessionInboxWireV3
+ | SessionInboxWireV4
+ | Record<string, unknown> {
if (target.version === 0) {
- const legacy = encodeSessionCommandV0(
- encodeSessionCommandV1(withoutAcceptedDeployment(command)),
+ const currentTaskWire =
+ target.variant === "send" && command.kind === "send" && command.payload.task !== undefined
+ ? encodeSessionCommandV4(command)
+ : undefined;
+ let legacy = encodeSessionCommandV0(
+ encodeSessionCommandV1(withoutCurrentTaskMessages(withoutAcceptedDeployment(command))),
target.variant,
);
+ if (currentTaskWire?.kind === "deliver") {
+ legacy = { ...legacy, payload: currentTaskWire.payload };
+ }
const legacyRecord = legacy as Record<string, unknown>;
const delivery = legacyRecord.delivery;
const acceptedDeploymentId = readAcceptedDeploymentId(command);
@@ -83,13 +106,24 @@ function encode(
return versionedEncoders[target.version](command) as
| SessionInboxWireV1
| SessionInboxWireV2
- | SessionInboxWireV3;
+ | SessionInboxWireV3
+ | SessionInboxWireV4;
}
throw new SessionInboxWireError(
`Cannot encode session inbox payload for unknown wire version ${JSON.stringify((target as { version?: unknown }).version)}.`,
);
}
+function withoutCurrentTaskMessages(command: SessionInboxCommand): SessionInboxCommand {
+ if (command.kind !== "send" || command.payload.task === undefined) return command;
+ const {
+ agentRequests: _agentRequests,
+ inputRequests: _inputRequests,
+ ...task
+ } = command.payload.task;
+ return { ...command, payload: { ...command.payload, task } };
+}
+
function withoutAcceptedDeployment(command: SessionInboxCommand): SessionInboxCommand {
if (command.kind === "send" && command.delivery?.acceptedDeploymentId !== undefined) {
const { acceptedDeploymentId: _acceptedDeploymentId, ...delivery } = command.delivery;
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.ts b/packages/eve/src/execution/wire/session-inbox-wire.ts
index 4a129c6af..fd7b3c04e 100644
--- a/packages/eve/src/execution/wire/session-inbox-wire.ts
+++ b/packages/eve/src/execution/wire/session-inbox-wire.ts
@@ -17,6 +17,8 @@ import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.
import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";
import { sessionInboxWireV1Migration } from "#execution/wire/session-inbox-wire.v2.migration.js";
import { sessionInboxWireV2Migration } from "#execution/wire/session-inbox-wire.v3.migration.js";
+import { sessionInboxWireV3Migration } from "#execution/wire/session-inbox-wire.v4.migration.js";
+import { isObject } from "#shared/guards.js";
/**
* The session inbox wire family: every payload persisted to a session's
@@ -38,21 +40,22 @@ export type DecodedSessionInbox =
export { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
-/** Prefixes chain and schema failures alike, so messages read as one voice. */
+/** Prefixes migration and contract failures alike, so messages read as one voice. */
const WIRE_LABEL = "session inbox payload";
const sessionInboxMigrations: readonly VersionMigration[] = [
sessionInboxWireV0Migration,
sessionInboxWireV1Migration,
sessionInboxWireV2Migration,
+ sessionInboxWireV3Migration,
];
/**
* Decodes a persisted inbox payload or throws {@link SessionInboxWireError}.
*
- * Unknown newer versions and shape mismatches both throw: a lost delivery
- * with an operator-visible signal is the designed failure; a reinterpreted
- * delivery is the bug this module exists to prevent.
+ * Unknown newer versions and migration-bound shape mismatches both throw: a
+ * lost delivery with an operator-visible signal is the designed failure; a
+ * reinterpreted delivery is the bug this module exists to prevent.
*/
function decode(value: unknown): DecodedSessionInbox {
const declaredVersion =
@@ -64,6 +67,14 @@ function decode(value: unknown): DecodedSessionInbox {
throw new SessionInboxWireError(`${WIRE_LABEL}: value has no numeric "version" field.`);
}
const normalized = normalizeSessionInboxWireV2(value);
+ if (
+ (declaredVersion === 1 || declaredVersion === 2 || declaredVersion === 3) &&
+ containsCurrentTaskMessages(normalized)
+ ) {
+ throw new SessionInboxWireError(
+ `${WIRE_LABEL} does not match wire version ${declaredVersion}.`,
+ );
+ }
let migrated: unknown;
try {
migrated = runMigrationChain({
@@ -99,6 +110,22 @@ function decode(value: unknown): DecodedSessionInbox {
/** Workflow-safe consumer facade. */
export const sessionInboxWire = { decode } as const;
+function containsCurrentTaskMessages(value: unknown): boolean {
+ if (!isObject(value) || value.kind !== "deliver") return false;
+ const payloads = Array.isArray(value.payloads) ? value.payloads : [];
+ return payloads.some((payload) => {
+ if (!isObject(payload) || !isObject(payload.task)) return false;
+ if (Object.hasOwn(payload.task, "agentRequests")) return true;
+ const inputRequests = payload.task.inputRequests;
+ return (
+ Array.isArray(inputRequests) &&
+ inputRequests.some(
+ (request) => isObject(request) && ("request" in request || "requests" in request),
+ )
+ );
+ });
+}
+
/** Strips wire-only fields (`version`, the deliver mirror) for consumption. */
function normalizeWire(wire: SessionInboxWire): DecodedSessionInbox {
switch (wire.kind) {
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.test.ts
new file mode 100644
index 000000000..c7af41e5d
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+
+import { sessionInboxWireV3Migration } from "#execution/wire/session-inbox-wire.v4.migration.js";
+
+describe("session inbox wire v4 migration", () => {
+ it("rejects malformed direct migration input", () => {
+ expect(() => sessionInboxWireV3Migration.migrate(null)).toThrow(
+ "session inbox wire v3 value is not an object",
+ );
+ });
+
+ it("translates legacy task envelopes and preserves v3 provenance", () => {
+ const request = { kind: "question", prompt: "Continue?", requestId: "request-1" };
+ const authorization = {
+ callId: "call-1",
+ childSessionId: "child-1",
+ event: { type: "authorization.required" },
+ kind: "subagent-authorization-event",
+ subagentName: "research",
+ };
+ expect(
+ sessionInboxWireV3Migration.migrate({
+ deliveryMetadata: [
+ {
+ acceptedDeploymentId: "dpl_current",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-1",
+ payloadIndex: 0,
+ },
+ ],
+ kind: "deliver",
+ payload: {},
+ payloads: [
+ {
+ task: {
+ authorizationEvents: [{ hookPayload: authorization, taskId: "task-1" }],
+ inputRequests: [
+ {
+ hookPayload: {
+ childContinuationToken: "answer-hook",
+ event: { requests: [request], sequence: 2, stepIndex: 3, turnId: "turn-1" },
+ },
+ taskId: "task-1",
+ },
+ ],
+ views: [
+ {
+ executor: {
+ binding: { data: {}, kind: "subagent" },
+ childSessionId: "child-1",
+ lifecycle: "parked",
+ },
+ metadata: { kind: "subagent", name: "research" },
+ status: "working",
+ taskId: "task-1",
+ },
+ ],
+ },
+ },
+ ],
+ version: 3,
+ }),
+ ).toMatchObject({
+ deliveryMetadata: [{ acceptedDeploymentId: "dpl_current" }],
+ kind: "deliver",
+ payloads: [
+ {
+ task: {
+ authorizationEvents: [{ hookPayload: authorization, taskId: "task-1" }],
+ inputRequests: [
+ {
+ replyTo: "answer-hook",
+ request,
+ sequence: 2,
+ stepIndex: 3,
+ taskId: "task-1",
+ turnId: "turn-1",
+ },
+ ],
+ views: [
+ {
+ executor: { binding: { data: {}, kind: "subagent" } },
+ taskId: "task-1",
+ },
+ ],
+ },
+ },
+ ],
+ version: 4,
+ });
+ });
+});
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.ts
new file mode 100644
index 000000000..a697f26a8
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v4.migration.ts
@@ -0,0 +1,71 @@
+import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";
+import { isObject } from "#shared/guards.js";
+
+/** Translates v3 task envelopes into typed workflow-run requests. */
+export const sessionInboxWireV3Migration: VersionMigration = {
+ from: 3,
+ migrate(prior) {
+ if (!isObject(prior)) throw new Error("session inbox wire v3 value is not an object.");
+ if (prior.kind !== "deliver") return { ...prior, version: 4 };
+ return {
+ ...prior,
+ payload: migratePayload(prior.payload),
+ payloads: Array.isArray(prior.payloads) ? prior.payloads.map(migratePayload) : prior.payloads,
+ version: 4,
+ };
+ },
+ to: 4,
+};
+
+function migratePayload(payload: unknown): unknown {
+ if (!isObject(payload) || !isObject(payload.task)) return payload;
+ const task = payload.task;
+ return {
+ ...payload,
+ task: {
+ agentRequests: task.agentRequests,
+ authorizationEvents: task.authorizationEvents,
+ inputRequests: migrateInputRequests(task.inputRequests),
+ views: Array.isArray(task.views) ? task.views.map(migrateTaskView) : task.views,
+ },
+ };
+}
+
+function migrateInputRequests(value: unknown): unknown {
+ if (!Array.isArray(value)) return undefined;
+ return value.flatMap((entry) => {
+ if (!isObject(entry)) return [];
+ if ("request" in entry || "requests" in entry) return [entry];
+ if (!isObject(entry.hookPayload) || typeof entry.taskId !== "string") return [];
+ const hookPayload = entry.hookPayload;
+ const event = hookPayload.event;
+ if (
+ typeof hookPayload.childContinuationToken !== "string" ||
+ !isObject(event) ||
+ !Array.isArray(event.requests) ||
+ typeof event.sequence !== "number" ||
+ typeof event.stepIndex !== "number" ||
+ typeof event.turnId !== "string"
+ ) {
+ return [];
+ }
+ return event.requests.map((request) => ({
+ ...entry,
+ replyTo: hookPayload.childContinuationToken,
+ request,
+ sequence: event.sequence,
+ stepIndex: event.stepIndex,
+ taskId: entry.taskId,
+ turnId: event.turnId,
+ }));
+ });
+}
+
+function migrateTaskView(value: unknown): unknown {
+ if (!isObject(value) || !isObject(value.executor)) return value;
+ return {
+ ...value,
+ executor:
+ value.executor.binding === undefined ? undefined : { binding: value.executor.binding },
+ };
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.test.ts
new file mode 100644
index 000000000..7c3be4d05
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v4.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from "vitest";
+import { z } from "#compiled/zod/index.js";
+
+import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
+import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";
+import { sessionInboxWireV4Schema } from "#execution/wire/session-inbox-wire.v4.js";
+
+const agentRequest = {
+ replyTo: "agent-reply",
+ request: {
+ input: { message: "Find it", target: "research" },
+ invocationId: "call-1:research",
+ kind: "agent-invoke" as const,
+ },
+ taskId: "task-1",
+};
+const authorizationEvent = {
+ hookPayload: {
+ callId: "call-1",
+ childSessionId: "child-1",
+ event: {
+ data: {
+ description: "Authorize Linear",
+ name: "linear",
+ sequence: 1,
+ stepIndex: 2,
+ turnId: "turn-child",
+ },
+ type: "authorization.required" as const,
+ },
+ kind: "subagent-authorization-event" as const,
+ subagentName: "research",
+ },
+ taskId: "task-1",
+};
+const inputRequest = {
+ replyTo: "answer-hook",
+ request: { kind: "question", prompt: "Continue?", requestId: "request-1" },
+ sequence: 2,
+ stepIndex: 3,
+ taskId: "task-1",
+ turnId: "turn-1",
+};
+
+describe("session inbox wire v4", () => {
+ it("round-trips task-owned agent requests, authorization events, and input requests", () => {
+ const task = {
+ agentRequests: [agentRequest],
+ authorizationEvents: [authorizationEvent],
+ inputRequests: [inputRequest],
+ };
+ const wire = sessionInboxWire.encode({ kind: "send", payload: { task } }, { version: 4 });
+
+ expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({
+ kind: "deliver",
+ payloads: [{ task }],
+ });
+ });
+
+ it("rejects malformed task authorization events", () => {
+ expect(() =>
+ sessionInboxWire.encode(
+ {
+ kind: "send",
+ payload: {
+ task: { authorizationEvents: [{ hookPayload: { kind: "other" }, taskId: "task-1" }] },
+ } as never,
+ },
+ { version: 4 },
+ ),
+ ).toThrow(/wire version 4/);
+ });
+
+ it.each([1, 2, 3] as const)("keeps v%i strict for task agent requests", (version) => {
+ expect(() =>
+ sessionInboxWire.encode(
+ { kind: "send", payload: { task: { agentRequests: [agentRequest] } } },
+ { version },
+ ),
+ ).toThrow(new RegExp(`wire version ${version}`));
+ });
+
+ it.each([1, 2, 3] as const)(
+ "rejects v4 task agent requests falsely declared as immutable v%i",
+ (version) => {
+ expect(() =>
+ sessionInboxWireDecoder.decode({
+ kind: "deliver",
+ payload: { task: { agentRequests: [agentRequest] } },
+ payloads: [{ task: { agentRequests: [agentRequest] } }],
+ version,
+ }),
+ ).toThrow(new RegExp(`does not match wire version ${version}`));
+ },
+ );
+
+ it.each([1, 2, 3] as const)(
+ "rejects v4 task input requests falsely declared as immutable v%i",
+ (version) => {
+ const { request: _request, ...inputRequestBase } = inputRequest;
+ for (const request of [inputRequest, { ...inputRequestBase, requests: [] }]) {
+ expect(() =>
+ sessionInboxWireDecoder.decode({
+ kind: "deliver",
+ payload: { task: { inputRequests: [request] } },
+ payloads: [{ task: { inputRequests: [request] } }],
+ version,
+ }),
+ ).toThrow(new RegExp(`does not match wire version ${version}`));
+ }
+ },
+ );
+
+ it("round-trips batched task input requests", () => {
+ const { request: _request, ...batch } = inputRequest;
+ const batchedRequest = { ...batch, requests: [inputRequest.request] };
+
+ expect(
+ sessionInboxWireDecoder.decode({
+ kind: "deliver",
+ payload: { task: { inputRequests: [batchedRequest] } },
+ payloads: [{ task: { inputRequests: [batchedRequest] } }],
+ version: 4,
+ }),
+ ).toMatchObject({
+ payloads: [{ task: { inputRequests: [batchedRequest] } }],
+ });
+ });
+
+ it("carries current task messages through the stable raw-send fast path", () => {
+ const wire = sessionInboxWire.encode(
+ {
+ kind: "send",
+ payload: { task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } },
+ },
+ { variant: "send", version: 0 },
+ );
+
+ expect(wire).toMatchObject({
+ kind: "send",
+ payload: { task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } },
+ });
+ expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({
+ kind: "deliver",
+ payloads: [{ task: { agentRequests: [agentRequest], inputRequests: [inputRequest] } }],
+ });
+ });
+
+ it("round-trips accepted deployment provenance", () => {
+ const delivery = {
+ acceptedDeploymentId: "dpl_current",
+ channelKind: "channel:webhook",
+ channelName: "webhook",
+ deliveryId: "delivery-1",
+ };
+ const wire = sessionInboxWire.encode(
+ { delivery, kind: "send", payload: { message: "hello" } },
+ { version: 4 },
+ );
+
+ expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({
+ deliveryMetadata: [{ ...delivery, payloadIndex: 0 }],
+ kind: "deliver",
+ });
+ });
+
+ it("pins the complete schema byte for byte", () => {
+ expect(
+ stableStringify(
+ z.toJSONSchema(sessionInboxWireV4Schema, { io: "input", unrepresentable: "any" }),
+ ),
+ ).toMatchSnapshot();
+ });
+});
+
+function stableStringify(value: unknown): string {
+ return JSON.stringify(value, (_key, item) => {
+ if (item === null || typeof item !== "object" || Array.isArray(item)) return item;
+ return Object.fromEntries(
+ Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),
+ );
+ });
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v4.ts b/packages/eve/src/execution/wire/session-inbox-wire.v4.ts
new file mode 100644
index 000000000..3ae9e299f
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v4.ts
@@ -0,0 +1,202 @@
+import { z } from "#compiled/zod/index.js";
+
+import type {
+ DeliverHookPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
+import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
+import { sessionInboxWireV3Schema } from "#execution/wire/session-inbox-wire.v3.js";
+import { formatValidationError } from "#runtime/validation.js";
+import { runtimeSubagentChildResultSchema } from "#shared/action-types.js";
+import { jsonValueSchema } from "#shared/json-schemas.js";
+import { tokenUsageSchema } from "#shared/token-usage.js";
+import type { TaskView } from "#tasks/types.js";
+
+const taskMetadataSchema = z
+ .object({
+ agentId: z.string().optional(),
+ kind: z.string(),
+ mode: z.enum(["local", "remote"]).optional(),
+ name: z.string(),
+ })
+ .strict();
+const taskExecutorSchema = z
+ .object({
+ binding: z
+ .object({
+ data: z.record(z.string(), jsonValueSchema),
+ kind: z.string(),
+ })
+ .strict()
+ .optional(),
+ })
+ .strict();
+const taskViewBase = {
+ executor: taskExecutorSchema.optional(),
+ metadata: taskMetadataSchema,
+ taskId: z.string(),
+ usage: tokenUsageSchema.optional(),
+};
+const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", [
+ z.object({ ...taskViewBase, status: z.literal("working") }).strict(),
+ z
+ .object({
+ ...taskViewBase,
+ inputRequests: z.array(jsonValueSchema),
+ status: z.literal("input_required"),
+ })
+ .strict(),
+ z
+ .object({
+ ...taskViewBase,
+ lastOutput: z.object({ data: jsonValueSchema, type: z.literal("result") }).strict(),
+ status: z.literal("completed"),
+ })
+ .strict(),
+ z
+ .object({
+ ...taskViewBase,
+ lastOutput: z.object({ data: jsonValueSchema, type: z.literal("error") }).strict(),
+ status: z.literal("failed"),
+ })
+ .strict(),
+ z.object({ ...taskViewBase, status: z.literal("cancelled") }).strict(),
+]);
+const eventCoordinateSchema = z.number().int().nonnegative();
+const taskInputRequestBase = {
+ replyTo: z.string(),
+ sequence: eventCoordinateSchema,
+ stepIndex: eventCoordinateSchema,
+ taskId: z.string(),
+ turnId: z.string(),
+};
+const taskInputRequestSchema = z.union([
+ z
+ .object({
+ ...taskInputRequestBase,
+ request: jsonValueSchema,
+ })
+ .loose(),
+ z
+ .object({
+ ...taskInputRequestBase,
+ requests: z.array(jsonValueSchema),
+ })
+ .loose(),
+]);
+const agentInvocationInputSchema = z
+ .object({
+ agentId: z.string().optional(),
+ message: z.string(),
+ outputSchema: z.record(z.string(), jsonValueSchema).optional(),
+ target: z.string(),
+ })
+ .strict();
+const taskAgentRequestSchema = z
+ .object({
+ replyTo: z.string(),
+ request: z.discriminatedUnion("kind", [
+ z
+ .object({
+ input: agentInvocationInputSchema,
+ invocationId: z.string(),
+ kind: z.literal("agent-invoke"),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("agent-settled"),
+ result: runtimeSubagentChildResultSchema,
+ })
+ .strict(),
+ ]),
+ taskId: z.string(),
+ })
+ .strict();
+const subagentAuthorizationEventHookPayloadSchema = z
+ .object({
+ callId: z.string(),
+ childSessionId: z.string(),
+ event: z.custom<Record<string, unknown>>(
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value),
+ "Expected an object.",
+ ),
+ kind: z.literal("subagent-authorization-event"),
+ subagentName: z.string(),
+ })
+ .strict();
+const taskAuthorizationEventSchema = z
+ .object({
+ hookPayload: subagentAuthorizationEventHookPayloadSchema,
+ taskId: z.string(),
+ })
+ .strict();
+const taskPayloadV4Schema = z
+ .object({
+ agentRequests: z.array(taskAgentRequestSchema).optional(),
+ authorizationEvents: z.array(taskAuthorizationEventSchema).optional(),
+ inputRequests: z.array(taskInputRequestSchema).optional(),
+ views: z.array(taskViewSchema).optional(),
+ })
+ .strict();
+
+const v3 = sessionInboxWireV3Schema.options;
+const v3Deliver = v3[0];
+const deliverPayloadV4Schema = v3Deliver.shape.payload.extend({
+ task: taskPayloadV4Schema.optional(),
+});
+const VERSION = 4;
+const version = z.literal(VERSION);
+
+/** Version 4 replaces executor-specific task envelopes with typed workflow-run requests. */
+export const sessionInboxWireV4Schema = z.discriminatedUnion("kind", [
+ v3Deliver.extend({
+ payload: deliverPayloadV4Schema,
+ payloads: z.array(deliverPayloadV4Schema),
+ version,
+ }),
+ v3[1].extend({ version }),
+ v3[2].extend({ version }),
+ v3[3].extend({ version }),
+ v3[4].extend({ version }),
+ v3[5].extend({ version }),
+]);
+
+export type SessionInboxWireV4 = z.infer<typeof sessionInboxWireV4Schema>;
+
+/** Builds and validates one complete version-4 wire value. */
+export function encodeSessionCommandV4(
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): SessionInboxWireV4 {
+ const wire =
+ command.kind === "send"
+ ? {
+ auth: command.auth,
+ caller: command.caller,
+ deliveryMetadata:
+ command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],
+ kind: "deliver" as const,
+ payload: command.payload,
+ payloads: [command.payload],
+ requestId: command.requestId,
+ taskDeliveryId: command.taskDeliveryId,
+ turnPolicy: command.turnPolicy,
+ version: VERSION,
+ }
+ : command.kind === "deliver"
+ ? {
+ ...command,
+ payload: coalesceDeliverPayloads(command.payloads),
+ version: VERSION,
+ }
+ : { ...command, version: VERSION };
+ const parsed = sessionInboxWireV4Schema.safeParse(wire);
+ if (!parsed.success) {
+ throw new SessionInboxWireError(
+ `Produced a session inbox payload that does not match wire version ${VERSION}: ${formatValidationError(parsed.error)}`,
+ );
+ }
+ return parsed.data;
+}
diff --git a/packages/eve/src/execution/workflow-entry-finalization.ts b/packages/eve/src/execution/workflow-entry-finalization.ts
index 1ab38e1ba..463ba4cbc 100644
--- a/packages/eve/src/execution/workflow-entry-finalization.ts
+++ b/packages/eve/src/execution/workflow-entry-finalization.ts
@@ -1,15 +1,12 @@
import type { TurnCaller } from "#channel/types.js";
-import {
- notifyDelegatedParentStep,
- notifyTurnCallerStep,
-} from "#execution/delegated-parent-notification.js";
+import { notifyDelegatedParentStep, notifyTurnCallerStep } from "#subagents/parent-notification.js";
import {
createDelegatedSubagentErrorResult,
createDelegatedSubagentSuccessResult,
-} from "#execution/delegated-parent-result.js";
+} from "#subagents/parent-result.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
-import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
+import { fireSessionCallbackStep } from "#subagents/callback-step.js";
import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
import type { RunMode } from "#shared/run-mode.js";
@@ -21,6 +18,7 @@ export async function finalizeExpiredSession(input: {
readonly mode: RunMode;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly terminalState?: { terminalEmitted: boolean };
}): Promise<{ readonly output: unknown }> {
await terminateChildSessionsStep({
serializedContext: input.serializedContext,
@@ -30,6 +28,7 @@ export async function finalizeExpiredSession(input: {
parentWritable: input.driverWritable,
serializedContext: input.serializedContext,
});
+ if (input.terminalState !== undefined) input.terminalState.terminalEmitted = true;
if (input.mode === "task") {
await fireSessionCallbackStep({
@@ -56,6 +55,7 @@ export async function finalizeDone(input: {
readonly action: NextDriverAction & { readonly kind: "done" };
readonly caller: TurnCaller | undefined;
readonly mode: RunMode;
+ readonly terminalState?: { terminalEmitted: boolean };
}): Promise<{ readonly output: unknown }> {
const { output, serializedContext } = input.action;
const failed = input.action.isError === true;
@@ -64,6 +64,7 @@ export async function finalizeDone(input: {
serializedContext,
sessionState: input.action.sessionState,
});
+ if (input.terminalState !== undefined) input.terminalState.terminalEmitted = true;
if (input.mode === "task") {
await fireSessionCallbackStep({
error: failed ? output : undefined,
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index a53757e12..ebc081893 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -3,19 +3,18 @@ import { createHook } from "#compiled/@workflow/core/index.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import type { HookPayload } from "#channel/types.js";
-import { ChannelRequestIdKey, SubagentDepthKey } from "#context/keys.js";
+import { ChannelRequestIdKey } from "#context/keys.js";
import { createSessionStep } from "#execution/create-session-step.js";
import {
bindTurnCallerContextStep,
notifyCancelledTaskCallerStep,
notifyDelegatedParentStep,
- notifyTaskTurnStartedStep,
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
-} from "#execution/delegated-parent-notification.js";
+} from "#subagents/parent-notification.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { dispatchTurnStep } from "#execution/dispatch-turn-step.js";
-import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
+import { fireSessionCallbackStep } from "#subagents/callback-step.js";
import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
import {
createSessionTimeoutControl,
@@ -81,13 +80,12 @@ vi.mock("./route-child-delivery.js", () => ({
})),
}));
-vi.mock("./delegated-parent-notification.js", () => ({
+vi.mock("../subagents/parent-notification.js", () => ({
bindTurnCallerContextStep: vi
.fn()
.mockImplementation(async ({ serializedContext }) => serializedContext),
notifyCancelledTaskCallerStep: vi.fn().mockResolvedValue(undefined),
notifyDelegatedParentStep: vi.fn().mockResolvedValue(undefined),
- notifyTaskTurnStartedStep: vi.fn().mockResolvedValue(undefined),
notifyTurnCallerStep: vi.fn().mockResolvedValue(undefined),
resolveInitialTurnCallerStep: vi.fn().mockResolvedValue(undefined),
}));
@@ -140,7 +138,7 @@ function createSessionStepResultForMock(state: DurableSessionState) {
};
}
-vi.mock("./session-callback-step.js", () => ({
+vi.mock("../subagents/callback-step.js", () => ({
fireSessionCallbackStep: vi.fn().mockResolvedValue(undefined),
}));
@@ -203,7 +201,7 @@ describe("workflowEntry", () => {
continuationToken: "http:test",
nodeId: undefined,
sessionId: "wrun_test_123",
- taskOwned: false,
+ taskId: undefined,
}),
);
expect(dispatchTurnStep).toHaveBeenCalledWith(
@@ -323,11 +321,6 @@ describe("workflowEntry", () => {
);
expect(resolveInitialTurnCallerStep).toHaveBeenCalledExactlyOnceWith({ serializedContext });
- expect(notifyTaskTurnStartedStep).toHaveBeenCalledExactlyOnceWith({
- caller,
- childSessionId: "wrun_test_123",
- childTurnId: "turn_0",
- });
expect(bindTurnCallerContextStep).toHaveBeenCalledExactlyOnceWith({
caller,
serializedContext: expect.objectContaining({ "eve.sessionCallback": expect.any(Object) }),
@@ -534,15 +527,12 @@ describe("workflowEntry", () => {
await workflowEntry({
input: { message: "hello there" },
limits: { maxInputTokensPerSession: 4 },
- serializedContext: createSerializedContext({
- [SubagentDepthKey.name]: 3,
- }),
+ serializedContext: createSerializedContext({}),
});
expect(createSessionStep).toHaveBeenCalledWith(
expect.objectContaining({
inheritedLimits: { maxInputTokensPerSession: 4 },
- subagentDepth: 3,
}),
);
});
@@ -1379,7 +1369,7 @@ describe("workflowEntry", () => {
expect.objectContaining({
error: expect.objectContaining({ message: "caller notification failed" }),
serializedContext: settledContext,
- turnId: undefined,
+ turnId: "turn_0",
}),
);
});
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index b3bcc757e..ebd543b27 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -16,40 +16,34 @@ import {
bindTurnCallerContextStep,
notifyCancelledTaskCallerStep,
notifyDelegatedParentStep,
- notifyTaskTurnStartedStep,
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
-} from "#execution/delegated-parent-notification.js";
-import { createDelegatedSubagentErrorResult } from "#execution/delegated-parent-result.js";
+} from "#subagents/parent-notification.js";
+import { createDelegatedSubagentErrorResult } from "#subagents/parent-result.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { nextTurnDelivery, type NextTurnInstruction } from "#execution/parked-delivery-wait.js";
import { SessionStateCursor } from "#execution/session-state-cursor.js";
+import { rebaseTaskAgentHandleMutations } from "#subagents/handles/rebase.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
import { normalizeSerializableError } from "#execution/workflow-errors.js";
-import { finalizeDone } from "#execution/workflow-entry-finalization.js";
import { createSessionStep } from "#execution/create-session-step.js";
import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
-import { finalizeTerminalSession } from "#execution/finalize-terminal-session.js";
-import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
+import { fireSessionCallbackStep } from "#subagents/callback-step.js";
+import { finalizeDone, finalizeExpiredSession } from "#execution/workflow-entry-finalization.js";
import { isHookConflictError } from "#execution/hook-ownership.js";
import {
createSessionCommandInbox,
type SessionCommandInbox,
} from "#execution/session-command-inbox.js";
-import { activeTurnId } from "#harness/active-turn-id.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";
import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
-import { readSerializedSubagentDepth } from "#harness/subagent-depth.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
-import { isTaskOwnedSerializedContext } from "#execution/tasks/child/instructions.js";
import { attachClientContext, readClientContext } from "#internal/client-context.js";
-import { CHANNEL_CONTEXT_KEY_NAME, SESSION_CALLBACK_CONTEXT_KEY_NAME } from "#context/key-names.js";
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";
const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE =
@@ -71,6 +65,7 @@ export interface WorkflowEntryInput {
readonly limits?: RunInput["limits"];
readonly sessionTimeoutMs?: number | false;
readonly serializedContext: Record<string, unknown>;
+ readonly taskId?: string;
}
export interface WorkflowEntryResult {
@@ -79,8 +74,7 @@ export interface WorkflowEntryResult {
type DriverLoopOutcome =
| {
- readonly kind: "terminal";
- readonly notifyCaller: boolean;
+ readonly kind: "expired";
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}
@@ -106,19 +100,15 @@ type DriverLoopOutcome =
* instead of mirroring it here.
*/
interface CrashCleanupState {
- // The turn currently owned by `dispatchAndAwaitTurn`, when a crash occurs
- // before its terminal state returns to the driver.
- activeTurnId: string | undefined;
// The caller whose awaited reply is still unsettled, so the catch can
// reject it with the error instead of leaving it parked forever.
- // Root sessions leave it undefined; only conversation-mode paths read it.
+ // Populated for every session; only conversation-mode paths read it.
caller: TurnCaller | undefined;
- // Whether initial lineage has been classified, either by proving it is a
- // root session or by resolving its caller. `caller: undefined` is ambiguous
- // on its own: it also means "resolved and later cleared because its reply
- // settled". This flag lets the crash path tell that apart from "crashed
- // before lineage was classified", where a delegated caller may still be
- // parked on this session's reply.
+ // Whether `resolveInitialTurnCallerStep` has run. `caller: undefined` is
+ // ambiguous on its own: it also means "resolved and later cleared because
+ // its reply settled". This flag lets the crash path tell that apart from
+ // "crashed before the caller was ever resolved", where a delegated caller
+ // may still be parked on this session's reply.
callerResolved: boolean;
// The latest snapshot the driver has received, so the catch can
// terminate children adopted after turn 1. Honest staleness window: the
@@ -130,8 +120,13 @@ interface CrashCleanupState {
// and trace state needed by terminal instrumentation.
serializedContext: Record<string, unknown>;
// Whether the session already emitted a terminal protocol and instrumentation
- // event, so later callback or teardown failures cannot contradict it.
+ // event (set here on the crash path, or by the finalization steps via
+ // `terminalState`), so later callback or teardown failures cannot contradict it.
terminalEmitted: boolean;
+ // The most recently dispatched turn, derived from the dispatch index so the
+ // durable workflow body does not import the harness. Never cleared on settle:
+ // a crash between turns is attributed to the last dispatched turn.
+ turnId?: string;
}
/**
@@ -143,7 +138,7 @@ interface CrashCleanupState {
*
* Owns the stable command inbox, its channel alias, and the session lifecycle; each turn-owned
* turn resolves its own runtime actions in-line and reports back only
- * `done`/`park` via the closed `NextDriverAction` contract. The
+ * `done`/`park` via the closed-contract {@link NextDriverAction}. The
* only session-shape flag the driver reads (besides identity) is
* `hasProxyInputRequests`, the documented short-circuit for hook-payload
* routing to any descendant still active when the parent parks.
@@ -168,7 +163,6 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
const driverWritable = getWritable<Uint8Array>();
const crashCleanupState: CrashCleanupState = {
- activeTurnId: undefined,
caller: undefined,
callerResolved: false,
lastSessionState: undefined,
@@ -180,22 +174,16 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
// Derived once and reused for createSession + tag emission so the
// chain-root id can never drift between persisted session and tags.
const rootSessionIdFromParent = readRootSessionId(input.serializedContext);
- const subagentDepth = readSerializedSubagentDepth(input.serializedContext);
const dynamicSubagentAgentConfig = input.serializedContext["eve.dynamicSubagentAgentConfig"] as
| DynamicSubagentAgentConfig
| undefined;
const commandInbox = createSessionCommandInbox();
const stableCommandToken = sessionCommandHookToken(sessionId);
- // getHookUrl() builds authorization callback URLs with this token. It is
- // inlined because the durable workflow body cannot import the harness.
const authorizationHookToken = `${sessionId}:auth`;
let sessionState: DurableSessionState;
let outcome: DriverLoopOutcome;
try {
- // Hook ownership is independent of session hydration. Start every
- // readiness claim immediately so Workflow can persist them while the
- // session bundle is loading, then join every sibling before cleanup.
const [sessionCreation, stableClaim, authorizationClaim, continuationClaim] =
await Promise.allSettled([
createSessionStep({
@@ -207,8 +195,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
outputSchema: input.input.outputSchema,
rootSessionId: rootSessionIdFromParent,
sessionId,
- subagentDepth,
- taskOwned: isTaskOwnedSerializedContext(input.serializedContext),
+ taskId: input.taskId,
}),
commandInbox.claimStable(stableCommandToken),
commandInbox.claimAuthorization(authorizationHookToken),
@@ -219,8 +206,10 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
if (stableClaim.status === "rejected") throw stableClaim.reason;
if (authorizationClaim.status === "rejected") throw authorizationClaim.reason;
if (continuationClaim.status === "rejected") {
- // Only the durable alias owner runs a first turn; a losing candidate
- // hands its address delivery to that owner before exiting.
+ // Two runs can race for the same continuation alias (e.g. two messages
+ // hit one thread before either session owns it). Only the winner runs
+ // a turn; the loser forwards its `send` to the owner and exits with an
+ // empty result, since it produced nothing.
if (isHookConflictError(continuationClaim.reason)) {
if (
input.activityCollectorRunId !== undefined ||
@@ -243,11 +232,9 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
sessionState = sessionCreation.value.state;
crashCleanupState.lastSessionState = sessionState;
- if (!hasGuaranteedRootLineage(input.serializedContext)) {
- crashCleanupState.caller = await resolveInitialTurnCallerStep({
- serializedContext: input.serializedContext,
- });
- }
+ crashCleanupState.caller = hasDelegatedCallerContext(input.serializedContext)
+ ? await resolveInitialTurnCallerStep({ serializedContext: input.serializedContext })
+ : undefined;
crashCleanupState.callerResolved = true;
outcome = await runDriverLoop({
@@ -298,21 +285,21 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
if (outcome.kind === "result") {
return outcome.result;
}
- return await finalizeTerminalSession({
+ return await finalizeExpiredSession({
caller: crashCleanupState.caller,
driverWritable,
mode,
- notifyCaller: outcome.notifyCaller,
serializedContext: outcome.serializedContext,
sessionState: outcome.sessionState,
terminalState: crashCleanupState,
});
} catch (error) {
+ const terminalAlreadyEmitted = crashCleanupState.terminalEmitted;
// Safety net for failures the tool-loop harness does not already
// surface as `session.failed` (deserialization, runtime-action
// throws, adapter `deliver` throws, staging errors, etc.) so the
// channel still sees a terminal event.
- if (crashCleanupState.lastSessionState !== undefined) {
+ if (!crashCleanupState.terminalEmitted && crashCleanupState.lastSessionState !== undefined) {
await terminateChildSessionsStep({
serializedContext: crashCleanupState.serializedContext,
sessionState: crashCleanupState.lastSessionState,
@@ -323,43 +310,50 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow
error: normalizeSerializableError(error),
parentWritable: driverWritable,
serializedContext: crashCleanupState.serializedContext,
- turnId: crashCleanupState.activeTurnId,
+ turnId: crashCleanupState.turnId,
+ });
+ crashCleanupState.terminalEmitted = true;
+ }
+ if (terminalAlreadyEmitted) throw createSafeOuterWorkflowError();
+ if (mode === "task") {
+ await fireSessionCallbackStep({
+ error: normalizeSerializableError(error),
+ serializedContext: crashCleanupState.serializedContext,
+ status: "failed",
+ });
+ await notifyDelegatedParentStep({
+ result: createDelegatedSubagentErrorResult(crashCleanupState.serializedContext, error),
+ serializedContext: crashCleanupState.serializedContext,
+ });
+ } else if (crashCleanupState.caller !== undefined || !crashCleanupState.callerResolved) {
+ await notifyTurnCallerStep({
+ caller: await resolveCallerForCrash(crashCleanupState, crashCleanupState.serializedContext),
+ lifecycle: "terminal",
+ sessionId,
+ settled: { isError: true, output: error },
});
- if (mode === "task") {
- await fireSessionCallbackStep({
- error: normalizeSerializableError(error),
- serializedContext: input.serializedContext,
- status: "failed",
- });
- await notifyDelegatedParentStep({
- result: createDelegatedSubagentErrorResult(input.serializedContext, error),
- serializedContext: input.serializedContext,
- });
- } else {
- const caller = await resolveCallerForCrash(crashCleanupState, input.serializedContext);
- if (caller !== undefined) {
- await notifyTurnCallerStep({
- caller,
- lifecycle: "terminal",
- sessionId,
- settled: { isError: true, output: error },
- });
- }
- }
}
throw createSafeOuterWorkflowError();
}
}
+function hasDelegatedCallerContext(serializedContext: Record<string, unknown>): boolean {
+ if (serializedContext["eve.sessionCallback"] !== undefined) return true;
+ const channel = serializedContext["eve.channel"];
+ return (
+ typeof channel === "object" && channel !== null && Reflect.get(channel, "kind") === "subagent"
+ );
+}
+
/**
* Caller to reject from the crash path. Normally the resolved cell value —
* including `undefined` after a settled reply cleared it, when there is
* nothing left to notify. When the crash happened before
- * initial lineage was classified (e.g. `createSessionStep` threw), the cell is
- * empty even though a delegated caller may be parked on this session's reply,
- * so the caller is resolved from the serialized context — which needs nothing
- * from the failed steps. Best-effort: when resolution fails there is no
- * reachable caller to notify.
+ * `resolveInitialTurnCallerStep` ever ran (e.g. `createSessionStep` threw),
+ * the cell is empty even though a delegated caller may be parked on this
+ * session's reply, so the caller is re-resolved from the serialized context
+ * — which needs nothing from the failed steps. Best-effort: when resolution
+ * fails again there is no reachable caller to notify.
*/
async function resolveCallerForCrash(
state: CrashCleanupState,
@@ -381,18 +375,6 @@ function createSafeOuterWorkflowError(): Error {
return error;
}
-/** Root lineage has no turn caller to resolve, bind, or notify. */
-function hasGuaranteedRootLineage(serializedContext: Record<string, unknown>): boolean {
- if (serializedContext[SESSION_CALLBACK_CONTEXT_KEY_NAME] !== undefined) return false;
- if (serializedContext["eve.parentSession"] !== undefined) return false;
- if (serializedContext["eve.subagentDepth"] !== undefined) return false;
-
- const channel = serializedContext[CHANNEL_CONTEXT_KEY_NAME];
- if (channel === null || typeof channel !== "object") return false;
- const kind = Reflect.get(channel, "kind");
- return typeof kind === "string" && kind !== SUBAGENT_ADAPTER_KIND;
-}
-
async function runDriverLoop(input: {
readonly capabilities?: SessionCapabilities;
readonly commandInbox: SessionCommandInbox;
@@ -485,6 +467,10 @@ async function runDriverLoop(input: {
const bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset"> = [];
const cancelledTaskIds = new Set<string>();
const seenTaskDeliveries = new Set<string>();
+ const stateCursor = new SessionStateCursor({
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ });
const sessionTimeout =
input.sessionTimeoutDeadline === undefined
? undefined
@@ -493,25 +479,13 @@ async function runDriverLoop(input: {
token: input.stableCommandToken,
});
- // Durable state accumulated across turns and the parked waits between
- // them. Turn results and settle/routing steps are adopted here, so the
- // loop never threads `serializedContext`/`sessionState` pairs by hand.
- const stateCursor = new SessionStateCursor({
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- });
-
// Control-hook disposal is deferred one turn — see DispatchedTurn.
let disposeSettledTurnControl: (() => Promise<void>) | undefined;
const runTurn = async (delivery: HookPayload): Promise<TurnDriverAction> => {
+ const dispatchedSessionState = stateCursor.sessionState;
const caller = input.crashCleanupState.caller;
if (caller?.taskId !== undefined) {
seenTaskDeliveries.add(caller.taskId);
- await notifyTaskTurnStartedStep({
- caller,
- childSessionId: stateCursor.sessionState.sessionId,
- childTurnId: activeTurnId(stateCursor.sessionState.emissionState),
- });
}
const serializedContext =
caller === undefined
@@ -520,8 +494,7 @@ async function runDriverLoop(input: {
caller,
serializedContext: stateCursor.serializedContext,
});
- const dispatchedTurnId = activeTurnId(stateCursor.sessionState.emissionState);
- input.crashCleanupState.activeTurnId = dispatchedTurnId;
+ input.crashCleanupState.turnId = `turn_${String(turnDispatchIndex)}`;
const turn = await dispatchAndAwaitTurn({
bufferedDeliveries,
bufferedSessionControls,
@@ -536,15 +509,20 @@ async function runDriverLoop(input: {
seenTaskDeliveries,
sessionState: stateCursor.sessionState,
});
- input.crashCleanupState.activeTurnId =
- turn.action.kind === "park" && turn.action.cancelled === true ? dispatchedTurnId : undefined;
- input.crashCleanupState.lastSessionState = turn.action.sessionState;
- input.crashCleanupState.serializedContext = turn.action.serializedContext;
- if (turn.action.kind === "done") input.crashCleanupState.terminalEmitted = true;
await disposeSettledTurnControl?.();
disposeSettledTurnControl = turn.dispose;
- stateCursor.adoptState(turn.action);
- return turn.action;
+ const action =
+ stateCursor.sessionState === dispatchedSessionState
+ ? turn.action
+ : rebaseTaskAgentHandleMutations(
+ turn.action,
+ stateCursor.sessionState,
+ dispatchedSessionState,
+ );
+ stateCursor.adoptState(action);
+ input.crashCleanupState.lastSessionState = stateCursor.sessionState;
+ input.crashCleanupState.serializedContext = stateCursor.serializedContext;
+ return action;
};
try {
@@ -560,6 +538,7 @@ async function runDriverLoop(input: {
action,
caller: input.crashCleanupState.caller,
mode: input.mode,
+ terminalState: input.crashCleanupState,
}),
};
}
@@ -578,8 +557,6 @@ async function runDriverLoop(input: {
sessionState: stateCursor.sessionState,
});
stateCursor.adoptState(settled);
- input.crashCleanupState.activeTurnId = undefined;
- input.crashCleanupState.lastSessionState = stateCursor.sessionState;
input.crashCleanupState.serializedContext = stateCursor.serializedContext;
const cancelledCaller = {
caller: input.crashCleanupState.caller,
@@ -590,6 +567,7 @@ async function runDriverLoop(input: {
? cancelledCaller
: { ...cancelledCaller, usage: settled.usage },
);
+ input.crashCleanupState.lastSessionState = stateCursor.sessionState;
}
// Channel-created sessions may rekey their dynamic alias. Sessions
@@ -625,7 +603,6 @@ async function runDriverLoop(input: {
expectedAttemptIds: action.authorizationAttemptIds ?? [],
});
input.crashCleanupState.lastSessionState = stateCursor.sessionState;
- input.crashCleanupState.serializedContext = stateCursor.serializedContext;
if (next.kind === "authorization-resume") {
action = await runTurn({
@@ -637,8 +614,7 @@ async function runDriverLoop(input: {
if (next.kind === "expired") {
return {
- kind: "terminal",
- notifyCaller: true,
+ kind: "expired",
serializedContext: stateCursor.serializedContext,
sessionState: stateCursor.sessionState,
};
@@ -646,10 +622,15 @@ async function runDriverLoop(input: {
if (next.kind === "reset") {
return {
- kind: "terminal",
- notifyCaller: false,
- serializedContext: stateCursor.serializedContext,
- sessionState: stateCursor.sessionState,
+ kind: "result",
+ result: await finalizeExpiredSession({
+ caller: input.crashCleanupState.caller,
+ driverWritable: input.driverWritable,
+ mode: input.mode,
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
+ terminalState: input.crashCleanupState,
+ }),
};
}
@@ -660,10 +641,15 @@ async function runDriverLoop(input: {
if (next.kind === "closed") {
return {
- kind: "terminal",
- notifyCaller: false,
- serializedContext: stateCursor.serializedContext,
- sessionState: stateCursor.sessionState,
+ kind: "result",
+ result: await finalizeExpiredSession({
+ caller: input.crashCleanupState.caller,
+ driverWritable: input.driverWritable,
+ mode: input.mode,
+ serializedContext: stateCursor.serializedContext,
+ sessionState: stateCursor.sessionState,
+ terminalState: input.crashCleanupState,
+ }),
};
}
@@ -678,13 +664,13 @@ async function runDriverLoop(input: {
sessionState: stateCursor.sessionState,
});
stateCursor.adoptState(cancelled);
+ input.crashCleanupState.serializedContext = stateCursor.serializedContext;
// Re-enter with `settled` cleared: the parked answer was already
// delivered to its caller before this wait, so the next iteration
// must not treat it as a fresh settlement.
action = { ...action, settled: undefined };
input.crashCleanupState.caller = undefined;
input.crashCleanupState.lastSessionState = stateCursor.sessionState;
- input.crashCleanupState.serializedContext = stateCursor.serializedContext;
continue;
}
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index d18f16b87..d661975c1 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -18,6 +18,7 @@ import {
startWorkflowOnCurrentDeployment,
turnWorkflowReference,
workflowEntryReference,
+ workflowToolRunWorkflowReference,
} from "#execution/workflow-runtime.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";
@@ -84,6 +85,10 @@ describe("workflowEntryReference", () => {
expect(activityCollectorWorkflowReference.workflowId).toBe(
`workflow//${packageInfo.name}//activityCollectorWorkflow`,
);
+ expect(workflowToolRunWorkflowReference.workflowId).toBe(
+ `workflow//${packageInfo.name}//workflowToolRunWorkflow`,
+ );
+ expect(workflowToolRunWorkflowReference.workflowId).not.toContain("@");
});
});
@@ -768,6 +773,23 @@ describe("createWorkflowRuntime#createSession", () => {
});
});
+ it("passes explicit task ownership to the durable session workflow", async () => {
+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
+ mockBundleAndRun(compiledArtifactsSource);
+ startMock.mockResolvedValue({ runId: "subagent-run" });
+ getHookByTokenMock.mockResolvedValue({ runId: "subagent-run" });
+
+ await buildRuntime(compiledArtifactsSource).createSession({
+ adapter: { kind: "subagent", state: { parentContinuationToken: "opaque-reply-hook" } },
+ auth: null,
+ input: { message: "research this" },
+ mode: "conversation",
+ taskId: "task-1",
+ });
+
+ expect(startMock.mock.calls[0]?.[1][0]).toMatchObject({ taskId: "task-1" });
+ });
+
it("lets the Workflow world provide its current deployment when Vercel has no id", async () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource);
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 9f83b79ff..aad3fa3d5 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -72,7 +72,7 @@ import {
ACTIVITY_COLLECTOR_WORKFLOW_NAME,
SESSION_TIMEOUT_WORKFLOW_NAME,
TASK_RUN_WORKFLOW_NAME,
- TOOL_RUN_WORKFLOW_NAME,
+ WORKFLOW_TOOL_RUN_WORKFLOW_NAME,
TURN_WORKFLOW_NAME,
WORKFLOW_ENTRY_NAME,
} from "#execution/stable-workflow-names.js";
@@ -124,8 +124,8 @@ export const activityCollectorWorkflowReference = {
};
/** Stable workflow reference for authored workflow tool runs. */
-export const toolRunWorkflowReference = {
- workflowId: `workflow//${STABLE_ID_BASE}//${TOOL_RUN_WORKFLOW_NAME}`,
+export const workflowToolRunWorkflowReference = {
+ workflowId: `workflow//${STABLE_ID_BASE}//${WORKFLOW_TOOL_RUN_WORKFLOW_NAME}`,
};
/**
@@ -206,6 +206,8 @@ export function createWorkflowRuntime(config: {
limits: input.limits,
serializedContext,
};
+ const taskId = input.taskId ?? input.callback?.taskId;
+ if (taskId !== undefined) workflowInput.taskId = taskId;
if (collectorRunId !== undefined) {
workflowInput.activityCollectorRunId = collectorRunId;
}
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 05b5cebb2..6246de3a5 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -1,6 +1,5 @@
import type { ModelMessage } from "ai";
import { afterEach, describe, expect, it, vi } from "vitest";
-
import type { ChannelAdapter, ChannelAdapterContext } from "#channel/adapter.js";
import type {
DeliverPayload,
@@ -18,7 +17,6 @@ import {
ModeKey,
SessionCallbackKey,
SessionDynamicSubagentRuntimeRevisionKey,
- SessionDynamicSubagentSelectionsKey,
SessionDynamicModelReferenceKey,
SessionDynamicToolMetadataKey,
SessionDynamicToolRuntimeRevisionKey,
@@ -29,8 +27,7 @@ import {
} from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { serializeContext } from "#context/serialize.js";
-import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
-import { AGENT_HANDLES_STATE_KEY, getAgentHandleStore } from "#harness/handles/store.js";
+import { getPendingCoordinationBatch, setPendingCoordinationBatch } from "#harness/coordination.js";
import { requestTurnSleep } from "#harness/turn-sleep.js";
import { TurnCancelledError } from "#harness/turn-cancellation.js";
import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";
@@ -53,18 +50,15 @@ import { projectToDurableSession } from "#execution/session.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
import { defineTool } from "#tools/definition.js";
import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
-import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";
+import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
+import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";
import { readLatestTaskView, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
import { recordTaskInputRequestStep } from "#execution/tasks/parent/hitl-proxy-steps.js";
-import { appendTaskAgentAnnouncement } from "#execution/tasks/parent/agent-views.js";
-import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
-import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";
import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema.js";
import { turnStep } from "#execution/workflow-steps.js";
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
-import { turnWorkflowReference, workflowEntryReference } from "#execution/workflow-runtime.js";
+import { turnWorkflowReference } from "#execution/workflow-runtime.js";
const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());
vi.mock("#instrumentation/runtime.js", async (importOriginal) => {
@@ -90,9 +84,6 @@ vi.mock("./tasks/parent/run-parent.js", () => ({
readLatestTaskView: vi.fn(),
sendTaskInboundPayload: vi.fn(),
}));
-vi.mock("./tasks/parent/agent-views.js", () => ({
- appendTaskAgentAnnouncement: vi.fn(async (session) => session),
-}));
const mockIdentityHistoryViewProjector = vi.hoisted(() =>
vi.fn(({ messages }: { readonly messages: readonly ModelMessage[] }) => messages),
@@ -247,7 +238,6 @@ function createSerializedContext(
}
afterEach(() => {
- delete (globalThis as Record<symbol, unknown>)[Symbol.for("eve.instrumentation-runtime")];
getRunMock.mockReset();
resumeHookMock.mockReset();
startMock.mockReset();
@@ -258,8 +248,6 @@ afterEach(() => {
vi.mocked(readLatestTaskView).mockReset();
vi.mocked(sendTaskInboundPayload).mockReset();
vi.mocked(sendTaskInboundPayload).mockResolvedValue("delivered");
- vi.mocked(appendTaskAgentAnnouncement).mockReset();
- vi.mocked(appendTaskAgentAnnouncement).mockImplementation(async (session) => session);
mockIdentityHistoryViewProjector.mockReset();
mockIdentityHistoryViewProjector.mockImplementation(({ messages }) => messages);
});
@@ -407,20 +395,28 @@ describe("routeProxiedDeliverStep", () => {
});
});
- function createTaskRouteSession(options?: { readonly owned?: boolean }): HarnessSession {
+ function createTaskRouteSession(options?: {
+ readonly childContinuationToken?: string;
+ readonly childResponseUrl?: string;
+ readonly owned?: boolean;
+ }): HarnessSession {
+ const childContinuationToken = options?.childContinuationToken ?? "child-token";
return upsertProxyInputRequests({
entries: [
[
"task-1:request-1",
{
- childContinuationToken: "child-token",
+ childContinuationToken,
childRequestId: "request-1",
+ ...(options?.childResponseUrl === undefined
+ ? {}
+ : { childResponseUrl: options.childResponseUrl }),
kind: "tool-approval",
taskId: "task-1",
},
],
],
- forChildContinuationToken: "child-token",
+ forChildContinuationToken: childContinuationToken,
session: createStubSession({
continuationToken: "parent-token",
sessionId: "parent-session",
@@ -433,17 +429,12 @@ describe("routeProxiedDeliverStep", () => {
{
taskInboxToken: "task-token",
createdByTurnId: "turn-parent",
- metadata: {
- agentId: "agent-1",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
- operationId: "operation-1",
+ metadata: { kind: "tool", name: "research" },
taskId: "task-1",
taskRunId: "run-1",
},
],
+ version: 2,
},
},
}),
@@ -455,7 +446,7 @@ describe("routeProxiedDeliverStep", () => {
sessionState: createStubSessionState({ hasProxyInputRequests: true }),
};
- it("hands a task-owned answer to the task run instead of the child", async () => {
+ it("hands a task-owned answer to its task controller", async () => {
installSessionStoreMocks([createTaskRouteSession()]);
const result = await routeProxiedDeliverStep({
@@ -464,19 +455,52 @@ describe("routeProxiedDeliverStep", () => {
});
expect(result).toMatchObject({ kind: "continue", remainder: undefined });
expect(sendTaskInboundPayload).toHaveBeenCalledWith({
- taskInboxToken: "task-token",
payload: {
auth: undefined,
childContinuationToken: "child-token",
+ childResponseUrl: undefined,
inputResponses: [{ optionId: "approve", requestId: "request-1" }],
kind: "input-response",
taskId: "task-1",
},
+ taskInboxToken: "task-token",
});
- expect(resumeHookMock).not.toHaveBeenCalled();
expect(getProxyInputRequests(result.sessionState.snapshot?.session.state).size).toBe(0);
});
+ it("preserves the task-owned workflow-tool answer route for its controller", async () => {
+ installSessionStoreMocks([
+ createTaskRouteSession({ childContinuationToken: "eve:workflow-tool-run-answer:run-1:0" }),
+ ]);
+
+ await routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() });
+
+ expect(sendTaskInboundPayload).toHaveBeenCalledWith({
+ payload: expect.objectContaining({
+ childContinuationToken: "eve:workflow-tool-run-answer:run-1:0",
+ kind: "input-response",
+ }),
+ taskInboxToken: "task-token",
+ });
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+
+ it("preserves a task-owned remote answer route for its controller", async () => {
+ installSessionStoreMocks([
+ createTaskRouteSession({ childResponseUrl: "https://child.example/eve/v1/task-input/token" }),
+ ]);
+
+ await routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() });
+
+ expect(sendTaskInboundPayload).toHaveBeenCalledWith({
+ payload: expect.objectContaining({
+ childResponseUrl: "https://child.example/eve/v1/task-input/token",
+ kind: "input-response",
+ }),
+ taskInboxToken: "task-token",
+ });
+ });
+
it("keeps a response for a task this session does not own on the parent", async () => {
installSessionStoreMocks([createTaskRouteSession({ owned: false })]);
@@ -488,13 +512,12 @@ describe("routeProxiedDeliverStep", () => {
inputResponses: [{ optionId: "approve", requestId: "task-1:request-1" }],
},
});
- expect(sendTaskInboundPayload).not.toHaveBeenCalled();
expect(resumeHookMock).not.toHaveBeenCalled();
});
it("returns answers to the parent when the task run already finished", async () => {
installSessionStoreMocks([createTaskRouteSession()]);
- vi.mocked(sendTaskInboundPayload).mockResolvedValue("unreachable");
+ vi.mocked(sendTaskInboundPayload).mockResolvedValueOnce("unreachable");
await expect(
routeProxiedDeliverStep({ ...taskRouteInput, parentWritable: createTestWritable() }),
@@ -532,43 +555,23 @@ function currentSessionHook(token: string) {
}
describe("recordTaskInputRequestStep", () => {
- const hookPayload: SubagentInputRequestHookPayload = {
- callId: "call-task",
- childContinuationToken: "child-token",
- childSessionId: "child-session",
- event: {
- requests: [
- {
- action: { callId: "call-q", input: {}, kind: "tool-call", toolName: "ask" },
- kind: "question",
- prompt: "Which?",
- requestId: "request-1",
- },
- ],
- sequence: 1,
- stepIndex: 2,
- turnId: "turn_child",
+ const taskRequest = {
+ replyTo: "eve:workflow-tool-run-answer:run-1:0",
+ request: {
+ action: { callId: "call-q", input: {}, kind: "tool-call" as const, toolName: "ask" },
+ kind: "question" as const,
+ prompt: "Which?",
+ requestId: "request-1",
},
- kind: "subagent-input-request",
- subagentName: "research",
+ sequence: 1,
+ stepIndex: 2,
+ taskId: "task-1",
+ turnId: "turn_child",
};
it("records an exact route only for a current task owned by this parent", async () => {
const session = createStubSession({
state: {
- [AGENT_HANDLES_STATE_KEY]: {
- handles: [
- {
- address: {
- continuationToken: "child-token",
- kind: "agent/local",
- sessionId: "child-session",
- },
- identity: { id: "agent-1", name: "research", nodeId: "node-1" },
- phase: "addressed",
- },
- ],
- },
"eve.tasks": {
tasks: [
{
@@ -586,11 +589,11 @@ describe("recordTaskInputRequestStep", () => {
kind: "subagent",
},
metadata: { kind: "tool", name: "research" },
- operationId: "operation-1",
taskId: "task-1",
taskRunId: "run-1",
},
],
+ version: 2,
},
},
});
@@ -609,38 +612,29 @@ describe("recordTaskInputRequestStep", () => {
},
kind: "subagent",
},
- childSessionId: "child-session",
},
- inputRequests: hookPayload.event.requests,
+ inputRequests: [taskRequest.request],
status: "input_required",
taskId: "task-1",
});
const result = await recordTaskInputRequestStep({
- hookPayload,
- serializedContext: createSerializedContext(),
+ request: taskRequest,
sessionState: createStubSessionState(),
- taskId: "task-1",
});
expect(result.accepted).toBe(true);
expect(
getProxyInputRequests(result.sessionState.snapshot?.session.state).get("task-1:request-1"),
).toEqual({
- batch: {
- approvalRequestIds: [],
- requestIds: ["task-1:request-1"],
- },
- childContinuationToken: "child-token",
+ childContinuationToken: "eve:workflow-tool-run-answer:run-1:0",
childRequestId: "request-1",
kind: "question",
taskId: "task-1",
});
expect(result).toMatchObject({
accepted: true,
- hookPayload: {
- event: { requests: [{ requestId: "task-1:request-1" }] },
- },
+ request: { request: { requestId: "task-1:request-1" } },
});
});
@@ -650,10 +644,8 @@ describe("recordTaskInputRequestStep", () => {
vi.mocked(readLatestTaskView).mockResolvedValue(undefined);
const result = await recordTaskInputRequestStep({
- hookPayload,
- serializedContext: createSerializedContext(),
+ request: { ...taskRequest, taskId: "foreign-task" },
sessionState: createStubSessionState(),
- taskId: "foreign-task",
});
expect(result).toEqual({ accepted: false, sessionState: createStubSessionState() });
@@ -860,232 +852,92 @@ describe("dispatchTurnStep", () => {
});
});
-describe("dispatchRuntimeActionsStep", () => {
- it("preserves a started local child when a later start fails", async () => {
- vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_driver");
- const compiledArtifactsSource = {} as never;
- const compiledBundle = {
+describe("dispatchCoordinationStep", () => {
+ it("repairs an empty pending turn id from the active session turn", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
adapterRegistry: {
adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
},
- compiledArtifactsSource,
+ compiledArtifactsSource: {},
graph: {
nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
+ root: { sandboxRegistry: { sandbox: null }, turnAgent: TestTurnAgent },
},
hookRegistry: createEmptyHookRegistry(),
resolvedAgent: { config: {} },
- subagentRegistry: {
- subagentsByNodeId: new Map([
- [
- "subagents/agent",
- {
- definition: {
- description: "Explicitly declared agent child description.",
- kind: "subagent",
- },
- },
- ],
- ]),
- },
+ subagentRegistry: { subagentsByNodeId: new Map() },
toolRegistry: {},
turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- startMock
- .mockResolvedValueOnce({ runId: "child-run" })
- .mockRejectedValueOnce(new Error("child start failed"));
- getRunMock.mockReturnValue({
- getReadable: () =>
- new ReadableStream<Uint8Array>({
- start(controller) {
- controller.close();
- },
- }),
- });
-
- const session = setPendingRuntimeActionBatch({
- actions: [
+ } as never);
+ const session = setPendingCoordinationBatch({
+ runtimeActions: [
{
callId: "call-1",
- description: "Runtime action event description.",
- input: { message: "investigate latest routing" },
- target: { kind: "subagent-call", nodeId: "subagents/agent", subagentName: "agent" },
- toolName: "agent",
- },
- {
- callId: "call-2",
- description: "Second runtime action event description.",
- input: { message: "investigate fallback routing" },
- target: { kind: "subagent-call", nodeId: "subagents/agent", subagentName: "agent" },
- toolName: "agent",
+ input: {},
+ kind: "tool-call",
+ toolName: "task_update",
},
],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ tasks: [],
+ event: { sequence: 3, stepIndex: 2, turnId: "" },
responseMessages: [],
- session: createStubSession({
- continuationToken: "http:parent",
- rootSessionId: "root-session",
- sessionId: "parent-session",
- subagentDepth: 99,
- }),
+ session: createStubSession(),
});
installSessionStoreMocks([session]);
-
const sessionState = createStubSessionState({
- continuationToken: "http:parent",
- sessionId: "parent-session",
+ emissionState: { sequence: 3, sessionStarted: true, stepIndex: 2, turnId: "" },
});
- const result = await dispatchRuntimeActionsStep({
- parentContinuationToken: "turn-inbox",
+ const result = await dispatchCoordinationStep({
+ action: "park",
parentWritable: createTestWritable(),
serializedContext: createSerializedContext(),
sessionState,
});
- expect(result).toEqual({
- results: [
- {
- callId: "call-2",
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: "SUBAGENT_START_FAILED",
- message: "child start failed",
- },
- subagentName: "agent",
- },
- ],
- sessionState: expect.any(Object),
- pendingTasks: [],
- });
- // The started child stays owned as a running handle; the dead start's
- // prepared handle was rejected.
- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
- handles: [
- expect.objectContaining({
- address: {
- continuationToken: "subagent:parent-session:call-1",
- kind: "agent/local",
- sessionId: "child-run",
- },
- operation: expect.objectContaining({ callId: "call-1", kind: "start" }),
- phase: "running",
- }),
- ],
- });
- expect(startMock).toHaveBeenCalledWith(
- workflowEntryReference,
- [
- expect.objectContaining({
- input: {
- message: expect.stringContaining(
- "Description: Explicitly declared agent child description.",
- ),
- },
- limits: {
- maxInputTokensPerSession: false,
- maxOutputTokensPerSession: false,
- },
- serializedContext: expect.objectContaining({
- "eve.channel": expect.objectContaining({
- kind: "subagent",
- state: expect.objectContaining({ parentContinuationToken: "turn-inbox" }),
- }),
- }),
- }),
- ],
- {
- allowReservedAttributes: true,
- attributes: expect.objectContaining({
- "$eve.parent": "parent-session",
- "$eve.root": "root-session",
- "$eve.type": "subagent",
- }),
- deploymentId: "dpl_driver",
- },
- );
- expect(startMock).toHaveBeenCalledWith(
- workflowEntryReference,
- [
- expect.objectContaining({
- input: {
- message: expect.stringContaining("investigate latest routing"),
- },
- }),
- ],
- expect.any(Object),
- );
- expect(startMock).toHaveBeenCalledWith(
- workflowEntryReference,
- [
- expect.objectContaining({
- input: {
- message: expect.not.stringContaining("Runtime action event description."),
- },
- }),
- ],
- expect.any(Object),
- );
+ const persisted = vi.mocked(createDurableSessionState).mock.calls.at(-1)?.[0].session;
+ expect(result.sessionState).not.toBe(sessionState);
+ expect(getPendingCoordinationBatch(persisted?.state)?.event.turnId).toBe("turn_3");
});
- it("returns a failed subagent result when remote session creation fails", async () => {
- const remote = {
- definition: {
- description: "Research remote",
- kind: "remote",
- name: "research",
- path: "/eve/v1/session",
- url: "https://remote.example.com",
- },
- };
- const compiledBundle = {
+ it("rejects direct agent actions outside a workflow-tool execute", async () => {
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
adapterRegistry: {
adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
},
compiledArtifactsSource: {},
graph: {
nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
+ root: { sandboxRegistry: { sandbox: null }, turnAgent: TestTurnAgent },
},
hookRegistry: createEmptyHookRegistry(),
resolvedAgent: { config: {} },
subagentRegistry: {
- subagentsByNodeId: new Map([["remote/research", remote]]),
+ subagentsByNodeId: new Map([
+ ["subagents/agent", { definition: { kind: "subagent", name: "agent" } }],
+ ]),
},
toolRegistry: {},
turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 503 }));
- vi.stubGlobal("fetch", fetchMock);
-
- const session = setPendingRuntimeActionBatch({
- actions: [
+ } as never);
+ const session = setPendingCoordinationBatch({
+ runtimeActions: [
{
callId: "call-1",
- description: "Delegate the work.",
+ description: "Runtime action event description.",
input: { message: "investigate latest routing" },
- target: {
- kind: "remote-agent-call",
- nodeId: "remote/research",
- remoteAgentName: "research",
- },
- toolName: "research",
- },
+ kind: "subagent-call",
+ name: "agent",
+ nodeId: "subagents/agent",
+ subagentName: "agent",
+ } as never,
],
+ tasks: [],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
session: createStubSession({
continuationToken: "http:parent",
+ rootSessionId: "root-session",
sessionId: "parent-session",
}),
});
@@ -1095,243 +947,18 @@ describe("dispatchRuntimeActionsStep", () => {
continuationToken: "http:parent",
sessionId: "parent-session",
});
+ startMock.mockResolvedValue({ runId: "child-run" });
- const result = await dispatchRuntimeActionsStep({
- callbackBaseUrl: "https://caller.example.com",
- parentContinuationToken: "turn-inbox",
- parentWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState,
- });
-
- expect(result.results).toEqual([
- {
- callId: "call-1",
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: "REMOTE_AGENT_START_FAILED",
- message: 'Remote agent "research" create-session request failed with HTTP 503.',
- },
- subagentName: "research",
- },
- ]);
- // The prepared handle was committed before the effect and rejected as
- // dead when the start failed, so no handle survives.
- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
- handles: [],
- });
- expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).callback.token).toBe(
- "turn-inbox",
- );
- expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();
- });
-
- it("records a successfully started remote child session for cancellation", async () => {
- const remote = {
- definition: {
- description: "Research remote",
- kind: "remote",
- name: "research",
- nodeId: "remote/research",
- path: "/eve/v1/session",
- url: "https://remote.example.com",
- },
- };
- const compiledBundle = {
- adapterRegistry: {
- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
- },
- compiledArtifactsSource: {},
- graph: {
- nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
- },
- hookRegistry: createEmptyHookRegistry(),
- resolvedAgent: { config: {} },
- subagentRegistry: {
- subagentsByNodeId: new Map([["remote/research", remote]]),
- },
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue(
- Response.json(
- {
- ok: true,
- sessionId: "remote-child",
- status: "accepted",
- },
- { headers: { "x-eve-session-id": "remote-child" }, status: 202 },
- ),
- ),
- );
-
- const session = setPendingRuntimeActionBatch({
- actions: [
- {
- callId: "call-remote",
- description: "Delegate the work.",
- input: { message: "investigate latest routing" },
- target: {
- kind: "remote-agent-call",
- nodeId: "remote/research",
- remoteAgentName: "research",
- },
- toolName: "research",
- },
- ],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createStubSession({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- }),
- });
- installSessionStoreMocks([session]);
-
- const result = await dispatchRuntimeActionsStep({
- callbackBaseUrl: "https://caller.example.com",
- parentContinuationToken: "turn-inbox",
- parentWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState: createStubSessionState({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- }),
- });
-
- expect(result.results).toEqual([]);
- expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
- handles: [
- expect.objectContaining({
- address: expect.objectContaining({
- kind: "agent/remote",
- sessionId: "remote-child",
- url: "https://remote.example.com",
- }),
- phase: "running",
- }),
- ],
- });
- });
-
- it("starts a remote agent from the current dynamic selection", async () => {
- const nodeId = "subagents/research";
- const compiledBundle = {
- adapterRegistry: {
- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
- },
- compiledArtifactsSource: {},
- graph: {
- nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
- },
- hookRegistry: createEmptyHookRegistry(),
- resolvedAgent: { config: {} },
- subagentRegistry: {
- dynamicNodeIds: new Set([nodeId]),
- subagentsByNodeId: new Map([
- [
- nodeId,
- {
- definition: {
- kind: "subagent",
- logicalPath: "subagents/research.ts",
- name: "research",
- nodeId,
- sourceId: "subagents/research.ts",
- sourceKind: "module",
- },
- },
- ],
- ]),
- },
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- const credentialsStepId = "eve:dynamic-remote-agent//workflow-research";
- const registryKey = Symbol.for("@workflow/core//registeredSteps");
- const globalRecord = globalThis as Record<symbol, Map<string, Function> | undefined>;
- const stepRegistry = globalRecord[registryKey] ?? new Map<string, Function>();
- globalRecord[registryKey] = stepRegistry;
- stepRegistry.set(credentialsStepId, () => ({
- headers: { authorization: "Bearer selected" },
- }));
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- Response.json(
- { ok: true, sessionId: "dynamic-remote-child", status: "accepted" },
- { headers: { "x-eve-session-id": "dynamic-remote-child" }, status: 202 },
- ),
- );
- vi.stubGlobal("fetch", fetchMock);
-
- const session = setPendingRuntimeActionBatch({
- actions: [
- {
- callId: "call-dynamic-remote",
- description: "Delegate the work.",
- input: { message: "investigate latest routing" },
- target: { kind: "remote-agent-call", nodeId, remoteAgentName: "research" },
- toolName: "research",
- },
- ],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createStubSession({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- }),
- });
- installSessionStoreMocks([session]);
- const serializedContext = createSerializedContext();
- serializedContext[SessionDynamicSubagentSelectionsKey.name] = {
- [nodeId]: {
- kind: "remote",
- prepared: {},
- remoteAgent: {
- credentialsStepId,
- description: "Selected remote research.",
- path: "/custom/session",
- url: "https://selected.example.com",
- },
- },
- };
-
- const result = await dispatchRuntimeActionsStep({
- callbackBaseUrl: "https://caller.example.com",
- parentContinuationToken: "turn-inbox",
- parentWritable: createTestWritable(),
- serializedContext,
- sessionState: createStubSessionState({
- continuationToken: "http:parent",
- sessionId: "parent-session",
- }),
- });
-
- expect(result.results).toEqual([]);
- expect(fetchMock).toHaveBeenCalledWith(
- "https://selected.example.com/custom/session",
- expect.objectContaining({
- headers: {
- authorization: "Bearer selected",
- "content-type": "application/json",
- },
+ await expect(
+ dispatchCoordinationStep({
+ action: "park",
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
+ sessionState,
}),
- );
+ ).rejects.toThrow('Unsupported coordination request "subagent-call".');
+ expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();
});
it("blocks a stale recursive agent call from a delegated session", async () => {
@@ -1358,23 +985,25 @@ describe("dispatchRuntimeActionsStep", () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- const session = setPendingRuntimeActionBatch({
- actions: [
+ const session = setPendingCoordinationBatch({
+ runtimeActions: [
{
callId: "call-1",
description: "Delegate the work.",
input: { message: "try to recurse" },
- target: { kind: "self-agent-call", nodeId: "__root__", subagentName: "agent" },
- toolName: "agent",
- },
+ kind: "subagent-call",
+ name: "agent",
+ nodeId: "__root__",
+ subagentName: "agent",
+ } as never,
],
+ tasks: [],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
session: createStubSession({
continuationToken: "http:parent",
rootSessionId: "root-session",
sessionId: "parent-session",
- subagentDepth: 1,
}),
});
installSessionStoreMocks([session]);
@@ -1385,38 +1014,16 @@ describe("dispatchRuntimeActionsStep", () => {
});
await expect(
- dispatchRuntimeActionsStep({
+ dispatchCoordinationStep({
+ action: "park",
parentContinuationToken: "turn-inbox",
parentWritable: createTestWritable(),
serializedContext: createSerializedContext(),
sessionState,
}),
- ).resolves.toEqual({
- results: [
- {
- callId: "call-1",
- isError: true,
- 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: "agent",
- },
- ],
- sessionState,
- pendingTasks: [],
- });
+ ).rejects.toThrow('Unsupported coordination request "subagent-call".');
expect(startMock).not.toHaveBeenCalled();
- expect(warn).toHaveBeenCalledWith(
- "[eve:execution.dispatch-runtime-actions] recursive agent call blocked outside the root session",
- expect.objectContaining({
- callId: "call-1",
- currentDepth: 1,
- subagentName: "agent",
- }),
- );
+ expect(warn).not.toHaveBeenCalled();
expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toBeUndefined();
});
@@ -1457,16 +1064,19 @@ describe("dispatchRuntimeActionsStep", () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
vi.spyOn(console, "warn").mockImplementation(() => {});
- const session = setPendingRuntimeActionBatch({
- actions: [
+ const session = setPendingCoordinationBatch({
+ runtimeActions: [
{
callId: "call-dynamic",
description: "Research the request.",
input: { message: "investigate" },
- target: { kind: "subagent-call", nodeId, subagentName: "researcher" },
- toolName: "researcher",
- },
+ kind: "subagent-call",
+ name: "researcher",
+ nodeId,
+ subagentName: "researcher",
+ } as never,
],
+ tasks: [],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
session: createStubSession({
@@ -1481,29 +1091,14 @@ describe("dispatchRuntimeActionsStep", () => {
});
await expect(
- dispatchRuntimeActionsStep({
+ dispatchCoordinationStep({
+ action: "park",
parentContinuationToken: "turn-inbox",
parentWritable: createTestWritable(),
serializedContext: createSerializedContext(),
sessionState,
}),
- ).resolves.toEqual({
- results: [
- {
- callId: "call-dynamic",
- isError: true,
- kind: "subagent-result",
- origin: "dispatch",
- output: {
- code: "SUBAGENT_UNAVAILABLE",
- message: 'Subagent "researcher" is not available in the current session context.',
- },
- subagentName: "researcher",
- },
- ],
- sessionState,
- pendingTasks: [],
- });
+ ).rejects.toThrow('Unsupported coordination request "subagent-call".');
expect(startMock).not.toHaveBeenCalled();
});
});
@@ -1793,7 +1388,7 @@ describe("turnStep", () => {
moduleMap: { nodes: {} },
hookRegistry: createEmptyHookRegistry(),
resolvedAgent: {
- config: { experimental: { tasks: true } },
+ config: {},
},
subagentRegistry: {},
toolRegistry: {},
@@ -2054,12 +1649,7 @@ describe("turnStep", () => {
);
});
- it("returns tasksEnabled on park results so the turn workflow selects dispatchTaskStep", async () => {
- // Regression: a stack rebase once dropped `tasksEnabled` from the park
- // arms while keeping the computation, so every tasks-mode agent silently
- // fell back to dispatchRuntimeActionsStep and no background task receipt
- // was ever minted. The park result is the only wire that carries this
- // flag to the dispatch selection in turn-workflow.ts.
+ it("refreshes the session before execution without a task-owned agent projection", async () => {
const tasksBundle = {
adapterRegistry: {
adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
@@ -2075,71 +1665,7 @@ describe("turnStep", () => {
moduleMap: { nodes: {} },
hookRegistry: createEmptyHookRegistry(),
resolvedAgent: {
- config: { experimental: { tasks: true } },
- },
- subagentRegistry: {},
- toolRegistry: {},
- turnAgent: TestTurnAgent,
- } as never;
- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(tasksBundle);
-
- const session = createStubSession();
- installSessionStoreMocks([session]);
- vi.mocked(createExecutionNodeStep).mockImplementation(() => {
- return async (stepSession): Promise<StepResult> => ({
- next: null,
- session: stepSession,
- });
- });
-
- const parked = await turnStep({
- input: {
- kind: "deliver",
- payloads: [{ message: "start a background task" }],
- },
- parentWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState: createStubSessionState(),
- });
- expect(parked).toMatchObject({ action: "park", tasksEnabled: true });
-
- installSessionStoreMocks([session]);
- vi.mocked(createExecutionNodeStep).mockImplementation(() => {
- return async (stepSession): Promise<StepResult> => ({
- next: null,
- session: stepSession,
- settledTurn: { output: "settled" },
- });
- });
- const settled = await turnStep({
- input: {
- kind: "deliver",
- payloads: [{ message: "settle" }],
- },
- parentWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState: createStubSessionState(),
- });
- expect(settled).toMatchObject({ action: "park", tasksEnabled: true });
- });
-
- it("passes task-agent availability projection into execution", async () => {
- const tasksBundle = {
- adapterRegistry: {
- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
- },
- compiledArtifactsSource: {} as never,
- graph: {
- nodesByNodeId: new Map(),
- root: {
- sandboxRegistry: { sandbox: null },
- turnAgent: TestTurnAgent,
- },
- },
- moduleMap: { nodes: {} },
- hookRegistry: createEmptyHookRegistry(),
- resolvedAgent: {
- config: { experimental: { tasks: true } },
+ config: {},
},
subagentRegistry: {},
toolRegistry: {},
@@ -2148,12 +1674,7 @@ describe("turnStep", () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(tasksBundle);
const session = createStubSession();
- const projectedSession = {
- ...session,
- history: [{ content: "[Agents]\n<agents>\n</agents>", role: "user" as const }],
- };
installSessionStoreMocks([session]);
- vi.mocked(appendTaskAgentAnnouncement).mockResolvedValue(projectedSession);
let executedSession: HarnessSession | undefined;
vi.mocked(createExecutionNodeStep).mockImplementation(() => {
@@ -2173,8 +1694,10 @@ describe("turnStep", () => {
sessionState: createStubSessionState(),
});
- expect(appendTaskAgentAnnouncement).toHaveBeenCalledOnce();
- expect(executedSession).toBe(projectedSession);
+ expect(executedSession).toMatchObject({
+ continuationToken: session.continuationToken,
+ sessionId: session.sessionId,
+ });
});
it("carries a settled turn through the typed park action when no work remains pending", async () => {
@@ -2381,20 +1904,16 @@ describe("turnStep", () => {
{
name: "runtime action",
withPending: (session: HarnessSession): HarnessSession =>
- setPendingRuntimeActionBatch({
- actions: [
+ setPendingCoordinationBatch({
+ runtimeActions: [
{
callId: "call-runtime",
- description: "Delegate work.",
input: {},
- target: {
- kind: "subagent-call",
- nodeId: "subagents/runtime-tool",
- subagentName: "runtime-tool",
- },
+ kind: "tool-call",
toolName: "runtime-tool",
},
],
+ tasks: [],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
session,
@@ -2481,6 +2000,7 @@ describe("turnStep", () => {
},
},
],
+ version: 2,
},
},
});
@@ -2543,7 +2063,7 @@ describe("turnStep", () => {
moduleMap: { nodes: {} },
hookRegistry: createEmptyHookRegistry(),
resolvedAgent: {
- config: { experimental: { tasks: true } },
+ config: {},
},
subagentRegistry: {},
toolRegistry: {},
@@ -2564,13 +2084,14 @@ describe("turnStep", () => {
{
createdByStepIndex: 0,
createdByTurnId: "turn_0",
- executor: { data: {}, kind: "subagent" },
+ executor: { data: {}, kind: "workflow-tool" },
metadata: { kind: "report-probe", name: "report_probe" },
taskId: "task_1",
taskInboxToken: "task-token",
taskRunId: "run_1",
},
],
+ version: 2,
},
},
});
@@ -3177,7 +2698,7 @@ describe("turnStep", () => {
});
});
-describe("terminal session event steps", () => {
+describe("emitTerminalSessionFailureStep", () => {
function buildSerializedContextWithAdapter(
adapter: ChannelAdapter,
sessionId: string,
@@ -3219,47 +2740,6 @@ describe("terminal session event steps", () => {
return serialized;
}
- function installTerminalInstrumentation() {
- const forceFlush = vi.fn(async () => undefined);
- const publish = vi.fn(async () => undefined);
- registerInstrumentationRuntime({
- forceFlush,
- hooks: { capturesContent: false, publish },
- otelSettings: undefined,
- runInContext: (_operation, execute) => execute(),
- shutdown: async () => undefined,
- });
- return { forceFlush, publish };
- }
-
- it("publishes and flushes an out-of-turn session completion", async () => {
- const sessionCompleted = vi.fn();
- const adapter: ChannelAdapter = {
- kind: "thread-context",
- "session.completed": sessionCompleted,
- };
- const serializedContext = buildSerializedContextWithAdapter(adapter, "session-completed");
- const instrumentation = installTerminalInstrumentation();
-
- await emitTerminalSessionCompletionStep({
- parentWritable: createTestWritable(),
- serializedContext,
- });
-
- expect(sessionCompleted).toHaveBeenCalledOnce();
- expect(instrumentation.publish).toHaveBeenCalledExactlyOnceWith({
- idempotencyKey: "session:session-completed",
- sessionId: "session-completed",
- turnId: undefined,
- type: "session.completed",
- });
- expect(instrumentation.forceFlush).toHaveBeenCalledOnce();
- expect(instrumentation.publish.mock.invocationCallOrder[0]).toBeLessThan(
- instrumentation.forceFlush.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
- expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE)).toHaveLength(1);
- });
-
it("invokes the adapter's session.failed handler with a formatted error payload", async () => {
// Capture adapter side effects — this is how we verify the step
// actually reaches the user-visible notification path. A terminal
@@ -3273,7 +2753,6 @@ describe("terminal session event steps", () => {
};
const serialized = buildSerializedContextWithAdapter(capturingAdapter, "session-terminal");
- const instrumentation = installTerminalInstrumentation();
// Use a plain-object error shape — the workflow body converts
// raw Errors to this shape (`normalizeSerializableError`) before
@@ -3290,7 +2769,6 @@ describe("terminal session event steps", () => {
error,
parentWritable: createTestWritable(),
serializedContext: serialized,
- turnId: "turn-active",
});
expect(sessionFailedCalls).toHaveLength(1);
@@ -3310,21 +2788,6 @@ describe("terminal session event steps", () => {
sessionId: "session-terminal",
});
expect(JSON.stringify(providerLog)).not.toContain("confidential.png");
- expect(instrumentation.publish).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({
- error: expect.objectContaining({
- message: "attachment staging failed for confidential.png",
- }),
- idempotencyKey: "session:session-terminal",
- sessionId: "session-terminal",
- turnId: "turn-active",
- type: "session.failed",
- }),
- );
- expect(instrumentation.forceFlush).toHaveBeenCalledOnce();
- expect(instrumentation.publish.mock.invocationCallOrder[0]).toBeLessThan(
- instrumentation.forceFlush.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
// The terminal step must also write the event to the durable
// stream so event-stream consumers see a canonical tail instead
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index d1458cd50..d90c98651 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -28,7 +28,6 @@ import {
ModeKey,
SessionDynamicSubagentRuntimeRevisionKey,
SessionDynamicToolRuntimeRevisionKey,
- TasksEnabledKey,
TurnTaskDeliveryKey,
TurnTaskStateKey,
} from "#context/keys.js";
@@ -52,10 +51,7 @@ import { observeSessionActivity } from "#execution/session-activity-projection.j
import { hasPendingInputBatch } from "#harness/input-requests.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { coalesceTurnInputs } from "#harness/messages.js";
-import {
- getRuntimeActionKeysFromWorkflowInterrupt,
- isWorkflowRuntimeActionInterrupt,
-} from "#harness/workflow-runtime-action-state.js";
+import { getWorkflowTaskCallIds, isWorkflowTaskInterrupt } from "#harness/workflow-task-state.js";
import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";
import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";
@@ -82,7 +78,6 @@ import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema
import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
-import { appendTaskAgentAnnouncement } from "#execution/tasks/parent/agent-views.js";
import {
resolveInitiatingTaskContext,
resolveTaskDeliveryContext,
@@ -91,10 +86,7 @@ import {
readRetainedBackgroundToolResult,
runBackgroundStep,
} from "#execution/tasks/parent/tool-execution.js";
-import {
- isTaskOwnedSerializedContext,
- TASK_UPDATE_SESSION_INSTRUCTION,
-} from "#execution/tasks/child/instructions.js";
+import { TASK_UPDATE_SESSION_INSTRUCTION } from "#tools/framework/task-update.js";
import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
@@ -136,12 +128,9 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
}
const adapter = ctx.require(ChannelKey);
const bundle = ctx.require(BundleKey);
- const tasksEnabled = bundle.resolvedAgent.config?.experimental?.tasks === true;
- ctx.set(TasksEnabledKey, tasksEnabled);
const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
const taskUpdatesEnabled =
- isTaskOwnedSerializedContext(input.serializedContext) &&
- tasksEnabled &&
+ durableSession.taskId !== undefined &&
effectiveAgent.turnAgent.tools.some(
(tool) =>
tool.kind === "authored-tool" &&
@@ -282,7 +271,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
}
}
- if (tasksEnabled && ctx.get(TurnTaskDeliveryKey) === "none") {
+ if (ctx.get(TurnTaskDeliveryKey) === "none") {
const taskContext = resolveInitiatingTaskContext({
state: durableSession.state,
turnId: activeTurnId(initialEmissionState),
@@ -321,7 +310,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
...derivePendingState(rekeyed),
serializedContext: nextSerializedContext,
sessionState: nextState,
- tasksEnabled,
};
}
@@ -529,9 +517,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
systemPromptAdditions: taskUpdatesEnabled ? [TASK_UPDATE_SESSION_INSTRUCTION] : undefined,
turnAgent: effectiveAgent.turnAgent,
});
- const modelSession = tasksEnabled
- ? await appendTaskAgentAnnouncement(refreshedSession, history.messages(refreshedSession))
- : refreshedSession;
+ const modelSession = refreshedSession;
const step = createExecutionNodeStep({
abortSignal: input.abortSignal,
@@ -637,16 +623,11 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
writer.releaseLock();
const workflowInterrupt = getPendingWorkflowInterrupt(stepResult.session.state);
- if (
- workflowInterrupt !== undefined &&
- isWorkflowRuntimeActionInterrupt(workflowInterrupt.interrupt)
- ) {
+ if (workflowInterrupt !== undefined && isWorkflowTaskInterrupt(workflowInterrupt.interrupt)) {
return {
- action: "dispatch-workflow-runtime-actions",
+ action: "dispatch-workflow-tasks",
...backgroundTransition,
- pendingRuntimeActionKeys: getRuntimeActionKeysFromWorkflowInterrupt(
- workflowInterrupt.interrupt,
- ),
+ pendingTaskCallIds: getWorkflowTaskCallIds(workflowInterrupt.interrupt),
...sleepTransition,
serializedContext: nextSerializedContext,
sessionState: nextState,
@@ -673,7 +654,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
isError: stepResult.settledTurn.isError,
usage: delta,
},
- tasksEnabled,
};
}
@@ -684,7 +664,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
...sleepTransition,
serializedContext: nextSerializedContext,
sessionState: nextState,
- tasksEnabled,
};
}
diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.ts
index 159a8a623..fa01ae2b4 100644
--- a/packages/eve/src/framework/sources/registry.ts
+++ b/packages/eve/src/framework/sources/registry.ts
@@ -53,6 +53,14 @@ const localDefaults = defineProgrammaticAgentSource({
logicalPath: "tools/ask_question.ts",
loadNamespace: () => import("#tools/framework/ask-question.js"),
},
+ {
+ logicalPath: "tools/task_update.ts",
+ loadNamespace: () => import("#tools/framework/task-update.js"),
+ },
+ {
+ logicalPath: "tools/task_cancel.ts",
+ loadNamespace: () => import("#tools/framework/task-cancel.js"),
+ },
{
logicalPath: "tools/web_search.ts",
loadNamespace: () => import("#tools/provided/web-search.js"),
@@ -68,14 +76,6 @@ const rootDefaults = defineProgrammaticAgentSource({
logicalPath: "tools/agent.ts",
loadNamespace: () => import("#tools/framework/agent.js"),
},
- {
- logicalPath: "tools/task_update.ts",
- loadNamespace: () => import("#tools/framework/task-update.js"),
- },
- {
- logicalPath: "tools/task_cancel.ts",
- loadNamespace: () => import("#tools/framework/task-cancel.js"),
- },
{
logicalPath: "channels/eve.ts",
loadNamespace: () => import("#framework/sources/modules/eve-channel.js"),
diff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.ts
index ca26f83f3..3003886d9 100644
--- a/packages/eve/src/harness/advertised-tools.test.ts
+++ b/packages/eve/src/harness/advertised-tools.test.ts
@@ -5,7 +5,6 @@ import { getAdvertisedTools } from "#harness/advertised-tools.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { HarnessSession, HarnessToolMap } from "#harness/types.js";
import { buildToolSet } from "#harness/tools.js";
-import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
describe("getAdvertisedTools", () => {
@@ -20,14 +19,14 @@ describe("getAdvertisedTools", () => {
expect([...advertisedTools.keys()]).toEqual(["add", "agent"]);
});
- it("keeps declared subagent tools at any subagent depth", () => {
+ it("keeps declared subagent tools in delegated sessions", () => {
const tools = new Map([
["add", createTool("add")],
["delegate", createSubagentTool("delegate")],
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({
- session: { subagentDepth: 99 },
+ session: { rootSessionId: "root-session" },
tools,
});
@@ -41,7 +40,7 @@ describe("getAdvertisedTools", () => {
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({
- session: { rootSessionId: "root-session", subagentDepth: 1 },
+ session: { rootSessionId: "root-session" },
tools,
});
@@ -55,50 +54,19 @@ describe("getAdvertisedTools", () => {
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({
- session: { rootSessionId: "root-session", subagentDepth: 1 },
+ session: { rootSessionId: "root-session" },
tools,
});
expect([...advertisedTools.keys()]).toEqual(["add", "agent"]);
});
- it("removes the built-in agent tool when depth identifies a delegated session", () => {
- const tools = new Map([
- ["add", createTool("add")],
- ["agent", createBuiltInAgentTool()],
- ]) satisfies HarnessToolMap;
-
- const advertisedTools = getAdvertisedTools({
- session: { subagentDepth: 1 },
- tools,
- });
-
- expect([...advertisedTools.keys()]).toEqual(["add"]);
- });
-
- it("keeps declared subagent tools in runtime subagent sessions", () => {
- const tools = new Map([
- ["add", createTool("add")],
- ["delegate", createSubagentTool("delegate")],
- ]) satisfies HarnessToolMap;
-
- const advertisedTools = getAdvertisedTools({
- session: {
- rootSessionId: "root-session",
- subagentDepth: 99,
- },
- tools,
- });
-
- expect([...advertisedTools.keys()]).toEqual(["add", "delegate"]);
- });
-
it("does not add Workflow in runtime subagent sessions", async () => {
const tools = new Map([["delegate", createSubagentTool("delegate")]]) satisfies HarnessToolMap;
const advertisedTools = await getAdvertisedTools({
modelTools: buildToolSet({ tools }),
- session: createSession({ rootSessionId: "root-session", subagentDepth: 1 }),
+ session: createSession({ rootSessionId: "root-session" }),
tools,
workflow: {},
});
@@ -107,7 +75,7 @@ describe("getAdvertisedTools", () => {
expect(advertisedTools.modelTools[WORKFLOW_TOOL_NAME]).toBeUndefined();
});
- it("adds Workflow in root sessions below the depth limit", async () => {
+ it("adds Workflow in root sessions", async () => {
const tools = new Map([
["add", createTool("add")],
["delegate", createSubagentTool("delegate")],
@@ -128,7 +96,7 @@ describe("getAdvertisedTools", () => {
describe("getAdvertisedTools for definition arrays", () => {
it("removes built-in agent tool definitions from delegated sessions", () => {
const advertisedTools = getAdvertisedTools({
- session: { rootSessionId: "root-session", subagentDepth: 1 },
+ session: { rootSessionId: "root-session" },
tools: [createTool("add"), createSubagentTool("delegate"), createBuiltInAgentTool()],
});
@@ -138,8 +106,8 @@ describe("getAdvertisedTools for definition arrays", () => {
it("keeps the task tools in the root session", () => {
const tools = new Map([
["add", createTool("add")],
- ["task_cancel", createTaskControlTool("task_cancel")],
- ["task_update", createTaskControlTool("task_update")],
+ ["task_cancel", createTaskControlTool("task_cancel", ["root-session"])],
+ ["task_update", createTaskControlTool("task_update", ["delegated-task-child"])],
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({ session: {}, tools });
@@ -147,26 +115,25 @@ describe("getAdvertisedTools for definition arrays", () => {
expect([...advertisedTools.keys()]).toEqual(["add", "task_cancel"]);
});
- it("keeps only task_update in delegated sessions", () => {
+ it("exposes delegated-task-child tools from persisted session ownership", () => {
const tools = new Map([
["add", createTool("add")],
- ["task_cancel", createTaskControlTool("task_cancel")],
- ["task_update", createTaskControlTool("task_update")],
+ ["task_cancel", createTaskControlTool("task_cancel", ["root-session"])],
+ ["task_update", createTaskControlTool("task_update", ["delegated-task-child"])],
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({
- delegatedCaller: true,
- session: { rootSessionId: "root-session", subagentDepth: 1 },
+ session: { rootSessionId: "root-session", taskId: "task-1" },
tools,
});
expect([...advertisedTools.keys()]).toEqual(["add", "task_update"]);
});
- it("removes task_update from sessions without a delegated caller", () => {
+ it("removes task_update from sessions without task ownership", () => {
const tools = new Map([
["add", createTool("add")],
- ["task_update", createTaskControlTool("task_update")],
+ ["task_update", createTaskControlTool("task_update", ["delegated-task-child"])],
]) satisfies HarnessToolMap;
const advertisedTools = getAdvertisedTools({ session: {}, tools });
@@ -186,43 +153,26 @@ function createTool(name: string): HarnessToolDefinition {
function createSubagentTool(name: string): HarnessToolDefinition {
return {
...createTool(name),
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: { kind: "subagent-call", nodeId: "workers", subagentName: name },
- },
- },
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
};
}
function createBuiltInAgentTool(): HarnessToolDefinition {
return {
...createSubagentTool("agent"),
- behavior: {
- availability: ["root-session"],
- handling: {
- kind: "dispatch",
- target: {
- kind: "self-agent-call",
- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- subagentName: "agent",
- },
- },
- },
+ rootOnly: true,
};
}
-function createTaskControlTool(name: string): HarnessToolDefinition {
+function createTaskControlTool(
+ name: string,
+ availability: NonNullable<HarnessToolDefinition["behavior"]>["availability"],
+): HarnessToolDefinition {
return {
...createTool(name),
- behavior: {
- availability: [name === "task_update" ? "delegated-task-child" : "root-session"],
- handling: {
- kind: "dispatch",
- target: { kind: name === "task_update" ? "task-update" : "task-cancel" },
- },
- },
+ behavior: { availability },
+ runtimeAction: { kind: "task-control" },
};
}
diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.ts
index 80ba182b8..b697f45dd 100644
--- a/packages/eve/src/harness/advertised-tools.ts
+++ b/packages/eve/src/harness/advertised-tools.ts
@@ -1,6 +1,5 @@
import type { ToolSet } from "ai";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { resolveSubagentDepth } from "#harness/subagent-depth.js";
import {
ensureWorkflowContinuationSecurity,
getWorkflowContinuationSecurity,
@@ -8,25 +7,19 @@ import {
import { applyWorkflowTool } from "#harness/workflow-sandbox.js";
import type { HarnessSession, HarnessToolMap } from "#harness/types.js";
-type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "subagentDepth">;
+type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "taskId">;
type AdvertisedToolMapInput = {
- readonly canRequestInput?: boolean;
- readonly delegatedCaller?: boolean;
readonly session: AdvertisedToolSession;
readonly tools: HarnessToolMap;
};
type AdvertisedToolDefinitionsInput = {
- readonly canRequestInput?: boolean;
- readonly delegatedCaller?: boolean;
readonly session: AdvertisedToolSession;
readonly tools: readonly HarnessToolDefinition[];
};
type AdvertisedModelToolsInput = {
- readonly canRequestInput?: boolean;
- readonly delegatedCaller?: boolean;
readonly modelTools: ToolSet;
readonly session: HarnessSession;
readonly tools: HarnessToolMap;
@@ -60,16 +53,16 @@ export function getAdvertisedTools(
}
if (isToolDefinitionList(input.tools)) {
- return filterUnavailableDelegationToolDefinitions(input.tools, input.session, input);
+ return filterUnavailableToolDefinitions(input.tools, input.session);
}
- return filterUnavailableToolMap(input.tools, input.session, input);
+ return filterUnavailableToolMap(input.tools, input.session);
}
async function getAdvertisedModelTools(
input: AdvertisedModelToolsInput,
): Promise<AdvertisedModelTools> {
- const tools = filterUnavailableToolMap(input.tools, input.session, input);
+ const tools = filterUnavailableToolMap(input.tools, input.session);
if (input.workflow === undefined) {
return {
harnessTools: tools,
@@ -102,15 +95,14 @@ async function getAdvertisedModelTools(
};
}
-function filterUnavailableDelegationToolDefinitions(
+function filterUnavailableToolDefinitions(
tools: readonly HarnessToolDefinition[],
session: AdvertisedToolSession,
- availability: Pick<AdvertisedToolDefinitionsInput, "canRequestInput" | "delegatedCaller">,
): readonly HarnessToolDefinition[] {
const filteredTools: HarnessToolDefinition[] = [];
for (const tool of tools) {
- if (!isToolAvailable(tool, session, availability)) {
+ if (shouldHideTool(tool, session)) {
continue;
}
filteredTools.push(tool);
@@ -121,12 +113,11 @@ function filterUnavailableDelegationToolDefinitions(
function filterUnavailableToolMap(
tools: HarnessToolMap,
session: AdvertisedToolSession,
- availability: Pick<AdvertisedToolMapInput, "canRequestInput" | "delegatedCaller">,
): HarnessToolMap {
const filteredTools = new Map<string, HarnessToolDefinition>();
for (const [name, tool] of tools) {
- if (!isToolAvailable(tool, session, availability)) {
+ if (shouldHideTool(tool, session)) {
continue;
}
filteredTools.set(name, tool);
@@ -139,54 +130,35 @@ function filterWorkflowHostToolsForRootSession(
session: AdvertisedToolSession,
): HarnessToolMap {
const filteredTools = new Map<string, HarnessToolDefinition>();
- const subagentDepth = resolveSubagentDepth(session);
- if (session.rootSessionId !== undefined || subagentDepth.currentDepth > 0) {
+ if (session.rootSessionId !== undefined) {
return filteredTools;
}
for (const [name, tool] of tools) {
- const target =
- tool.behavior?.handling?.kind === "dispatch" ? tool.behavior.handling.target : undefined;
- if (
- target?.kind === "self-agent-call" ||
- target?.kind === "subagent-call" ||
- target?.kind === "remote-agent-call"
- ) {
+ if (tool.resultKind === "subagent") {
filteredTools.set(name, tool);
}
}
return filteredTools;
}
-function isToolAvailable(
+function shouldHideTool(
definition: HarnessToolDefinition,
session: AdvertisedToolSession,
- availability: {
- readonly canRequestInput?: boolean;
- readonly delegatedCaller?: boolean;
- },
): boolean {
- for (const condition of definition.behavior?.availability ?? []) {
- switch (condition) {
- case "delegated-task-child":
- if (availability.delegatedCaller !== true) return false;
- break;
- case "requires-request-input":
- if (availability.canRequestInput !== true) return false;
- break;
- case "root-session":
- if (session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0) {
- return false;
- }
- break;
- default: {
- const _exhaustive: never = condition;
- return _exhaustive;
- }
- }
+ const delegated = session.rootSessionId !== undefined;
+ if (
+ definition.rootOnly === true ||
+ definition.behavior?.availability.includes("root-session") === true
+ ) {
+ return delegated;
+ }
+ if (definition.behavior?.availability.includes("delegated-task-child") === true) {
+ return session.taskId === undefined;
}
- return true;
+
+ return false;
}
function isToolDefinitionList(
diff --git a/packages/eve/src/harness/background-tools.ts b/packages/eve/src/harness/background-tools.ts
index ce0dec43d..8299803b5 100644
--- a/packages/eve/src/harness/background-tools.ts
+++ b/packages/eve/src/harness/background-tools.ts
@@ -2,12 +2,17 @@ import { loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
import type { TaskExec } from "#tools/task.js";
-import type { PreparedToolBehavior } from "#tools/behavior.js";
+import type { AgentView } from "#subagents/handles/prompt.js";
+import type { JsonValue } from "#shared/json.js";
export interface BackgroundExecutableTool {
- readonly behavior?: PreparedToolBehavior;
readonly execute: (input: unknown, options: ToolExecuteOptions, task: TaskExec) => unknown;
+ readonly executeInput?: (input: unknown) => JsonValue;
readonly name: string;
+ readonly nodeId?: string;
+ readonly resultKind?: "subagent" | "tool";
+ /** Present when the execute body runs in the task-owned durable workflow. */
+ readonly workflowId?: string;
}
export interface BackgroundToolCall {
@@ -27,6 +32,7 @@ export interface BackgroundToolCallBatch {
}
export interface BackgroundToolExecutor {
+ readAgentViews?(): Promise<readonly AgentView[]>;
execute(input: {
readonly batch: BackgroundToolCallBatch;
readonly definition: BackgroundExecutableTool;
@@ -36,9 +42,8 @@ export interface BackgroundToolExecutor {
}
// A ContextKey rather than a direct import of the task runtime, for three reasons:
-// 1. The executor is per-step state, not a module export — each task-runtime step
-// installs a fresh instance whose commit/rollback rides that step's transaction,
-// so the correct instance can only be resolved at call time.
+// 1. The executor is per-step state, not a module export, so the correct
+// transaction and session-owned agent handle store can only be resolved at call time.
// 2. Importing the implementation from `execution/` would make the harness ↔
// execution dependency bidirectional; the key keeps it one-way (harness declares
// the contract, execution installs it).
diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/coordination.test.ts
similarity index 75%
rename from packages/eve/src/harness/runtime-actions.test.ts
rename to packages/eve/src/harness/coordination.test.ts
index 7de40f24e..e52931d4f 100644
--- a/packages/eve/src/harness/runtime-actions.test.ts
+++ b/packages/eve/src/harness/coordination.test.ts
@@ -1,26 +1,22 @@
import {
isInboxSubagentResultFromRunningHandle,
isResultBoundToRunningHandle,
-} from "#harness/handles/query.js";
+} from "#subagents/handles/query.js";
import { describe, expect, it } from "vitest";
import {
+ createCoordinationRequestFromToolCall,
createRuntimeActionRequestFromToolCall,
- getPendingRuntimeActionBatch,
- resolvePendingRuntimeActions,
+ getPendingCoordinationBatch,
+ resolvePendingCoordination,
resolveToolCallInputObject,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import { deriveAgentId, getAgentHandleStore } from "#harness/handles/store.js";
-import {
- confirmAgentStarted,
- confirmTaskAgentAddress,
- prepareAgentContinuation,
- prepareAgentStart,
-} from "#harness/handles/transitions.js";
+ setPendingCoordinationBatch,
+} from "#harness/coordination.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
+import { deriveAgentId, getAgentHandleStore } from "#subagents/handles/store.js";
+import { confirmAgentStarted, prepareAgentStart } from "#subagents/handles/transitions.js";
import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
-import { getToolRuns, recordToolRun } from "#harness/tool-runs.js";
+import { getWorkflowToolRuns, recordWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { toolOutput } from "#tools/model-output.js";
import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";
import type { HarnessSession } from "#harness/types.js";
@@ -56,8 +52,8 @@ describe("createRuntimeActionRequestFromToolCall", () => {
[
"load_skill",
{
- behavior: { availability: [], presentation: "load-skill" as const },
description: "Load a skill.",
+ frameworkAction: "load-skill" as const,
inputSchema: jsonSchema({ type: "object" }),
name: "load_skill",
},
@@ -86,6 +82,73 @@ describe("createRuntimeActionRequestFromToolCall", () => {
});
});
+describe("createCoordinationRequestFromToolCall", () => {
+ const toolCall = {
+ input: { message: "research this" },
+ toolCallId: "call-1",
+ toolName: "researcher",
+ type: "tool-call" as const,
+ };
+
+ it("lowers blocking workflow tools to workflow tasks", () => {
+ expect(
+ createCoordinationRequestFromToolCall({
+ toolCall,
+ tools: new Map([
+ [
+ "researcher",
+ {
+ description: "Delegate research.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "researcher",
+ resultKind: "subagent" as const,
+ workflowId: "workflow://subagent-tool",
+ },
+ ],
+ ]),
+ }),
+ ).toEqual({
+ kind: "task",
+ request: {
+ callId: "call-1",
+ executeInput: undefined,
+ input: { message: "research this" },
+ kind: "workflow-task",
+ resultKind: "subagent",
+ toolName: "researcher",
+ workflowId: "workflow://subagent-tool",
+ },
+ });
+ });
+
+ it("reserves runtime actions for task controls", () => {
+ expect(
+ createCoordinationRequestFromToolCall({
+ toolCall: { ...toolCall, toolName: "task_update" },
+ tools: new Map([
+ [
+ "task_update",
+ {
+ description: "Update a task.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "task_update",
+ runtimeAction: { kind: "task-control" as const },
+ },
+ ],
+ ]),
+ }),
+ ).toEqual({
+ kind: "runtime-action",
+ request: {
+ callId: "call-1",
+ input: { message: "research this" },
+ kind: "tool-call",
+ toolName: "task_update",
+ },
+ });
+ });
+});
+
function createParkedSession(): HarnessSession {
const base: HarnessSession = {
agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
@@ -109,18 +172,17 @@ function createParkedSession(): HarnessSession {
turnId: "turn_0",
});
- return setPendingRuntimeActionBatch({
- actions: [
+ return setPendingCoordinationBatch({
+ runtimeActions: [],
+ tasks: [
{
callId: "call-1",
- description: "research subagent",
+ executeInput: { message: "go", target: "researcher" },
input: { description: "Research the topic", message: "go" },
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
+ kind: "workflow-task",
+ resultKind: "subagent",
toolName: "researcher",
+ workflowId: "workflow://subagent-tool",
},
],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
@@ -129,26 +191,22 @@ function createParkedSession(): HarnessSession {
});
}
-describe("runtime action batch identity", () => {
+describe("coordination batch identity", () => {
it("rejects duplicate call ids before persisting the batch", () => {
- const action = {
+ const task = {
callId: "duplicate-call",
- description: "research subagent",
+ executeInput: { message: "go", target: "researcher" },
input: { message: "go" },
- target: {
- kind: "subagent-call" as const,
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
+ kind: "workflow-task" as const,
+ resultKind: "subagent" as const,
toolName: "researcher",
+ workflowId: "workflow://subagent-tool",
};
expect(() =>
- setPendingRuntimeActionBatch({
- actions: [
- action,
- { ...action, target: { ...action.target, subagentName: "other" }, toolName: "other" },
- ],
+ setPendingCoordinationBatch({
+ runtimeActions: [],
+ tasks: [task, { ...task, toolName: "other" }],
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
session: createParkedSession(),
@@ -183,41 +241,16 @@ function createSessionWithRunningChild(): HarnessSession {
});
}
-function createSessionWithTaskAddress(): HarnessSession {
- const prepared = prepareAgentStart(createParkedSession(), {
- identity: {
- id: deriveAgentId("researcher", OPERATION_ID),
- name: "researcher",
- nodeId: "subagents/researcher",
- },
- operation: {
- callId: "call-1",
- id: OPERATION_ID,
- kind: "start",
- parentTurnId: "turn_0",
- },
- target: { continuationToken: CHILD_CONTINUATION_TOKEN, kind: "agent/local" },
- });
- return confirmTaskAgentAddress(prepared, {
- address: {
- continuationToken: CHILD_CONTINUATION_TOKEN,
- kind: "agent/local",
- sessionId: CHILD_SESSION_ID,
- },
- operationId: OPERATION_ID,
- });
-}
-
-describe("resolvePendingRuntimeActions", () => {
+describe("resolvePendingCoordination", () => {
it("marks a working task receipt as backgrounded on subagent.completed", async () => {
const events: UnstampedMessageStreamEvent[] = [];
const taskId = "task_0123456789abcdef";
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
emit: async (event) => {
events.push(event);
},
- session: createSessionWithTaskAddress(),
+ session: createParkedSession(),
stepInput: {
runtimeActionResults: [
{
@@ -244,15 +277,13 @@ describe("resolvePendingRuntimeActions", () => {
expect(events.find((event) => event.type === "subagent.completed")).toMatchObject({
data: { backgroundTask: { status: "working", taskId } },
});
- expect(getAgentHandleStore(resolved.session.state)?.handles).toEqual([
- expect.objectContaining({ phase: "addressed" }),
- ]);
+ expect(getAgentHandleStore(resolved.session.state)).toBeUndefined();
});
it("settles the running handle terminally and deletes it with the batch", async () => {
const session = createSessionWithRunningChild();
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -273,14 +304,14 @@ describe("resolvePendingRuntimeActions", () => {
});
expect(resolved.outcome).toBe("resolved");
- expect(getPendingRuntimeActionBatch(resolved.session.state)).toBeUndefined();
+ expect(getPendingCoordinationBatch(resolved.session.state)).toBeUndefined();
expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });
});
it("settles a failed child result terminally as well", async () => {
const session = createSessionWithRunningChild();
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -317,7 +348,7 @@ describe("resolvePendingRuntimeActions", () => {
session: createSessionWithRunningChild(),
});
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -342,30 +373,28 @@ describe("resolvePendingRuntimeActions", () => {
});
it("forgets a finished workflow tool run and withdraws only its unanswered requests", async () => {
- const parked = setPendingRuntimeActionBatch({
- actions: [
+ const parked = setPendingCoordinationBatch({
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ runtimeActions: [],
+ session: createParkedSession(),
+ tasks: [
{
callId: "call-1",
- description: "Deploy.",
input: { service: "api" },
- target: {
- kind: "workflow-tool-call",
- workflowId: "workflow//./agent/tools/deploy//execute",
- },
+ kind: "workflow-task",
toolName: "deploy",
+ workflowId: "workflow//./agent/tools/deploy//execute",
},
],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createParkedSession(),
});
- const withRun = recordToolRun(parked, {
+ const withRun = recordWorkflowToolRun(parked, {
callId: "call-1",
- hookToken: "eve:tool-run:op-1",
+ hookToken: "eve:workflow-tool-run:op-1",
runId: "run-1",
toolName: "deploy",
});
- const answerToken = "eve:tool-run-answer:run-1:0";
+ const answerToken = "eve:workflow-tool-run-answer:run-1:0";
const session = upsertProxyInputRequests({
entries: [
["other-request", { childContinuationToken: CHILD_CONTINUATION_TOKEN, kind: "question" }],
@@ -387,7 +416,7 @@ describe("resolvePendingRuntimeActions", () => {
}),
});
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -397,27 +426,25 @@ describe("resolvePendingRuntimeActions", () => {
});
expect(resolved.outcome).toBe("resolved");
- expect(getToolRuns(resolved.session.state)).toEqual([]);
+ expect(getWorkflowToolRuns(resolved.session.state)).toEqual([]);
expect([...getProxyInputRequests(resolved.session.state).keys()]).toEqual(["other-request"]);
});
it("projects a workflow tool's result through its toModelOutput", async () => {
- const parked = setPendingRuntimeActionBatch({
- actions: [
+ const parked = setPendingCoordinationBatch({
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ runtimeActions: [],
+ session: createParkedSession(),
+ tasks: [
{
callId: "call-1",
- description: "Deploy.",
input: { service: "api" },
- target: {
- kind: "workflow-tool-call",
- workflowId: "workflow//./agent/tools/deploy//execute",
- },
+ kind: "workflow-task",
toolName: "deploy",
+ workflowId: "workflow//./agent/tools/deploy//execute",
},
],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createParkedSession(),
});
const tools = new Map([
[
@@ -432,7 +459,7 @@ describe("resolvePendingRuntimeActions", () => {
],
]);
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session: parked,
stepInput: {
runtimeActionResults: [
@@ -454,7 +481,7 @@ describe("resolvePendingRuntimeActions", () => {
});
it("accepts a dispatch-origin failure result by callId", async () => {
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session: createParkedSession(),
stepInput: {
runtimeActionResults: [
@@ -471,13 +498,13 @@ describe("resolvePendingRuntimeActions", () => {
});
expect(resolved.outcome).toBe("resolved");
- expect(getPendingRuntimeActionBatch(resolved.session.state)).toBeUndefined();
+ expect(getPendingCoordinationBatch(resolved.session.state)).toBeUndefined();
});
it("draws completed child usage down against the parent's session totals", async () => {
const session = createSessionWithRunningChild();
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -519,7 +546,7 @@ describe("resolvePendingRuntimeActions", () => {
const session = createSessionWithRunningChild();
const agentId = deriveAgentId("researcher", OPERATION_ID);
- const parkedResolve = await resolvePendingRuntimeActions({
+ const parkedResolve = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -553,46 +580,56 @@ describe("resolvePendingRuntimeActions", () => {
expect.objectContaining({ phase: "parked" }),
]);
- // The parked handle stays resumable: a continuation prepares cleanly.
+ // The parked handle stays resumable through the owner-scoped store.
const continueOperationId = deriveAgentOperationId({
callId: "call-2",
parentSessionId: "test-session",
parentTurnId: "turn_1",
});
- const continued = prepareAgentContinuation(parkedResolve.session, {
- agentId,
- invokedName: "researcher",
- operation: {
- callId: "call-2",
- id: continueOperationId,
- kind: "continue",
- parentTurnId: "turn_1",
- previousStatus: "",
+ const parkedHandle = getAgentHandleStore(parkedResolve.session.state)?.handles[0];
+ if (parkedHandle?.phase !== "parked") throw new Error("expected parked handle");
+ const continuedSession = {
+ ...parkedResolve.session,
+ state: {
+ ...parkedResolve.session.state,
+ "eve.agent.handles": {
+ handles: [
+ {
+ address: parkedHandle.address,
+ identity: parkedHandle.identity,
+ operation: {
+ callId: "call-2",
+ id: continueOperationId,
+ kind: "continue",
+ parentTurnId: "turn_1",
+ previousStatus: parkedHandle.lastStatus,
+ },
+ phase: "running",
+ },
+ ],
+ },
},
- });
- expect(continued.kind).toBe("ready");
- if (continued.kind !== "ready") throw new Error("expected ready continuation");
+ } as HarnessSession;
// A terminal failure on the follow-up turn deletes the handle.
- const secondBatch = setPendingRuntimeActionBatch({
- actions: [
+ const secondBatch = setPendingCoordinationBatch({
+ runtimeActions: [],
+ tasks: [
{
callId: "call-2",
- description: "research subagent",
+ executeInput: { agentId, message: "continue", target: "researcher" },
input: { agentId, message: "continue" },
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
+ kind: "workflow-task",
+ resultKind: "subagent",
toolName: "researcher",
+ workflowId: "workflow://subagent-tool",
},
],
event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },
responseMessages: [],
- session: continued.session,
+ session: continuedSession,
});
- const terminalResolve = await resolvePendingRuntimeActions({
+ const terminalResolve = await resolvePendingCoordination({
session: secondBatch,
stepInput: {
runtimeActionResults: [
@@ -629,7 +666,7 @@ describe("resolvePendingRuntimeActions", () => {
// Turn 1: the child spent 4000/400 and parked.
const session = createSessionWithRunningChild();
const agentId = deriveAgentId("researcher", OPERATION_ID);
- const firstResolve = await resolvePendingRuntimeActions({
+ const firstResolve = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
@@ -667,41 +704,52 @@ describe("resolvePendingRuntimeActions", () => {
});
// Turn 2: the child spent another 1000/100 (cumulative 5000/500).
- const continued = prepareAgentContinuation(firstResolve.session, {
- agentId,
- invokedName: "researcher",
- operation: {
- callId: "call-2",
- id: deriveAgentOperationId({
- callId: "call-2",
- parentSessionId: "test-session",
- parentTurnId: "turn_1",
- }),
- kind: "continue",
- parentTurnId: "turn_1",
- previousStatus: "",
+ const parkedHandle = getAgentHandleStore(firstResolve.session.state)?.handles[0];
+ if (parkedHandle?.phase !== "parked") throw new Error("expected parked handle");
+ const continuedSession = {
+ ...firstResolve.session,
+ state: {
+ ...firstResolve.session.state,
+ "eve.agent.handles": {
+ handles: [
+ {
+ address: parkedHandle.address,
+ identity: parkedHandle.identity,
+ operation: {
+ callId: "call-2",
+ id: deriveAgentOperationId({
+ callId: "call-2",
+ parentSessionId: "test-session",
+ parentTurnId: "turn_1",
+ }),
+ kind: "continue",
+ parentTurnId: "turn_1",
+ previousStatus: parkedHandle.lastStatus,
+ },
+ phase: "running",
+ },
+ ],
+ },
},
- });
- if (continued.kind !== "ready") throw new Error("expected ready continuation");
- const secondBatch = setPendingRuntimeActionBatch({
- actions: [
+ } as HarnessSession;
+ const secondBatch = setPendingCoordinationBatch({
+ runtimeActions: [],
+ tasks: [
{
callId: "call-2",
- description: "research subagent",
+ executeInput: { agentId, message: "continue", target: "researcher" },
input: { agentId, message: "continue" },
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
+ kind: "workflow-task",
+ resultKind: "subagent",
toolName: "researcher",
+ workflowId: "workflow://subagent-tool",
},
],
event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },
responseMessages: [],
- session: continued.session,
+ session: continuedSession,
});
- const secondResolve = await resolvePendingRuntimeActions({
+ const secondResolve = await resolvePendingCoordination({
session: secondBatch,
stepInput: {
runtimeActionResults: [
@@ -743,7 +791,7 @@ describe("resolvePendingRuntimeActions", () => {
it("leaves the parent's totals untouched when the child reports a zero usage delta", async () => {
const session = createSessionWithRunningChild();
- const resolved = await resolvePendingRuntimeActions({
+ const resolved = await resolvePendingCoordination({
session,
stepInput: {
runtimeActionResults: [
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/coordination.ts
similarity index 69%
rename from packages/eve/src/harness/runtime-actions.ts
rename to packages/eve/src/harness/coordination.ts
index 74b7a972b..e9c731317 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/coordination.ts
@@ -1,19 +1,26 @@
import type { ModelMessage, ToolSet, TypedToolCall } from "ai";
import { createActionResultEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { getPendingDispatchActionKey } from "#runtime/actions/keys.js";
-import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";
-import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
-import type { PendingDispatchAction } from "#shared/dispatch-action.js";
+import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";
+import type {
+ RuntimeActionRequest,
+ RuntimeActionResult,
+ RuntimeToolCallActionRequest,
+ RuntimeWorkflowTaskRequest,
+} from "#shared/action-types.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
-import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#harness/handles/query.js";
-import { settleAgentTurn } from "#harness/handles/transitions.js";
+import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#subagents/handles/query.js";
+import { settleAgentTurn } from "#subagents/handles/transitions.js";
import {
clearProxyInputRequestsForChild,
clearProxyInputRequestsWhere,
} from "#harness/proxy-input-requests.js";
-import { findToolRun, removeToolRun } from "#harness/tool-runs.js";
+import {
+ findWorkflowToolRun,
+ isInboxSubagentResultFromRecordedWorkflowToolRun,
+ removeWorkflowToolRun,
+} from "#harness/workflow-tool-runs.js";
import { normalizeToolModelOutput } from "#harness/tool-model-output.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import {
@@ -29,7 +36,7 @@ import type {
StepInput,
} from "#harness/types.js";
-const PENDING_RUNTIME_ACTION_BATCH_KEY = "eve.runtime.pendingActionBatch";
+const PENDING_COORDINATION_BATCH_KEY = "eve.runtime.pendingCoordinationBatch";
type ToolResponsePart = Extract<ModelMessage, { role: "tool" }>["content"][number];
type ToolResultPart = Extract<ToolResponsePart, { type: "tool-result" }>;
@@ -45,53 +52,58 @@ function readSubagentResultOutcome(
}
/**
- * Serializable event coordinates for one pending runtime-action batch.
+ * Serializable event coordinates for one pending coordination batch.
*
* Runtime action results are projected back onto the parent stream using the
* same turn and step identity as the originating `actions.requested` batch.
*/
-interface PendingRuntimeActionEventMetadata {
+interface PendingCoordinationEventMetadata {
readonly sequence: number;
readonly stepIndex: number;
readonly turnId: string;
}
/**
- * Serializable pending runtime-action batch stored on `session.state`.
+ * Serializable pending coordination batch stored on `session.state`.
*
* Child ownership does not live here: the agent handle store records every
* dispatched child (from before its start side effect) and is the sole
* authority for continuing, settling, and cancelling children.
*/
-export interface PendingRuntimeActionBatch {
- readonly actions: readonly PendingDispatchAction[];
- readonly event: PendingRuntimeActionEventMetadata;
+export interface PendingCoordinationBatch {
+ /** Framework task controls deferred to the turn owner. */
+ readonly runtimeActions: readonly RuntimeToolCallActionRequest[];
+ /** Authored-tool and subagent workflow tasks pending coordination. */
+ readonly tasks: readonly RuntimeWorkflowTaskRequest[];
+ readonly event: PendingCoordinationEventMetadata;
+ readonly localFanoutSize?: number;
readonly responseMessages: readonly ModelMessage[];
}
/**
- * Outcome of resolving a pending runtime-action batch.
+ * Outcome of resolving a pending coordination batch.
*/
-interface ResolvePendingRuntimeActionsResult {
+interface ResolvePendingCoordinationResult {
readonly messages: ModelMessage[];
readonly outcome: "continue" | "resolved" | "unresolved";
readonly session: HarnessSession;
}
-/** Returns the pending runtime-action batch stored on the session, if any. */
-export function getPendingRuntimeActionBatch(
+/** Returns the pending coordination batch stored on the session, if any. */
+export function getPendingCoordinationBatch(
state: SessionStateMap | undefined,
-): PendingRuntimeActionBatch | undefined {
- const value = state?.[PENDING_RUNTIME_ACTION_BATCH_KEY];
+): PendingCoordinationBatch | undefined {
+ const value = state?.[PENDING_COORDINATION_BATCH_KEY];
if (typeof value !== "object" || value === null) {
return undefined;
}
- const batch = value as PendingRuntimeActionBatch;
+ const batch = value as PendingCoordinationBatch;
if (
- !Array.isArray(batch.actions) ||
+ !Array.isArray(batch.runtimeActions) ||
+ !Array.isArray(batch.tasks) ||
!Array.isArray(batch.responseMessages) ||
typeof batch.event !== "object" ||
batch.event === null
@@ -103,101 +115,114 @@ export function getPendingRuntimeActionBatch(
}
/**
- * Returns true when the session is parked on a pending runtime-action batch.
+ * Returns true when the session is parked on pending task/control coordination.
*/
-export function hasPendingRuntimeActionBatch(state: SessionStateMap | undefined): boolean {
- return getPendingRuntimeActionBatch(state) !== undefined;
+export function hasPendingCoordinationBatch(state: SessionStateMap | undefined): boolean {
+ return getPendingCoordinationBatch(state) !== undefined;
}
-export function clearPendingRuntimeActionBatch(session: HarnessSession): HarnessSession {
- if (session.state?.[PENDING_RUNTIME_ACTION_BATCH_KEY] === undefined) {
+export function clearPendingCoordinationBatch(session: HarnessSession): HarnessSession {
+ if (session.state?.[PENDING_COORDINATION_BATCH_KEY] === undefined) {
return session;
}
const state = { ...session.state };
- delete state[PENDING_RUNTIME_ACTION_BATCH_KEY];
+ delete state[PENDING_COORDINATION_BATCH_KEY];
return { ...session, state: Object.keys(state).length > 0 ? state : undefined };
}
/**
- * Stores one pending runtime-action batch on the session.
+ * Stores one pending coordination batch on the session.
*/
-export function setPendingRuntimeActionBatch(input: {
- readonly actions: readonly PendingDispatchAction[];
- readonly event: PendingRuntimeActionEventMetadata;
+export function setPendingCoordinationBatch(input: {
+ readonly runtimeActions: readonly RuntimeToolCallActionRequest[];
+ readonly tasks: readonly RuntimeWorkflowTaskRequest[];
+ readonly event: PendingCoordinationEventMetadata;
+ readonly localFanoutSize?: number;
readonly responseMessages: readonly ModelMessage[];
readonly session: HarnessSession;
}): HarnessSession {
- assertUniqueRuntimeActionCallIds(input.actions);
+ assertUniqueCoordinationCallIds([...input.runtimeActions, ...input.tasks]);
const state = { ...input.session.state };
- state[PENDING_RUNTIME_ACTION_BATCH_KEY] = {
- actions: [...input.actions],
+ state[PENDING_COORDINATION_BATCH_KEY] = {
+ runtimeActions: [...input.runtimeActions],
+ tasks: [...input.tasks],
event: input.event,
+ localFanoutSize: input.localFanoutSize,
responseMessages: [...input.responseMessages],
- } satisfies PendingRuntimeActionBatch;
+ } satisfies PendingCoordinationBatch;
return { ...input.session, state };
}
-/** Rejects an ambiguous action batch before any result or side effect can bind by call id. */
-export function assertUniqueRuntimeActionCallIds(actions: readonly PendingDispatchAction[]): void {
+/** Rejects a batch before any result or side effect can bind ambiguously by call id. */
+export function assertUniqueCoordinationCallIds(
+ requests: readonly { readonly callId: string }[],
+): void {
const seen = new Set<string>();
- for (const action of actions) {
- if (seen.has(action.callId)) {
- throw new Error(`Runtime action batch contains duplicate callId "${action.callId}".`);
+ for (const request of requests) {
+ if (seen.has(request.callId)) {
+ throw new Error(`Coordination batch contains duplicate callId "${request.callId}".`);
}
- seen.add(action.callId);
+ seen.add(request.callId);
}
}
/**
- * Returns the stable ordered runtime-action results for the current pending
- * batch when every action has a matching result. Unknown and duplicate results
+ * Returns the ordered results for the current pending coordination batch when
+ * every request has a matching result. Unknown and duplicate results
* are ignored.
*/
-function resolveReadyRuntimeActionResults(input: {
+function resolveReadyCoordinationResults(input: {
readonly results: readonly RuntimeActionResult[];
readonly session: HarnessSession;
}): RuntimeActionResult[] | undefined {
- const batch = getPendingRuntimeActionBatch(input.session.state);
+ const batch = getPendingCoordinationBatch(input.session.state);
if (batch === undefined) {
return undefined;
}
- return resolveRuntimeActionResultsForBatch({
+ return resolveResultsForCoordinationBatch({
batch,
results: input.results,
state: input.session.state,
});
}
-function resolveRuntimeActionResultsForBatch(input: {
- readonly batch: PendingRuntimeActionBatch;
+function resolveResultsForCoordinationBatch(input: {
+ readonly batch: PendingCoordinationBatch;
readonly results: readonly RuntimeActionResult[];
readonly state: SessionStateMap | undefined;
}): RuntimeActionResult[] | undefined {
- return resolveRuntimeActionResultsForKeys({
- pendingKeys: input.batch.actions.map((action) => getPendingDispatchActionKey(action)),
- results: input.results.filter((result) => isResultBoundToRunningHandle(input.state, result)),
+ return resolveRuntimeActionResultsForCallIds({
+ pendingCallIds: [...input.batch.runtimeActions, ...input.batch.tasks].map(
+ (request) => request.callId,
+ ),
+ results: input.results.filter(
+ (result) =>
+ isResultBoundToRunningHandle(input.state, result) ||
+ (result.kind === "subagent-result" &&
+ isInboxSubagentResultFromRecordedWorkflowToolRun(input.state, result)),
+ ),
});
}
/**
- * Resolves one pending runtime-action batch back into model history.
+ * Resolves one pending coordination batch back into model history.
*
* When all expected runtime action results are present, this appends the
* stored assistant tool-call messages plus synthesized tool-result messages to
* history, clears the pending batch, and emits `subagent.completed` and
* `action.result` events back onto the parent stream.
*/
-export async function resolvePendingRuntimeActions(input: {
+export async function resolvePendingCoordination(input: {
readonly emit?: HarnessEmitFn;
readonly session: HarnessSession;
readonly stepInput?: StepInput;
/** Definitions whose `toModelOutput` projects a workflow tool's result for the model. */
readonly tools?: HarnessToolMap;
-}): Promise<ResolvePendingRuntimeActionsResult> {
- const batch = getPendingRuntimeActionBatch(input.session.state);
+}): Promise<ResolvePendingCoordinationResult> {
+ const batch = getPendingCoordinationBatch(input.session.state);
if (batch === undefined) {
return {
@@ -207,7 +232,7 @@ export async function resolvePendingRuntimeActions(input: {
};
}
- const readyResults = resolveReadyRuntimeActionResults({
+ const readyResults = resolveReadyCoordinationResults({
results: input.stepInput?.runtimeActionResults ?? [],
session: input.session,
});
@@ -287,9 +312,9 @@ export async function resolvePendingRuntimeActions(input: {
// Drop a finished run's unanswered requests so a late click cannot reach it.
for (const result of readyResults) {
if (result.kind !== "tool-result") continue;
- const record = findToolRun(nextSession.state, result.callId);
+ const record = findWorkflowToolRun(nextSession.state, result.callId);
if (record === undefined) continue;
- nextSession = removeToolRun(
+ nextSession = removeWorkflowToolRun(
clearProxyInputRequestsWhere(
nextSession,
(route) => route.answerHook?.runId === record.runId,
@@ -297,9 +322,18 @@ export async function resolvePendingRuntimeActions(input: {
record.callId,
);
}
+ for (const result of readyResults) {
+ if (result.kind !== "subagent-result") continue;
+ const record = findWorkflowToolRun(nextSession.state, result.callId);
+ if (record?.resultKind !== "subagent") continue;
+ nextSession = removeWorkflowToolRun(
+ clearProxyInputRequestsForChild(nextSession, record.hookToken),
+ record.callId,
+ );
+ }
const state = { ...nextSession.state };
- delete state[PENDING_RUNTIME_ACTION_BATCH_KEY];
+ delete state[PENDING_COORDINATION_BATCH_KEY];
nextSession = {
...nextSession,
state: Object.keys(state).length > 0 ? state : undefined,
@@ -390,81 +424,67 @@ export function createRuntimeActionRequestFromToolCall(input: {
readonly tools: HarnessToolMap;
}): RuntimeActionRequest {
const definition = input.tools.get(input.toolCall.toolName);
- const toolInput = resolveToolCallInputObject(input.toolCall.input, {
- callId: input.toolCall.toolCallId,
- toolName: input.toolCall.toolName,
- });
- if (definition?.behavior?.presentation === "load-skill") {
+ if (definition?.frameworkAction === "load-skill") {
return {
callId: input.toolCall.toolCallId,
- input: toolInput,
+ input: resolveToolCallInputObject(input.toolCall.input, {
+ callId: input.toolCall.toolCallId,
+ toolName: input.toolCall.toolName,
+ }),
kind: "load-skill",
};
}
- const target =
- definition?.execution === "background" || definition?.behavior?.handling?.kind !== "dispatch"
- ? undefined
- : definition.behavior.handling.target;
- if (
- definition !== undefined &&
- (target?.kind === "self-agent-call" || target?.kind === "subagent-call")
- ) {
- return {
- callId: input.toolCall.toolCallId,
- description: definition.description,
- input: toolInput,
- kind: "subagent-call",
- name: definition.name,
- nodeId: target.nodeId,
- subagentName: target.subagentName,
- };
- }
-
- if (definition !== undefined && target?.kind === "remote-agent-call") {
- return {
- callId: input.toolCall.toolCallId,
- description: definition.description,
- input: toolInput,
- kind: "remote-agent-call",
- name: definition.name,
- nodeId: target.nodeId,
- remoteAgentName: target.remoteAgentName,
- };
- }
-
return {
callId: input.toolCall.toolCallId,
- input: toolInput,
+ input: resolveToolCallInputObject(input.toolCall.input, {
+ callId: input.toolCall.toolCallId,
+ toolName: input.toolCall.toolName,
+ }),
kind: "tool-call",
toolName: input.toolCall.toolName,
};
}
-/** Projects one execute-less dispatch tool call into the durable pending contract. */
-export function createPendingDispatchActionFromToolCall(input: {
+/** Projects one deferred harness tool call into task/control coordination. */
+export function createCoordinationRequestFromToolCall(input: {
readonly toolCall: TypedToolCall<ToolSet>;
readonly tools: HarnessToolMap;
-}): PendingDispatchAction {
+}):
+ | { readonly kind: "runtime-action"; readonly request: RuntimeToolCallActionRequest }
+ | { readonly kind: "task"; readonly request: RuntimeWorkflowTaskRequest } {
const definition = input.tools.get(input.toolCall.toolName);
- if (definition === undefined) {
- throw new Error(`Unknown tool "${input.toolCall.toolName}" in dispatch projection.`);
+ const inputObject = resolveToolCallInputObject(input.toolCall.input, {
+ callId: input.toolCall.toolCallId,
+ toolName: input.toolCall.toolName,
+ });
+ if (definition?.runtimeAction?.kind === "task-control") {
+ return {
+ kind: "runtime-action",
+ request: {
+ callId: input.toolCall.toolCallId,
+ input: inputObject,
+ kind: "tool-call",
+ toolName: input.toolCall.toolName,
+ },
+ };
}
- const handling = definition.behavior?.handling;
- if (handling?.kind !== "dispatch" || definition.execution === "background") {
- throw new Error(`Tool "${input.toolCall.toolName}" is not a durable dispatch tool.`);
+ if (definition?.workflowId !== undefined) {
+ return {
+ kind: "task",
+ request: {
+ callId: input.toolCall.toolCallId,
+ executeInput: definition.executeInput?.(inputObject),
+ input: inputObject,
+ kind: "workflow-task",
+ resultKind: definition.resultKind,
+ toolName: input.toolCall.toolName,
+ workflowId: definition.workflowId,
+ },
+ };
}
- return {
- callId: input.toolCall.toolCallId,
- description: definition.description,
- input: resolveToolCallInputObject(input.toolCall.input, {
- callId: input.toolCall.toolCallId,
- toolName: input.toolCall.toolName,
- }),
- target: handling.target,
- toolName: definition.name,
- };
+ throw new Error(`Deferred tool "${input.toolCall.toolName}" has no task or runtime action.`);
}
/**
diff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.ts
index becf11a88..259a3e4ba 100644
--- a/packages/eve/src/harness/emission.test.ts
+++ b/packages/eve/src/harness/emission.test.ts
@@ -471,20 +471,11 @@ describe("emitStreamContent action requests", () => {
[
"delegate",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
- },
- },
description: "Delegate work to a subagent.",
inputSchema: jsonSchema({ type: "object" }),
name: "delegate",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]);
@@ -610,6 +601,59 @@ describe("emitStreamContent action requests", () => {
]);
});
+ it("marks a background subagent receipt on subagent.completed", async () => {
+ const emit = createEmitStub();
+ const tools = new Map<string, HarnessToolDefinition>([
+ [
+ "delegate",
+ {
+ description: "Delegate work to a subagent.",
+ execution: "background",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "delegate",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
+ },
+ ],
+ ]);
+
+ await emitStreamContent(
+ emit,
+ EMISSION_STATE,
+ streamOf([
+ {
+ input: { message: "research the release" },
+ toolCallId: "call-delegate",
+ toolName: "delegate",
+ type: "tool-call",
+ },
+ {
+ output: { status: "working", taskId: "task-1" },
+ toolCallId: "call-delegate",
+ toolName: "delegate",
+ type: "tool-result",
+ },
+ { finishReason: "tool-calls", type: "finish-step" },
+ ] as TextStreamPart<ToolSet>[]),
+ { excludedActionToolNames: new Set(), tools },
+ );
+
+ const events = vi.mocked(emit).mock.calls.map(([event]) => event);
+ expect(events.map((event) => event.type)).toEqual([
+ "actions.requested",
+ "subagent.completed",
+ "action.result",
+ ]);
+ expect(events[1]).toMatchObject({
+ data: {
+ backgroundTask: { status: "working", taskId: "task-1" },
+ callId: "call-delegate",
+ subagentName: "delegate",
+ },
+ type: "subagent.completed",
+ });
+ });
+
it("projects local and provider tool failures at the same stream position", async () => {
const tools = new Map<string, HarnessToolDefinition>([
[
diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.ts
index dd8c10c0f..2cdb30fff 100644
--- a/packages/eve/src/harness/emission.ts
+++ b/packages/eve/src/harness/emission.ts
@@ -43,7 +43,7 @@ import {
createRuntimeToolResultFromToolError,
createToolResultMessagePartFromToolError,
} from "#harness/action-result-helpers.js";
-import { createRuntimeActionRequestFromToolCall } from "#harness/runtime-actions.js";
+import { createRuntimeActionRequestFromToolCall } from "#harness/coordination.js";
import {
createInvalidToolCallInputError,
isInvalidToolCall,
@@ -215,14 +215,12 @@ export async function emitTurnEpilogue(
emitFn: HarnessEmitFn,
state: HarnessEmissionState,
mode: RunMode,
- messages?: readonly import("ai").ModelMessage[],
): Promise<HarnessEmissionState> {
await emitFn(
createTurnCompletedEvent({
sequence: state.sequence,
turnId: state.turnId,
}),
- messages,
);
if (mode === "conversation") {
@@ -285,7 +283,29 @@ interface StreamActionEmissionOptions {
readonly tools: HarnessToolMap;
}
-/** Consumes `fullStream` in source order, batching provider calls before their first result. */
+function readSubagentBackgroundTaskReceipt(
+ result: RuntimeToolResultActionResult,
+ tools: HarnessToolMap | undefined,
+): { readonly status: "working"; readonly taskId: string } | undefined {
+ if (result.isError === true || tools?.get(result.toolName)?.resultKind !== "subagent") {
+ return undefined;
+ }
+ if (typeof result.output !== "object" || result.output === null || Array.isArray(result.output)) {
+ return undefined;
+ }
+ const status = Reflect.get(result.output, "status");
+ const taskId = Reflect.get(result.output, "taskId");
+ return status === "working" && typeof taskId === "string" ? { status, taskId } : undefined;
+}
+
+/**
+ * Consumes the AI SDK `fullStream` and emits real-time text and reasoning
+ * events.
+ *
+ * Emits local tool events in source order. Provider calls that arrive in one
+ * stream batch into one request event before their first result. A result
+ * without a streamed call resumes a call from an earlier step.
+ */
export async function emitStreamContent(
emitFn: HarnessEmitFn,
state: HarnessEmissionState,
@@ -424,6 +444,18 @@ async function consumeStreamContent(
return;
}
emittedActionResultCallIds.add(result.callId);
+ const backgroundTask = readSubagentBackgroundTaskReceipt(result, options?.tools);
+ if (backgroundTask !== undefined) {
+ await emitFn({
+ data: {
+ backgroundTask,
+ callId: result.callId,
+ output: typeof result.output === "string" ? result.output : JSON.stringify(result.output),
+ subagentName: result.toolName,
+ },
+ type: "subagent.completed",
+ });
+ }
await emitFn(
createActionResultEvent({
result,
diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.ts
index 1d955b483..a7be02829 100644
--- a/packages/eve/src/harness/execute-tool.ts
+++ b/packages/eve/src/harness/execute-tool.ts
@@ -3,8 +3,19 @@ import type { FlexibleSchema } from "ai";
import type { Approval } from "#approval/definition.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
import type { TaskExec } from "#tools/task.js";
+import type { JsonValue } from "#shared/json.js";
import type { PreparedToolBehavior } from "#tools/behavior.js";
+/**
+ * Runtime-owned action metadata attached to one harness-visible tool.
+ *
+ * `task-control` marks the parent-side background task tools
+ * (`task_cancel`, `task_update`): they carry no child
+ * address of their own — the dispatch step resolves targets through the
+ * session task index by tool name.
+ */
+export type HarnessRuntimeActionDefinition = { readonly kind: "task-control" };
+
/**
* Unified harness-owned tool definition.
*/
@@ -13,10 +24,50 @@ export interface HarnessToolDefinition {
readonly behavior?: PreparedToolBehavior;
readonly description: string;
readonly execute?: (input: any, options: ToolExecuteOptions, task?: TaskExec) => any;
+ /** Optional JSON input substituted when this tool starts its workflow body. */
+ readonly executeInput?: (input: unknown) => JsonValue;
readonly execution?: "background";
+ readonly frameworkAction?: "load-skill";
readonly inputSchema: FlexibleSchema;
readonly name: string;
+ /** Runtime graph node for a framework subagent workflow body. */
+ readonly nodeId?: string;
readonly approval?: Approval;
readonly outputSchema?: FlexibleSchema;
+ /**
+ * How the result of this workflow-backed tool is settled: as a
+ * `subagent-result` (delegation tools — `behavior.handling.target.kind` is
+ * `subagent-call`, `remote-agent-call`, or `self-agent-call`) or as an
+ * ordinary `tool-result` (authored workflow tools). Absent means `"tool"`.
+ *
+ * On the definition itself this duplicates the dispatch target kind; it
+ * exists because the value must survive past the tool map. `buildToolSet`,
+ * `createCoordinationRequestFromToolCall`, and the workflow sandbox host
+ * tool copy it into the `RuntimeWorkflowTaskRequest`, which `startWorkflowTask`
+ * persists on the `WorkflowToolRunRecord` in session state and the run echoes
+ * back on every `WorkflowToolRunRef` inbox message. The owner turn then routes
+ * outcomes, counts the workflow subagent budget, and decides whether child
+ * usage accrues without access to a `HarnessToolMap`. Harness-side readers
+ * (`advertised-tools`, `emission`, the background tool executor) use it to
+ * expose only delegation tools inside workflow sandboxes, emit task receipts,
+ * and reserve/claim agent handles for subagent starts.
+ *
+ * The persisted copy is dropped by `removeWorkflowToolRun` when the run
+ * settles, or `clearWorkflowToolRuns` at turn end.
+ *
+ * TODO: once subagent starts no longer need harness-specific handling,
+ * derive this from `behavior.handling.target.kind` at the projection points
+ * above and remove the field.
+ */
+ readonly resultKind?: "subagent" | "tool";
+ /**
+ * Advertise this tool only to the root session, hiding it from subagent
+ * sessions. Set on the injected `agent` self-delegation tool so children
+ * cannot delegate recursively. Absent means visible everywhere.
+ */
+ readonly rootOnly?: boolean;
+ readonly runtimeAction?: HarnessRuntimeActionDefinition;
readonly toModelOutput?: (output: unknown) => unknown;
+ /** Present when this tool starts an associated durable workflow. */
+ readonly workflowId?: string;
}
diff --git a/packages/eve/src/harness/handles/query.ts b/packages/eve/src/harness/handles/query.ts
deleted file mode 100644
index 45f29b2bd..000000000
--- a/packages/eve/src/harness/handles/query.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#shared/action-types.js";
-import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/state-key.js";
-import type { AgentHandle } from "#harness/handles/store.js";
-import type { SessionStateMap } from "#harness/types.js";
-
-/** A handle with one outstanding operation and a confirmed child address. */
-export type RunningAgentHandle = Extract<AgentHandle, { phase: "running" }>;
-
-/**
- * Schema-free read of the agent handles from session state.
- *
- * Trust boundary: every write to this key goes through `writeHandles` in
- * transitions.ts, which runs the strict zod store schema at persist time and
- * refuses to write an invalid store. This driver-side query trusts that
- * invariant instead of re-validating, so the workflow driver bundle stays
- * free of the compiled zod runtime.
- */
-function readAgentHandles(state: SessionStateMap | undefined): readonly AgentHandle[] {
- const raw = state?.[AGENT_HANDLES_STATE_KEY];
- if (raw === undefined) {
- return [];
- }
- const handles = (raw as { handles?: unknown }).handles;
- return Array.isArray(handles) ? (handles as readonly AgentHandle[]) : [];
-}
-
-/**
- * Finds the running agent handle a child-produced result must settle: the
- * handle whose recorded operation carries the result's callId.
- *
- * Binding is by callId alone. Possession of the parent's callback token is
- * the authorization to settle; the handle's recorded address is used for
- * outbound delivery (continuation, cancellation), never as an inbound
- * identity check. Under the accepted at-least-once dispatch window a
- * replay-orphaned duplicate child holds the same token and callId and may
- * settle the call in place of the owned child — an accepted trade-off,
- * since both children computed the same input.
- */
-export function findRunningAgentHandle(
- state: SessionStateMap | undefined,
- input: { readonly callId: string },
-): RunningAgentHandle | undefined {
- const handles = readAgentHandles(state);
- return handles.find(
- (handle): handle is RunningAgentHandle =>
- handle.phase === "running" && handle.operation.callId === input.callId,
- );
-}
-
-/**
- * A subagent result may settle a call only when a running handle records
- * its callId: a late or duplicate result for an already-settled call finds
- * no running handle and is dropped.
- *
- * `dispatch`-origin failures pass unconditionally: the parent synthesizes
- * them for calls whose child never started, and they reach the harness only
- * through the trusted step-result path. Untrusted channels must use
- * {@link isInboxSubagentResultFromRunningHandle} instead.
- */
-export function isResultBoundToRunningHandle(
- state: SessionStateMap | undefined,
- result: RuntimeActionResult,
-): boolean {
- if (result.kind !== "subagent-result") {
- return true;
- }
- if (result.origin === "dispatch" || result.backgroundTask !== undefined) {
- return true;
- }
- return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
-}
-
-/**
- * Strict variant of {@link isResultBoundToRunningHandle} for results arriving
- * over the shared turn inbox (child notifications and remote callbacks).
- * An inbox result must bind to a running handle by callId; one with no
- * matching running handle — including one for a callId whose dispatch
- * already failed — must not overwrite the dispatch-produced error result.
- */
-export function isInboxSubagentResultFromRunningHandle(
- state: SessionStateMap | undefined,
- result: RuntimeSubagentChildResult,
-): boolean {
- return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
-}
diff --git a/packages/eve/src/harness/handles/transitions.ts b/packages/eve/src/harness/handles/transitions.ts
deleted file mode 100644
index 2e60e883a..000000000
--- a/packages/eve/src/harness/handles/transitions.ts
+++ /dev/null
@@ -1,491 +0,0 @@
-import {
- AGENT_HANDLES_STATE_KEY,
- assertPersistableAgentHandleStore,
- formatAgentStatus,
- getAgentHandleStore,
- type AgentAddress,
- type AgentHandle,
- type AgentIdentity,
- type ContinueOperation,
- type StartOperation,
-} from "#harness/handles/store.js";
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
-import { jsonValuesEqual } from "#shared/json.js";
-
-/**
- * Records intent to start a fresh child. Must be applied to the step's
- * working snapshot before the start side effect runs, so the returned state
- * owns any child the step may have created.
- *
- * The guarantee is intra-step, not exactly-once: the prepared handle
- * durably commits only when the enclosing dispatch step's result commits.
- * A crash between an accepted start and that commit replays the step from
- * the pre-step snapshot and re-runs the side effect.
- *
- * Throws when the identity or operation already exists: fresh starts mint
- * a new identity, so a collision means corrupted derivation, not a replay.
- */
-export function prepareAgentStart(
- session: HarnessSession,
- input: {
- readonly identity: AgentIdentity;
- readonly operation: StartOperation;
- readonly target: AgentStartTargetInput;
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- if (handles.some((handle) => handle.identity.id === input.identity.id)) {
- throw new Error(`Agent handle "${input.identity.id}" already exists.`);
- }
- return writeHandles(session, [
- ...handles,
- {
- identity: input.identity,
- operation: input.operation,
- phase: "starting",
- target: input.target,
- },
- ]);
-}
-
-type AgentStartTargetInput = Extract<AgentHandle, { phase: "starting" }>["target"];
-
-/** Result of preparing a continuation against an existing handle. */
-export type PrepareAgentContinuationResult =
- | {
- readonly kind: "ready";
- readonly session: HarnessSession;
- readonly handle: Extract<AgentHandle, { phase: "running" }>;
- }
- | { readonly kind: "unknown" }
- | { readonly kind: "mismatch" }
- | { readonly kind: "busy" };
-
-/**
- * Records intent to deliver a follow-up turn to a parked child. Must be
- * applied to the step's working snapshot before the delivery side effect
- * runs.
- *
- * Delivery is at-least-once, not exactly-once: the `running` handle durably
- * commits only when the enclosing dispatch step's result commits. If the
- * step dies after a successful delivery, replay starts from `parked` and
- * delivers the same operation again — which is why replaying the operation
- * already recorded on a running handle returns `ready` with the unchanged
- * session instead of a busy conflict.
- *
- * `unknown`, `mismatch`, and `busy` do not change the session; the caller
- * maps them onto `AGENT_UNREACHABLE`, `AGENT_MISMATCH`, and `AGENT_BUSY`
- * results.
- */
-export function prepareAgentContinuation(
- session: HarnessSession,
- input: {
- readonly agentId: string;
- readonly invokedName: string;
- readonly operation: ContinueOperation;
- },
-): PrepareAgentContinuationResult {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = handles.find((handle) => handle.identity.id === input.agentId);
- if (existing === undefined) {
- return { kind: "unknown" };
- }
- if (existing.identity.name !== input.invokedName) {
- return { kind: "mismatch" };
- }
- if (existing.phase === "running" && existing.operation.id === input.operation.id) {
- return { handle: existing, kind: "ready", session };
- }
- if (existing.phase !== "parked") {
- return { kind: "busy" };
- }
-
- const running: Extract<AgentHandle, { phase: "running" }> = {
- address: existing.address,
- identity: existing.identity,
- operation: { ...input.operation, previousStatus: existing.lastStatus },
- phase: "running",
- };
- return {
- handle: running,
- kind: "ready",
- session: writeHandles(
- session,
- handles.map((handle) => (handle.identity.id === input.agentId ? running : handle)),
- ),
- };
-}
-
-type ActiveAgentHandle = Extract<AgentHandle, { phase: "starting" | "running" }>;
-
-function findActiveHandle(
- handles: readonly AgentHandle[],
- operationId: string,
-): ActiveAgentHandle | undefined {
- return handles.find(
- (handle): handle is ActiveAgentHandle =>
- (handle.phase === "starting" || handle.phase === "running") &&
- handle.operation.id === operationId,
- );
-}
-
-/**
- * Confirms a started child: `starting` becomes `running` with the child's
- * confirmed address. Throws when no starting handle carries the operation,
- * because confirming an unprepared start means ownership was never
- * committed. Re-confirming an already-running handle with the same
- * operation and address is a replay no-op.
- */
-export function confirmAgentStarted(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly address: AgentAddress;
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = findActiveHandle(handles, input.operationId);
- if (existing === undefined) {
- throw new Error(`No prepared agent handle for operation "${input.operationId}".`);
- }
- if (existing.phase === "running") {
- return session;
- }
-
- return writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: input.address,
- identity: existing.identity,
- operation: existing.operation,
- phase: "running",
- }
- : handle,
- ),
- );
-}
-
-/** Confirms a task-mode child as a persistent identity/address record. */
-export function confirmTaskAgentAddress(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly address: AgentAddress;
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = findActiveHandle(handles, input.operationId);
- if (existing === undefined) {
- throw new Error(`No prepared agent handle for operation "${input.operationId}".`);
- }
- if (existing.phase === "running") {
- throw new Error(
- `Task agent operation "${input.operationId}" was confirmed as a running handle.`,
- );
- }
-
- return writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: input.address,
- identity: existing.identity,
- phase: "addressed" as const,
- }
- : handle,
- ),
- );
-}
-
-/**
- * Records a task-mode child's persistent address from its durable executor
- * binding, applied when the parent step that delegated the task commits.
- *
- * Replay-idempotent: a record identical to the stored handle is a no-op
- * (a resumed child, or a replayed commit). A different record under the
- * same id throws — ids derive from unique operations, so a collision
- * means corrupted derivation, not a replay.
- */
-export function recordTaskAgentAddress(
- session: HarnessSession,
- input: {
- readonly address: AgentAddress;
- readonly identity: AgentIdentity;
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const record: AgentHandle = {
- address: input.address,
- identity: input.identity,
- phase: "addressed",
- };
- const existing = handles.find((handle) => handle.identity.id === input.identity.id);
- if (existing !== undefined) {
- if (jsonValuesEqual(existing, record)) return session;
- throw new Error(`Agent handle "${input.identity.id}" already exists with different content.`);
- }
- return writeHandles(session, [...handles, record]);
-}
-
-/** Removes a task-mode address after permanent delivery failure. */
-export function removeTaskAgentAddress(session: HarnessSession, agentId: string): HarnessSession {
- return { ...session, state: removeTaskAgentAddressFromState(session.state, agentId) };
-}
-
-/** State-only variant used while consuming a terminal task wake. */
-export function removeTaskAgentAddressFromState(
- state: SessionStateMap | undefined,
- agentId: string,
-): SessionStateMap {
- const handles = getAgentHandleStore(state)?.handles ?? [];
- return {
- ...state,
- [AGENT_HANDLES_STATE_KEY]: assertPersistableAgentHandleStore({
- handles: handles.filter(
- (handle) => !(handle.phase === "addressed" && handle.identity.id === agentId),
- ),
- }),
- };
-}
-
-/**
- * Resolves a dispatch that definitively failed.
- *
- * - A dead start or dead continuation deletes the handle: there is no
- * child left to own.
- * - A retryable continuation failure restores `parked` with the status the
- * handle showed before the delivery, so the model may retry the same
- * `agentId` later.
- *
- * Unknown operations are a no-op: the failure raced a settlement that
- * already resolved the handle.
- */
-export function rejectAgentEffect(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly disposition: "dead" | "retryable";
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = findActiveHandle(handles, input.operationId);
- if (existing === undefined) {
- return session;
- }
-
- if (input.disposition === "retryable" && existing.phase === "running") {
- const { operation } = existing;
- if (operation.kind === "continue") {
- return writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: existing.address,
- identity: existing.identity,
- lastStatus: operation.previousStatus,
- phase: "parked",
- }
- : handle,
- ),
- );
- }
- }
-
- return writeHandles(
- session,
- handles.filter((handle) => handle !== existing),
- );
-}
-
-/**
- * Parks every running child when the parent abandons a cancelled turn.
- *
- * Cancellation requests each running descendant's cancellation and then
- * tears down the turn inbox — the only hook a child settlement can
- * resume — so no later settlement can move these handles. Without this
- * transition they would stay `running` forever: invisible to the model,
- * unresumable, and retried by every future cancellation.
- *
- * A cancelled child settles its own turn as a park, so `parked` with
- * `"(cancelled)"` mirrors {@link settleAgentTurn}'s cancelled outcome. If
- * the child instead died, a later continuation attempt discovers the dead
- * session and {@link rejectAgentEffect} deletes the handle.
- */
-export function abandonRunningAgentTurns(session: HarnessSession): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- if (!handles.some((handle) => handle.phase === "running")) {
- return session;
- }
- return writeHandles(
- session,
- handles.map((handle) =>
- handle.phase === "running"
- ? {
- address: handle.address,
- identity: handle.identity,
- lastStatus: "(cancelled)",
- phase: "parked",
- }
- : handle,
- ),
- );
-}
-
-/** Result of applying a settled child turn to the store. */
-export type SettleAgentTurnResult =
- | { readonly kind: "settled"; readonly session: HarnessSession }
- | { readonly kind: "ignored"; readonly reason: "unknown-operation" };
-
-/**
- * Applies one settled child turn: `running` becomes `parked` for a parked
- * outcome or is deleted for a terminal outcome.
- *
- * The settlement must carry the operation currently recorded on the
- * running handle; anything else is ignored so a stale delivery can never
- * move a newer turn.
- */
-export function settleAgentTurn(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly outcome: AgentTurnOutcome;
- },
-): SettleAgentTurnResult {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = handles.find(
- (handle) => handle.phase === "running" && handle.operation.id === input.operationId,
- );
- if (existing === undefined || existing.phase !== "running") {
- return { kind: "ignored", reason: "unknown-operation" };
- }
-
- if (input.outcome.kind === "terminal") {
- return {
- kind: "settled",
- session: writeHandles(
- session,
- handles.filter((handle) => handle !== existing),
- ),
- };
- }
-
- const { result } = input.outcome;
- const lastStatus =
- result.kind === "succeeded"
- ? formatAgentStatus(result.output)
- : result.kind === "failed"
- ? formatAgentStatus(result.error)
- : "(cancelled)";
- return {
- kind: "settled",
- session: writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: existing.address,
- identity: existing.identity,
- lastStatus,
- phase: "parked",
- }
- : handle,
- ),
- ),
- };
-}
-
-/**
- * Rebases the handle delta one dispatch produced (`base` → `next`) onto a
- * working session that other concurrently staged effects may have advanced
- * past `base`.
- *
- * Per handle id:
- *
- * - deleted by the dispatch → deleted from the working session.
- * - added by the dispatch → appended. If the working session already holds
- * the id with different content, throws: ids derive from unique
- * operations, so a collision means corrupted derivation.
- * - changed in place by the dispatch → the dispatched copy replaces the
- * working copy while that copy still matches `base`. A working copy that
- * diverged from both throws instead of silently dropping either change.
- * - untouched by the dispatch → the working copy is kept.
- *
- * A delta the working session already contains is a no-op, so replaying an
- * effect is safe.
- */
-export function rebaseAgentHandles(
- session: HarnessSession,
- input: {
- readonly base: SessionStateMap | undefined;
- readonly next: SessionStateMap | undefined;
- },
-): HarnessSession {
- const baseById = handlesById(input.base);
- const nextById = handlesById(input.next);
- const currentHandles = getAgentHandleStore(session.state)?.handles ?? [];
- const currentIds = new Set(currentHandles.map((handle) => handle.identity.id));
-
- let changed = false;
- const rebased: AgentHandle[] = [];
- for (const current of currentHandles) {
- const id = current.identity.id;
- const base = baseById.get(id);
- const next = nextById.get(id);
- if (base !== undefined && next === undefined) {
- changed = true;
- continue;
- }
- if (base === undefined && next !== undefined && !jsonValuesEqual(current, next)) {
- throw new Error(
- `Agent handle "${id}" added by a dispatch already exists with different content.`,
- );
- }
- if (base !== undefined && next !== undefined && !jsonValuesEqual(base, next)) {
- if (jsonValuesEqual(current, base)) {
- rebased.push(next);
- changed = true;
- continue;
- }
- if (!jsonValuesEqual(current, next)) {
- throw new Error(
- `Agent handle "${id}" was changed by a dispatch and concurrently by another effect.`,
- );
- }
- }
- rebased.push(current);
- }
- const added = [...nextById.values()].filter(
- (handle) => !baseById.has(handle.identity.id) && !currentIds.has(handle.identity.id),
- );
- if (!changed && added.length === 0) {
- return session;
- }
- return writeHandles(session, [...rebased, ...added]);
-}
-
-function handlesById(state: SessionStateMap | undefined): ReadonlyMap<string, AgentHandle> {
- const handles = getAgentHandleStore(state)?.handles ?? [];
- return new Map(handles.map((handle) => [handle.identity.id, handle]));
-}
-
-/**
- * Persists the handle store, validating it against the strict store schema
- * first. This write-time check is what lets the schema-free driver-side
- * reader (`query.ts`) trust any stored value without revalidating: a
- * transition bug fails loudly here instead of poisoning the session for
- * every later read.
- */
-function writeHandles(session: HarnessSession, handles: readonly AgentHandle[]): HarnessSession {
- return {
- ...session,
- state: {
- ...session.state,
- [AGENT_HANDLES_STATE_KEY]: assertPersistableAgentHandleStore({ handles }),
- },
- };
-}
diff --git a/packages/eve/src/harness/input-requests.ts b/packages/eve/src/harness/input-requests.ts
index 80bdfcac9..4a1d8d327 100644
--- a/packages/eve/src/harness/input-requests.ts
+++ b/packages/eve/src/harness/input-requests.ts
@@ -19,7 +19,7 @@ import type {
ResolvedStepInput,
} from "#harness/hitl/pending-input-resolution.js";
import { resolveQuestionOnlyInputBatches } from "#harness/hitl/question-input-requests.js";
-import { resolveToolCallInputObject } from "#harness/runtime-actions.js";
+import { resolveToolCallInputObject } from "#harness/coordination.js";
import {
clearPendingSessionLimitPrompt,
isSessionLimitInputBatch,
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index edc803c9f..3644c9e87 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -131,10 +131,10 @@ export function clearProxyInputRequestsForChild(
}
/** Removes every proxy route the predicate selects. */
-export function clearProxyInputRequestsWhere(
- session: HarnessSession,
+export function clearProxyInputRequestsWhere<T extends { readonly state?: SessionStateMap }>(
+ session: T,
select: (route: ProxyInputRequest) => boolean,
-): HarnessSession {
+): T {
const current = readMap(session.state);
const next: Record<string, ProxyInputRequest> = {};
let changed = false;
@@ -170,10 +170,10 @@ export function retireProxyInputRequests<T extends { readonly state?: SessionSta
}
/** Removes every proxy route owned by one durable task. */
-export function clearProxyInputRequestsForTask(
- session: HarnessSession,
+export function clearProxyInputRequestsForTask<T extends { readonly state?: SessionStateMap }>(
+ session: T,
taskId: string,
-): HarnessSession {
+): T {
return clearProxyInputRequestsWhere(session, (route) => route.taskId === taskId);
}
diff --git a/packages/eve/src/harness/step-hooks.ts b/packages/eve/src/harness/step-hooks.ts
index 168fb28ab..e1af89d15 100644
--- a/packages/eve/src/harness/step-hooks.ts
+++ b/packages/eve/src/harness/step-hooks.ts
@@ -10,7 +10,6 @@ import type {
TypedToolCall,
TypedToolResult,
} from "ai";
-import type { SessionAuthContext } from "#channel/types.js";
import {
createActionResultEvent,
createActionsRequestedEvent,
@@ -31,8 +30,7 @@ import {
mergeGatewayAutoCaching,
type PromptCachePath,
} from "#harness/prompt-cache.js";
-import { mergeProviderSafetyIdentifier } from "#harness/provider-safety.js";
-import { createRuntimeActionRequestFromToolCall } from "#harness/runtime-actions.js";
+import { createRuntimeActionRequestFromToolCall } from "#harness/coordination.js";
import { isInvalidToolCall } from "#harness/tool-call-input-errors.js";
import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
import {
@@ -44,6 +42,8 @@ import {
import { contextStorage } from "#context/container.js";
import { isAuthorizationSignal, isPendingAuthorizationToolOutput } from "#harness/authorization.js";
import { readToolInterrupt } from "#harness/tool-interrupts.js";
+import { AuthKey } from "#context/keys.js";
+import { mergeProviderSafetyIdentifier } from "#harness/provider-safety.js";
// ---------------------------------------------------------------------------
// Step result type
@@ -77,7 +77,7 @@ export type HarnessStepResult = Pick<
* Input for {@link buildStepHooks}.
*/
interface StepHooksInput {
- readonly auth: SessionAuthContext | null;
+ readonly auth?: import("#channel/types.js").SessionAuthContext | null;
readonly cachePath: PromptCachePath;
readonly emit?: HarnessEmitFn;
readonly emissionState: HarnessEmissionState;
@@ -186,7 +186,7 @@ export function buildStepHooks(input: StepHooksInput): StepHooks {
const providerOptions = mergeProviderSafetyIdentifier(
modelReference,
modelReference.providerOptions,
- input.auth,
+ input.auth ?? contextStorage.getStore()?.get(AuthKey) ?? null,
);
if (input.cachePath.kind === "gateway-auto") {
stepResult.providerOptions = mergeGatewayAutoCaching(providerOptions) as NonNullable<
diff --git a/packages/eve/src/harness/subagent-depth.ts b/packages/eve/src/harness/subagent-depth.ts
deleted file mode 100644
index c73fde1c8..000000000
--- a/packages/eve/src/harness/subagent-depth.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { SubagentDepthKey } from "#context/keys.js";
-import type { HarnessSession } from "#harness/types.js";
-import type { PendingAgentDispatchAction, PendingDispatchAction } from "#shared/dispatch-action.js";
-
-export type ResolvedSubagentDepth = {
- readonly currentDepth: number;
- readonly nextChildDepth: number;
-};
-
-export function resolveSubagentDepth(
- session: Pick<HarnessSession, "subagentDepth">,
-): ResolvedSubagentDepth {
- const currentDepth = parseSubagentDepth(session.subagentDepth);
- return {
- currentDepth,
- nextChildDepth: currentDepth + 1,
- };
-}
-
-export function readSerializedSubagentDepth(
- serializedContext: Readonly<Record<string, unknown>>,
-): number | undefined {
- const subagentDepth = parseSubagentDepth(serializedContext[SubagentDepthKey.name]);
- return subagentDepth === 0 ? undefined : subagentDepth;
-}
-
-export function isSubagentDelegationAction(
- action: PendingDispatchAction,
-): action is PendingAgentDispatchAction {
- return (
- action.target.kind === "self-agent-call" ||
- action.target.kind === "subagent-call" ||
- action.target.kind === "remote-agent-call"
- );
-}
-
-export function getSubagentDelegationName(action: PendingAgentDispatchAction): string {
- switch (action.target.kind) {
- case "remote-agent-call":
- return action.target.remoteAgentName;
- case "self-agent-call":
- case "subagent-call":
- return action.target.subagentName;
- default: {
- const _exhaustive: never = action.target;
- return _exhaustive;
- }
- }
-}
-
-function parseSubagentDepth(value: unknown): number {
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : 0;
-}
diff --git a/packages/eve/src/harness/tool-call-action.ts b/packages/eve/src/harness/tool-call-action.ts
index a591480c4..e585c4871 100644
--- a/packages/eve/src/harness/tool-call-action.ts
+++ b/packages/eve/src/harness/tool-call-action.ts
@@ -1,5 +1,5 @@
import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
-import { resolveToolCallInputObject } from "#harness/runtime-actions.js";
+import { resolveToolCallInputObject } from "#harness/coordination.js";
/** Creates a runtime tool-call action shape from an AI SDK tool call. */
export function createRuntimeToolCallActionFromToolCall(input: {
diff --git a/packages/eve/src/harness/tool-call-input-errors.ts b/packages/eve/src/harness/tool-call-input-errors.ts
index f6aa99c28..f099372c3 100644
--- a/packages/eve/src/harness/tool-call-input-errors.ts
+++ b/packages/eve/src/harness/tool-call-input-errors.ts
@@ -1,7 +1,7 @@
import type { ToolSet, TypedToolCall, TypedToolError } from "ai";
import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
-import { resolveToolCallInputObject } from "#harness/runtime-actions.js";
+import { resolveToolCallInputObject } from "#harness/coordination.js";
/**
* Returns true when the AI SDK marked the tool call `invalid` (typically
diff --git a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts
index 05d6838b1..b00c09b70 100644
--- a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts
+++ b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts
@@ -383,7 +383,7 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
}
},
mode: "conversation",
- prepareStepDynamicTools: (input) =>
+ resolveStepDynamicTools: (input) =>
preparePersistedStepDynamicToolMetadata({ ...input, resolvers: [resolver] }),
resolveModel: async (): Promise<LanguageModel> => model,
tools: new Map(),
@@ -480,12 +480,12 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
} satisfies OldSourceOffsetDynamicToolMetadata,
]);
const execute = vi.fn(async () => "/workspace");
- const prepareStepDynamicTools = vi.fn((input) =>
+ const resolveStepDynamicTools = vi.fn((input) =>
preparePersistedStepDynamicToolMetadata({ ...input, resolvers: [] }),
);
const runStep = createToolLoopHarness({
...createConfig(createModel(), execute),
- prepareStepDynamicTools,
+ resolveStepDynamicTools,
});
await expect(
@@ -501,7 +501,7 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
),
).resolves.toBeDefined();
- expect(prepareStepDynamicTools).not.toHaveBeenCalled();
+ expect(resolveStepDynamicTools).not.toHaveBeenCalled();
expect(execute).not.toHaveBeenCalled();
});
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index d9278970d..20b0dfc85 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -44,6 +44,7 @@ import type {
} from "#public/instrumentation/index.js";
import { defineInstructions } from "#public/definitions/instructions.js";
import type { ResolvedDynamicInstructionsResolver } from "#runtime/types.js";
+import { createPreparedRuntimeSubagentTool } from "#runtime/subagents/registry.js";
import type { DynamicResolveContext } from "#dynamic/definition.js";
import { registerDurableDynamicCallback } from "#tools/durable-callbacks.js";
import type { RunMode } from "#shared/run-mode.js";
@@ -66,9 +67,8 @@ import {
hasPendingInputBatch,
appendPendingInputBatch,
} from "#harness/input-requests.js";
-import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
+import { getPendingCoordinationBatch } from "#harness/coordination.js";
+import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/store.js";
import { BackgroundToolExecutorKey } from "#harness/background-tools.js";
import { stashToolInterrupt } from "#harness/tool-interrupts.js";
import { appendMissingToolResultMessages, createToolLoopHarness } from "#harness/tool-loop.js";
@@ -114,7 +114,6 @@ vi.mock("ai", () => ({
const {
mockCreateAiSdkHookBridge,
mockGetRegisteredTelemetryIntegrations,
- mockSetEveAttributes,
registeredAuthorIntegration,
registeredOtelIntegration,
} = vi.hoisted(() => ({
@@ -122,9 +121,6 @@ const {
mockGetRegisteredTelemetryIntegrations: vi.fn(
(_options?: { readonly sanitizeEveOtelErrors?: boolean }): unknown[] => [],
),
- mockSetEveAttributes: vi.fn<(attrs: Record<string, unknown>) => Promise<void>>(
- async () => undefined,
- ),
registeredAuthorIntegration: { onStart: vi.fn() },
registeredOtelIntegration: { onStart: vi.fn() },
}));
@@ -139,10 +135,6 @@ vi.mock("#instrumentation/ai-sdk-telemetry.js", () => ({
mockGetRegisteredTelemetryIntegrations(options),
}));
-vi.mock("#runtime/attributes/emit.js", () => ({
- setEveAttributes: (attrs: Record<string, unknown>) => mockSetEveAttributes(attrs),
-}));
-
let declaredAudience: ChannelAudience = "unknown";
let declaredDecision: InstrumentationDecision | undefined;
let declaredInstrumentation: SessionInstrumentation | undefined;
@@ -250,7 +242,6 @@ afterEach(() => {
vi.unstubAllEnvs();
declareTelemetry(undefined);
mockGetRegisteredTelemetryIntegrations.mockReturnValue([]);
- mockSetEveAttributes.mockResolvedValue(undefined);
});
function createTestSession(overrides?: Partial<HarnessSession>): HarnessSession {
@@ -307,33 +298,31 @@ function createDelegationToolMap(): ToolLoopHarnessConfig["tools"] {
[
"delegate",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },
- },
- },
description: "Delegate to a subagent.",
inputSchema: jsonSchema({ type: "object" }),
name: "delegate",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]);
}
-const QUESTION_BEHAVIOR = {
- availability: ["requires-request-input"],
- handling: { kind: "request-input", request: "question" },
-} as const;
-
-function createQuestionHarnessTool() {
- return {
- behavior: QUESTION_BEHAVIOR,
- description: "Ask the user a question.",
- inputSchema: jsonSchema({ type: "object" }),
- name: "ask_question",
- };
+function createQuestionToolMap(): ToolLoopHarnessConfig["tools"] {
+ return new Map([
+ [
+ "ask_question",
+ {
+ behavior: {
+ availability: ["requires-request-input"],
+ handling: { kind: "request-input", request: "question" },
+ },
+ description: "Ask the user a question.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "ask_question",
+ },
+ ],
+ ]);
}
function createScheduleContext(): ContextContainer {
@@ -1546,7 +1535,7 @@ describe("createToolLoopHarness", () => {
expect(ToolLoopAgent).not.toHaveBeenCalled();
});
- it("keeps declared subagent tools visible in deeply nested sessions", async () => {
+ it("keeps declared subagent tools visible in delegated sessions", async () => {
setupMockAgent({
finishReason: "stop",
response: { messages: [{ content: "Hello!", role: "assistant" }] },
@@ -1560,7 +1549,7 @@ describe("createToolLoopHarness", () => {
});
const runStep = createToolLoopHarness(config);
- await runStep(createTestSession({ subagentDepth: 99 }), {
+ await runStep(createTestSession({ rootSessionId: "root-session" }), {
message: "Hi",
});
@@ -1578,7 +1567,7 @@ describe("createToolLoopHarness", () => {
{
content: [
{
- input: { message: "delegate at depth 2" },
+ input: { message: "delegate from child" },
toolCallId: "call-1",
toolName: "delegate",
type: "tool-call",
@@ -1591,7 +1580,7 @@ describe("createToolLoopHarness", () => {
text: "",
toolCalls: [
{
- input: { message: "delegate at depth 2" },
+ input: { message: "delegate from child" },
toolCallId: "call-1",
toolName: "delegate",
type: "tool-call",
@@ -1605,33 +1594,30 @@ describe("createToolLoopHarness", () => {
createTestConfig("conversation", emit, { tools: createDelegationToolMap() }),
);
- const result = await runStep(createTestSession({ subagentDepth: 98 }), {
+ const result = await runStep(createTestSession({ rootSessionId: "root-session" }), {
message: "Hi",
});
expect(events.find((event) => event.type === "actions.requested")?.data.actions).toEqual([
- {
+ expect.objectContaining({
callId: "call-1",
- description: "Delegate to a subagent.",
- input: { message: "delegate at depth 2" },
- kind: "subagent-call",
- name: "delegate",
- nodeId: "workers",
- subagentName: "worker",
- },
+ input: { message: "delegate from child" },
+ kind: "tool-call",
+ toolName: "delegate",
+ }),
]);
- expect(getPendingRuntimeActionBatch(result.session.state)?.actions).toEqual([
- {
+ expect(getPendingCoordinationBatch(result.session.state)?.tasks).toEqual([
+ expect.objectContaining({
callId: "call-1",
- description: "Delegate to a subagent.",
- input: { message: "delegate at depth 2" },
- target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },
+ input: { message: "delegate from child" },
+ kind: "workflow-task",
+ resultKind: "subagent",
toolName: "delegate",
- },
+ }),
]);
});
- it("parks dynamic subagent calls as pending runtime actions", async () => {
+ it("does not park dynamic background subagent calls on the turn", async () => {
setupMockAgent({
finishReason: "tool-calls",
response: {
@@ -1668,26 +1654,15 @@ describe("createToolLoopHarness", () => {
model: { id: "openai/gpt-5.5" },
},
kind: "subagent",
- prepared: {
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
- },
- },
+ prepared: createPreparedRuntimeSubagentTool({
description: "Research the request.",
- inputSchema: { type: "object" },
kind: "subagent",
logicalPath: "subagents/researcher",
name: "researcher",
nodeId: "subagents/researcher",
sourceId: "subagents/researcher",
- },
+ sourceKind: "module",
+ }),
},
});
const { emit, events } = createEventCollector();
@@ -1700,23 +1675,15 @@ describe("createToolLoopHarness", () => {
expect(events.find((event) => event.type === "actions.requested")?.data.actions).toEqual([
expect.objectContaining({
callId: "call-dynamic",
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- }),
- ]);
- expect(getPendingRuntimeActionBatch(result.session.state)?.actions).toEqual([
- expect.objectContaining({
- callId: "call-dynamic",
- target: expect.objectContaining({
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- }),
+ input: { message: "investigate" },
+ kind: "tool-call",
+ toolName: "researcher",
}),
]);
+ expect(getPendingCoordinationBatch(result.session.state)).toBeUndefined();
});
- it("parks on both batches when one step carries a runtime action and an approval", async () => {
+ it("parks on both batches when one step carries a workflow task and an approval", async () => {
const gateToolCall = {
input: { action: "run" },
toolCallId: "gate-1",
@@ -1784,11 +1751,8 @@ describe("createToolLoopHarness", () => {
});
expect(parked.next).toBeNull();
- expect(getPendingRuntimeActionBatch(parked.session.state)?.actions).toEqual([
- expect.objectContaining({
- callId: "delegate-1",
- target: expect.objectContaining({ kind: "subagent-call" }),
- }),
+ expect(getPendingCoordinationBatch(parked.session.state)?.tasks).toEqual([
+ expect.objectContaining({ callId: "delegate-1", kind: "workflow-task" }),
]);
expect(hasPendingInputBatch(parked.session.state)).toBe(true);
expect(events.filter((event) => event.type === "input.requested")).toHaveLength(1);
@@ -1815,8 +1779,8 @@ describe("createToolLoopHarness", () => {
sessionId: "delegate-session",
},
identity: {
- id: "ag_worker:delegate",
- name: "worker",
+ id: "ag_delegate:delegate",
+ name: "delegate",
nodeId: "workers",
},
operation: {
@@ -1848,13 +1812,13 @@ describe("createToolLoopHarness", () => {
},
},
output: "delegated-done",
- subagentName: "worker",
+ subagentName: "delegate",
},
],
});
expect(reparked.next).toBeNull();
- expect(getPendingRuntimeActionBatch(reparked.session.state)).toBeUndefined();
+ expect(getPendingCoordinationBatch(reparked.session.state)).toBeUndefined();
expect(hasPendingInputBatch(reparked.session.state)).toBe(true);
const toolMessages = reparked.session.history.filter((message) => message.role === "tool");
expect(JSON.stringify(toolMessages)).toContain("delegated-done");
@@ -1862,55 +1826,6 @@ describe("createToolLoopHarness", () => {
expect(events.at(-1)?.type).toBe("session.waiting");
});
- it("publishes declared subagent calls from deeply nested sessions", async () => {
- setupMockAgent({
- finishReason: "tool-calls",
- response: {
- messages: [
- {
- content: [
- {
- input: { message: "delegate at depth 3" },
- toolCallId: "call-1",
- toolName: "delegate",
- type: "tool-call",
- },
- ],
- role: "assistant",
- },
- ],
- },
- text: "",
- toolCalls: [
- {
- input: { message: "delegate at depth 3" },
- toolCallId: "call-1",
- toolName: "delegate",
- type: "tool-call",
- },
- ],
- toolResults: [],
- });
- const { emit, events } = createEventCollector();
- const runStep = createToolLoopHarness(
- createTestConfig("conversation", emit, { tools: createDelegationToolMap() }),
- );
-
- const result = await runStep(createTestSession({ subagentDepth: 99 }), {
- message: "Hi",
- });
-
- expect(events.find((event) => event.type === "actions.requested")?.data.actions).toEqual([
- expect.objectContaining({
- callId: "call-1",
- kind: "subagent-call",
- name: "delegate",
- subagentName: "worker",
- }),
- ]);
- expect(getPendingRuntimeActionBatch(result.session.state)?.actions).toHaveLength(1);
- });
-
it("keeps declared subagent tools when Workflow is unavailable outside the root", async () => {
setupMockAgent({
finishReason: "stop",
@@ -1926,23 +1841,18 @@ describe("createToolLoopHarness", () => {
[
"delegate",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },
- },
- },
description: "Delegate to a subagent.",
inputSchema: jsonSchema({ type: "object" }),
name: "delegate",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]),
});
const runStep = createToolLoopHarness(config);
- await runStep(createTestSession({ subagentDepth: 99 }), {
+ await runStep(createTestSession({ rootSessionId: "root-session" }), {
message: "Hi",
});
@@ -1970,7 +1880,6 @@ describe("createToolLoopHarness", () => {
await runStep(
createTestSession({
rootSessionId: "root-session",
- subagentDepth: 1,
}),
{ message: "Hi" },
);
@@ -2032,61 +1941,6 @@ describe("createToolLoopHarness", () => {
});
});
- it("emits the terminal result while Workflow attributes persist, then joins", async () => {
- setupMockAgent({
- finishReason: "stop",
- response: { messages: [{ content: "Hello!", role: "assistant" }] },
- text: "Hello!",
- toolCalls: [],
- toolResults: [],
- });
- const attributeWrite = Promise.withResolvers<void>();
- mockSetEveAttributes.mockReturnValueOnce(attributeWrite.promise);
- const { emit, events } = createEventCollector();
- const result = createToolLoopHarness(createTestConfig("conversation", emit))(
- createTestSession(),
- { message: "Hi" },
- );
-
- try {
- await vi.waitFor(
- () => {
- expect(events.at(-1)?.type).toBe("session.waiting");
- },
- { timeout: 1_000 },
- );
-
- let settled = false;
- void result.then(() => {
- settled = true;
- });
- await Promise.resolve();
- expect(settled).toBe(false);
- } finally {
- attributeWrite.resolve();
- await result;
- }
- });
-
- it("keeps an unexpected Workflow attribute rejection out of the turn result", async () => {
- setupMockAgent({
- finishReason: "stop",
- response: { messages: [{ content: "Hello!", role: "assistant" }] },
- text: "Hello!",
- toolCalls: [],
- toolResults: [],
- });
- mockSetEveAttributes.mockRejectedValueOnce(new Error("attribute write rejected"));
- const { emit, events } = createEventCollector();
-
- await expect(
- createToolLoopHarness(createTestConfig("conversation", emit))(createTestSession(), {
- message: "Hi",
- }),
- ).resolves.toMatchObject({ next: null });
- expect(events.at(-1)?.type).toBe("session.waiting");
- });
-
it.each([
{
details: {
@@ -3605,7 +3459,16 @@ describe("createToolLoopHarness", () => {
const runStep = createToolLoopHarness(
createTestConfig("conversation", emit, {
capabilities: { requestInput: true },
- tools: new Map([["ask_question", createQuestionHarnessTool()]]),
+ tools: new Map([
+ [
+ "ask_question",
+ {
+ description: "Ask the user a question.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "ask_question",
+ },
+ ],
+ ]),
}),
);
const session = createTestSession({
@@ -3833,16 +3696,11 @@ describe("createToolLoopHarness", () => {
[
"delegate",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },
- },
- },
description: "Delegate to a subagent.",
inputSchema: jsonSchema({ type: "object" }),
name: "delegate",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]),
@@ -3858,7 +3716,7 @@ describe("createToolLoopHarness", () => {
expect(events.some((event) => event.type === "turn.failed")).toBe(false);
});
- it("stamps the live emission state onto a parked runtime-action batch so resume is a continuation", async () => {
+ it("stamps live emission state onto a parked coordination batch so resume is a continuation", async () => {
setupMockAgent({
finishReason: "tool-calls",
response: {
@@ -3895,16 +3753,11 @@ describe("createToolLoopHarness", () => {
[
"delegate",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: { kind: "subagent-call", nodeId: "workers", subagentName: "worker" },
- },
- },
description: "Delegate to a subagent.",
inputSchema: jsonSchema({ type: "object" }),
name: "delegate",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]),
@@ -3913,13 +3766,13 @@ describe("createToolLoopHarness", () => {
const runStep = createToolLoopHarness(config);
const result = await runStep(createTestSession(), { message: "Go" });
- // Parked on the runtime-action batch.
+ // Parked on the coordination batch.
expect(result.next).toBeNull();
- expect(result.session.state?.["eve.runtime.pendingActionBatch"]).toBeDefined();
+ expect(result.session.state?.["eve.runtime.pendingCoordinationBatch"]).toBeDefined();
// The parked session must carry the live turn's emission identity so
// the resume turn is classified as a continuation, not a fresh turn.
- // Regression: the runtime-action park previously dropped the
+ // Regression: the coordination park previously dropped the
// post-preamble emission update, persisting the default `turnId: ""`,
// which mis-routed the resume through the fresh-turn lifecycle path.
const emission = getHarnessEmissionState(result.session.state);
@@ -4946,7 +4799,7 @@ describe("createToolLoopHarness", () => {
const config: ToolLoopHarnessConfig = {
mode: "conversation",
resolveModel: vi.fn().mockResolvedValue("anthropic/claude-opus-4.7"),
- tools: new Map<string, HarnessToolDefinition>([
+ tools: new Map([
[
"add",
{
@@ -5724,7 +5577,7 @@ describe("createToolLoopHarness", () => {
const config: ToolLoopHarnessConfig = {
mode: "conversation",
resolveModel: vi.fn().mockResolvedValue("anthropic/claude-opus-4.7"),
- tools: new Map<string, HarnessToolDefinition>([
+ tools: new Map([
[
"web_search",
{
@@ -6881,24 +6734,7 @@ describe("createToolLoopHarness", () => {
});
const harness = createToolLoopHarness(
- createTestConfig("conversation", undefined, {
- capabilities: { requestInput: true },
- tools: new Map<string, HarnessToolDefinition>([
- [
- "web_search",
- {
- behavior: {
- availability: [],
- handling: { kind: "provider-tool", provider: "exa" },
- },
- description: "Search the web",
- inputSchema: jsonSchema({}),
- name: "web_search",
- },
- ],
- ["ask_question", createQuestionHarnessTool()],
- ]),
- }),
+ createTestConfig("conversation", undefined, { tools: new Map() }),
);
const result = await harness(
createTestSession({
@@ -7028,21 +6864,7 @@ describe("createToolLoopHarness", () => {
const harness = createToolLoopHarness(
createTestConfig("conversation", undefined, {
capabilities: { requestInput: true },
- tools: new Map<string, HarnessToolDefinition>([
- [
- "web_search",
- {
- behavior: {
- availability: [],
- handling: { kind: "provider-tool", provider: "exa" },
- },
- description: "Search the web",
- inputSchema: jsonSchema({}),
- name: "web_search",
- },
- ],
- ["ask_question", createQuestionHarnessTool()],
- ]),
+ tools: createQuestionToolMap(),
}),
);
const result = await harness(
@@ -8254,8 +8076,7 @@ describe("createToolLoopHarness", () => {
},
};
const config = createTestConfig("conversation", undefined, {
- capabilities: { requestInput: true },
- tools: new Map<string, HarnessToolDefinition>([
+ tools: new Map([
[
"bash",
{
@@ -8431,7 +8252,7 @@ describe("createToolLoopHarness", () => {
});
const config = createTestConfig("conversation", undefined, {
capabilities: { requestInput: true },
- tools: new Map<string, HarnessToolDefinition>([
+ tools: new Map([
[
"bash",
{
@@ -8441,7 +8262,7 @@ describe("createToolLoopHarness", () => {
name: "bash",
},
],
- ["ask_question", createQuestionHarnessTool()],
+ ...createQuestionToolMap(),
]),
});
@@ -8672,7 +8493,7 @@ describe("createToolLoopHarness", () => {
});
const config = createTestConfig("conversation", undefined, {
- tools: new Map<string, HarnessToolDefinition>([
+ tools: new Map([
[
"guarded_echo",
{
@@ -9162,7 +8983,7 @@ describe("createToolLoopHarness", () => {
};
const config = createTestConfig("conversation", undefined, {
capabilities: { requestInput: true },
- tools: new Map<string, HarnessToolDefinition>([
+ tools: new Map([
[
"bash",
{
@@ -9172,7 +8993,18 @@ describe("createToolLoopHarness", () => {
name: "bash",
},
],
- ["ask_question", createQuestionHarnessTool()],
+ [
+ "ask_question",
+ {
+ behavior: {
+ availability: ["requires-request-input"],
+ handling: { kind: "request-input", request: "question" },
+ },
+ description: "Ask the user a question.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "ask_question",
+ },
+ ],
]),
});
const runStep = createToolLoopHarness(config);
@@ -9237,7 +9069,7 @@ describe("createToolLoopHarness", () => {
const runStep = createToolLoopHarness(
createTestConfig("conversation", emit, {
capabilities: { requestInput: true },
- tools: new Map([["ask_question", createQuestionHarnessTool()]]),
+ tools: createQuestionToolMap(),
}),
);
const session = createTestSession({
@@ -9286,78 +9118,6 @@ describe("createToolLoopHarness", () => {
});
});
- it("uses dynamic override metadata when ask_question becomes an ordinary tool", async () => {
- const toolCall = {
- input: { prompt: "Handled inline." },
- toolCallId: "dynamic-question-1",
- toolName: "ask_question",
- type: "tool-call" as const,
- };
- const toolResult = {
- input: toolCall.input,
- output: { handled: true },
- toolCallId: toolCall.toolCallId,
- toolName: toolCall.toolName,
- type: "tool-result" as const,
- };
- setupMockAgent({
- content: [toolCall, toolResult],
- finishReason: "tool-calls",
- response: {
- messages: [
- { content: [toolCall], role: "assistant" },
- {
- content: [
- {
- output: { type: "json", value: toolResult.output },
- toolCallId: toolCall.toolCallId,
- toolName: toolCall.toolName,
- type: "tool-result",
- },
- ],
- role: "tool",
- },
- ],
- },
- text: "",
- toolCalls: [toolCall],
- toolResults: [toolResult],
- });
-
- registerDurableDynamicCallback({
- callback: () => ({ handled: true }),
- phase: "execute",
- toolName: "ask_question",
- });
- const ctx = new ContextContainer();
- ctx.set(StepDynamicToolMetadataKey, [
- {
- callbacks: { execute: { closure: {} } },
- description: "Handle a question inline.",
- entryKey: "ask_question",
- inputSchema: { type: "object" },
- name: "ask_question",
- resolverSlug: "question-override",
- },
- ]);
- const { emit, events } = createEventCollector();
- const runStep = createToolLoopHarness(
- createTestConfig("conversation", emit, {
- capabilities: { requestInput: true },
- tools: new Map([["ask_question", createQuestionHarnessTool()]]),
- }),
- );
- const result = await contextStorage.run(ctx, () =>
- runStep(createTestSession(), { message: "Handle this inline." }),
- );
-
- expect(typeof result.next).toBe("function");
- expect(hasPendingInputBatch(result.session.state)).toBe(false);
- expect(events.filter((event) => event.type === "input.requested")).toEqual([]);
- expect(events.filter((event) => event.type === "actions.requested")).toHaveLength(1);
- expect(events.filter((event) => event.type === "action.result")).toHaveLength(1);
- });
-
it("delivers a stale ask_question selection as a new user turn while another question is pending", async () => {
const nextQuestionInput = {
allowFreeform: false,
@@ -9410,7 +9170,7 @@ describe("createToolLoopHarness", () => {
const runStep = createToolLoopHarness(
createTestConfig("conversation", emit, {
capabilities: { requestInput: true },
- tools: new Map([["ask_question", createQuestionHarnessTool()]]),
+ tools: createQuestionToolMap(),
}),
);
const questionInput = {
@@ -9509,7 +9269,8 @@ describe("createToolLoopHarness", () => {
const { emit, events } = createEventCollector();
const runStep = createToolLoopHarness(
createTestConfig("conversation", emit, {
- tools: new Map([["ask_question", createQuestionHarnessTool()]]),
+ capabilities: { requestInput: true },
+ tools: createQuestionToolMap(),
}),
);
const questionInput = {
@@ -11757,7 +11518,7 @@ describe("createToolLoopHarness", () => {
expect(started).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
callId: "call-delegate",
- kind: "subagent-call",
+ kind: "tool-call",
name: "delegate",
type: "action.started",
}),
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 085492edc..a25f9c81a 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -62,12 +62,14 @@ import {
type UnstampedMessageStreamEvent,
} from "#protocol/message.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
-import { resolveAgentsAnnouncement } from "#harness/handles/prompt.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
+import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import { projectParkedAgentHandles, resolveAgentsAnnouncement } from "#subagents/handles/prompt.js";
+import { getAgentHandleStore } from "#subagents/handles/store.js";
import {
- getWorkflowRuntimeActionInterrupts,
- isWorkflowRuntimeActionInterrupt,
-} from "#harness/workflow-runtime-action-state.js";
+ getWorkflowTaskInterrupts,
+ isWorkflowTaskInterrupt,
+} from "#harness/workflow-task-state.js";
import type { InputRequest } from "#shared/input.js";
import {
hydrateSandboxAttachments,
@@ -141,8 +143,6 @@ import {
shouldPrepareApprovalReplayTools,
} from "#harness/approval-delivery-coordinator.js";
import type { InstrumentationAttempt, InstrumentationStepScope } from "#instrumentation/runtime.js";
-import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
import {
consumeDeferredStepInput,
getApprovedTools,
@@ -187,12 +187,14 @@ import {
import { summarizeKnownError, type SemanticErrorSummary } from "#harness/semantic-errors/index.js";
import { throwIfTurnAborted } from "#harness/turn-cancellation.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
-import type { PreparedDispatchTarget } from "#tools/behavior.js";
import { EMPTY_DELIVERY_SENTINEL, hasEmptyDeliverySentinel } from "#shared/empty-delivery.js";
import { resolveDeliveryPolicy } from "#tasks/delivery-policy.js";
import { extractWorkflowStreamWriteErrorDetails } from "#harness/workflow-stream-error.js";
import { getAdvertisedTools } from "#harness/advertised-tools.js";
-import { createBackgroundToolCallBatch } from "#harness/background-tools.js";
+import {
+ BackgroundToolExecutorKey,
+ createBackgroundToolCallBatch,
+} from "#harness/background-tools.js";
import {
applyLastToolCacheBreakpoint,
applySystemCacheBreakpoint,
@@ -201,10 +203,10 @@ import {
} from "#harness/prompt-cache.js";
import { resolveFrameworkToolFromUpstreamType } from "#harness/provider-tools.js";
import {
- createPendingDispatchActionFromToolCall,
- resolvePendingRuntimeActions,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
+ createCoordinationRequestFromToolCall,
+ resolvePendingCoordination,
+ setPendingCoordinationBatch,
+} from "#harness/coordination.js";
import {
getInvalidToolCallInputError,
isInvalidToolCall,
@@ -223,7 +225,6 @@ import {
unwrapWorkflowSandboxResult,
} from "#shared/workflow-sandbox.js";
import { buildFinalOutputTool, FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
import type { RunMode } from "#shared/run-mode.js";
import { createHistoryViewPreparer, type HistoryViewProjector } from "#shared/history-view.js";
@@ -449,13 +450,6 @@ function buildHarnessToolsWithDynamicSubagents(
return effectiveTools;
}
-function hasDispatchTarget(tools: HarnessToolMap, kind: PreparedDispatchTarget["kind"]): boolean {
- return [...tools.values()].some(
- (tool) =>
- tool.behavior?.handling?.kind === "dispatch" && tool.behavior.handling.target.kind === kind,
- );
-}
-
export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const baseEmit = config.handleEvent;
const resolveApprovalKey = resolveApprovalKeyFromTools(config.tools);
@@ -498,13 +492,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
let emissionState = getHarnessEmissionState(session.state);
const store = contextStorage.getStore();
const parent = store?.get(ParentSessionKey);
- const channel = store?.get(ChannelKey);
const callback = store?.get(SessionCallbackKey);
const hasDelegatedCaller = parent !== undefined || callback !== undefined;
- const taskOwned =
- callback?.taskId !== undefined ||
- readTaskIdFromInboxToken(String(channel?.state?.parentContinuationToken ?? "")) !== undefined;
- const taskUpdatesEnabled = taskOwned && hasDispatchTarget(config.tools, "task-update");
let activeAttemptScope: InstrumentationAttempt | undefined;
const emit =
stepInstrumentation?.createHandleEvent({
@@ -622,7 +611,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
return { next: null, session };
}
- // Resolve deferred input, runtime actions, then HITL input; each stage
+ // Resolve deferred input, task/control coordination, then HITL input; each stage
// may park when its resume payload has not arrived.
const stepInput = consumeDeferredStepInput({
@@ -633,23 +622,23 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
});
session = stepInput.session;
- const resolvedRuntimeActions = await resolvePendingRuntimeActions({
+ const resolvedCoordination = await resolvePendingCoordination({
emit,
session,
stepInput: stepInput.input,
tools: config.tools,
});
- if (resolvedRuntimeActions.outcome === "unresolved") {
- return { next: null, session: resolvedRuntimeActions.session };
+ if (resolvedCoordination.outcome === "unresolved") {
+ return { next: null, session: resolvedCoordination.session };
}
- session = resolvedRuntimeActions.session;
+ session = resolvedCoordination.session;
// Stale-response handling is two passes: drop what must never reach the
// model (session-limit continuation answers), then convert what should
// reach it as plain text.
const pendingRequestIds = getPendingInputRequestIds(session.state);
const staleConversion = convertStaleResponsesToUserMessage({
- history: resolvedRuntimeActions.messages,
+ history: resolvedCoordination.messages,
pendingRequestIds,
stepInput: dropStaleSessionLimitContinuationResponses({
pendingRequestIds,
@@ -665,11 +654,11 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const approvalContext = contextStorage.getStore();
if (
- shouldPrepareApprovalReplayTools({ session, stepInput: effectiveStepInput }) &&
approvalContext !== undefined &&
- config.prepareStepDynamicTools !== undefined
+ config.resolveStepDynamicTools !== undefined &&
+ shouldPrepareApprovalReplayTools({ session, stepInput: effectiveStepInput })
) {
- await config.prepareStepDynamicTools({
+ await config.resolveStepDynamicTools({
ctx: approvalContext,
event: createStepStartedEvent({
modelId: session.agent.modelReference?.id ?? "dynamic",
@@ -677,10 +666,9 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
stepIndex: emissionState.stepIndex,
turnId: emissionState.turnId,
}),
- messages: projectHistory(resolvedRuntimeActions.messages, session.state),
+ messages: projectHistory(resolvedCoordination.messages, session.state),
});
}
- // Only persisted policy work can invoke a dynamic tool's approval.response callback.
const responseAuthorizationTools = shouldPrepareApprovalPolicyTools({
session,
stepInput: effectiveStepInput,
@@ -819,19 +807,19 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const pending = resolvePendingInput({
deferMessagesWhileApprovalsPending: config.mode !== "conversation",
- history: resolvedRuntimeActions.messages,
+ history: resolvedCoordination.messages,
resolveApprovalKey,
session,
stepInput: coordinated.stepInput,
});
if (pending.outcome === "unresolved") {
- // The runtime-action batch owns the assistant messages. Once that batch
+ // The coordination batch owns the assistant messages. Once that batch
// resolves, commit its results before the still-pending HITL batch parks.
let parkedSession =
- resolvedRuntimeActions.outcome === "resolved"
+ resolvedCoordination.outcome === "resolved"
? {
...pending.session,
- history: [...resolvedRuntimeActions.messages],
+ history: [...resolvedCoordination.messages],
}
: pending.session;
@@ -885,7 +873,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
};
}
- if (resolvedRuntimeActions.outcome === "resolved") {
+ if (resolvedCoordination.outcome === "resolved") {
if (emit && config.mode === "conversation") {
emissionState = await emitTurnEpilogue(emit, emissionState, config.mode);
parkedSession = setHarnessEmissionState(parkedSession, emissionState);
@@ -1047,12 +1035,22 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
// assistant-final histories. See resolveAgentsAnnouncement for the role
// rationale (assistant-final rejection, prompt-cache preservation).
const agentStore = getAgentHandleStore(session.state);
- if (
- agentStore !== undefined &&
- !hasUnansweredToolCall(messages) &&
- agentStore.handles.some((handle) => handle.phase === "addressed") !== true
- ) {
+ if (!hasUnansweredToolCall(messages)) {
+ const taskAgentViews = await store?.get(BackgroundToolExecutorKey)?.readAgentViews?.();
+ const agentViews =
+ taskAgentViews === undefined || taskAgentViews.length === 0
+ ? undefined
+ : [
+ ...projectParkedAgentHandles(agentStore ?? { handles: [] }).map((handle) => ({
+ availability: "available" as const,
+ id: handle.identity.id,
+ name: handle.identity.name,
+ statusLine: handle.phase === "parked" ? handle.lastStatus : undefined,
+ })),
+ ...taskAgentViews,
+ ];
const announcement = resolveAgentsAnnouncement({
+ agentViews,
messages: projectHistory(messages, session.state),
store: agentStore,
});
@@ -1250,7 +1248,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
suppressStepStartedEmission?: boolean;
trailingUserNote?: string;
};
- let modelCallRuntimeActionTools = config.tools;
+ let modelCallCoordinationTools = config.tools;
const runSingleModelCall = async (
opts: ModelCallOptions & { readonly attemptIndex: number },
@@ -1272,12 +1270,10 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);
const backgroundBatch = createBackgroundToolCallBatch();
const advertisedHarnessTools = getAdvertisedTools({
- canRequestInput: config.capabilities?.requestInput === true,
- delegatedCaller: taskUpdatesEnabled,
session,
tools: harnessTools,
});
- const effectiveHarnessTools = new Map(advertisedHarnessTools);
+ modelCallCoordinationTools = advertisedHarnessTools;
const flatTools = await buildToolSetWithProviderTools({
approvedTools,
@@ -1290,8 +1286,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
if (ctx !== undefined) {
const dynamicTools = getAdvertisedTools({
- canRequestInput: config.capabilities?.requestInput === true,
- delegatedCaller: taskUpdatesEnabled,
session,
tools: buildDynamicTools(ctx),
});
@@ -1302,22 +1296,14 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
disabledProviderTools: opts.disabledProviderTools,
tools: dynamicTools,
});
- const dynamicToolsByName = new Map<string, HarnessToolDefinition>();
- for (const definition of dynamicTools) {
- if (!dynamicToolsByName.has(definition.name)) {
- dynamicToolsByName.set(definition.name, definition);
- }
- }
// Dynamic tools override a same-named authored tool.
for (const [name, toolDefinition] of Object.entries(dynamicToolSet)) {
- if (advertisedHarnessTools.get(name)?.behavior?.handling?.kind === "dispatch") {
- throw new Error(`Dynamic tool "${name}" collides with a runtime-visible subagent.`);
- }
- const dynamicDefinition = dynamicToolsByName.get(name);
- if (dynamicDefinition === undefined) {
- throw new Error(`Dynamic tool "${name}" has no effective harness definition.`);
+ const advertised = advertisedHarnessTools.get(name);
+ if (advertised?.runtimeAction !== undefined || advertised?.workflowId !== undefined) {
+ throw new Error(
+ `Dynamic tool "${name}" collides with a coordination-visible deferred tool.`,
+ );
}
- effectiveHarnessTools.set(name, dynamicDefinition);
flatTools[name] = toolDefinition;
}
}
@@ -1330,15 +1316,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
config.workflow === true ? { maxSubagents: config.workflowMaxSubagents } : undefined;
const advertisedModelTools = await getAdvertisedTools({
- canRequestInput: config.capabilities?.requestInput === true,
- delegatedCaller: taskUpdatesEnabled,
modelTools: flatTools,
session,
- tools: effectiveHarnessTools,
+ tools: advertisedHarnessTools,
workflow: workflowConfig,
});
session = advertisedModelTools.session;
- modelCallRuntimeActionTools = advertisedModelTools.harnessTools;
const modelTools = advertisedModelTools.modelTools;
const effectiveTools = marker ? applyLastToolCacheBreakpoint(modelTools, marker) : modelTools;
@@ -1411,17 +1394,13 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const hiddenRuntimeActionToolNames = [...config.tools]
.filter(
([name, tool]) =>
- tool.behavior?.handling?.kind === "dispatch" &&
- effectiveHarnessTools.get(name) === undefined,
+ tool.runtimeAction !== undefined && advertisedHarnessTools.get(name) === undefined,
)
.map(([name]) => name);
- const requestInputToolNames = [...effectiveHarnessTools.values()]
- .filter((tool) => tool.behavior?.handling?.kind === "request-input")
- .map((tool) => tool.name);
const excludedActionToolNames = new Set([
+ ASK_QUESTION_TOOL_NAME,
FINAL_OUTPUT_TOOL_NAME,
...hiddenRuntimeActionToolNames,
- ...requestInputToolNames,
]);
const streamResult = await agent.stream({
abortSignal: config.abortSignal,
@@ -1435,7 +1414,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
trailingInlineToolResultParts,
} = await emitStreamContent(emit, emissionState, streamResult.fullStream, {
excludedActionToolNames,
- tools: effectiveHarnessTools,
+ tools: advertisedHarnessTools,
});
throwIfTurnAborted(config.abortSignal);
const [stepResult, accumulatedResponseMessages] = await Promise.all([
@@ -1455,7 +1434,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
excludedActionCallIds: invalidInputToolCallIds,
excludedActionToolNames,
handledInlineToolResultCallIds,
- tools: effectiveHarnessTools,
+ tools: advertisedHarnessTools,
});
const existingToolResults = stepResult.toolResults as TypedToolResult<ToolSet>[];
const toolResultsByCallId = new Map(
@@ -1783,7 +1762,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
} catch {
modelTag = undefined;
}
- const attributeWrite = setEveAttributes({
+ await setEveAttributes({
"$eve.model": modelTag,
"$eve.input_tokens": nextTurnUsage.inputTokens,
"$eve.output_tokens": nextTurnUsage.outputTokens,
@@ -1791,40 +1770,22 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
"$eve.cache_write_tokens": nextTurnUsage.cacheWriteTokens,
"$eve.cost_usd": nextTurnUsage.sawCost ? nextTurnUsage.costUsd : undefined,
"$eve.tool_count": config.tools.size,
- }).catch((error: unknown) => {
- // `setEveAttributes` owns this best-effort boundary. Keep the overlap
- // defensive if a future implementation accidentally lets a rejection
- // escape before result handling reaches the join below.
- logError(log, "Workflow attribute write failed unexpectedly", error, {
- sessionId: session.sessionId,
- turnId: emissionState.turnId,
- });
});
// --- Handle result ------------------------------------------------------
- // Overlap the best-effort attribute write with result processing, including
- // the terminal stream epilogue, but keep it inside this step's lifetime so
- // cumulative writes cannot reorder or race the workflow's terminal state.
- let stepResult: StepResult;
- try {
- stepResult = await handleStepResult({
- config,
- emit,
- emissionState,
- delegatedCaller: taskUpdatesEnabled,
- durableModelPromptMessageCount:
- ephemeralContextMessages.length === 0 ? projectedMessages.length : undefined,
- promptMessages: messages,
- result,
- runStep,
- session,
- runtimeActionTools: modelCallRuntimeActionTools,
- });
- } finally {
- await attributeWrite;
- }
- return stepResult;
+ return handleStepResult({
+ config,
+ emit,
+ emissionState,
+ durableModelPromptMessageCount:
+ ephemeralContextMessages.length === 0 ? projectedMessages.length : undefined,
+ promptMessages: messages,
+ result,
+ runStep,
+ session,
+ coordinationTools: modelCallCoordinationTools,
+ });
}
return runStep;
@@ -2348,12 +2309,11 @@ async function handleStepResult(input: {
readonly config: ToolLoopHarnessConfig;
readonly emit?: ToolLoopHarnessConfig["handleEvent"];
readonly emissionState: ReturnType<typeof getHarnessEmissionState>;
- readonly delegatedCaller: boolean;
readonly durableModelPromptMessageCount?: number;
readonly promptMessages: readonly ModelMessage[];
readonly result: HarnessStepResult;
readonly runStep: StepFn;
- readonly runtimeActionTools: HarnessToolMap;
+ readonly coordinationTools: HarnessToolMap;
readonly session: HarnessSession;
}): Promise<StepResult> {
const { config, emit, promptMessages, result, runStep } = input;
@@ -2418,7 +2378,7 @@ async function handleStepResult(input: {
workflowContinuationSecurity,
);
if (workflowInterrupt !== undefined) {
- if (!isWorkflowRuntimeActionInterrupt(workflowInterrupt)) {
+ if (!isWorkflowTaskInterrupt(workflowInterrupt)) {
throw new Error(`Unsupported Workflow interrupt kind "${workflowInterrupt.payload.kind}".`);
}
return await parkOnWorkflowInterrupt({
@@ -2428,7 +2388,7 @@ async function handleStepResult(input: {
interrupt: workflowInterrupt,
promptMessages,
responseMessages,
- tools: input.runtimeActionTools,
+ tools: input.coordinationTools,
usedCalls: 0,
});
}
@@ -2441,8 +2401,8 @@ async function handleStepResult(input: {
const approvalRequestCallIds = new Set(approvalRequests.map((request) => request.action.callId));
const questionRequests = extractQuestionInputRequests({
toolCalls: result.toolCalls,
- tools: input.runtimeActionTools,
excludedCallIds: new Set([...invalidInputToolCallIds, ...approvalRequestCallIds]),
+ tools: input.coordinationTools,
});
const inputRequests: InputRequest[] = [...approvalRequests, ...questionRequests];
const pendingApprovals = renderPendingApprovalsSnippet(approvalRequests);
@@ -2461,28 +2421,18 @@ async function handleStepResult(input: {
? []
: [{ content: pendingApprovals, role: "user" as const }]),
];
- const advertisedRuntimeActionTools = getAdvertisedTools({
- canRequestInput: input.config.capabilities?.requestInput === true,
- delegatedCaller: input.delegatedCaller,
+ const advertisedCoordinationTools = getAdvertisedTools({
session: baseSession,
- tools: input.runtimeActionTools,
+ tools: input.coordinationTools,
});
- const pendingRuntimeActions = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[])
+ const pendingCoordination = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[])
.filter((toolCall) => !invalidInputToolCallIds.has(toolCall.toolCallId))
- .filter(
- (toolCall) =>
- input.runtimeActionTools.get(toolCall.toolName)?.behavior?.handling?.kind === "dispatch" &&
- input.runtimeActionTools.get(toolCall.toolName)?.execution !== "background",
- )
+ .filter((toolCall) => isDeferredHarnessTool(input.coordinationTools.get(toolCall.toolName)))
.filter((toolCall) => {
- if (
- advertisedRuntimeActionTools.get(toolCall.toolName)?.behavior?.handling?.kind ===
- "dispatch" &&
- advertisedRuntimeActionTools.get(toolCall.toolName)?.execution !== "background"
- ) {
+ if (isDeferredHarnessTool(advertisedCoordinationTools.get(toolCall.toolName))) {
return true;
}
- log.warn("runtime action tool call blocked because tool is not advertised", {
+ log.warn("deferred tool call blocked because tool is not advertised", {
callId: toolCall.toolCallId,
sessionId: baseSession.sessionId,
toolName: toolCall.toolName,
@@ -2490,13 +2440,19 @@ async function handleStepResult(input: {
return false;
})
.map((toolCall) =>
- createPendingDispatchActionFromToolCall({
+ createCoordinationRequestFromToolCall({
toolCall,
- tools: advertisedRuntimeActionTools,
+ tools: advertisedCoordinationTools,
}),
);
- if (pendingRuntimeActions.length > 0) {
+ if (pendingCoordination.length > 0) {
+ const runtimeActions = pendingCoordination.flatMap((entry) =>
+ entry.kind === "runtime-action" ? [entry.request] : [],
+ );
+ const tasks = pendingCoordination.flatMap((entry) =>
+ entry.kind === "task" ? [entry.request] : [],
+ );
// Stamp the live emission state onto the parked session so the
// resume turn is classified as a continuation (turnId set), not a
// fresh turn. Every other park path does this; without it the
@@ -2507,8 +2463,9 @@ async function handleStepResult(input: {
return {
next: null,
session: setHarnessEmissionState(
- setPendingRuntimeActionBatch({
- actions: pendingRuntimeActions,
+ setPendingCoordinationBatch({
+ runtimeActions,
+ tasks,
event: {
sequence: emissionState.sequence,
stepIndex: emissionState.stepIndex,
@@ -2522,8 +2479,9 @@ async function handleStepResult(input: {
};
}
- let parkedSession = setPendingRuntimeActionBatch({
- actions: pendingRuntimeActions,
+ let parkedSession = setPendingCoordinationBatch({
+ runtimeActions,
+ tasks,
event: {
sequence: emissionState.sequence,
stepIndex: emissionState.stepIndex,
@@ -2533,7 +2491,7 @@ async function handleStepResult(input: {
session: { ...baseSession, history: parkedInputHistory },
});
- // The runtime-action batch already owns the shared assistant response.
+ // The coordination batch already owns the shared assistant response.
parkedSession = appendPendingInputBatch({
event: {
sequence: emissionState.sequence,
@@ -2733,6 +2691,13 @@ async function handleStepResult(input: {
});
}
+function isDeferredHarnessTool(tool: HarnessToolDefinition | undefined): boolean {
+ return (
+ tool?.runtimeAction !== undefined ||
+ (tool?.workflowId !== undefined && tool.execution !== "background")
+ );
+}
+
const OUTPUT_SCHEMA_NOT_FULFILLED = {
code: "OUTPUT_SCHEMA_NOT_FULFILLED",
message: "The agent could not produce a result matching the requested schema.",
@@ -2771,7 +2736,6 @@ async function emitStructuredResult(
emissionState: ReturnType<typeof getHarnessEmissionState>,
structured: JsonValue,
mode: RunMode,
- messages: readonly ModelMessage[],
): Promise<ReturnType<typeof getHarnessEmissionState>> {
await emit(
createResultCompletedEvent({
@@ -2781,7 +2745,7 @@ async function emitStructuredResult(
turnId: emissionState.turnId,
}),
);
- return emitTurnEpilogue(emit, emissionState, mode, messages);
+ return emitTurnEpilogue(emit, emissionState, mode);
}
/**
@@ -2803,7 +2767,7 @@ async function finishTaskTurn(input: {
if (schema === undefined) {
if (emit) {
- emissionState = await emitTurnEpilogue(emit, emissionState, "task", session.history);
+ emissionState = await emitTurnEpilogue(emit, emissionState, "task");
session = setHarnessEmissionState(session, emissionState);
}
return { next: { done: true, output: stepOutput ?? "" }, session };
@@ -2827,13 +2791,7 @@ async function finishTaskTurn(input: {
session = persistStructuredAssistantTurn(session, history, structured);
if (emit) {
- emissionState = await emitStructuredResult(
- emit,
- emissionState,
- structured,
- "task",
- session.history,
- );
+ emissionState = await emitStructuredResult(emit, emissionState, structured, "task");
session = setHarnessEmissionState(session, emissionState);
}
return { next: { done: true, output: structured }, session };
@@ -2858,7 +2816,7 @@ async function finishConversationTurn(input: {
if (schema === undefined) {
if (emit) {
- emissionState = await emitTurnEpilogue(emit, emissionState, "conversation", session.history);
+ emissionState = await emitTurnEpilogue(emit, emissionState, "conversation");
session = setHarnessEmissionState(session, emissionState);
}
const settledTurn = { output: stepOutput ?? "" } satisfies SettledTurn;
@@ -2886,13 +2844,7 @@ async function finishConversationTurn(input: {
session = persistStructuredAssistantTurn(session, history, structured);
if (emit) {
- emissionState = await emitStructuredResult(
- emit,
- emissionState,
- structured,
- "conversation",
- session.history,
- );
+ emissionState = await emitStructuredResult(emit, emissionState, structured, "conversation");
session = setHarnessEmissionState(session, emissionState);
}
const settledTurn = { output: structured } satisfies SettledTurn;
@@ -2913,12 +2865,12 @@ async function continuePendingWorkflowInterrupt(input: {
if (pending === undefined) return null;
const interrupt = pending.interrupt;
- if (!isWorkflowRuntimeActionInterrupt(interrupt)) {
+ if (!isWorkflowTaskInterrupt(interrupt)) {
throw new Error(`Unsupported Workflow interrupt kind "${interrupt.payload.kind}".`);
}
const childResults = input.childResults ?? [];
- const pendingInterrupts = getWorkflowRuntimeActionInterrupts(interrupt);
+ const pendingInterrupts = getWorkflowTaskInterrupts(interrupt);
if (input.emit !== undefined && childResults.length > 0) {
await emitWorkflowActionResults({
emit: input.emit,
@@ -2956,11 +2908,11 @@ async function continuePendingWorkflowInterrupt(input: {
continuationSecurity,
);
if (loopUnwrapped.status !== "interrupted") break;
- if (!isWorkflowRuntimeActionInterrupt(loopUnwrapped.interrupt)) break;
+ if (!isWorkflowTaskInterrupt(loopUnwrapped.interrupt)) break;
if (resultIndex + 1 >= childResults.length) break;
- const nextInterrupt = getWorkflowRuntimeActionInterrupts(loopUnwrapped.interrupt)[0];
+ const nextInterrupt = getWorkflowTaskInterrupts(loopUnwrapped.interrupt)[0];
if (nextInterrupt === undefined) {
- throw new Error("Workflow continuation contains no pending runtime-action interrupt.");
+ throw new Error("Workflow continuation contains no pending workflow-task interrupt.");
}
resultIndex++;
currentInterrupt = nextInterrupt;
@@ -2989,7 +2941,7 @@ async function continuePendingWorkflowInterrupt(input: {
});
if (unwrapped.status === "interrupted") {
- if (!isWorkflowRuntimeActionInterrupt(unwrapped.interrupt)) {
+ if (!isWorkflowTaskInterrupt(unwrapped.interrupt)) {
throw new Error(`Unsupported Workflow interrupt kind "${unwrapped.interrupt.payload.kind}".`);
}
const promptMessageCount = input.session.history.length;
@@ -3043,10 +2995,10 @@ async function parkOnWorkflowInterrupt(input: {
readonly tools: HarnessToolMap;
readonly usedCalls: number;
}): Promise<StepResult> {
- const interrupts = getWorkflowRuntimeActionInterrupts(input.interrupt);
+ const interrupts = getWorkflowTaskInterrupts(input.interrupt);
const interrupt = interrupts[0];
if (interrupt === undefined) {
- throw new Error("Workflow continuation contains no pending runtime-action interrupt.");
+ throw new Error("Workflow continuation contains no pending workflow-task interrupt.");
}
if (input.emit !== undefined) {
diff --git a/packages/eve/src/harness/tool-runs.test.ts b/packages/eve/src/harness/tool-runs.test.ts
deleted file mode 100644
index 246860765..000000000
--- a/packages/eve/src/harness/tool-runs.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- clearToolRuns,
- findToolRun,
- getToolRuns,
- isInboxToolResultFromRecordedRun,
- recordToolRun,
- removeToolRun,
-} from "#harness/tool-runs.js";
-import type { HarnessSession } from "#harness/types.js";
-
-const RECORD = {
- callId: "call_1",
- hookToken: "eve:tool-run:abc",
- runId: "wrun_1",
- toolName: "deploy",
-};
-
-function session(state?: HarnessSession["state"]): HarnessSession {
- return { state } as HarnessSession;
-}
-
-describe("tool run records", () => {
- it("records, finds, and removes runs by call id", () => {
- const recorded = recordToolRun(session({ other: true }), RECORD);
- expect(getToolRuns(recorded.state)).toEqual([RECORD]);
- expect(findToolRun(recorded.state, "call_1")).toEqual(RECORD);
-
- const replaced = recordToolRun(recorded, { ...RECORD, runId: "wrun_2" });
- expect(getToolRuns(replaced.state)).toEqual([{ ...RECORD, runId: "wrun_2" }]);
-
- const removed = removeToolRun(replaced, "call_1");
- expect(getToolRuns(removed.state)).toEqual([]);
- expect(removed.state).toEqual({ other: true });
- expect(removeToolRun(removed, "call_1")).toBe(removed);
- });
-
- it("drops the state map entirely when nothing else is recorded", () => {
- const recorded = recordToolRun(session(), RECORD);
- expect(clearToolRuns(recorded).state).toBeUndefined();
- expect(clearToolRuns(session())).toEqual(session());
- });
-
- it("binds inbox tool results to the recorded run by call id and tool name", () => {
- const state = recordToolRun(session(), RECORD).state;
- const result = {
- callId: "call_1",
- kind: "tool-result" as const,
- output: 1,
- toolName: "deploy",
- };
-
- expect(isInboxToolResultFromRecordedRun(state, result)).toBe(true);
- expect(isInboxToolResultFromRecordedRun(state, { ...result, toolName: "other" })).toBe(false);
- expect(isInboxToolResultFromRecordedRun(state, { ...result, callId: "call_2" })).toBe(false);
- expect(isInboxToolResultFromRecordedRun(undefined, result)).toBe(false);
- });
-
- it("ignores malformed state", () => {
- expect(getToolRuns({ "eve.runtime.toolRuns": { not: "an array" } })).toEqual([]);
- });
-});
diff --git a/packages/eve/src/harness/tool-runs.ts b/packages/eve/src/harness/tool-runs.ts
deleted file mode 100644
index b37033a27..000000000
--- a/packages/eve/src/harness/tool-runs.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
-
-const TOOL_RUNS_STATE_KEY = "eve.runtime.toolRuns";
-export function toolRunAnswerToken(runId: string, seq: number): string {
- return `eve:tool-run-answer:${runId}:${seq}`;
-}
-
-/** A workflow tool run the active turn waits on. Background runs live in the task index. */
-export interface ToolRunRecord {
- readonly callId: string;
- readonly hookToken: string;
- readonly runId: string;
- readonly toolName: string;
-}
-
-// Schema-free: this is bundled into the workflow driver.
-export function getToolRuns(state: SessionStateMap | undefined): readonly ToolRunRecord[] {
- const raw = state?.[TOOL_RUNS_STATE_KEY];
- return Array.isArray(raw) ? (raw as readonly ToolRunRecord[]) : [];
-}
-
-export function findToolRun(
- state: SessionStateMap | undefined,
- callId: string,
-): ToolRunRecord | undefined {
- return getToolRuns(state).find((record) => record.callId === callId);
-}
-
-export function recordToolRun<T extends { readonly state?: SessionStateMap }>(
- session: T,
- record: ToolRunRecord,
-): T {
- const others = getToolRuns(session.state).filter((entry) => entry.callId !== record.callId);
- return writeToolRuns(session, [...others, record]);
-}
-
-export function removeToolRun<T extends { readonly state?: SessionStateMap }>(
- session: T,
- callId: string,
-): T {
- const records = getToolRuns(session.state);
- const remaining = records.filter((entry) => entry.callId !== callId);
- return remaining.length === records.length ? session : writeToolRuns(session, remaining);
-}
-
-export function clearToolRuns(session: HarnessSession): HarnessSession {
- return getToolRuns(session.state).length === 0 ? session : writeToolRuns(session, []);
-}
-
-/** The turn inbox is shared; a result settles a call only if the turn recorded that run. */
-export function isInboxToolResultFromRecordedRun(
- state: SessionStateMap | undefined,
- result: RuntimeToolResultActionResult,
-): boolean {
- const record = findToolRun(state, result.callId);
- return record !== undefined && record.toolName === result.toolName;
-}
-
-function writeToolRuns<T extends { readonly state?: SessionStateMap }>(
- session: T,
- records: readonly ToolRunRecord[],
-): T {
- const state = { ...session.state };
- if (records.length === 0) {
- delete state[TOOL_RUNS_STATE_KEY];
- } else {
- state[TOOL_RUNS_STATE_KEY] = records;
- }
- return { ...session, state: Object.keys(state).length > 0 ? state : undefined };
-}
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index d821284d5..1f318ad18 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -76,7 +76,14 @@ export function buildToolSet(input: {
backgroundBatch.setTool(
definition.name,
definition.execution === "background" && definition.execute !== undefined
- ? (definition as BackgroundExecutableTool)
+ ? {
+ execute: definition.execute,
+ executeInput: definition.executeInput,
+ name: definition.name,
+ nodeId: definition.nodeId,
+ resultKind: definition.resultKind,
+ workflowId: definition.workflowId,
+ }
: undefined,
);
const authorToModelOutput = definition.toModelOutput;
diff --git a/packages/eve/src/harness/turn-tag-state.ts b/packages/eve/src/harness/turn-tag-state.ts
index 47b10948b..036409068 100644
--- a/packages/eve/src/harness/turn-tag-state.ts
+++ b/packages/eve/src/harness/turn-tag-state.ts
@@ -205,7 +205,10 @@ export function takeSessionUsageDelta(session: HarnessSession): {
}
/** Writes per-turn token state onto a new copy of the session. */
-export function setTurnUsageState(session: HarnessSession, next: TurnUsageState): HarnessSession {
+export function setTurnUsageState<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ next: TurnUsageState,
+): T {
return {
...session,
state: {
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index 6866910e6..60f9b422b 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -94,11 +94,8 @@ export interface HarnessSession {
readonly sessionId: string;
readonly sandboxState?: SandboxState;
readonly state?: SessionStateMap;
- /**
- * Number of local delegated subagent hops from the root session to this
- * session. Root sessions are depth 0.
- */
- readonly subagentDepth?: number;
+ /** Framework task that owns this durable session, when present. */
+ readonly taskId?: string;
/**
* Effective maximum subagent calls one `Workflow` invocation may dispatch
* for this session, configured by `experimental_workflow({ maxSubagents })`.
@@ -329,8 +326,8 @@ export interface ToolLoopHarnessConfig {
* compacted history.
*/
readonly onCompaction?: () => readonly ModelMessage[];
- /** Prepares persisted step-scoped tools before an approved call is resumed. */
- readonly prepareStepDynamicTools?: (input: {
+ /** Resolves persisted step-scoped tools before an approval policy reads them. */
+ readonly resolveStepDynamicTools?: (input: {
readonly ctx: AlsContext;
readonly event: StepStartedStreamEvent;
readonly messages: readonly ModelMessage[];
diff --git a/packages/eve/src/harness/workflow-interrupt-state.test.ts b/packages/eve/src/harness/workflow-interrupt-state.test.ts
index e46f39a0f..3e12b40f1 100644
--- a/packages/eve/src/harness/workflow-interrupt-state.test.ts
+++ b/packages/eve/src/harness/workflow-interrupt-state.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
-import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";
import type { SessionStateMap } from "#harness/types.js";
describe("pending workflow interrupt state", () => {
@@ -17,7 +17,7 @@ describe("pending workflow interrupt state", () => {
},
interruptId: "workflow-call:tool-1:interrupt",
outerToolCallId: "workflow-call",
- payload: { kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND },
+ payload: { kind: WORKFLOW_TASK_INTERRUPT_KIND },
type: "code-mode-interrupt",
},
responseMessages: [],
@@ -40,7 +40,7 @@ describe("pending workflow interrupt state", () => {
},
interruptId: "workflow-call:tool-1:interrupt",
outerToolCallId: "workflow-call",
- payload: { kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND },
+ payload: { kind: WORKFLOW_TASK_INTERRUPT_KIND },
type: "code-mode-interrupt",
},
responseMessages: [],
diff --git a/packages/eve/src/harness/workflow-interrupt-state.ts b/packages/eve/src/harness/workflow-interrupt-state.ts
index 5367807bf..fc0f05e4b 100644
--- a/packages/eve/src/harness/workflow-interrupt-state.ts
+++ b/packages/eve/src/harness/workflow-interrupt-state.ts
@@ -1,7 +1,7 @@
import type { ModelMessage } from "ai";
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";
import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
const PENDING_KEY = "eve.harness.pendingWorkflowInterrupt";
@@ -79,7 +79,7 @@ function isWorkflowInterruptShape(value: unknown): value is WorkflowSandboxInter
typeof value.interruptId === "string" &&
typeof value.outerToolCallId === "string" &&
isRecord(value.payload) &&
- value.payload.kind === WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND &&
+ value.payload.kind === WORKFLOW_TASK_INTERRUPT_KIND &&
isRecord(value.continuation) &&
value.continuation.version === 2 &&
typeof value.continuation.outerToolCallId === "string" &&
diff --git a/packages/eve/src/harness/workflow-lifecycle.test.ts b/packages/eve/src/harness/workflow-lifecycle.test.ts
index bedaa770e..effcde85d 100644
--- a/packages/eve/src/harness/workflow-lifecycle.test.ts
+++ b/packages/eve/src/harness/workflow-lifecycle.test.ts
@@ -7,7 +7,7 @@ import {
emitWorkflowActionResults,
emitWorkflowActionsRequested,
} from "#harness/workflow-lifecycle.js";
-import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";
import type { HarnessToolMap } from "#harness/types.js";
import { defineState } from "#public/definitions/state.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -25,20 +25,11 @@ function createTools(): HarnessToolMap {
[
"researcher",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
- },
- },
description: "Delegate to the researcher.",
inputSchema: jsonSchema({ type: "object" }),
name: "researcher",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]);
@@ -46,11 +37,10 @@ function createTools(): HarnessToolMap {
function workflowInterrupt(): WorkflowSandboxInterrupt {
const payload = {
- kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,
- runtimeAction: {
- kind: "subagent-call" as const,
- nodeId: "subagents/researcher",
- subagentName: "researcher",
+ kind: WORKFLOW_TASK_INTERRUPT_KIND,
+ task: {
+ resultKind: "subagent" as const,
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
toolInput: { message: "Investigate" },
toolName: "researcher",
@@ -116,8 +106,8 @@ describe("workflow lifecycle projection", () => {
actions: [
{
callId: "outer-call:tool-1",
- kind: "subagent-call",
- subagentName: "researcher",
+ kind: "tool-call",
+ toolName: "researcher",
},
],
sequence: 2,
diff --git a/packages/eve/src/harness/workflow-lifecycle.ts b/packages/eve/src/harness/workflow-lifecycle.ts
index adad4be1f..01fba3519 100644
--- a/packages/eve/src/harness/workflow-lifecycle.ts
+++ b/packages/eve/src/harness/workflow-lifecycle.ts
@@ -2,7 +2,7 @@ import type { ToolSet, TypedToolCall } from "ai";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import type { HarnessEmissionState } from "#harness/emission.js";
-import { createRuntimeActionRequestFromToolCall } from "#harness/runtime-actions.js";
+import { createRuntimeActionRequestFromToolCall } from "#harness/coordination.js";
import type { HarnessToolMap } from "#harness/types.js";
import {
createActionResultEvent,
@@ -10,6 +10,36 @@ import {
type UnstampedMessageStreamEvent,
} from "#protocol/message.js";
import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
+import {
+ getWorkflowSandboxInterrupt,
+ type WorkflowSandboxContinuationSecurity,
+} from "#shared/workflow-sandbox.js";
+
+export function createWorkflowLifecycle(input: {
+ readonly emit: EmitWorkflowLifecycleEvent;
+ readonly emissionState: HarnessEmissionState;
+ readonly skipReplayed?: boolean;
+ readonly tools: HarnessToolMap;
+}): {
+ onAfterExecute?: (input: { readonly result: unknown }) => Promise<void>;
+} {
+ return {
+ async onAfterExecute(result) {
+ if (input.skipReplayed) return;
+ const interrupt = await getWorkflowSandboxInterrupt(
+ result.result,
+ {} as WorkflowSandboxContinuationSecurity,
+ );
+ if (interrupt === undefined) return;
+ await emitWorkflowActionsRequested({
+ emit: input.emit,
+ emissionState: input.emissionState,
+ interrupts: [interrupt],
+ tools: input.tools,
+ });
+ },
+ };
+}
type EmitWorkflowLifecycleEvent = (event: UnstampedMessageStreamEvent) => Promise<void>;
diff --git a/packages/eve/src/harness/workflow-runtime-action-state.ts b/packages/eve/src/harness/workflow-runtime-action-state.ts
deleted file mode 100644
index 337b98f12..000000000
--- a/packages/eve/src/harness/workflow-runtime-action-state.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { getPendingDispatchActionKey } from "#runtime/actions/keys.js";
-import type { PendingDispatchAction } from "#shared/dispatch-action.js";
-import type { JsonObject } from "#shared/json.js";
-import {
- getWorkflowSandboxPendingInterrupts,
- type WorkflowSandboxInterrupt,
-} from "#shared/workflow-sandbox.js";
-import type { PreparedDispatchTarget } from "#tools/behavior.js";
-
-export const WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND = "eve.workflow-runtime-action";
-
-export function isWorkflowRuntimeActionInterrupt(interrupt: unknown): boolean {
- return (
- isRecord(interrupt) &&
- isRecord(interrupt.payload) &&
- interrupt.payload.kind === WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND
- );
-}
-
-export function buildRuntimeActionFromWorkflowInterrupt(
- interrupt: WorkflowSandboxInterrupt,
-): PendingDispatchAction {
- const raw = interrupt.payload as Record<string, unknown>;
- const dispatchTarget = raw.dispatchTarget as PreparedDispatchTarget;
- const toolInput = raw.toolInput as JsonObject;
- const toolName = raw.toolName as string;
- const interruptId = "interruptId" in interrupt ? String(interrupt.interruptId) : "";
- const callId = sanitizeCallId(`${toolName}_${interruptId}`);
-
- if (
- dispatchTarget.kind === "self-agent-call" ||
- dispatchTarget.kind === "subagent-call" ||
- dispatchTarget.kind === "remote-agent-call"
- ) {
- return {
- callId,
- description: "",
- input: toolInput,
- target: dispatchTarget,
- toolName,
- };
- }
-
- // Dynamic workflows only interrupt on delegation tools; task controls
- // never enter a workflow sandbox.
- throw new Error(`Workflow runtime actions cannot carry "${dispatchTarget.kind}" tools.`);
-}
-
-/** Returns every pending runtime-action interrupt in deterministic request order. */
-export function getWorkflowRuntimeActionInterrupts(
- interrupt: WorkflowSandboxInterrupt,
-): WorkflowSandboxInterrupt[] {
- return getWorkflowSandboxPendingInterrupts(interrupt).filter(isWorkflowRuntimeActionInterrupt);
-}
-
-export function buildRuntimeActionsFromWorkflowInterrupt(
- interrupt: WorkflowSandboxInterrupt,
-): PendingDispatchAction[] {
- return getWorkflowRuntimeActionInterrupts(interrupt).map((pending) =>
- buildRuntimeActionFromWorkflowInterrupt(pending),
- );
-}
-
-export function getRuntimeActionKeysFromWorkflowInterrupt(
- interrupt: WorkflowSandboxInterrupt,
-): string[] {
- return buildRuntimeActionsFromWorkflowInterrupt(interrupt).map(getPendingDispatchActionKey);
-}
-
-function sanitizeCallId(id: string): string {
- return id.replace(/[^a-zA-Z0-9_-]/g, "_");
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/packages/eve/src/harness/workflow-sandbox.scenario.test.ts b/packages/eve/src/harness/workflow-sandbox.scenario.test.ts
index 59e49e0cf..9c77a44e6 100644
--- a/packages/eve/src/harness/workflow-sandbox.scenario.test.ts
+++ b/packages/eve/src/harness/workflow-sandbox.scenario.test.ts
@@ -2,7 +2,7 @@ import { jsonSchema } from "ai";
import { describe, expect, it } from "vitest";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { getWorkflowRuntimeActionInterrupts } from "#harness/workflow-runtime-action-state.js";
+import { getWorkflowTaskInterrupts } from "#harness/workflow-task-state.js";
import {
applyWorkflowTool,
resolveWorkflowSandboxBridgeRequestLimit,
@@ -20,17 +20,6 @@ function orchestrationTools(): HarnessToolMap {
[
"echo-marker",
{
- behavior: {
- availability: [],
- handling: {
- kind: "dispatch",
- target: {
- kind: "subagent-call",
- nodeId: "subagents/echo-marker",
- subagentName: "echo-marker",
- },
- },
- },
description: "Echo one marker.",
inputSchema: jsonSchema({
properties: { message: { type: "string" } },
@@ -38,6 +27,8 @@ function orchestrationTools(): HarnessToolMap {
type: "object",
}),
name: "echo-marker",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
]);
@@ -81,7 +72,7 @@ describe("Workflow concurrent continuation", () => {
);
const interrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);
- expect(getWorkflowRuntimeActionInterrupts(interrupt!)).toHaveLength(highFanOutCount);
+ expect(getWorkflowTaskInterrupts(interrupt!)).toHaveLength(highFanOutCount);
});
it("collects an over-budget call above the default bridge-request floor", async () => {
@@ -102,7 +93,7 @@ describe("Workflow concurrent continuation", () => {
);
const interrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);
- expect(getWorkflowRuntimeActionInterrupts(interrupt!)).toHaveLength(overBudgetFanOutCount);
+ expect(getWorkflowTaskInterrupts(interrupt!)).toHaveLength(overBudgetFanOutCount);
});
it("collects promptly interrupted Promise.all siblings in one ledger", async () => {
@@ -125,7 +116,7 @@ describe("Workflow concurrent continuation", () => {
expect(interrupt!.continuation.auth.expiresAtMs - interrupt!.continuation.auth.issuedAtMs).toBe(
continuationSecurity.maxAgeMs,
);
- expect(getWorkflowRuntimeActionInterrupts(interrupt!).map((entry) => entry.input)).toEqual([
+ expect(getWorkflowTaskInterrupts(interrupt!).map((entry) => entry.input)).toEqual([
{ message: "alpha" },
{ message: "beta" },
]);
@@ -149,7 +140,7 @@ describe("Workflow concurrent continuation", () => {
);
const racedInterrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);
- const pending = getWorkflowRuntimeActionInterrupts(racedInterrupt!);
+ const pending = getWorkflowTaskInterrupts(racedInterrupt!);
expect(pending.map((interrupt) => interrupt.input)).toEqual([
{ message: "alpha" },
{ message: "beta" },
diff --git a/packages/eve/src/harness/workflow-sandbox.test.ts b/packages/eve/src/harness/workflow-sandbox.test.ts
index c31c6740a..c82e4b6f1 100644
--- a/packages/eve/src/harness/workflow-sandbox.test.ts
+++ b/packages/eve/src/harness/workflow-sandbox.test.ts
@@ -31,25 +31,41 @@ function orchestrationTools(): HarnessToolMap {
description: "Delegate to the researcher subagent.",
inputSchema: jsonSchema({ type: "object" }),
name: "researcher",
+ nodeId: "subagents/researcher",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
],
[
"remote_reviewer",
+ {
+ description: "Delegate to the remote reviewer.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "remote_reviewer",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
+ },
+ ],
+ [
+ "agent",
{
behavior: {
- availability: [],
+ availability: ["root-session"],
handling: {
kind: "dispatch",
target: {
- kind: "remote-agent-call",
- nodeId: "subagents/remote-reviewer.ts",
- remoteAgentName: "remote_reviewer",
+ kind: "self-agent-call",
+ nodeId: "__root__",
+ subagentName: "agent",
},
},
},
- description: "Delegate to the remote reviewer.",
+ description: "Delegate to a root-agent copy.",
inputSchema: jsonSchema({ type: "object" }),
- name: "remote_reviewer",
+ name: "agent",
+ nodeId: "__root__",
+ resultKind: "subagent",
+ workflowId: "workflow//eve//subagentToolExecuteWorkflow",
},
],
[
@@ -73,7 +89,7 @@ describe("applyWorkflowTool", () => {
expect(resolveWorkflowSandboxBridgeRequestLimit(300)).toBe(301);
});
- it("adds only agent runtime actions to the sandbox", async () => {
+ it("adds only agent workflow tasks to the sandbox", async () => {
const harnessTools = orchestrationTools();
const flatTools = buildToolSet({ tools: harnessTools });
const { hostTools, modelTools } = await applyWorkflowTool({
@@ -88,6 +104,7 @@ describe("applyWorkflowTool", () => {
expect(modelTools.bash).toBeDefined();
expect(hostTools.researcher?.execute).toBeDefined();
expect(hostTools.remote_reviewer?.execute).toBeDefined();
+ expect(hostTools.agent?.execute).toBeDefined();
expect(hostTools.bash).toBeUndefined();
});
@@ -116,7 +133,7 @@ describe("applyWorkflowTool", () => {
});
});
- it("does not add Workflow when no agent runtime actions exist", async () => {
+ it("does not add Workflow when no agent workflow tasks exist", async () => {
const harnessTools: HarnessToolMap = new Map([
[
"bash",
@@ -145,6 +162,7 @@ describe("applyWorkflowTool", () => {
expect(hostTools.researcher).toBeDefined();
expect(hostTools.remote_reviewer).toBeDefined();
+ expect(hostTools.agent).toBeDefined();
expect(hostTools.bash).toBeUndefined();
});
diff --git a/packages/eve/src/harness/workflow-sandbox.ts b/packages/eve/src/harness/workflow-sandbox.ts
index 99247231f..b8dd8a671 100644
--- a/packages/eve/src/harness/workflow-sandbox.ts
+++ b/packages/eve/src/harness/workflow-sandbox.ts
@@ -3,7 +3,7 @@ import { z } from "#compiled/zod/index.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { HarnessToolMap } from "#harness/types.js";
-import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";
import { DEFAULT_WORKFLOW_MAX_SUBAGENTS } from "#harness/workflow-subagent-limit.js";
import { workflowToolDescription } from "#harness/workflow-tool-description.js";
import {
@@ -31,7 +31,7 @@ const workflowInputSchema = z.strictObject({
/**
* Adds the dynamic `Workflow` tool while leaving every ordinary model tool
- * untouched. Only subagent and remote-agent runtime actions enter the sandbox.
+ * untouched. Only workflow-callable delegation tasks enter the sandbox.
*/
export async function applyWorkflowTool(input: {
readonly continuationSecurity: WorkflowSandboxContinuationSecurity;
@@ -95,22 +95,15 @@ function createWorkflowHostTools(tools: HarnessToolMap, names: Iterable<string>)
for (const name of names) {
const tool = tools.get(name);
- if (tool === undefined) continue;
- const target =
- tool.behavior?.handling?.kind === "dispatch" ? tool.behavior.handling.target : undefined;
- if (
- target?.kind === "self-agent-call" ||
- target?.kind === "subagent-call" ||
- target?.kind === "remote-agent-call"
- ) {
- hostTools[name] = createWorkflowRuntimeActionHostTool(tool);
+ if (tool?.workflowId !== undefined) {
+ hostTools[name] = createWorkflowTaskHostTool(tool);
}
}
return hostTools as ToolSet;
}
-function createWorkflowRuntimeActionHostTool(harnessTool: HarnessToolDefinition): ToolSet[string] {
+function createWorkflowTaskHostTool(harnessTool: HarnessToolDefinition): ToolSet[string] {
return {
description: harnessTool.description,
inputSchema: harnessTool.inputSchema,
@@ -119,11 +112,13 @@ function createWorkflowRuntimeActionHostTool(harnessTool: HarnessToolDefinition)
if (resolution !== undefined) return resolution;
return requestWorkflowSandboxInterrupt({
- dispatchTarget:
- harnessTool.behavior?.handling?.kind === "dispatch"
- ? harnessTool.behavior.handling.target
- : undefined,
- kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,
+ kind: WORKFLOW_TASK_INTERRUPT_KIND,
+ task: {
+ executeInput: harnessTool.executeInput?.(toolInput),
+ nodeId: harnessTool.nodeId,
+ resultKind: harnessTool.resultKind,
+ workflowId: harnessTool.workflowId,
+ },
toolInput,
toolName: harnessTool.name,
});
diff --git a/packages/eve/src/harness/workflow-subagent-limit.test.ts b/packages/eve/src/harness/workflow-subagent-limit.test.ts
index fa882b679..e1a3688dd 100644
--- a/packages/eve/src/harness/workflow-subagent-limit.test.ts
+++ b/packages/eve/src/harness/workflow-subagent-limit.test.ts
@@ -4,52 +4,59 @@ import {
DEFAULT_WORKFLOW_MAX_SUBAGENTS,
planWorkflowSubagentDispatch,
} from "#harness/workflow-subagent-limit.js";
-import type { PendingDispatchAction } from "#shared/dispatch-action.js";
+import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
-function createAction(index: number): PendingDispatchAction {
+function createTask(index: number): RuntimeWorkflowTaskRequest {
return {
callId: `call-${index}`,
- description: "",
input: {},
- target: {
- kind: "subagent-call",
- nodeId: "subagents/echo-marker",
- subagentName: "echo-marker",
- },
+ kind: "workflow-task",
+ resultKind: "subagent",
toolName: "echo-marker",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
};
}
describe("planWorkflowSubagentDispatch", () => {
it("allows every pending action while the budget holds", () => {
- const actions = [createAction(1), createAction(2)];
+ const tasks = [createTask(1), createTask(2)];
const plan = planWorkflowSubagentDispatch({
- actions,
+ tasks,
maxSubagents: 3,
usedCalls: 0,
});
- expect(plan.allowed).toEqual(actions);
+ expect(plan.allowed).toEqual(tasks);
expect(plan.blocked).toEqual([]);
expect(plan.usedCalls).toBe(0);
});
- it("blocks actions beyond the remaining budget while preserving order", () => {
- const actions = [createAction(1), createAction(2), createAction(3)];
+ it("blocks tasks beyond the remaining budget while preserving order", () => {
+ const tasks = [createTask(1), createTask(2), createTask(3)];
const plan = planWorkflowSubagentDispatch({
- actions,
+ tasks,
maxSubagents: 3,
usedCalls: 1,
});
- expect(plan.allowed).toEqual([actions[0], actions[1]]);
- expect(plan.blocked).toEqual([actions[2]]);
+ expect(plan.allowed).toEqual([tasks[0], tasks[1]]);
+ expect(plan.blocked).toEqual([tasks[2]]);
expect(plan.usedCalls).toBe(1);
});
+ it("does not charge ordinary workflow tasks against the subagent budget", () => {
+ const toolTask = { ...createTask(2), resultKind: "tool" as const };
+ const tasks = [createTask(1), toolTask, createTask(3)];
+
+ const plan = planWorkflowSubagentDispatch({ tasks, maxSubagents: 1, usedCalls: 0 });
+
+ expect(plan.allowed).toEqual([tasks[0], toolTask]);
+ expect(plan.blocked).toEqual([tasks[2]]);
+ });
+
it("blocks everything once the persisted budget is spent", () => {
const plan = planWorkflowSubagentDispatch({
- actions: [createAction(1)],
+ tasks: [createTask(1)],
maxSubagents: 2,
usedCalls: 2,
});
@@ -60,7 +67,7 @@ describe("planWorkflowSubagentDispatch", () => {
it("defaults the budget to DEFAULT_WORKFLOW_MAX_SUBAGENTS", () => {
const plan = planWorkflowSubagentDispatch({
- actions: [createAction(1)],
+ tasks: [createTask(1)],
usedCalls: 0,
});
diff --git a/packages/eve/src/harness/workflow-subagent-limit.ts b/packages/eve/src/harness/workflow-subagent-limit.ts
index 3dead1965..aa5279eae 100644
--- a/packages/eve/src/harness/workflow-subagent-limit.ts
+++ b/packages/eve/src/harness/workflow-subagent-limit.ts
@@ -1,4 +1,4 @@
-import type { PendingDispatchAction } from "#shared/dispatch-action.js";
+import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
/**
* Default maximum number of subagent (and remote-agent) calls one `Workflow`
@@ -7,13 +7,13 @@ import type { PendingDispatchAction } from "#shared/dispatch-action.js";
export const DEFAULT_WORKFLOW_MAX_SUBAGENTS = 100;
/**
- * Partition of one workflow interrupt's pending runtime actions against the
- * invocation's subagent budget. `allowed` actions may dispatch; `blocked`
- * actions must resolve with an error result instead of starting a child.
+ * Partition of one workflow interrupt's pending tasks against the invocation's
+ * subagent budget. Allowed tasks may dispatch; blocked tasks resolve with an
+ * error result instead of starting a child.
*/
export type WorkflowSubagentDispatchPlan = {
- readonly allowed: readonly PendingDispatchAction[];
- readonly blocked: readonly PendingDispatchAction[];
+ readonly allowed: readonly RuntimeWorkflowTaskRequest[];
+ readonly blocked: readonly RuntimeWorkflowTaskRequest[];
readonly maxSubagents: number;
readonly usedCalls: number;
};
@@ -25,17 +25,29 @@ export type WorkflowSubagentDispatchPlan = {
* program's call order.
*/
export function planWorkflowSubagentDispatch(input: {
- readonly actions: readonly PendingDispatchAction[];
+ readonly tasks: readonly RuntimeWorkflowTaskRequest[];
readonly maxSubagents?: number;
readonly usedCalls: number;
}): WorkflowSubagentDispatchPlan {
const maxSubagents = input.maxSubagents ?? DEFAULT_WORKFLOW_MAX_SUBAGENTS;
const usedCalls = input.usedCalls;
- const remaining = Math.max(0, maxSubagents - usedCalls);
+ let remaining = Math.max(0, maxSubagents - usedCalls);
+ const allowed: RuntimeWorkflowTaskRequest[] = [];
+ const blocked: RuntimeWorkflowTaskRequest[] = [];
+ for (const task of input.tasks) {
+ if (task.resultKind !== "subagent") {
+ allowed.push(task);
+ } else if (remaining > 0) {
+ allowed.push(task);
+ remaining--;
+ } else {
+ blocked.push(task);
+ }
+ }
return {
- allowed: input.actions.slice(0, remaining),
- blocked: input.actions.slice(remaining),
+ allowed,
+ blocked,
maxSubagents,
usedCalls,
};
diff --git a/packages/eve/src/harness/workflow-runtime-action-state.test.ts b/packages/eve/src/harness/workflow-task-state.test.ts
similarity index 64%
rename from packages/eve/src/harness/workflow-runtime-action-state.test.ts
rename to packages/eve/src/harness/workflow-task-state.test.ts
index ea0bdeef9..abba5deee 100644
--- a/packages/eve/src/harness/workflow-runtime-action-state.test.ts
+++ b/packages/eve/src/harness/workflow-task-state.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
import {
- buildRuntimeActionsFromWorkflowInterrupt,
- getRuntimeActionKeysFromWorkflowInterrupt,
- getWorkflowRuntimeActionInterrupts,
- WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,
-} from "#harness/workflow-runtime-action-state.js";
+ buildWorkflowTasksFromInterrupt,
+ getWorkflowTaskCallIds,
+ getWorkflowTaskInterrupts,
+ WORKFLOW_TASK_INTERRUPT_KIND,
+} from "#harness/workflow-task-state.js";
import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
function concurrentWorkflowInterrupt(): WorkflowSandboxInterrupt {
@@ -15,12 +15,13 @@ function concurrentWorkflowInterrupt(): WorkflowSandboxInterrupt {
input: { message },
interruptId: `${toolCallId}:interrupt`,
payload: {
- dispatchTarget: {
- kind: "subagent-call" as const,
- nodeId: "subagents/echo-marker",
- subagentName: "echo-marker",
+ kind: WORKFLOW_TASK_INTERRUPT_KIND,
+ task: {
+ action: "subagent-call" as const,
+ nodeId: "subagents/researcher",
+ resultKind: "subagent",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
- kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,
toolInput: { message },
toolName: "echo-marker",
},
@@ -59,11 +60,11 @@ function concurrentWorkflowInterrupt(): WorkflowSandboxInterrupt {
};
}
-describe("workflow runtime action state", () => {
- it("derives concurrent actions in request order when a later interrupt wins the race", () => {
+describe("workflow task state", () => {
+ it("derives concurrent tasks in request order when a later interrupt wins the race", () => {
const interrupt = concurrentWorkflowInterrupt();
- const pending = getWorkflowRuntimeActionInterrupts(interrupt);
+ const pending = getWorkflowTaskInterrupts(interrupt);
expect(pending.map((entry) => entry.input)).toEqual([
{ message: "alpha" },
{ message: "beta" },
@@ -73,21 +74,29 @@ describe("workflow runtime action state", () => {
"workflow-call:tool-2",
]);
- expect(buildRuntimeActionsFromWorkflowInterrupt(interrupt)).toMatchObject([
+ expect(buildWorkflowTasksFromInterrupt(interrupt)).toMatchObject([
{
callId: "echo-marker_workflow-call_tool-1_interrupt",
input: { message: "alpha" },
- target: { kind: "subagent-call", subagentName: "echo-marker" },
+ kind: "workflow-task",
+ nodeId: "subagents/researcher",
+ resultKind: "subagent",
+ toolName: "echo-marker",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
{
callId: "echo-marker_workflow-call_tool-2_interrupt",
input: { message: "beta" },
- target: { kind: "subagent-call", subagentName: "echo-marker" },
+ kind: "workflow-task",
+ nodeId: "subagents/researcher",
+ resultKind: "subagent",
+ toolName: "echo-marker",
+ workflowId: "workflow//./agent/subagents/researcher//execute",
},
]);
- expect(getRuntimeActionKeysFromWorkflowInterrupt(interrupt)).toEqual([
- "subagent-call:echo-marker:echo-marker_workflow-call_tool-1_interrupt",
- "subagent-call:echo-marker:echo-marker_workflow-call_tool-2_interrupt",
+ expect(getWorkflowTaskCallIds(interrupt)).toEqual([
+ "echo-marker_workflow-call_tool-1_interrupt",
+ "echo-marker_workflow-call_tool-2_interrupt",
]);
});
@@ -104,7 +113,7 @@ describe("workflow runtime action state", () => {
toolCallId: "workflow-call:tool-2",
};
- expect(getWorkflowRuntimeActionInterrupts(resumed).map((entry) => entry.input)).toEqual([
+ expect(getWorkflowTaskInterrupts(resumed).map((entry) => entry.input)).toEqual([
{ message: "beta" },
]);
});
diff --git a/packages/eve/src/harness/workflow-task-state.ts b/packages/eve/src/harness/workflow-task-state.ts
new file mode 100644
index 000000000..14c9a7139
--- /dev/null
+++ b/packages/eve/src/harness/workflow-task-state.ts
@@ -0,0 +1,78 @@
+import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
+import type { JsonObject } from "#shared/json.js";
+import {
+ getWorkflowSandboxPendingInterrupts,
+ type WorkflowSandboxInterrupt,
+} from "#shared/workflow-sandbox.js";
+
+export const WORKFLOW_TASK_INTERRUPT_KIND = "eve.workflow-task";
+
+interface SerializedWorkflowTaskDefinition {
+ readonly executeInput?: import("#shared/json.js").JsonValue;
+ readonly nodeId?: string;
+ readonly resultKind?: "subagent" | "tool";
+ readonly workflowId: string;
+}
+
+export function isWorkflowTaskInterrupt(interrupt: unknown): boolean {
+ return (
+ isRecord(interrupt) &&
+ isRecord(interrupt.payload) &&
+ interrupt.payload.kind === WORKFLOW_TASK_INTERRUPT_KIND
+ );
+}
+
+export function buildWorkflowTaskFromInterrupt(
+ interrupt: WorkflowSandboxInterrupt,
+): RuntimeWorkflowTaskRequest {
+ const raw = interrupt.payload as Record<string, unknown>;
+ const task = raw.task as SerializedWorkflowTaskDefinition | undefined;
+ const toolInput = raw.toolInput as JsonObject;
+ const toolName = raw.toolName as string;
+ const interruptId = "interruptId" in interrupt ? String(interrupt.interruptId) : "";
+ const callId = sanitizeCallId(`${toolName}_${interruptId}`);
+
+ if (task === undefined || typeof task.workflowId !== "string") {
+ throw new Error("Workflow delegation interrupts require a workflow task.");
+ }
+ const result: {
+ -readonly [K in keyof RuntimeWorkflowTaskRequest]: RuntimeWorkflowTaskRequest[K];
+ } = {
+ callId,
+ executeInput: task.executeInput,
+ input: toolInput,
+ kind: "workflow-task",
+ resultKind: task.resultKind,
+ toolName,
+ workflowId: task.workflowId,
+ };
+ if (task.nodeId !== undefined) result.nodeId = task.nodeId;
+ return result;
+}
+
+/** Returns every pending workflow-task interrupt in deterministic ledger order. */
+export function getWorkflowTaskInterrupts(
+ interrupt: WorkflowSandboxInterrupt,
+): WorkflowSandboxInterrupt[] {
+ return getWorkflowSandboxPendingInterrupts(interrupt).filter(isWorkflowTaskInterrupt);
+}
+
+export function buildWorkflowTasksFromInterrupt(
+ interrupt: WorkflowSandboxInterrupt,
+): RuntimeWorkflowTaskRequest[] {
+ return getWorkflowTaskInterrupts(interrupt).map((pending) =>
+ buildWorkflowTaskFromInterrupt(pending),
+ );
+}
+
+export function getWorkflowTaskCallIds(interrupt: WorkflowSandboxInterrupt): string[] {
+ return buildWorkflowTasksFromInterrupt(interrupt).map((task) => task.callId);
+}
+
+function sanitizeCallId(id: string): string {
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_");
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/packages/eve/src/harness/workflow-tool-runs.test.ts b/packages/eve/src/harness/workflow-tool-runs.test.ts
new file mode 100644
index 000000000..575ba9767
--- /dev/null
+++ b/packages/eve/src/harness/workflow-tool-runs.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ clearWorkflowToolRuns,
+ findWorkflowToolRun,
+ getWorkflowToolRuns,
+ isInboxToolResultFromRecordedWorkflowToolRun,
+ recordWorkflowToolRun,
+ removeWorkflowToolRun,
+} from "#harness/workflow-tool-runs.js";
+import type { HarnessSession } from "#harness/types.js";
+
+const RECORD = {
+ callId: "call_1",
+ hookToken: "eve:workflow-tool-run:abc",
+ runId: "wrun_1",
+ toolName: "deploy",
+};
+
+function session(state?: HarnessSession["state"]): HarnessSession {
+ return { state } as HarnessSession;
+}
+
+describe("workflow tool run records", () => {
+ it("records, finds, and removes runs by call id", () => {
+ const recorded = recordWorkflowToolRun(session({ other: true }), RECORD);
+ expect(getWorkflowToolRuns(recorded.state)).toEqual([RECORD]);
+ expect(findWorkflowToolRun(recorded.state, "call_1")).toEqual(RECORD);
+
+ const replaced = recordWorkflowToolRun(recorded, { ...RECORD, runId: "wrun_2" });
+ expect(getWorkflowToolRuns(replaced.state)).toEqual([{ ...RECORD, runId: "wrun_2" }]);
+
+ const removed = removeWorkflowToolRun(replaced, "call_1");
+ expect(getWorkflowToolRuns(removed.state)).toEqual([]);
+ expect(removed.state).toEqual({ other: true });
+ expect(removeWorkflowToolRun(removed, "call_1")).toBe(removed);
+ });
+
+ it("drops the state map entirely when nothing else is recorded", () => {
+ const recorded = recordWorkflowToolRun(session(), RECORD);
+ expect(clearWorkflowToolRuns(recorded).state).toBeUndefined();
+ expect(clearWorkflowToolRuns(session())).toEqual(session());
+ });
+
+ it("binds inbox tool results to the recorded run by call id and tool name", () => {
+ const state = recordWorkflowToolRun(session(), RECORD).state;
+ const result = {
+ callId: "call_1",
+ kind: "tool-result" as const,
+ output: 1,
+ toolName: "deploy",
+ };
+
+ expect(isInboxToolResultFromRecordedWorkflowToolRun(state, result)).toBe(true);
+ expect(
+ isInboxToolResultFromRecordedWorkflowToolRun(state, { ...result, toolName: "other" }),
+ ).toBe(false);
+ expect(
+ isInboxToolResultFromRecordedWorkflowToolRun(state, { ...result, callId: "call_2" }),
+ ).toBe(false);
+ expect(isInboxToolResultFromRecordedWorkflowToolRun(undefined, result)).toBe(false);
+ });
+
+ it("ignores malformed state", () => {
+ expect(getWorkflowToolRuns({ "eve.runtime.workflowToolRuns": { not: "an array" } })).toEqual(
+ [],
+ );
+ });
+});
diff --git a/packages/eve/src/harness/workflow-tool-runs.ts b/packages/eve/src/harness/workflow-tool-runs.ts
new file mode 100644
index 000000000..4ad6d7ac5
--- /dev/null
+++ b/packages/eve/src/harness/workflow-tool-runs.ts
@@ -0,0 +1,89 @@
+import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+
+const WORKFLOW_TOOL_RUNS_STATE_KEY = "eve.runtime.workflowToolRuns";
+export function workflowToolRunAnswerToken(runId: string, seq: number): string {
+ return `eve:workflow-tool-run-answer:${runId}:${seq}`;
+}
+
+/** A workflow tool run the active turn waits on. Background runs live in the task index. */
+export interface WorkflowToolRunRecord {
+ readonly callId: string;
+ readonly hookToken: string;
+ readonly runId: string;
+ readonly toolName: string;
+ readonly resultKind?: "subagent" | "tool";
+}
+
+// Schema-free: this is bundled into the workflow driver.
+export function getWorkflowToolRuns(
+ state: SessionStateMap | undefined,
+): readonly WorkflowToolRunRecord[] {
+ const raw = state?.[WORKFLOW_TOOL_RUNS_STATE_KEY];
+ return Array.isArray(raw) ? (raw as readonly WorkflowToolRunRecord[]) : [];
+}
+
+export function findWorkflowToolRun(
+ state: SessionStateMap | undefined,
+ callId: string,
+): WorkflowToolRunRecord | undefined {
+ return getWorkflowToolRuns(state).find((record) => record.callId === callId);
+}
+
+export function recordWorkflowToolRun<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ record: WorkflowToolRunRecord,
+): T {
+ const others = getWorkflowToolRuns(session.state).filter(
+ (entry) => entry.callId !== record.callId,
+ );
+ return writeWorkflowToolRuns(session, [...others, record]);
+}
+
+export function removeWorkflowToolRun<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ callId: string,
+): T {
+ const records = getWorkflowToolRuns(session.state);
+ const remaining = records.filter((entry) => entry.callId !== callId);
+ return remaining.length === records.length ? session : writeWorkflowToolRuns(session, remaining);
+}
+
+export function clearWorkflowToolRuns(session: HarnessSession): HarnessSession {
+ return getWorkflowToolRuns(session.state).length === 0
+ ? session
+ : writeWorkflowToolRuns(session, []);
+}
+
+/** The turn inbox is shared; a result settles a call only if the turn recorded that run. */
+export function isInboxToolResultFromRecordedWorkflowToolRun(
+ state: SessionStateMap | undefined,
+ result: RuntimeToolResultActionResult,
+): boolean {
+ const record = findWorkflowToolRun(state, result.callId);
+ return (
+ record !== undefined && record.resultKind !== "subagent" && record.toolName === result.toolName
+ );
+}
+
+/** A child result reported through a shared subagent execute run. */
+export function isInboxSubagentResultFromRecordedWorkflowToolRun(
+ state: SessionStateMap | undefined,
+ result: { readonly callId: string; readonly subagentName: string },
+): boolean {
+ const record = findWorkflowToolRun(state, result.callId);
+ return record?.resultKind === "subagent" && record.toolName === result.subagentName;
+}
+
+function writeWorkflowToolRuns<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ records: readonly WorkflowToolRunRecord[],
+): T {
+ const state = { ...session.state };
+ if (records.length === 0) {
+ delete state[WORKFLOW_TOOL_RUNS_STATE_KEY];
+ } else {
+ state[WORKFLOW_TOOL_RUNS_STATE_KEY] = records;
+ }
+ return { ...session, state: Object.keys(state).length > 0 ? state : undefined };
+}
diff --git a/packages/eve/src/instrumentation/native-events.test.ts b/packages/eve/src/instrumentation/native-events.test.ts
index 48a6f6b67..2750cf927 100644
--- a/packages/eve/src/instrumentation/native-events.test.ts
+++ b/packages/eve/src/instrumentation/native-events.test.ts
@@ -252,6 +252,13 @@ describe("createInstrumentationHandleEvent", () => {
remoteAgentName: "analyst",
},
{ callId: "add-1", input: { a: 1, b: 2 }, kind: "tool-call", toolName: "add" },
+ {
+ callId: "workflow-1",
+ input: { report: "weekly" },
+ kind: "workflow-tool-call",
+ toolName: "publish",
+ workflowId: "publish-workflow",
+ },
],
sequence: 0,
stepIndex: 0,
@@ -337,7 +344,7 @@ describe("createInstrumentationHandleEvent", () => {
);
});
- expect(events.slice(0, 4)).toEqual([
+ expect(events.slice(0, 5)).toEqual([
{
callId: "delegate-1",
idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "delegate-1"),
@@ -374,15 +381,24 @@ describe("createInstrumentationHandleEvent", () => {
scope,
type: "action.started",
},
+ {
+ callId: "workflow-1",
+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "workflow-1"),
+ input: { report: "weekly" },
+ kind: "tool-call",
+ name: "publish",
+ scope,
+ type: "action.started",
+ },
]);
- expect(events[4]).toMatchObject({
+ expect(events[5]).toMatchObject({
errorCode: "ACTION_RESULT_FAILED",
idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "delegate-1"),
outcome: "failed",
scope,
type: "action.failed",
});
- expect(events[5]).toEqual({
+ expect(events[6]).toEqual({
acceptedAtMs: 1_234,
idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "remote-1"),
outcome: "completed",
@@ -395,7 +411,7 @@ describe("createInstrumentationHandleEvent", () => {
outputTokens: 5,
},
});
- expect(events[6]).toEqual({
+ expect(events[7]).toEqual({
acceptedAtMs: undefined,
idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "add-1"),
outcome: "completed",
@@ -404,7 +420,7 @@ describe("createInstrumentationHandleEvent", () => {
type: "action.completed",
usage: undefined,
});
- expect(events).toHaveLength(7);
+ expect(events).toHaveLength(8);
expect(events.every(Object.isFrozen)).toBe(true);
});
diff --git a/packages/eve/src/instrumentation/native-events.ts b/packages/eve/src/instrumentation/native-events.ts
index 18492b96d..99a13369a 100644
--- a/packages/eve/src/instrumentation/native-events.ts
+++ b/packages/eve/src/instrumentation/native-events.ts
@@ -203,7 +203,7 @@ async function publishActionStarts(
callId: action.callId,
idempotencyKey,
input: capturesInputs ? action.input : undefined,
- kind: action.kind,
+ kind: action.kind === "workflow-tool-call" ? "tool-call" : action.kind,
name: actionName(action),
scope,
type: "action.started",
@@ -285,7 +285,7 @@ function actionUsage(result: RuntimeActionResult): InstrumentationUsage | undefi
}
function actionName(action: RuntimeActionRequest): string {
- if (action.kind === "tool-call") return action.toolName;
+ if (action.kind === "tool-call" || action.kind === "workflow-tool-call") return action.toolName;
if (action.kind === "load-skill") return "load_skill";
return action.name;
}
diff --git a/packages/eve/src/instrumentation/parent-lineage.ts b/packages/eve/src/instrumentation/parent-lineage.ts
index dd651e955..d8cdbea89 100644
--- a/packages/eve/src/instrumentation/parent-lineage.ts
+++ b/packages/eve/src/instrumentation/parent-lineage.ts
@@ -1,5 +1,5 @@
import type { SessionParent } from "#channel/types.js";
-import { isSubagentAdapterState } from "#execution/subagent-adapter-state.js";
+import { isSubagentAdapterState } from "#subagents/adapter-state.js";
import type { InstrumentationParentLineage } from "#instrumentation/lifecycle.js";
/**
diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.ts
index f37904312..f0a8aebdf 100644
--- a/packages/eve/src/internal/authored-definition/core.test.ts
+++ b/packages/eve/src/internal/authored-definition/core.test.ts
@@ -267,32 +267,18 @@ describe("normalizeAgentDefinition", () => {
).toThrow('Unknown key "subagentPersistentSessions"');
});
- it("accepts a boolean tasks flag", () => {
- const definition = normalizeAgentDefinition(
- {
- model: "openai/gpt-5.5",
- experimental: {
- tasks: true,
- },
- },
- FAILURE_MESSAGE,
- );
-
- expect(definition.experimental?.tasks).toBe(true);
- });
-
- it("rejects non-boolean tasks values", () => {
+ it.each([true, false, "yes"])("rejects the removed tasks flag", (tasks) => {
expect(() =>
normalizeAgentDefinition(
{
model: "openai/gpt-5.5",
experimental: {
- tasks: "yes",
+ tasks,
},
},
FAILURE_MESSAGE,
),
- ).toThrow('"experimental.tasks" must be a boolean.');
+ ).toThrow('Unknown key "tasks"');
});
});
diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.ts
index 281a0fd92..4dbfda88f 100644
--- a/packages/eve/src/internal/authored-definition/core.ts
+++ b/packages/eve/src/internal/authored-definition/core.ts
@@ -258,7 +258,7 @@ function normalizeAgentExperimentalDefinition(
message: string,
): NonNullable<NormalizedAgentDefinition["experimental"]> {
const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(record, ["instrumentationProviders", "tasks", "workflow"], message);
+ expectOnlyKnownKeys(record, ["instrumentationProviders", "workflow"], message);
const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["experimental"]>> = {};
if (record.instrumentationProviders !== undefined) {
@@ -268,13 +268,6 @@ function normalizeAgentExperimentalDefinition(
normalizedDefinition.instrumentationProviders = record.instrumentationProviders;
}
- if (record.tasks !== undefined) {
- if (typeof record.tasks !== "boolean") {
- throw new Error(`${message} "experimental.tasks" must be a boolean.`);
- }
- normalizedDefinition.tasks = record.tasks;
- }
-
if (record.workflow !== undefined) {
normalizedDefinition.workflow = normalizeAgentWorkflowDefinition(record.workflow, message);
}
diff --git a/packages/eve/src/internal/nitro/routes/runtime-stack.ts b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
index 878704677..2a8fd1a13 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-stack.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
@@ -1,6 +1,6 @@
import type { Runtime } from "#channel/types.js";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
-import { resolveRemoteAgentStreamHeaders } from "#execution/remote-agent-dispatch.js";
+import { resolveRemoteAgentStreamHeaders } from "#subagents/remote-dispatch.js";
import type { RemoteAgentStreamHeadersResolver } from "#internal/nitro/routes/channel-route-context.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
diff --git a/packages/eve/src/internal/structural-tests/file-length.test.ts b/packages/eve/src/internal/structural-tests/file-length.test.ts
index fa5fc1f13..991fdaef2 100644
--- a/packages/eve/src/internal/structural-tests/file-length.test.ts
+++ b/packages/eve/src/internal/structural-tests/file-length.test.ts
@@ -16,6 +16,8 @@ const LONG_SOURCE_FILE_ALLOWLIST = new Set<string>([
"cli/dev/tui/setup-panel.ts",
"cli/dev/tui/terminal-renderer.ts",
"compiler/manifest.ts",
+ // Lifecycle and stream emission share one ordered protocol boundary.
+ "harness/emission.ts",
"harness/tool-loop.ts",
"internal/nitro/host/create-application-nitro.ts",
"protocol/message.ts",
diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
index 30a288f87..e8470d75e 100644
--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
@@ -8,7 +8,7 @@
import { createHook, sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
-import { ask } from "#execution/tool-run/messages.js";
+import { ask } from "#execution/tools/workflow/ask.js";
import type { ToolContext } from "#tools/definition.js";
export interface DeployInput {
@@ -50,6 +50,26 @@ export async function failingDeployWorkflow(input: DeployInput): Promise<never>
throw new Error(`deploy of ${input.service} exploded`);
}
+export async function subagentShapedDeployWorkflow(): Promise<{
+ readonly callId: string;
+ readonly isError: true;
+ readonly kind: "subagent-result";
+ readonly origin: "dispatch";
+ readonly output: string;
+ readonly subagentName: string;
+}> {
+ "use workflow";
+
+ return {
+ callId: "authored-call",
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: "authored payload",
+ subagentName: "authored-name",
+ };
+}
+
export async function* reportingDeployWorkflow(
input: DeployInput,
): AsyncGenerator<string, { readonly plan: string }> {
diff --git a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
index d0d43c166..0c5598825 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
@@ -138,7 +138,11 @@ describe("WorkflowBundleBuilder", () => {
expect(builder.snapshot.projectRoot).toBe(appRoot);
expect(builder.snapshot.workingDir).toBe(rootDir);
- expect(builder.snapshot.dirs).toEqual([resolvePackageSourceDirectoryPath("src/execution")]);
+ expect(builder.snapshot.dirs).toEqual([
+ resolvePackageSourceDirectoryPath("src/execution"),
+ resolvePackageSourceDirectoryPath("src/runtime/subagents"),
+ resolvePackageSourceDirectoryPath("src/subagents"),
+ ]);
});
it("writes a Nitro-owned step registration entry", async () => {
diff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.ts
index 1ddf7cd7c..521991e81 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.ts
@@ -60,7 +60,11 @@ export class WorkflowBundleBuilder {
protected readonly config: WorkflowBundleBuilderConfig;
constructor(options: WorkflowBundleBuilderOptions) {
- const dirs = [resolvePackageSourceDirectoryPath("src/execution")];
+ const dirs = [
+ resolvePackageSourceDirectoryPath("src/execution"),
+ resolvePackageSourceDirectoryPath("src/runtime/subagents"),
+ resolvePackageSourceDirectoryPath("src/subagents"),
+ ];
if (options.includeTestFixtures === true) {
dirs.push(resolvePackageSourceDirectoryPath("src/internal/testing"));
}
@@ -95,7 +99,7 @@ export class WorkflowBundleBuilder {
if (frameworkInputFiles.length === 0) {
throw new Error(
- `Expected the execution workflow source file under "${resolvePackageSourceDirectoryPath("src/execution")}".`,
+ `Expected framework workflow source files under eve's execution, runtime/subagents, or subagents source directories.`,
);
}
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
index 2535eef29..08199d706 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from "node:fs";
+
import { describe, expect, it } from "vitest";
import { resolvePackageRoot, resolvePackageSourceFilePath } from "#internal/application/package.js";
@@ -23,6 +25,31 @@ describe("applyWorkflowTransform", () => {
});
});
+ it("keeps the shared subagent tool workflow stable", async () => {
+ const filename = "src/runtime/subagents/workflow.ts";
+ const transformed = await applyWorkflowTransform(
+ filename,
+ [
+ "export async function subagentToolExecuteWorkflow(): Promise<void> {",
+ ' "use workflow";',
+ "}",
+ "",
+ ].join("\n"),
+ "workflow",
+ resolvePackageSourceFilePath(filename),
+ resolvePackageRoot(),
+ );
+
+ expect(transformed.workflowManifest.workflows?.[filename]?.subagentToolExecuteWorkflow).toEqual(
+ {
+ workflowId: "workflow//eve//subagentToolExecuteWorkflow",
+ },
+ );
+ expect(transformed.code).toContain(
+ 'globalThis.__private_workflows.set("workflow//eve//subagentToolExecuteWorkflow", subagentToolExecuteWorkflow);',
+ );
+ });
+
it("registers step functions in step mode", async () => {
const transformed = await applyWorkflowTransform(
"steps/ping.ts",
@@ -374,4 +401,21 @@ describe("applyWorkflowTransform for authored application modules", () => {
"workflow//eve//turnWorkflow",
);
});
+
+ it("keeps the session command inbox factory visible in workflow driver builds", async () => {
+ const eveRoot = resolvePackageRoot();
+ const filename = "src/execution/session-command-inbox.ts";
+ const source = readFileSync(resolvePackageSourceFilePath(filename), "utf8");
+ const transformed = await applyWorkflowTransform(
+ filename,
+ source,
+ "workflow",
+ resolvePackageSourceFilePath(filename),
+ eveRoot,
+ );
+
+ expect(transformed.code).toContain("export function createSessionCommandInbox");
+ expect(transformed.code).not.toContain("subagent");
+ expect(transformed.code).not.toContain("WORKFLOW_USE_STEP");
+ });
});
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
index f3ab4dca3..992758ead 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
@@ -4,6 +4,7 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { STABLE_WORKFLOW_NAMES } from "#execution/stable-workflow-names.js";
import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
+import { SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME } from "#runtime/subagents/workflow-reference.js";
import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
import {
createWorkflowId,
@@ -54,7 +55,10 @@ export async function applyWorkflowTransform(
mode: "workflow" | "step" | "client" | false,
absolutePath?: string,
projectRoot?: string,
- stableWorkflowNames: ReadonlySet<string> = STABLE_WORKFLOW_NAMES,
+ stableWorkflowNames: ReadonlySet<string> = new Set([
+ ...STABLE_WORKFLOW_NAMES,
+ SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME,
+ ]),
): Promise<{
code: string;
workflowManifest: WorkflowManifest;
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index d09ecf47d..aac039bd6 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -335,6 +335,7 @@ export interface ActionPartialStreamEvent {
*/
export interface SubagentCalledStreamEvent {
data: {
+ agentId?: string;
callId: string;
childSessionId: string;
childStreamPath: string;
@@ -1309,6 +1310,7 @@ export function createActionPartialEvent(input: {
* Creates the `subagent.called` event for one started child workflow session.
*/
export function createSubagentCalledEvent(input: {
+ readonly agentId?: string;
readonly callId: string;
readonly childSessionId: string;
readonly sessionId: string;
@@ -1324,6 +1326,7 @@ export function createSubagentCalledEvent(input: {
}): SubagentCalledStreamEvent {
return {
data: {
+ agentId: input.agentId,
callId: input.callId,
childSessionId: input.childSessionId,
childStreamPath:
diff --git a/packages/eve/src/public/channels/slack/action-status.test.ts b/packages/eve/src/public/channels/slack/action-status.test.ts
index a6ac59553..7f7588c7f 100644
--- a/packages/eve/src/public/channels/slack/action-status.test.ts
+++ b/packages/eve/src/public/channels/slack/action-status.test.ts
@@ -74,6 +74,15 @@ describe("describeActionRequest", () => {
expect(
describeActionRequest({ callId: "c1", input: { skill: "arena" }, kind: "load-skill" }),
).toBe("load_skill arena");
+ expect(
+ describeActionRequest({
+ callId: "c1",
+ input: { path: "agent/agent.ts" },
+ kind: "workflow-tool-call",
+ toolName: "publish",
+ workflowId: "publish-workflow",
+ }),
+ ).toBe("publish agent/agent.ts");
});
});
diff --git a/packages/eve/src/public/channels/slack/action-status.ts b/packages/eve/src/public/channels/slack/action-status.ts
index 7c07d94a2..533e83b9c 100644
--- a/packages/eve/src/public/channels/slack/action-status.ts
+++ b/packages/eve/src/public/channels/slack/action-status.ts
@@ -74,6 +74,7 @@ export function describeActionRequest(action: RuntimeActionRequest): string {
case "subagent-call":
return action.subagentName;
case "tool-call":
+ case "workflow-tool-call":
return toolCallLabel(action.toolName, action.input);
}
}
diff --git a/packages/eve/src/public/workflow/index.ts b/packages/eve/src/public/workflow/index.ts
index 191b47121..ca8bab380 100644
--- a/packages/eve/src/public/workflow/index.ts
+++ b/packages/eve/src/public/workflow/index.ts
@@ -1,3 +1,5 @@
/** `eve/workflow`: what eve adds inside a workflow tool body. The SDK's own constructs come from `workflow`. */
-export { ask } from "#execution/tool-run/messages.js";
+export { ask } from "#execution/tools/workflow/ask.js";
+export { agent } from "#execution/tools/subagent/invoke-agent.js";
+export type { AgentInput } from "#execution/tools/subagent/invoke-agent.js";
export type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
diff --git a/packages/eve/src/runtime/actions/keys.test.ts b/packages/eve/src/runtime/actions/keys.test.ts
deleted file mode 100644
index 18f37654b..000000000
--- a/packages/eve/src/runtime/actions/keys.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { getRuntimeActionRequestKey, getRuntimeActionResultKey } from "#runtime/actions/keys.js";
-
-describe("runtime action keys", () => {
- it("pairs load-skill requests and results", () => {
- expect(getRuntimeActionRequestKey({ callId: "call_1", input: {}, kind: "load-skill" })).toBe(
- "runtime-action:load-skill:call_1",
- );
- expect(
- getRuntimeActionResultKey({ callId: "call_1", kind: "load-skill-result", output: null }),
- ).toBe("runtime-action:load-skill:call_1");
- });
-
- it("pairs subagent requests and results", () => {
- expect(
- getRuntimeActionRequestKey({
- callId: "call_2",
- description: "check",
- input: {},
- kind: "subagent-call",
- name: "reviewer",
- nodeId: "node_1",
- subagentName: "reviewer",
- }),
- ).toBe("subagent-call:reviewer:call_2");
- expect(
- getRuntimeActionResultKey({
- callId: "call_2",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "terminal",
- result: { kind: "succeeded", output: "done" },
- usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 },
- },
- output: "done",
- subagentName: "reviewer",
- }),
- ).toBe("subagent-call:reviewer:call_2");
- });
-
- it("pairs tool requests and results", () => {
- expect(
- getRuntimeActionRequestKey({
- callId: "call_3",
- input: {},
- kind: "tool-call",
- toolName: "shell",
- }),
- ).toBe("tool-call:shell:call_3");
- expect(
- getRuntimeActionResultKey({
- callId: "call_3",
- kind: "tool-result",
- output: 42,
- toolName: "shell",
- }),
- ).toBe("tool-call:shell:call_3");
- });
-});
diff --git a/packages/eve/src/runtime/actions/keys.ts b/packages/eve/src/runtime/actions/keys.ts
deleted file mode 100644
index 2e60792f6..000000000
--- a/packages/eve/src/runtime/actions/keys.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
-import type { PendingDispatchAction } from "#shared/dispatch-action.js";
-
-/**
- * Returns the stable match key used to pair one pending runtime action request
- * with its resume result.
- */
-export function getRuntimeActionRequestKey(action: RuntimeActionRequest): string {
- switch (action.kind) {
- case "load-skill":
- return `runtime-action:${action.kind}:${action.callId}`;
- case "remote-agent-call":
- return `subagent-call:${action.remoteAgentName}:${action.callId}`;
- case "subagent-call":
- return `subagent-call:${action.subagentName}:${action.callId}`;
- case "tool-call":
- return `tool-call:${action.toolName}:${action.callId}`;
- }
-}
-
-/** Returns the stable match key for one durable dispatch request. */
-export function getPendingDispatchActionKey(action: PendingDispatchAction): string {
- switch (action.target.kind) {
- case "remote-agent-call":
- return `subagent-call:${action.target.remoteAgentName}:${action.callId}`;
- case "self-agent-call":
- case "subagent-call":
- return `subagent-call:${action.target.subagentName}:${action.callId}`;
- case "task-cancel":
- case "task-update":
- case "workflow-tool-call":
- return `tool-call:${action.toolName}:${action.callId}`;
- default: {
- const _exhaustive: never = action.target;
- return _exhaustive;
- }
- }
-}
-
-/**
- * Returns the stable match key used to pair one runtime action result with its
- * originating request.
- */
-export function getRuntimeActionResultKey(result: RuntimeActionResult): string {
- switch (result.kind) {
- case "load-skill-result":
- return `runtime-action:load-skill:${result.callId}`;
- case "subagent-result":
- return `subagent-call:${result.subagentName}:${result.callId}`;
- case "tool-result":
- return `tool-call:${result.toolName}:${result.callId}`;
- }
-}
diff --git a/packages/eve/src/runtime/actions/results.ts b/packages/eve/src/runtime/actions/results.ts
index d4ca86ade..304ace978 100644
--- a/packages/eve/src/runtime/actions/results.ts
+++ b/packages/eve/src/runtime/actions/results.ts
@@ -1,28 +1,24 @@
-import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
-/** Returns results in pending-key order once every requested action has completed. */
-export function resolveRuntimeActionResultsForKeys<TResult extends RuntimeActionResult>(input: {
- readonly pendingKeys: readonly string[];
+/** Returns results in pending-call order once every requested call has completed. */
+export function resolveRuntimeActionResultsForCallIds<TResult extends RuntimeActionResult>(input: {
+ readonly pendingCallIds: readonly string[];
readonly results: readonly TResult[];
}): TResult[] | undefined {
- const pendingKeySet = new Set(input.pendingKeys);
- const resultsByKey = new Map<string, TResult>();
+ const pendingCallIdSet = new Set(input.pendingCallIds);
+ const resultsByCallId = new Map<string, TResult>();
for (const result of input.results) {
- const key = getRuntimeActionResultKey(result);
-
- if (!pendingKeySet.has(key)) {
+ if (!pendingCallIdSet.has(result.callId)) {
continue;
}
-
- resultsByKey.set(key, result);
+ resultsByCallId.set(result.callId, result);
}
const orderedResults: TResult[] = [];
- for (const key of input.pendingKeys) {
- const result = resultsByKey.get(key);
+ for (const callId of input.pendingCallIds) {
+ const result = resultsByCallId.get(callId);
if (result === undefined) {
return undefined;
diff --git a/packages/eve/src/runtime/agent/bootstrap-model-utils.ts b/packages/eve/src/runtime/agent/bootstrap-model-utils.ts
index 9f5cac87a..ef547e443 100644
--- a/packages/eve/src/runtime/agent/bootstrap-model-utils.ts
+++ b/packages/eve/src/runtime/agent/bootstrap-model-utils.ts
@@ -1,6 +1,6 @@
import type { MockLanguageModelV3 } from "ai/test";
-import { AGENTS_SNIPPET_LABEL } from "#harness/handles/prompt.js";
+import { AGENTS_SNIPPET_LABEL } from "#subagents/handles/prompt.js";
export type BootstrapGenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];
export type BootstrapPrompt = BootstrapGenerateOptions["prompt"];
diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.ts
index 2942c0b56..cf25047f8 100644
--- a/packages/eve/src/runtime/agent/bootstrap.test.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts
@@ -22,6 +22,7 @@ function createFrameworkAgentTool(): PreparedRuntimeTool {
},
},
description: "Message a persistent agent.",
+ execution: "background",
inputSchema: null,
kind: "authored-tool",
logicalPath: `tools/${AGENT_TOOL_NAME}.ts`,
@@ -87,25 +88,20 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
);
});
- it("includes the messaging instruction for the root framework agent tool", () => {
+ it("includes background messaging instructions for the root framework agent tool", () => {
const turnAgent = createResolvedRuntimeTurnAgent({
agent: createResolvedAgentForTest(),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
tools: [createFrameworkAgentTool()],
});
- expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(turnAgent.instructions).toContainEqual(expect.stringContaining("task receipt"));
expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Tool execution"));
});
it("explains task-derived busy agents in task mode", () => {
const turnAgent = createResolvedRuntimeTurnAgent({
- agent: createResolvedAgentForTest({
- config: {
- experimental: { tasks: true },
- name: "test-agent",
- } as ResolvedAgent["config"],
- }),
+ agent: createResolvedAgentForTest(),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
tools: [createFrameworkAgentTool()],
});
diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.ts
index 63542ad14..6e196942c 100644
--- a/packages/eve/src/runtime/agent/bootstrap.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.ts
@@ -80,6 +80,7 @@ export const BOOTSTRAP_RUNTIME_SYSTEM_PROMPT =
*/
export function createResolvedRuntimeTurnAgent(input: {
readonly agent: ResolvedAgent;
+ readonly dynamicSubagentsAvailable?: boolean;
readonly id?: string;
readonly nodeId?: string;
readonly tools: readonly PreparedRuntimeTool[];
@@ -110,8 +111,10 @@ export function createResolvedRuntimeTurnAgent(input: {
instructions: composeRuntimeBasePrompt({
connections: agent.connections,
instructions: agent.instructions,
- subagentsAvailable: subagentDeclaredTool || subagentFrameworkRootTool,
- tasksEnabled: config?.experimental?.tasks === true,
+ subagentsAvailable:
+ input.dynamicSubagentsAvailable === true ||
+ subagentDeclaredTool ||
+ subagentFrameworkRootTool,
toolsAvailable: input.tools.length > 0,
workspaceSpec: agent.workspaceSpec,
}),
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
index d30c0a182..543fe85dd 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
@@ -73,6 +73,63 @@ describe("createMockAuthoredRuntimeModel", () => {
]);
});
+ it("delegates through Workflow when the directive requests blocking orchestration", async () => {
+ const result = await generateWithPrompt(
+ [
+ {
+ content: "Delegate through Workflow to a subagent: use the wait_for_cancel tool.",
+ role: "user",
+ },
+ ],
+ [
+ {
+ inputSchema: {
+ additionalProperties: false,
+ properties: { js: { type: "string" } },
+ required: ["js"],
+ type: "object",
+ },
+ name: "Workflow",
+ type: "function",
+ },
+ ],
+ );
+
+ expect(result.content).toEqual([
+ {
+ input: JSON.stringify({
+ js: 'return await tools.agent({ message: "use the wait_for_cancel tool." });',
+ }),
+ toolCallId: "call_workflow",
+ toolName: "Workflow",
+ type: "tool-call",
+ },
+ ]);
+ });
+
+ it("reports a task notification instead of re-calling the named tool", async () => {
+ const result = await generateWithPrompt(
+ [
+ {
+ content:
+ "Background task task_abc123 (conditional-marker) is completed.\n\nResult:\nDYNAMIC_SUBAGENT_ENABLED",
+ role: "user",
+ },
+ ],
+ [
+ {
+ inputSchema: { properties: { message: { type: "string" } }, type: "object" },
+ name: "conditional-marker",
+ type: "function",
+ },
+ ],
+ );
+
+ expect(result.content).toEqual([
+ expect.objectContaining({ text: expect.stringContaining("DYNAMIC_SUBAGENT_ENABLED") }),
+ ]);
+ });
+
it("activates a matching skill when the available skill line includes a skill path", async () => {
const result = await generateWithPrompt([
{
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.ts
index 9b4a75119..4b895ee94 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts
@@ -207,7 +207,8 @@ function createSkillLoadResult(
}
const SUBAGENT_TOOL_NAME = "agent";
-const SUBAGENT_DELEGATION_DIRECTIVE = /\bdelegate\s+to\s+a\s+subagent\s*:\s*(.+)$/iu;
+const SUBAGENT_DELEGATION_DIRECTIVE =
+ /\bdelegate\s+(?:(through\s+workflow)\s+)?to\s+a\s+subagent\s*:\s*(.+)$/iu;
const PARALLEL_AUTHORED_TOOLS_DIRECTIVE = /^call tools in parallel:\s*(.+)$/imu;
function createParallelAuthoredToolCallsResult(
@@ -258,7 +259,7 @@ function createParallelAuthoredToolCallsResult(
/**
* Emits one built-in `agent` tool call when the current user message uses
* the explicit directive `Delegate to a subagent: <message>`, letting
- * tests exercise a real runtime-action wait. Fires only before the
+ * tests exercise a real coordination wait. Fires only before the
* delegated call resolves; then the reply path takes over.
*/
function createSubagentDelegationResult(
@@ -273,26 +274,30 @@ function createSubagentDelegationResult(
const directive = SUBAGENT_DELEGATION_DIRECTIVE.exec(lastUserMessage);
- if (directive?.[1] === undefined) {
+ if (directive?.[2] === undefined) {
return null;
}
- const tool = getAvailableTools(options).find((entry) => entry.name === SUBAGENT_TOOL_NAME);
+ const toolName = directive[1] === undefined ? SUBAGENT_TOOL_NAME : "Workflow";
+ const tool = getAvailableTools(options).find((entry) => entry.name === toolName);
if (tool === undefined) {
return null;
}
- const message = directive[1].trim();
- const toolInput = { message };
+ const message = directive[2].trim();
+ const toolInput =
+ toolName === "Workflow"
+ ? { js: `return await tools.agent({ message: ${JSON.stringify(message)} });` }
+ : { message };
return createToolCallGenerateResult({
input: toolInput,
inputTokens: estimateTokenCount(getPromptText(options.prompt)),
modelId,
- outputTokens: estimateTokenCount(toolInput.message),
- toolCallId: createToolCallId(SUBAGENT_TOOL_NAME),
- toolName: SUBAGENT_TOOL_NAME,
+ outputTokens: estimateTokenCount(message),
+ toolCallId: createToolCallId(toolName),
+ toolName,
});
}
@@ -302,7 +307,7 @@ function createAuthoredToolCallResult(
): BootstrapGenerateResult | null {
const lastUserMessage = getLastUserPromptText(options.prompt);
- if (lastUserMessage === null) {
+ if (lastUserMessage === null || /^Background task task_[a-z0-9]+\b/iu.test(lastUserMessage)) {
return null;
}
diff --git a/packages/eve/src/runtime/channels/registry.test.ts b/packages/eve/src/runtime/channels/registry.test.ts
index a3e22165a..5aacfa3fd 100644
--- a/packages/eve/src/runtime/channels/registry.test.ts
+++ b/packages/eve/src/runtime/channels/registry.test.ts
@@ -7,8 +7,8 @@ import {
getChannelActivityPresentation,
} from "#channel/activity-renderer.js";
import { SCHEDULE_ADAPTER, SCHEDULE_ADAPTER_KIND } from "#channel/schedule.js";
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
-import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
+import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
import { RuntimeRegistryError } from "#internal/runtime-registry.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
import {
diff --git a/packages/eve/src/runtime/channels/registry.ts b/packages/eve/src/runtime/channels/registry.ts
index c0630902a..f3706dbd6 100644
--- a/packages/eve/src/runtime/channels/registry.ts
+++ b/packages/eve/src/runtime/channels/registry.ts
@@ -6,7 +6,7 @@ import {
} from "#channel/activity-renderer.js";
import { HTTP_ADAPTER } from "#channel/http.js";
import { SCHEDULE_ADAPTER } from "#channel/schedule.js";
-import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
+import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
import type { RuntimeRegistryEntryLocation } from "#internal/runtime-registry.js";
import { RuntimeRegistryError } from "#internal/runtime-registry.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.ts
index e31598063..ef13ffd97 100644
--- a/packages/eve/src/runtime/prompt/compose.test.ts
+++ b/packages/eve/src/runtime/prompt/compose.test.ts
@@ -12,10 +12,9 @@ describe("composeRuntimeBasePrompt", () => {
expect(prompt).toContainEqual(expect.stringContaining("<agents>"));
});
- it("instructs task-mode parents to rely on notifications instead of polling", () => {
+ it("instructs parents to rely on notifications instead of polling", () => {
const prompt = composeRuntimeBasePrompt({
subagentsAvailable: true,
- tasksEnabled: true,
});
expect(prompt).toContainEqual(
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index f20d56e10..7231f927e 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -12,9 +12,6 @@ const PARALLEL_ACTION_INSTRUCTION =
"Tool execution\nA single tool or subagent call runs as one serial action. If you call multiple independent tools or subagents in one response, eve treats that batch as parallel work. Only batch work that is independent and does not rely on another call in the same response.";
const AGENT_MESSAGING_INSTRUCTION =
- "Agent messaging\nAgents you have already delegated to stay available after they answer. eve injects the current `<agents>` list into the conversation as a note labeled `[Agents]`; it is added automatically by the framework, not written by the user, and never requires a reply. The list is only a record of those existing agents — their `agentId`, name, and latest status. It does not limit which subagent tools you can call: your tool list is the source of truth, and any subagent tool can always be called without `agentId` to start a new agent, including when the `<agents>` list is empty or absent. Pass `agentId` to the same subagent tool only to continue one of those existing agents' sessions.";
-
-const TASK_AGENT_MESSAGING_INSTRUCTION =
"Agent messaging\nSubagent calls start durable background tasks and return immediately with a task receipt. After delegating, continue helping the user or end your turn. The task will notify you when it completes, fails, needs input, or sends an update; completion and failure notifications include the task's result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. `availability=busy` means the listed task still owns that agent session: wait for its notification or use task_cancel with its taskId instead of starting a continuation. `availability=available` means no nonterminal task owns the session, so you may pass agentId to the original subagent tool to continue it. Calling a subagent without agentId always starts a new agent session.";
/**
@@ -24,7 +21,6 @@ const TASK_AGENT_MESSAGING_INSTRUCTION =
interface ComposeRuntimeBasePromptInput {
connections?: readonly ResolvedConnectionDefinition[];
instructions?: readonly ResolvedInstructionsDefinition[];
- tasksEnabled?: boolean;
skills?: readonly ResolvedSkillDefinition[];
subagentsAvailable?: boolean;
toolsAvailable?: boolean;
@@ -40,9 +36,7 @@ export function composeRuntimeBasePrompt(input: ComposeRuntimeBasePromptInput):
...createInstructionsPromptBlocks(input.instructions),
...createWorkspacePromptBlocks(input.workspaceSpec),
...(input.toolsAvailable ? [PARALLEL_ACTION_INSTRUCTION] : []),
- ...(input.subagentsAvailable
- ? [input.tasksEnabled ? TASK_AGENT_MESSAGING_INSTRUCTION : AGENT_MESSAGING_INSTRUCTION]
- : []),
+ ...(input.subagentsAvailable ? [AGENT_MESSAGING_INSTRUCTION] : []),
...createConnectionsPromptBlocks(input.connections),
...createSkillsPromptBlocks(input.skills),
];
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index 03ecacdba..2a42b2908 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -172,6 +172,7 @@ async function resolveRuntimeAgentNode(
toolRegistry,
turnAgent: createResolvedRuntimeTurnAgent({
agent,
+ dynamicSubagentsAvailable: subagentRegistry.dynamicResolvers.length > 0,
id: input.agentId,
nodeId,
tools: [...toolRegistry.preparedTools, ...subagentRegistry.preparedTools],
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index 90a0ea697..fba4a0f99 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -237,7 +237,6 @@ function createResolvedAgentConfig(
if (manifest.config.experimental !== undefined) {
config.experimental = {
instrumentationProviders: manifest.config.experimental.instrumentationProviders,
- tasks: manifest.config.experimental.tasks,
workflow:
manifest.config.experimental.workflow === undefined
? undefined
diff --git a/packages/eve/src/runtime/sessions/turn.ts b/packages/eve/src/runtime/sessions/turn.ts
index 81286fed3..d57dd688c 100644
--- a/packages/eve/src/runtime/sessions/turn.ts
+++ b/packages/eve/src/runtime/sessions/turn.ts
@@ -4,6 +4,19 @@ import type { InternalToolDefinition } from "#tools/definition.js";
import type { AgentSourceOwner } from "#compiler/source-graph.js";
import type { PreparedToolBehavior } from "#tools/behavior.js";
+/** Grouped durable workflow metadata for one prepared harness tool. */
+export type PreparedRuntimeWorkflowTask =
+ | {
+ readonly nodeId?: never;
+ readonly resultKind?: "tool";
+ readonly workflowId: string;
+ }
+ | {
+ readonly nodeId: string;
+ readonly resultKind: "subagent";
+ readonly workflowId: string;
+ };
+
/**
* Serializable authored tool descriptor prepared by the runtime for one
* harness turn.
@@ -14,15 +27,20 @@ export type PreparedRuntimeAuthoredTool = Readonly<
behavior?: PreparedToolBehavior;
kind: "authored-tool";
owner: AgentSourceOwner;
+ rootOnly?: boolean;
+ task?: PreparedRuntimeWorkflowTask;
}
>;
type PreparedRuntimeDelegationToolBase<TKind extends "remote" | "subagent"> = Readonly<
- InternalToolDefinition &
+ Omit<InternalToolDefinition, "execution"> &
SourceRef &
Node & {
behavior: PreparedToolBehavior;
+ execution: "background";
kind: TKind;
+ rootOnly?: boolean;
+ task: PreparedRuntimeWorkflowTask;
}
>;
diff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.ts
index d19959178..3a9f00e95 100644
--- a/packages/eve/src/runtime/subagents/registry.ts
+++ b/packages/eve/src/runtime/subagents/registry.ts
@@ -5,8 +5,10 @@ import type {
ResolvedRuntimeDelegationNode,
} from "#runtime/types.js";
import type { JsonObject } from "#shared/json.js";
-import { serializeInputSchema } from "#tools/schema.js";
+import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";
import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";
+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";
+import { subagentToolExecuteWorkflowReference } from "#runtime/subagents/workflow-reference.js";
/**
* One runtime-owned subagent tracked by the prepared registry.
@@ -38,6 +40,7 @@ export interface RuntimeSubagentRegistry {
* accept one free-form `message` string from the parent agent.
*/
const SUBAGENT_TOOL_INPUT_JSON_SCHEMA = serializeInputSchema(SUBAGENT_TOOL_INPUT_SCHEMA);
+const SUBAGENT_TOOL_OUTPUT_JSON_SCHEMA = serializeOutputSchema(SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA);
/**
* Builds the runtime-owned registry for the resolved subagents visible from one
@@ -73,7 +76,10 @@ export function createRuntimeSubagentRegistry(input: {
let registeredSubagent: RuntimeRegisteredSubagent;
const dynamic = subagentDefinition.kind === "subagent" ? subagentDefinition.dynamic : undefined;
if (dynamic === undefined) {
- const prepared = createPreparedRuntimeSubagentTool(subagentDefinition);
+ const prepared = createPreparedRuntimeSubagentTool(
+ subagentDefinition,
+ SUBAGENT_TOOL_INPUT_JSON_SCHEMA,
+ );
registeredSubagent = {
definition: subagentDefinition,
prepared,
@@ -137,13 +143,19 @@ export function createPreparedRuntimeSubagentTool(
},
},
},
- description: definition.description,
+ description: `${definition.description}\n\nThis call starts a background task and returns a task receipt immediately.`,
+ execution: "background",
inputSchema,
kind: definition.kind,
logicalPath: definition.logicalPath,
name: definition.name,
nodeId: definition.nodeId,
- outputSchema: definition.kind === "remote" ? definition.outputSchema : undefined,
+ outputSchema: SUBAGENT_TOOL_OUTPUT_JSON_SCHEMA,
sourceId: definition.sourceId,
+ task: {
+ nodeId: definition.nodeId,
+ resultKind: "subagent",
+ workflowId: subagentToolExecuteWorkflowReference.workflowId,
+ },
};
}
diff --git a/packages/eve/src/runtime/subagents/workflow-reference.ts b/packages/eve/src/runtime/subagents/workflow-reference.ts
new file mode 100644
index 000000000..4f612b8d8
--- /dev/null
+++ b/packages/eve/src/runtime/subagents/workflow-reference.ts
@@ -0,0 +1,8 @@
+import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
+
+export const SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME = "subagentToolExecuteWorkflow";
+
+/** Shared framework-owned execute body for local and remote subagent tools. */
+export const subagentToolExecuteWorkflowReference = {
+ workflowId: `workflow//${EVE_PACKAGE_NAME}//${SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME}`,
+};
diff --git a/packages/eve/src/runtime/subagents/workflow.ts b/packages/eve/src/runtime/subagents/workflow.ts
new file mode 100644
index 000000000..4afdeb158
--- /dev/null
+++ b/packages/eve/src/runtime/subagents/workflow.ts
@@ -0,0 +1,32 @@
+// The shared body owns the invocation id (the tool call id itself), so it uses
+// the framework entry rather than the public `agent()` which derives ids from a
+// user-supplied key. This is the only internal import rule 42 permits here.
+import { invokeAgent } from "#execution/tools/subagent/invoke-agent.js";
+
+type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;
+interface JsonObject {
+ readonly [key: string]: JsonValue;
+}
+
+export interface SubagentWorkflowInput {
+ readonly agentId?: string | null;
+ readonly message: string;
+ readonly outputSchema?: Record<string, unknown>;
+}
+
+/** Shared execute body for local, remote, dynamic, and self-agent tools. */
+export async function subagentToolExecuteWorkflow(
+ input: SubagentWorkflowInput,
+ ctx: Parameters<typeof invokeAgent>[0],
+): Promise<unknown> {
+ "use workflow";
+ const invocation = {
+ ...(typeof input.agentId === "string" && input.agentId.trim() !== ""
+ ? { agentId: input.agentId }
+ : {}),
+ message: input.message,
+ outputSchema: input.outputSchema as JsonObject | undefined,
+ target: ctx.toolName,
+ };
+ return await invokeAgent(ctx, invocation, { invocationId: ctx.callId, returnResult: true });
+}
diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.ts
index 5c9ee3edb..a2c6d38aa 100644
--- a/packages/eve/src/runtime/tools/registry.ts
+++ b/packages/eve/src/runtime/tools/registry.ts
@@ -2,7 +2,14 @@ import { RuntimeRegistry } from "#internal/runtime-registry.js";
import type { PreparedRuntimeAuthoredTool } from "#runtime/sessions/turn.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";
-import type { CompiledToolBehavior, PreparedToolBehavior } from "#tools/behavior.js";
+import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";
+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
+import { subagentToolExecuteWorkflowReference } from "#runtime/subagents/workflow-reference.js";
+import type {
+ CompiledToolBehavior,
+ PreparedToolBehavior,
+ PreparedToolHandling,
+} from "#tools/behavior.js";
/**
* One executable authored tool tracked by the runtime-owned registry.
@@ -76,69 +83,83 @@ async function createPreparedRuntimeTool(
definition: ResolvedToolDefinition,
nodeId: string | undefined,
): Promise<PreparedRuntimeAuthoredTool> {
+ const isFrameworkAgent =
+ definition.owner.kind === "framework" && definition.name === AGENT_TOOL_NAME;
+ const workflowId = isFrameworkAgent
+ ? subagentToolExecuteWorkflowReference.workflowId
+ : definition.behavior?.handling?.kind === "workflow-tool"
+ ? definition.behavior.handling.workflowId
+ : undefined;
return {
- behavior: prepareToolBehavior(definition.behavior, nodeId),
+ behavior: prepareToolBehavior(
+ definition.behavior,
+ nodeId,
+ isFrameworkAgent ? subagentToolExecuteWorkflowReference.workflowId : undefined,
+ ),
description: definition.description,
+ execution: definition.execution,
inputSchema: serializeInputSchema(definition.inputSchema),
kind: "authored-tool",
logicalPath: definition.logicalPath,
name: definition.name,
owner: definition.owner,
outputSchema: serializeOutputSchema(definition.outputSchema),
+ rootOnly: isFrameworkAgent || undefined,
sourceId: definition.sourceId,
+ task:
+ workflowId === undefined
+ ? undefined
+ : isFrameworkAgent
+ ? {
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ resultKind: "subagent",
+ workflowId,
+ }
+ : { workflowId },
};
}
function prepareToolBehavior(
behavior: CompiledToolBehavior | undefined,
nodeId: string | undefined,
+ workflowIdOverride?: string,
): PreparedToolBehavior | undefined {
- if (behavior === undefined) {
- return undefined;
- }
- if (behavior.handling === undefined) {
- return {
- availability: behavior.availability,
- presentation: behavior.presentation,
+ if (behavior === undefined) return undefined;
+
+ let handling: PreparedToolHandling | undefined;
+ if (workflowIdOverride !== undefined && nodeId !== undefined) {
+ handling = {
+ kind: "dispatch",
+ target: { kind: "self-agent-call", nodeId, subagentName: AGENT_TOOL_NAME },
};
- }
- if (behavior.handling.kind === "workflow-tool") {
- return {
- ...behavior,
- handling: {
- kind: "dispatch",
- target: { kind: "workflow-tool-call", workflowId: behavior.handling.workflowId },
+ } else if (behavior.handling?.kind === "dispatch") {
+ if (behavior.handling.action === "self-agent" && nodeId === undefined) {
+ throw new Error("The self-agent tool requires a concrete runtime node id.");
+ }
+ const target =
+ behavior.handling.action === "self-agent"
+ ? {
+ kind: "self-agent-call" as const,
+ nodeId: nodeId!,
+ subagentName: AGENT_TOOL_NAME,
+ }
+ : { kind: behavior.handling.action };
+ handling = { kind: "dispatch", target };
+ } else if (behavior.handling?.kind === "workflow-tool") {
+ handling = {
+ kind: "dispatch",
+ target: {
+ kind: "workflow-tool-call",
+ workflowId: workflowIdOverride ?? behavior.handling.workflowId,
},
};
- }
- if (behavior.handling.kind !== "dispatch") {
- return { ...behavior, handling: behavior.handling };
+ } else {
+ handling = behavior.handling;
}
- let target: Extract<PreparedToolBehavior["handling"], { readonly kind: "dispatch" }>["target"];
- switch (behavior.handling.action) {
- case "self-agent":
- if (nodeId === undefined) {
- throw new Error("The self-agent tool requires a concrete runtime node id.");
- }
- target = { kind: "self-agent-call", nodeId, subagentName: "agent" };
- break;
- case "task-cancel":
- target = { kind: "task-cancel" };
- break;
- case "task-update":
- target = { kind: "task-update" };
- break;
- default: {
- const _exhaustive: never = behavior.handling.action;
- return _exhaustive;
- }
- }
return {
- ...behavior,
- handling: {
- kind: "dispatch",
- target,
- },
+ availability: behavior.availability,
+ handling,
+ presentation: behavior.presentation,
};
}
diff --git a/packages/eve/src/shared/action-types.ts b/packages/eve/src/shared/action-types.ts
index 716c891e7..2b28364f9 100644
--- a/packages/eve/src/shared/action-types.ts
+++ b/packages/eve/src/shared/action-types.ts
@@ -24,18 +24,64 @@ export const runtimeToolCallActionRequestSchema = z
})
.strict();
-/**
- * Runtime-owned subagent-call request surfaced by a harness and executed later
- * by workflow-backed runtime code.
- */
export type RuntimeSubagentCallActionRequest = z.infer<
typeof runtimeSubagentCallActionRequestSchema
>;
+const runtimeSubagentCallActionRequestSchema = z
+ .object({
+ callId: z.string(),
+ description: z.string(),
+ input: jsonObjectSchema,
+ kind: z.literal("subagent-call"),
+ name: z.string(),
+ nodeId: z.string(),
+ subagentName: z.string(),
+ })
+ .strict();
+
+export type RuntimeRemoteAgentCallActionRequest = z.infer<
+ typeof runtimeRemoteAgentCallActionRequestSchema
+>;
+
+export const runtimeRemoteAgentCallActionRequestSchema = z
+ .object({
+ callId: z.string(),
+ description: z.string(),
+ input: jsonObjectSchema,
+ kind: z.literal("remote-agent-call"),
+ name: z.string(),
+ nodeId: z.string(),
+ remoteAgentName: z.string(),
+ })
+ .strict();
+
+export type RuntimeWorkflowToolCallActionRequest = z.infer<
+ typeof runtimeWorkflowToolCallActionRequestSchema
+>;
+
+const runtimeWorkflowToolCallActionRequestSchema = z
+ .object({
+ callId: z.string(),
+ input: jsonObjectSchema,
+ kind: z.literal("workflow-tool-call"),
+ toolName: z.string(),
+ workflowId: z.string(),
+ })
+ .strict();
+
/**
- * Zod schema for one runtime-owned subagent-call action request.
+ * Internal subagent dispatch request issued by the agent workflow task.
+ *
+ * This is deliberately not a {@link RuntimeActionRequest}: subagent tools are
+ * workflow tasks, while runtime actions are reserved for framework controls.
*/
-const runtimeSubagentCallActionRequestSchema = z
+export type RuntimeSubagentDispatchRequest = z.infer<typeof runtimeSubagentDispatchRequestSchema>;
+
+/**
+ * Zod schema for one internal local-subagent dispatch request.
+ */
+const runtimeSubagentDispatchRequestSchema = z
.object({
callId: z.string(),
description: z.string(),
@@ -48,17 +94,16 @@ const runtimeSubagentCallActionRequestSchema = z
.strict();
/**
- * Runtime-owned remote-agent-call request surfaced by a harness and executed
- * later by workflow-backed runtime code.
+ * Internal remote-agent dispatch request issued by the agent workflow task.
*/
-export type RuntimeRemoteAgentCallActionRequest = z.infer<
- typeof runtimeRemoteAgentCallActionRequestSchema
+export type RuntimeRemoteAgentDispatchRequest = z.infer<
+ typeof runtimeRemoteAgentDispatchRequestSchema
>;
/**
- * Zod schema for one runtime-owned remote-agent-call action request.
+ * Zod schema for one internal remote-agent dispatch request.
*/
-export const runtimeRemoteAgentCallActionRequestSchema = z
+export const runtimeRemoteAgentDispatchRequestSchema = z
.object({
callId: z.string(),
description: z.string(),
@@ -70,6 +115,29 @@ export const runtimeRemoteAgentCallActionRequestSchema = z
})
.strict();
+/**
+ * One workflow task requested by the harness. The turn owner starts the
+ * durable run named by `workflowId`; blocking tools wait for its result,
+ * while background tools settle after task admission.
+ *
+ * Tasks are the coordination contract for authored workflow tools and
+ * subagents. They are intentionally separate from `RuntimeActionRequest`.
+ */
+export type RuntimeWorkflowTaskRequest = z.infer<typeof runtimeWorkflowTaskRequestSchema>;
+
+export const runtimeWorkflowTaskRequestSchema = z
+ .object({
+ callId: z.string(),
+ executeInput: jsonValueSchema.optional(),
+ input: jsonObjectSchema,
+ kind: z.literal("workflow-task"),
+ nodeId: z.string().optional(),
+ resultKind: z.enum(["subagent", "tool"]).optional(),
+ toolName: z.string(),
+ workflowId: z.string(),
+ })
+ .strict();
+
/**
* Eve-owned `load-skill` action requested by the model.
*/
@@ -89,14 +157,21 @@ const runtimeLoadSkillActionRequestSchema = z
/**
* Eve-owned action request surfaced by the harness.
*
- * A `tool-call` is one action kind, alongside control-plane work such as
- * `load-skill` and runtime-dispatched subagent calls.
+ * `tool-call` covers ordinary model-visible calls, including framework task
+ * controls. Deferred workflow and subagent execution uses
+ * {@link RuntimeWorkflowTaskRequest} instead.
*/
export type RuntimeActionRequest =
| RuntimeLoadSkillActionRequest
| RuntimeRemoteAgentCallActionRequest
| RuntimeSubagentCallActionRequest
- | RuntimeToolCallActionRequest;
+ | RuntimeToolCallActionRequest
+ | RuntimeWorkflowToolCallActionRequest;
+
+/** Internal agent dispatch request owned by a workflow task. */
+export type RuntimeAgentDispatchRequest =
+ | RuntimeRemoteAgentDispatchRequest
+ | RuntimeSubagentDispatchRequest;
/**
* Zod schema for one runtime action request.
@@ -106,6 +181,7 @@ export const runtimeActionRequestSchema = z.discriminatedUnion("kind", [
runtimeRemoteAgentCallActionRequestSchema,
runtimeSubagentCallActionRequestSchema,
runtimeToolCallActionRequestSchema,
+ runtimeWorkflowToolCallActionRequestSchema,
]);
/**
@@ -157,7 +233,7 @@ export type RuntimeSubagentChildResult = z.infer<typeof runtimeSubagentChildResu
/**
* Zod schema for one child-produced subagent result.
*/
-const runtimeSubagentChildResultSchema = z
+export const runtimeSubagentChildResultSchema = z
.object({
backgroundTask: z
.strictObject({
diff --git a/packages/eve/src/shared/json.test.ts b/packages/eve/src/shared/json.test.ts
index fa766f52a..b98d70f05 100644
--- a/packages/eve/src/shared/json.test.ts
+++ b/packages/eve/src/shared/json.test.ts
@@ -1,3 +1,4 @@
+import { runInNewContext } from "node:vm";
import { describe, expect, it } from "vitest";
import { jsonValuesEqual, parseJsonObject, parseJsonValue } from "#shared/json.js";
@@ -60,6 +61,12 @@ describe("parseJsonValue", () => {
});
});
+ it("preserves plain objects from another JavaScript realm", () => {
+ const value = runInNewContext('({ city: "Brooklyn", nested: { active: true } })');
+
+ expect(parseJsonValue(value)).toEqual({ city: "Brooklyn", nested: { active: true } });
+ });
+
it("rejects arrays with undefined entries", () => {
expect(() => parseJsonValue(["brooklyn", undefined])).toThrow(
"Expected a JSON-serializable value.",
@@ -92,6 +99,14 @@ describe("parseJsonValue", () => {
);
});
+ it("rejects class instances", () => {
+ class City {
+ name = "Brooklyn";
+ }
+
+ expect(() => parseJsonValue(new City())).toThrow("Expected a JSON-serializable value.");
+ });
+
it("rejects non-JSON scalars", () => {
expect(() => parseJsonValue(undefined)).toThrow("Expected a JSON-serializable value.");
expect(() => parseJsonValue(1n)).toThrow("Expected a JSON-serializable value.");
diff --git a/packages/eve/src/shared/json.ts b/packages/eve/src/shared/json.ts
index 37a2c707e..8b7e1ddbf 100644
--- a/packages/eve/src/shared/json.ts
+++ b/packages/eve/src/shared/json.ts
@@ -154,5 +154,5 @@ export function isJsonObjectValue(value: JsonValue | undefined): value is JsonOb
function isPlainObject(value: object): value is Record<string, unknown> {
const prototype = Object.getPrototypeOf(value);
- return prototype === null || prototype === Object.prototype;
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
}
diff --git a/packages/eve/src/shared/workflow-sandbox.ts b/packages/eve/src/shared/workflow-sandbox.ts
index ec1659de5..93a58c4b7 100644
--- a/packages/eve/src/shared/workflow-sandbox.ts
+++ b/packages/eve/src/shared/workflow-sandbox.ts
@@ -44,8 +44,8 @@ export async function createWorkflowSandboxTool(input: {
}
export async function requestWorkflowSandboxInterrupt(input: {
- readonly dispatchTarget: unknown;
readonly kind: string;
+ readonly task: unknown;
readonly toolInput: unknown;
readonly toolName: string;
}): Promise<unknown> {
diff --git a/packages/eve/src/execution/subagent-adapter-state.ts b/packages/eve/src/subagents/adapter-state.ts
similarity index 89%
rename from packages/eve/src/execution/subagent-adapter-state.ts
rename to packages/eve/src/subagents/adapter-state.ts
index 02381a571..2b096d07e 100644
--- a/packages/eve/src/execution/subagent-adapter-state.ts
+++ b/packages/eve/src/subagents/adapter-state.ts
@@ -30,6 +30,8 @@ export interface SubagentAdapterState extends Record<string, unknown> {
readonly parentContinuationToken: string;
readonly parentSessionId: string;
readonly subagentName: string;
+ /** Owning task when this child was started by a background workflow tool. */
+ readonly taskId?: string;
}
/**
@@ -53,6 +55,7 @@ export function isSubagentAdapterState(value: unknown): value is SubagentAdapter
state.parentContinuationToken.length > 0 &&
typeof state.parentSessionId === "string" &&
typeof state.subagentName === "string" &&
- state.subagentName.length > 0
+ state.subagentName.length > 0 &&
+ (state.taskId === undefined || (typeof state.taskId === "string" && state.taskId.length > 0))
);
}
diff --git a/packages/eve/src/execution/subagent-adapter.test.ts b/packages/eve/src/subagents/adapter.test.ts
similarity index 96%
rename from packages/eve/src/execution/subagent-adapter.test.ts
rename to packages/eve/src/subagents/adapter.test.ts
index 0e5db344f..51547739a 100644
--- a/packages/eve/src/execution/subagent-adapter.test.ts
+++ b/packages/eve/src/subagents/adapter.test.ts
@@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { callAdapterEventHandler, type ChannelAdapterContext } from "#channel/adapter.js";
import { buildSessionHandle } from "#channel/session.js";
-import { type SubagentAdapterState } from "#execution/subagent-adapter-state.js";
+import { type SubagentAdapterState } from "#subagents/adapter-state.js";
import { ContextContainer } from "#context/container.js";
import { ContinuationTokenKey, SessionIdKey } from "#context/keys.js";
import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import type { InputRequest } from "#shared/input.js";
-import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
-import { bindTurnCallerContextStep } from "#execution/delegated-parent-notification.js";
+import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
+import { bindTurnCallerContextStep } from "#subagents/parent-notification.js";
const SUBAGENT_INPUT_REQUESTED = SUBAGENT_ADAPTER["input.requested"];
const SUBAGENT_AUTHORIZATION_REQUIRED = SUBAGENT_ADAPTER["authorization.required"];
@@ -171,7 +171,10 @@ describe("SUBAGENT_ADAPTER input.requested handler", () => {
expect(resumeHookMock).toHaveBeenCalledWith(
"parent-token-current",
- expect.objectContaining({ callId: "call-continued", kind: "subagent-input-request" }),
+ expect.objectContaining({
+ callId: "call-continued",
+ kind: "subagent-input-request",
+ }),
);
});
diff --git a/packages/eve/src/execution/subagent-adapter.ts b/packages/eve/src/subagents/adapter.ts
similarity index 97%
rename from packages/eve/src/execution/subagent-adapter.ts
rename to packages/eve/src/subagents/adapter.ts
index 53a199fe8..ef834cf02 100644
--- a/packages/eve/src/execution/subagent-adapter.ts
+++ b/packages/eve/src/subagents/adapter.ts
@@ -7,10 +7,7 @@ import type {
SubagentInputRequestHookPayload,
} from "#channel/types.js";
import { ContinuationTokenKey, SessionIdKey } from "#context/keys.js";
-import {
- SUBAGENT_ADAPTER_KIND,
- isSubagentAdapterState,
-} from "#execution/subagent-adapter-state.js";
+import { SUBAGENT_ADAPTER_KIND, isSubagentAdapterState } from "#subagents/adapter-state.js";
import { createErrorId, createLogger } from "#internal/logging.js";
const log = createLogger("execution.subagent-adapter");
diff --git a/packages/eve/src/subagents/agent-handle-errors.test.ts b/packages/eve/src/subagents/agent-handle-errors.test.ts
new file mode 100644
index 000000000..a32957773
--- /dev/null
+++ b/packages/eve/src/subagents/agent-handle-errors.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+
+import { formatAgentBusyMessage } from "#subagents/agent-handle-errors.js";
+
+describe("formatAgentBusyMessage", () => {
+ it.each([
+ ["task_123", 'Agent "research" with id "agent-1" is still working on task "task_123".'],
+ [
+ "workflow-run-1",
+ 'Agent "research" with id "agent-1" is still working on another invocation.',
+ ],
+ [undefined, 'Agent "research" with id "agent-1" is still working on another task.'],
+ ])("describes owner %s", (ownerId, expected) => {
+ expect(formatAgentBusyMessage({ agentId: "agent-1", agentName: "research", ownerId })).toBe(
+ expected,
+ );
+ });
+});
diff --git a/packages/eve/src/harness/agent-handle-errors.ts b/packages/eve/src/subagents/agent-handle-errors.ts
similarity index 71%
rename from packages/eve/src/harness/agent-handle-errors.ts
rename to packages/eve/src/subagents/agent-handle-errors.ts
index 6a3a16e5b..48858636a 100644
--- a/packages/eve/src/harness/agent-handle-errors.ts
+++ b/packages/eve/src/subagents/agent-handle-errors.ts
@@ -15,6 +15,19 @@ export const AGENT_UNREACHABLE = "AGENT_UNREACHABLE";
/** Error code for an agent that is starting or already running a turn. */
export const AGENT_BUSY = "AGENT_BUSY";
+/** Describes the owner blocking a continuation without exposing workflow run ids. */
+export function formatAgentBusyMessage(input: {
+ readonly agentId: string;
+ readonly agentName: string;
+ readonly ownerId?: string;
+}): string {
+ const agent = `Agent "${input.agentName}" with id "${input.agentId}" is still working on`;
+ if (input.ownerId?.startsWith("task_")) {
+ return `${agent} task "${input.ownerId}".`;
+ }
+ return `${agent} ${input.ownerId === undefined ? "another task" : "another invocation"}.`;
+}
+
/** Error code for a local subagent that failed to start. */
export const SUBAGENT_START_FAILED = "SUBAGENT_START_FAILED";
diff --git a/packages/eve/src/execution/subagent-auth-proxy.integration.test.ts b/packages/eve/src/subagents/auth-proxy.integration.test.ts
similarity index 91%
rename from packages/eve/src/execution/subagent-auth-proxy.integration.test.ts
rename to packages/eve/src/subagents/auth-proxy.integration.test.ts
index feabd560c..6abada6c8 100644
--- a/packages/eve/src/execution/subagent-auth-proxy.integration.test.ts
+++ b/packages/eve/src/subagents/auth-proxy.integration.test.ts
@@ -6,8 +6,8 @@ import type {
SubagentAuthorizationEventHookPayload,
} from "#channel/types.js";
import { ContextContainer } from "#context/container.js";
-import { AuthKey, ContinuationTokenKey, SessionIdKey } from "#context/keys.js";
-import { emitProxiedSubagentEvent } from "#execution/subagent-event-proxy-step.js";
+import { AuthKey, ContinuationTokenKey, ModeKey, SessionIdKey } from "#context/keys.js";
+import { emitProxiedSubagentEvent } from "#subagents/event-proxy-step.js";
import { projectToDurableSession } from "#execution/session.js";
import type { HarnessSession } from "#harness/types.js";
import type { MessageStreamEvent } from "#protocol/message.js";
@@ -78,6 +78,7 @@ function buildContext(input: { readonly adapter: ChannelAdapter; readonly sessio
ctx.set(BundleKey, bundle);
ctx.set(ChannelKey, input.adapter);
ctx.set(ContinuationTokenKey, "http:parent");
+ ctx.set(ModeKey, "conversation");
ctx.set(SessionIdKey, input.sessionId);
return { bundle, ctx };
}
@@ -97,6 +98,7 @@ function rehydrateContext(input: {
),
);
ctx.set(ContinuationTokenKey, input.serializedContext[ContinuationTokenKey.name] as string);
+ ctx.set(ModeKey, "conversation");
ctx.set(SessionIdKey, input.serializedContext[SessionIdKey.name] as string);
return ctx;
}
@@ -182,7 +184,7 @@ describe("subagent authorization proxy", () => {
expect(decodeEvent(chunks[0]!)).toMatchObject(candidateEvent);
expect(decodeEvent(chunks[1]!)).toMatchObject(settledEvent);
});
- it("preserves events and parent adapter state across required/completed steps", async () => {
+ it("preserves required/completed events as standalone parent turns", async () => {
const parentSessionId = "parent-session";
const session = createSession(parentSessionId);
const { bundle, ctx } = buildContext({
@@ -246,8 +248,12 @@ describe("subagent authorization proxy", () => {
state: { outcome: "authorized" },
audience: "unknown",
});
- expect(chunks).toHaveLength(2);
+ expect(chunks).toHaveLength(6);
expect(decodeEvent(chunks[0]!)).toMatchObject(requiredEvent);
- expect(decodeEvent(chunks[1]!)).toMatchObject(completedEvent);
+ expect(decodeEvent(chunks[1]!).type).toBe("turn.completed");
+ expect(decodeEvent(chunks[2]!).type).toBe("session.waiting");
+ expect(decodeEvent(chunks[3]!)).toMatchObject(completedEvent);
+ expect(decodeEvent(chunks[4]!).type).toBe("turn.completed");
+ expect(decodeEvent(chunks[5]!).type).toBe("session.waiting");
});
});
diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/subagents/callback-route.test.ts
similarity index 84%
rename from packages/eve/src/runtime/session-callback-route.test.ts
rename to packages/eve/src/subagents/callback-route.test.ts
index f830af783..9011d2d32 100644
--- a/packages/eve/src/runtime/session-callback-route.test.ts
+++ b/packages/eve/src/subagents/callback-route.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RouteContext } from "#public/definitions/channel.js";
-import { handleSessionCallbackRequest } from "#execution/session-callback-route.js";
+import { handleSessionCallbackRequest } from "#subagents/callback-route.js";
const resumeHookMock = vi.fn();
const TASK_ID = "task_1";
@@ -16,7 +16,7 @@ describe("session callback route", () => {
resumeHookMock.mockReset();
});
- it("forwards remote task turn-start identity to the task hook", async () => {
+ it("rejects removed direct task turn-start callbacks", async () => {
resumeHookMock.mockResolvedValue(undefined);
const response = await handleSessionCallbackRequest(
new Request(`https://app.example.com/eve/v1/callback/${TASK_TOKEN}`, {
@@ -33,16 +33,11 @@ describe("session callback route", () => {
createRouteContext({ token: TASK_TOKEN }),
);
- expect(response.status).toBe(202);
- expect(resumeHookMock).toHaveBeenCalledWith(TASK_TOKEN, {
- childSessionId: "child-session",
- childTurnId: "turn_child_7",
- kind: "turn-started",
- taskId: TASK_ID,
- });
+ expect(response.status).toBe(410);
+ expect(resumeHookMock).not.toHaveBeenCalled();
});
- it("forwards remote task input requests to the owning task hook", async () => {
+ it("rejects removed direct task input callbacks", async () => {
resumeHookMock.mockResolvedValue(undefined);
const event = {
requests: [
@@ -84,8 +79,43 @@ describe("session callback route", () => {
createRouteContext({ token: TASK_TOKEN }),
);
+ expect(response.status).toBe(410);
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+
+ it("routes remote task input through an invocation reply hook", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+ const event = {
+ requests: [
+ {
+ action: { callId: "call-1", input: {}, kind: "tool-call", toolName: "ask" },
+ kind: "question",
+ prompt: "Continue?",
+ requestId: "request-1",
+ },
+ ],
+ sequence: 3,
+ stepIndex: 2,
+ turnId: "turn-child",
+ };
+ const response = await handleSessionCallbackRequest(
+ new Request("https://app.example.com/eve/v1/callback/invocation-reply", {
+ body: JSON.stringify({
+ callId: "call-task",
+ childContinuationToken: "remote-child-token",
+ childSessionId: "child-session",
+ event,
+ kind: "task.input-requested",
+ subagentName: "research",
+ taskId: TASK_ID,
+ }),
+ method: "POST",
+ }),
+ createRouteContext({ token: "invocation-reply" }),
+ );
+
expect(response.status).toBe(202);
- expect(resumeHookMock).toHaveBeenCalledWith(TASK_TOKEN, {
+ expect(resumeHookMock).toHaveBeenCalledWith("invocation-reply", {
callId: "call-task",
childContinuationToken: "remote-child-token",
childSessionId: "child-session",
@@ -95,7 +125,46 @@ describe("session callback route", () => {
});
});
- it("forwards remote task updates to the owning task hook", async () => {
+ it("routes remote task authorization through an invocation reply hook", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+ const event = {
+ data: {
+ description: "Authorize Linear",
+ name: "linear",
+ sequence: 3,
+ stepIndex: 2,
+ turnId: "turn-child",
+ url: "https://linear.example/authorize",
+ },
+ type: "authorization.required",
+ };
+ const response = await handleSessionCallbackRequest(
+ new Request("https://app.example.com/eve/v1/callback/invocation-reply", {
+ body: JSON.stringify({
+ callId: "call-task",
+ childContinuationToken: "remote-child-token",
+ childSessionId: "child-session",
+ event,
+ kind: "task.authorization",
+ subagentName: "research",
+ taskId: TASK_ID,
+ }),
+ method: "POST",
+ }),
+ createRouteContext({ token: "invocation-reply" }),
+ );
+
+ expect(response.status).toBe(202);
+ expect(resumeHookMock).toHaveBeenCalledWith("invocation-reply", {
+ callId: "call-task",
+ childSessionId: "child-session",
+ event,
+ kind: "subagent-authorization-event",
+ subagentName: "research",
+ });
+ });
+
+ it("retains the generic task progress callback", async () => {
resumeHookMock.mockResolvedValue(undefined);
const response = await handleSessionCallbackRequest(
new Request(`https://app.example.com/eve/v1/callback/${TASK_TOKEN}`, {
diff --git a/packages/eve/src/execution/session-callback-route.ts b/packages/eve/src/subagents/callback-route.ts
similarity index 87%
rename from packages/eve/src/execution/session-callback-route.ts
rename to packages/eve/src/subagents/callback-route.ts
index e15cd8614..82b77ba36 100644
--- a/packages/eve/src/execution/session-callback-route.ts
+++ b/packages/eve/src/subagents/callback-route.ts
@@ -1,20 +1,19 @@
import { resumeHook } from "#internal/workflow/runtime.js";
import { z } from "#compiled/zod/index.js";
-import { REMOTE_AGENT_FAILED } from "#harness/agent-handle-errors.js";
+import { REMOTE_AGENT_FAILED } from "#subagents/agent-handle-errors.js";
import type { RouteContext } from "#public/definitions/channel.js";
-import type { SubagentAuthorizationEvent } from "#channel/types.js";
+import type {
+ SubagentAuthorizationEvent,
+ SubagentAuthorizationEventHookPayload,
+ SubagentInputRequestHookPayload,
+} from "#channel/types.js";
import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import { agentTurnOutcomeSchema } from "#shared/agent-turn-outcome.js";
import { jsonValueSchema } from "#shared/json-schemas.js";
import type { JsonValue } from "#shared/json.js";
import { isInputRequest } from "#shared/input.js";
import { tokenUsageSchema, type TokenUsage } from "#shared/token-usage.js";
-import type {
- TaskInboundAuthorizationEvent,
- TaskInboundInputRequest,
- TaskInboundTurnStarted,
- TaskInboundUpdate,
-} from "#tasks/types.js";
+import type { TaskInboundUpdate } from "#tasks/types.js";
import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
const ZERO_TOKEN_USAGE: TokenUsage = {
@@ -45,7 +44,7 @@ const authorizationChallengeSchema = z.looseObject({
* remaining keys through unchanged (loose objects): the parent re-emits
* the event, so a newer child extending an event is never rejected here.
*/
-const taskInputEventSchema: z.ZodType<TaskInboundInputRequest["event"]> = z.looseObject({
+const taskInputEventSchema = z.looseObject({
requests: z.array(jsonValueSchema.refine(isInputRequest)).min(1),
sequence: eventCoordinateSchema,
stepIndex: eventCoordinateSchema,
@@ -199,7 +198,7 @@ export async function handleSessionCallbackRequest(
return Response.json({ ok: true }, { status: 202 });
}
- const started = projectTaskTurnStarted(body, token);
+ const started = rejectDirectTaskTurnStarted(body, token);
if (started instanceof Response) return started;
if (started !== undefined) {
try {
@@ -235,7 +234,7 @@ function callbackKind(value: unknown): unknown {
function projectTaskEvent(
value: unknown,
token: string,
-): TaskInboundInputRequest | TaskInboundAuthorizationEvent | Response | undefined {
+): SubagentAuthorizationEventHookPayload | SubagentInputRequestHookPayload | Response | undefined {
const kind = callbackKind(value);
if (kind !== "task.input-requested" && kind !== "task.authorization") return undefined;
const parsed = taskEventCallbackSchema.safeParse(value);
@@ -243,31 +242,33 @@ function projectTaskEvent(
return Response.json({ error: "Invalid task event callback.", ok: false }, { status: 400 });
}
const payload = parsed.data;
- const tokenRejection = rejectMismatchedTaskToken(token, payload.taskId);
- if (tokenRejection !== undefined) return tokenRejection;
- if (payload.kind === "task.input-requested") {
- return {
- callId: payload.callId,
- childContinuationToken: payload.childContinuationToken,
- childSessionId: payload.childSessionId,
- event: payload.event,
- kind: "subagent-input-request",
- subagentName: payload.subagentName,
- };
+ if (readTaskIdFromInboxToken(token) !== undefined) {
+ const tokenRejection = rejectMismatchedTaskToken(token, payload.taskId);
+ if (tokenRejection !== undefined) return tokenRejection;
+ return Response.json(
+ { error: "Direct subagent task events are no longer accepted.", ok: false },
+ { status: 410 },
+ );
}
- return {
- callId: payload.callId,
- childSessionId: payload.childSessionId,
- event: payload.event,
- kind: "authorization-event",
- subagentName: payload.subagentName,
- };
+ return payload.kind === "task.input-requested"
+ ? {
+ callId: payload.callId,
+ childContinuationToken: payload.childContinuationToken,
+ childSessionId: payload.childSessionId,
+ event: payload.event,
+ kind: "subagent-input-request",
+ subagentName: payload.subagentName,
+ }
+ : {
+ callId: payload.callId,
+ childSessionId: payload.childSessionId,
+ event: payload.event,
+ kind: "subagent-authorization-event",
+ subagentName: payload.subagentName,
+ };
}
-function projectTaskTurnStarted(
- value: unknown,
- token: string,
-): TaskInboundTurnStarted | Response | undefined {
+function rejectDirectTaskTurnStarted(value: unknown, token: string): Response | undefined {
if (callbackKind(value) !== "turn.started") return undefined;
const parsed = taskTurnStartedCallbackSchema.safeParse(value);
if (!parsed.success) {
@@ -278,12 +279,10 @@ function projectTaskTurnStarted(
}
const tokenRejection = rejectMismatchedTaskToken(token, parsed.data.taskId);
if (tokenRejection !== undefined) return tokenRejection;
- return {
- childSessionId: parsed.data.sessionId,
- childTurnId: parsed.data.turnId,
- kind: "turn-started",
- taskId: parsed.data.taskId,
- };
+ return Response.json(
+ { error: "Direct subagent task turn callbacks are no longer accepted.", ok: false },
+ { status: 410 },
+ );
}
function projectTaskUpdate(
@@ -295,8 +294,10 @@ function projectTaskUpdate(
if (!parsed.success) {
return Response.json({ error: "Invalid task update callback.", ok: false }, { status: 400 });
}
- const tokenRejection = rejectMismatchedTaskToken(token, parsed.data.taskId);
- if (tokenRejection !== undefined) return tokenRejection;
+ if (readTaskIdFromInboxToken(token) !== undefined) {
+ const tokenRejection = rejectMismatchedTaskToken(token, parsed.data.taskId);
+ if (tokenRejection !== undefined) return tokenRejection;
+ }
return {
callId: parsed.data.callId,
kind: "task-update",
diff --git a/packages/eve/src/execution/session-callback-step.test.ts b/packages/eve/src/subagents/callback-step.test.ts
similarity index 98%
rename from packages/eve/src/execution/session-callback-step.test.ts
rename to packages/eve/src/subagents/callback-step.test.ts
index 71e3ad468..e06446605 100644
--- a/packages/eve/src/execution/session-callback-step.test.ts
+++ b/packages/eve/src/subagents/callback-step.test.ts
@@ -1,9 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- fireSessionCallbackStep,
- fireTaskUpdateCallbackStep,
-} from "#execution/session-callback-step.js";
+import { fireSessionCallbackStep, fireTaskUpdateCallbackStep } from "#subagents/callback-step.js";
const USAGE = { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 };
diff --git a/packages/eve/src/execution/session-callback-step.ts b/packages/eve/src/subagents/callback-step.ts
similarity index 98%
rename from packages/eve/src/execution/session-callback-step.ts
rename to packages/eve/src/subagents/callback-step.ts
index f77ea1376..617cdb396 100644
--- a/packages/eve/src/execution/session-callback-step.ts
+++ b/packages/eve/src/subagents/callback-step.ts
@@ -2,7 +2,7 @@ import type { SessionCallback, SubagentAuthorizationEvent } from "#channel/types
import { parseSessionCallback } from "#channel/session-callback.js";
import { SessionCallbackKey } from "#context/keys.js";
import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
-import { SESSION_FAILED } from "#harness/agent-handle-errors.js";
+import { SESSION_FAILED } from "#subagents/agent-handle-errors.js";
import { createLogger } from "#internal/logging.js";
import { toErrorMessage } from "#shared/errors.js";
import type { TokenUsage } from "#shared/token-usage.js";
diff --git a/packages/eve/src/execution/agent-continuation-bundle.ts b/packages/eve/src/subagents/continuation-bundle.ts
similarity index 89%
rename from packages/eve/src/execution/agent-continuation-bundle.ts
rename to packages/eve/src/subagents/continuation-bundle.ts
index 9849c50d4..76c72082b 100644
--- a/packages/eve/src/execution/agent-continuation-bundle.ts
+++ b/packages/eve/src/subagents/continuation-bundle.ts
@@ -1,5 +1,5 @@
-import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";
-import { resolveRemoteAgentForAction } from "#execution/remote-agent-dispatch.js";
+import type { RuntimeAgentHandleAction } from "#subagents/handle-dispatch.js";
+import { resolveRemoteAgentForAction } from "#subagents/remote-dispatch.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
diff --git a/packages/eve/src/execution/subagent-event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.ts
similarity index 76%
rename from packages/eve/src/execution/subagent-event-proxy-step.ts
rename to packages/eve/src/subagents/event-proxy-step.ts
index 5cb27a3e1..0f0b6f798 100644
--- a/packages/eve/src/execution/subagent-event-proxy-step.ts
+++ b/packages/eve/src/subagents/event-proxy-step.ts
@@ -17,7 +17,12 @@ import {
} from "#execution/durable-session-store.js";
import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
import { hydrateDurableSession } from "#execution/session.js";
-import { emitProxiedInputRequest } from "#execution/subagent-hitl-proxy.js";
+import {
+ emitTurnEpilogue,
+ getHarnessEmissionState,
+ setHarnessEmissionState,
+} from "#harness/emission.js";
+import { emitProxiedInputRequest } from "#subagents/hitl-proxy.js";
import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { AnswerHookRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
@@ -25,6 +30,8 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { encodeMessageStreamEvent, stampMessageStreamEvent } from "#protocol/message.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
+import type { RunMode } from "#shared/run-mode.js";
+import type { TaskInputRequestDelivery } from "#tasks/types.js";
type SubagentEventHookPayload =
| SubagentAuthorizationEventHookPayload
@@ -61,7 +68,7 @@ export async function runProxySubagentEventStep(input: {
/** Emits a task request whose proxy routes were committed by a prior step. */
export async function emitRecordedTaskInputRequestStep(input: {
- readonly hookPayload: SubagentInputRequestHookPayload;
+ readonly request: TaskInputRequestDelivery;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -70,30 +77,22 @@ export async function emitRecordedTaskInputRequestStep(input: {
const durableSession = await readDurableSession(input.sessionState);
const ctx = await deserializeContext(input.serializedContext);
- return emitProxiedSubagentEvent({
+ return await emitProxiedSubagentEvent({
ctx,
durableSession,
- hookPayload: input.hookPayload,
- parentWritable: input.parentWritable,
- recordProxyInputRequests: false,
- });
-}
-
-/** Emits a task authorization event after its ownership was validated. */
-export async function emitRecordedTaskAuthorizationEventStep(input: {
- readonly hookPayload: SubagentAuthorizationEventHookPayload;
- readonly parentWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
-}): Promise<ProxySubagentEventResult> {
- "use step";
-
- const durableSession = await readDurableSession(input.sessionState);
- const ctx = await deserializeContext(input.serializedContext);
- return emitProxiedSubagentEvent({
- ctx,
- durableSession,
- hookPayload: input.hookPayload,
+ hookPayload: {
+ callId: input.request.taskId,
+ childContinuationToken: input.request.replyTo,
+ childSessionId: input.request.taskId,
+ event: {
+ requests: (input.request.requests ?? [input.request.request]) as never,
+ sequence: input.request.sequence,
+ stepIndex: input.request.stepIndex,
+ turnId: input.request.turnId,
+ },
+ kind: "subagent-input-request",
+ subagentName: input.request.taskId,
+ },
parentWritable: input.parentWritable,
recordProxyInputRequests: false,
});
@@ -135,7 +134,15 @@ export async function emitProxiedSubagentEvent(input: {
const scopeResult = await withContextScope(ctx, session, async (enrichedSession) => {
if (input.hookPayload.kind === "subagent-authorization-event") {
await emit(input.hookPayload.event);
- return { result: undefined, session: enrichedSession };
+ return {
+ result: undefined,
+ session: await closeStandaloneAuthorizationEvent({
+ emit,
+ eventType: input.hookPayload.event.type,
+ mode: ctx.require(ModeKey),
+ session: enrichedSession,
+ }),
+ };
}
const proxyResult = await emitProxiedInputRequest({
@@ -177,3 +184,21 @@ export async function emitProxiedSubagentEvent(input: {
sessionState: createDurableSessionState({ session: nextSession }),
};
}
+
+async function closeStandaloneAuthorizationEvent(input: {
+ readonly emit: (event: UnstampedMessageStreamEvent) => Promise<void>;
+ readonly eventType: SubagentAuthorizationEventHookPayload["event"]["type"];
+ readonly mode: RunMode;
+ readonly session: HarnessSession;
+}): Promise<HarnessSession> {
+ if (
+ input.mode !== "conversation" ||
+ (input.eventType !== "authorization.required" && input.eventType !== "authorization.completed")
+ ) {
+ return input.session;
+ }
+
+ const state = getHarnessEmissionState(input.session.state);
+ const nextState = await emitTurnEpilogue(input.emit, state, input.mode);
+ return setHarnessEmissionState(input.session, nextState);
+}
diff --git a/packages/eve/src/subagents/handle-dispatch.ts b/packages/eve/src/subagents/handle-dispatch.ts
new file mode 100644
index 000000000..886a6bb1d
--- /dev/null
+++ b/packages/eve/src/subagents/handle-dispatch.ts
@@ -0,0 +1,269 @@
+/** Continuation delivery for task-owned agent sessions. */
+
+import type { SessionAuthContext } from "#channel/types.js";
+import { AGENT_UNREACHABLE } from "#subagents/agent-handle-errors.js";
+import type { AgentAddress, AgentIdentity } from "#subagents/handles/store.js";
+import type {
+ RuntimeAgentDispatchRequest,
+ RuntimeRemoteAgentDispatchRequest,
+ RuntimeSubagentDispatchRequest,
+ RuntimeSubagentDispatchFailure,
+} from "#shared/action-types.js";
+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+import {
+ continueRemoteAgentSession,
+ isAmbiguousRemoteAgentContinueError,
+ isRetryableRemoteAgentContinueError,
+ resolveRemoteAgentForAction,
+} from "#subagents/remote-dispatch.js";
+import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
+import type { hydrateDurableSession } from "#execution/session.js";
+import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
+import { createLogger, logError } from "#internal/logging.js";
+import { createEveCallbackRoutePath } from "#protocol/routes.js";
+import { err, ok, type Result } from "#shared/result.js";
+import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
+import type { TaskOwnedAgentHandle } from "#subagents/handles/store.js";
+
+const log = createLogger("execution.agent-handle-dispatch");
+
+/** Agent-task requests that may address an agent handle via `agentId`. */
+export type RuntimeAgentHandleAction =
+ | RuntimeRemoteAgentDispatchRequest
+ | RuntimeSubagentDispatchRequest;
+
+/** Narrows an action to the kinds that may carry an `agentId` continuation. */
+export function isAgentHandleAction(
+ action: RuntimeAgentDispatchRequest,
+): action is RuntimeAgentHandleAction {
+ return action.kind === "subagent-call" || action.kind === "remote-agent-call";
+}
+
+/** Hydrated parent session snapshot threaded through dispatch. */
+export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;
+
+/**
+ * Outcome of dispatching one planned agent task: an adopted child ready for
+ * the `subagent.called` emission tail, or a per-task error result.
+ * Either way the (possibly updated) session snapshot rides along.
+ *
+ * `address` is the same confirmed {@link AgentAddress} recorded on the
+ * child's running handle; consumers project it into wire shapes (e.g. the
+ * flat `childSessionId` / `remote` fields of `subagent.called`) at the
+ * emission site instead of this type re-encoding them.
+ */
+export type DispatchOutcome =
+ | {
+ readonly address: AgentAddress;
+ readonly callId: string;
+ readonly kind: "called";
+ readonly name: string;
+ readonly session: RuntimeSession;
+ readonly toolName: string;
+ }
+ | {
+ readonly deliveryAmbiguous?: boolean;
+ readonly deliveryPermanent?: boolean;
+ readonly kind: "error";
+ readonly result: RuntimeSubagentDispatchFailure;
+ readonly session: RuntimeSession;
+ };
+
+/** Delivers a continuation after the session handle store atomically claimed it for one owner. */
+export async function dispatchToClaimedAgentAddress(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly auth: SessionAuthContext | null;
+ readonly bundle: CompiledBundle;
+ readonly currentSession: RuntimeSession;
+ readonly parentToken: string;
+ readonly handle: Extract<TaskOwnedAgentHandle, { phase: "claimed" }>;
+ readonly taskId?: string;
+}): Promise<DispatchOutcome> {
+ return await dispatchToAgentAddress(input);
+}
+
+/** Delivers a continuation to an already-claimed local or remote agent address. */
+async function dispatchToAgentAddress(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly auth: SessionAuthContext | null;
+ readonly bundle: CompiledBundle;
+ readonly currentSession: RuntimeSession;
+ readonly parentToken: string;
+ readonly handle: { readonly address: AgentAddress; readonly identity: AgentIdentity };
+ readonly taskId?: string;
+}): Promise<DispatchOutcome> {
+ const { action, handle } = input;
+ const agentId = handle.identity.id;
+
+ const delivery = await deliverToAgentAddress({
+ action,
+ address: handle.address,
+ auth: input.auth,
+ bundle: input.bundle,
+ identity: handle.identity,
+ parentToken: input.parentToken,
+ taskId: input.taskId,
+ });
+ if (!delivery.ok) {
+ const { cause, permanent } = delivery.error;
+ logError(log, "task agent delivery failed", cause, {
+ agentId,
+ callId: action.callId,
+ nodeId: handle.identity.nodeId,
+ permanent,
+ subagentName: handle.identity.name,
+ });
+ return {
+ deliveryAmbiguous: delivery.error.deliveryAmbiguous,
+ deliveryPermanent: permanent,
+ kind: "error",
+ result: createAgentErrorResult({
+ action,
+ code: AGENT_UNREACHABLE,
+ message: permanent
+ ? `Agent "${handle.identity.name}" with id "${agentId}" is no longer reachable.`
+ : `Agent "${handle.identity.name}" with id "${agentId}" is temporarily unreachable. Try again.`,
+ }),
+ session: input.currentSession,
+ };
+ }
+
+ return {
+ address: handle.address,
+ callId: action.callId,
+ kind: "called",
+ name: action.name,
+ session: input.currentSession,
+ toolName: handle.identity.name,
+ };
+}
+
+/**
+ * Attempts the continuation delivery once and classifies the failure.
+ *
+ * Transient failures are never retried automatically: the callee may have
+ * accepted the message even though the response was lost, so a re-send could
+ * deliver the same turn twice. The caller surfaces a retryable
+ * AGENT_UNREACHABLE instead and the model decides whether to try again.
+ * Throwing is equally unsafe — a durable-step retry would re-dispatch
+ * already-started siblings.
+ */
+async function deliverToAgentAddress(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly address: AgentAddress;
+ readonly auth: SessionAuthContext | null;
+ readonly bundle: CompiledBundle;
+ readonly identity: AgentIdentity;
+ readonly parentToken: string;
+ readonly taskId?: string;
+}): Promise<
+ Result<
+ void,
+ { readonly cause: unknown; readonly deliveryAmbiguous: boolean; readonly permanent: boolean }
+ >
+> {
+ const { action, address, bundle, identity } = input;
+
+ if (address.kind === "agent/remote") {
+ let resolvedRemote;
+ try {
+ resolvedRemote = resolveRemoteAgentForAction({
+ nodeId: identity.nodeId,
+ remoteAgentName: identity.name,
+ registry: bundle.subagentRegistry.subagentsByNodeId,
+ });
+ } catch (error) {
+ // The agent's node is gone from the compiled bundle; no retry can
+ // reach this handle again.
+ return err({ cause: error, deliveryAmbiguous: false, permanent: true });
+ }
+ try {
+ await continueRemoteAgentSession({
+ auth: input.auth,
+ callback: {
+ callId: action.callId,
+ subagentName: identity.name,
+ taskId: input.taskId ?? readTaskIdFromInboxToken(input.parentToken),
+ token: input.parentToken,
+ url: createWorkflowCallbackUrl(
+ address.callbackBaseUrl,
+ createEveCallbackRoutePath(input.parentToken),
+ ),
+ },
+ message: readSubagentMessage(action),
+ outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),
+ remote: { ...resolvedRemote, url: address.url },
+ sessionId: address.sessionId,
+ });
+ } catch (error) {
+ return err({
+ cause: error,
+ deliveryAmbiguous: isAmbiguousRemoteAgentContinueError(error),
+ permanent: !isRetryableRemoteAgentContinueError(error),
+ });
+ }
+ return ok(undefined);
+ }
+
+ const childRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: bundle.compiledArtifactsSource,
+ nodeId: identity.nodeId,
+ });
+ try {
+ const result = await childRuntime.dispatchSession({
+ command: {
+ auth: input.auth,
+ caller: {
+ callId: action.callId,
+ replyTo: { kind: "hook", token: input.parentToken },
+ subagentName: identity.name,
+ taskId: input.taskId ?? readTaskIdFromInboxToken(input.parentToken),
+ },
+ kind: "send",
+ payload: {
+ message: readSubagentMessage(action),
+ outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),
+ },
+ },
+ sessionId: address.sessionId,
+ });
+ if (result.status === "session_not_active") {
+ return err({
+ cause: new Error(`Agent session "${address.sessionId}" is no longer active.`),
+ deliveryAmbiguous: false,
+ permanent: true,
+ });
+ }
+ } catch (error) {
+ const permanent = isRuntimeNoActiveSessionError(error);
+ return err({ cause: error, deliveryAmbiguous: !permanent, permanent });
+ }
+ return ok(undefined);
+}
+
+export function createAgentErrorResult(input: {
+ readonly action: RuntimeAgentHandleAction;
+ readonly code: string;
+ readonly message: string;
+}): RuntimeSubagentDispatchFailure {
+ return {
+ callId: input.action.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: input.code,
+ message: input.message,
+ },
+ subagentName:
+ input.action.kind === "remote-agent-call"
+ ? input.action.remoteAgentName
+ : input.action.subagentName,
+ };
+}
+
+function readSubagentMessage(action: RuntimeAgentHandleAction): string {
+ return typeof action.input.message === "string" ? action.input.message : "";
+}
diff --git a/packages/eve/src/harness/handles/operation-id.ts b/packages/eve/src/subagents/handles/operation-id.ts
similarity index 100%
rename from packages/eve/src/harness/handles/operation-id.ts
rename to packages/eve/src/subagents/handles/operation-id.ts
diff --git a/packages/eve/src/harness/handles/prompt.test.ts b/packages/eve/src/subagents/handles/prompt.test.ts
similarity index 91%
rename from packages/eve/src/harness/handles/prompt.test.ts
rename to packages/eve/src/subagents/handles/prompt.test.ts
index 21463f7cd..b04c8cc46 100644
--- a/packages/eve/src/harness/handles/prompt.test.ts
+++ b/packages/eve/src/subagents/handles/prompt.test.ts
@@ -5,8 +5,8 @@ import {
renderAgentViewsSnippet,
renderAgentsSnippet,
resolveAgentsAnnouncement,
-} from "#harness/handles/prompt.js";
-import type { AgentHandle } from "#harness/handles/store.js";
+} from "#subagents/handles/prompt.js";
+import type { AgentHandle } from "#subagents/handles/store.js";
const identity = {
id: "ag_research:abcdef123456",
@@ -43,7 +43,7 @@ const parkedRemoteHandle: AgentHandle = {
};
describe("projectParkedAgentHandles / renderAgentsSnippet", () => {
- it("projects and renders only parked handles", () => {
+ it("projects and renders only idle handles", () => {
const runningStore = { handles: [runningHandle] };
expect(projectParkedAgentHandles(runningStore)).toEqual([]);
expect(renderAgentsSnippet(runningStore)).toBe("[Agents]\n<agents>\n</agents>");
@@ -55,6 +55,15 @@ describe("projectParkedAgentHandles / renderAgentsSnippet", () => {
expect(snippet).toContain(
`<agent id="${identity.id}" name="research">initial findings</agent>`,
);
+
+ const availableHandle = {
+ address: runningHandle.address,
+ identity,
+ phase: "available" as const,
+ };
+ expect(renderAgentsSnippet({ handles: [availableHandle] })).toContain(
+ `<agent id="${identity.id}" name="research">(available)</agent>`,
+ );
});
it("omits private delivery coordinates and renders a placeholder for empty statuses", () => {
diff --git a/packages/eve/src/harness/handles/prompt.ts b/packages/eve/src/subagents/handles/prompt.ts
similarity index 81%
rename from packages/eve/src/harness/handles/prompt.ts
rename to packages/eve/src/subagents/handles/prompt.ts
index 07cdfe3d2..941693b61 100644
--- a/packages/eve/src/harness/handles/prompt.ts
+++ b/packages/eve/src/subagents/handles/prompt.ts
@@ -1,6 +1,6 @@
import type { ModelMessage } from "ai";
-import type { AgentHandle, AgentHandleStore } from "#harness/handles/store.js";
+import type { AgentHandle, AgentHandleStore } from "#subagents/handles/store.js";
/**
* Label prefixing every framework-injected agents announcement. Mock model
@@ -19,23 +19,26 @@ export interface AgentView {
readonly taskStatus?: "working" | "input_required";
}
-/** Returns the resumable handles: the only phase the model may continue. */
+/** Returns the resumable handles: the only phases the model may continue. */
export function projectParkedAgentHandles(
store: AgentHandleStore,
-): readonly Extract<AgentHandle, { phase: "parked" }>[] {
- return store.handles.filter((handle) => handle.phase === "parked");
+): readonly Extract<AgentHandle, { phase: "available" | "parked" }>[] {
+ return store.handles.filter(
+ (handle): handle is Extract<AgentHandle, { phase: "available" | "parked" }> =>
+ handle.phase === "available" || handle.phase === "parked",
+ );
}
/**
- * Renders the model-visible agent listing. Only parked handles appear:
+ * Renders the model-visible agent listing. Only idle handles appear:
* starting and running children cannot accept a continuation, and private
* delivery coordinates never render.
*/
export function renderAgentsSnippet(store: AgentHandleStore): string {
- const agents = projectParkedAgentHandles(store).map(
- (handle) =>
- `<agent id="${escapeXml(handle.identity.id)}" name="${escapeXml(handle.identity.name)}">${escapeXml(handle.lastStatus === "" ? "(no status)" : handle.lastStatus)}</agent>`,
- );
+ const agents = projectParkedAgentHandles(store).map((handle) => {
+ const status = handle.phase === "parked" ? handle.lastStatus : "(available)";
+ return `<agent id="${escapeXml(handle.identity.id)}" name="${escapeXml(handle.identity.name)}">${escapeXml(status === "" ? "(no status)" : status)}</agent>`;
+ });
return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
}
diff --git a/packages/eve/src/subagents/handles/query.test.ts b/packages/eve/src/subagents/handles/query.test.ts
new file mode 100644
index 000000000..a018a9705
--- /dev/null
+++ b/packages/eve/src/subagents/handles/query.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+
+import { mergeTaskOwnedAgentHandlesIntoTurnState } from "#subagents/handles/query.js";
+import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#subagents/handles/store.js";
+
+const address = {
+ continuationToken: "child-token",
+ kind: "agent/local" as const,
+ sessionId: "child-session",
+};
+const identity = { id: "agent-1", name: "research", nodeId: "subagents/research" };
+const available: AgentHandle = { address, identity, phase: "available" };
+const claimed: AgentHandle = {
+ address,
+ callId: "call-1",
+ identity,
+ operationId: "operation-1",
+ ownerId: "workflow-run-1",
+ phase: "claimed",
+};
+
+describe("mergeTaskOwnedAgentHandlesIntoTurnState", () => {
+ it("preserves a blocking workflow run's claim when the driver did not change the handle", () => {
+ const baseState = {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [{ phase: "available", identity: { ...identity }, address: { ...address } }],
+ },
+ };
+
+ expect(
+ mergeTaskOwnedAgentHandlesIntoTurnState({
+ baseState,
+ driverState: baseState,
+ turnState: { [AGENT_HANDLES_STATE_KEY]: { handles: [claimed] } },
+ }),
+ ).toEqual({ [AGENT_HANDLES_STATE_KEY]: { handles: [claimed] } });
+ });
+
+ it("rejects conflicting owner mutations from the driver and turn", () => {
+ const taskClaim: AgentHandle = { ...claimed, ownerId: "task_1" };
+
+ expect(() =>
+ mergeTaskOwnedAgentHandlesIntoTurnState({
+ baseState: { [AGENT_HANDLES_STATE_KEY]: { handles: [available] } },
+ driverState: { [AGENT_HANDLES_STATE_KEY]: { handles: [taskClaim] } },
+ turnState: { [AGENT_HANDLES_STATE_KEY]: { handles: [claimed] } },
+ }),
+ ).toThrow("changed ownership while its turn was running");
+ });
+});
diff --git a/packages/eve/src/subagents/handles/query.ts b/packages/eve/src/subagents/handles/query.ts
new file mode 100644
index 000000000..9e0dd98bf
--- /dev/null
+++ b/packages/eve/src/subagents/handles/query.ts
@@ -0,0 +1,156 @@
+import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#shared/action-types.js";
+import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/state-key.js";
+import type {
+ AgentHandle,
+ AgentHandleStore,
+ TurnOwnedAgentHandle,
+} from "#subagents/handles/store.js";
+import type { SessionStateMap } from "#harness/types.js";
+
+/** A handle with one outstanding operation and a confirmed child address. */
+export type RunningAgentHandle = Extract<TurnOwnedAgentHandle, { phase: "running" }>;
+
+/**
+ * Schema-free read of the agent handles from session state.
+ *
+ * Trust boundary: every source store was validated by a handle transition.
+ * Driver-side reads trust that invariant instead of re-validating, so the
+ * workflow driver bundle stays free of compiled zod.
+ */
+function readAgentHandles(state: SessionStateMap | undefined): readonly AgentHandle[] {
+ const raw = state?.[AGENT_HANDLES_STATE_KEY];
+ if (raw === undefined) {
+ return [];
+ }
+ const handles = (raw as { handles?: unknown }).handles;
+ return Array.isArray(handles) ? (handles as readonly AgentHandle[]) : [];
+}
+
+/** Preserves driver-owned task leases when a concurrent turn returns an older snapshot. */
+export function mergeTaskOwnedAgentHandlesIntoTurnState(input: {
+ readonly baseState: SessionStateMap | undefined;
+ readonly driverState: SessionStateMap | undefined;
+ readonly turnState: SessionStateMap | undefined;
+}): SessionStateMap | undefined {
+ const baseHandles = new Map(
+ readAgentHandles(input.baseState).map((handle) => [handle.identity.id, handle] as const),
+ );
+ const driverHandles = new Map(
+ readAgentHandles(input.driverState).map((handle) => [handle.identity.id, handle] as const),
+ );
+ const mutatedIds = new Set([...baseHandles.keys(), ...driverHandles.keys()]);
+ for (const id of mutatedIds) {
+ if (handlesEqual(baseHandles.get(id), driverHandles.get(id))) mutatedIds.delete(id);
+ }
+ if (mutatedIds.size === 0) return input.turnState;
+
+ const merged: AgentHandle[] = [];
+ for (const handle of readAgentHandles(input.turnState)) {
+ if (!mutatedIds.has(handle.identity.id)) {
+ merged.push(handle);
+ continue;
+ }
+ const current = driverHandles.get(handle.identity.id);
+ const base = baseHandles.get(handle.identity.id);
+ if (!handlesEqual(handle, base) && !handlesEqual(handle, current)) {
+ throw new Error(
+ `Agent handle "${handle.identity.id}" changed ownership while its turn was running.`,
+ );
+ }
+ if (current !== undefined) merged.push(current);
+ mutatedIds.delete(handle.identity.id);
+ }
+ for (const id of mutatedIds) {
+ const current = driverHandles.get(id);
+ if (current !== undefined) merged.push(current);
+ }
+
+ return {
+ ...input.turnState,
+ [AGENT_HANDLES_STATE_KEY]: { handles: merged } satisfies AgentHandleStore,
+ };
+}
+
+function handlesEqual(left: AgentHandle | undefined, right: AgentHandle | undefined): boolean {
+ if (left === right) return true;
+ if (left === undefined || right === undefined) return false;
+ const leftKeys = Object.keys(left);
+ const rightKeys = Object.keys(right);
+ return (
+ leftKeys.length === rightKeys.length &&
+ leftKeys.every((key) => valuesEqual(Reflect.get(left, key), Reflect.get(right, key)))
+ );
+}
+
+function valuesEqual(left: unknown, right: unknown): boolean {
+ if (left === right) return true;
+ if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) {
+ return false;
+ }
+ const leftKeys = Object.keys(left);
+ const rightKeys = Object.keys(right);
+ return (
+ leftKeys.length === rightKeys.length &&
+ leftKeys.every((key) => valuesEqual(Reflect.get(left, key), Reflect.get(right, key)))
+ );
+}
+
+/**
+ * Finds the running agent handle a child-produced result must settle: the
+ * handle whose recorded operation carries the result's callId.
+ *
+ * Binding is by callId alone. Possession of the parent's callback token is
+ * the authorization to settle; the handle's recorded address is used for
+ * outbound delivery (continuation, cancellation), never as an inbound
+ * identity check. Under the accepted at-least-once dispatch window a
+ * replay-orphaned duplicate child holds the same token and callId and may
+ * settle the call in place of the owned child — an accepted trade-off,
+ * since both children computed the same input.
+ */
+export function findRunningAgentHandle(
+ state: SessionStateMap | undefined,
+ input: { readonly callId: string },
+): RunningAgentHandle | undefined {
+ const handles = readAgentHandles(state);
+ return handles.find(
+ (handle): handle is RunningAgentHandle =>
+ handle.phase === "running" && handle.operation.callId === input.callId,
+ );
+}
+
+/**
+ * A subagent result may settle a call only when a running handle records
+ * its callId: a late or duplicate result for an already-settled call finds
+ * no running handle and is dropped.
+ *
+ * `dispatch`-origin failures pass unconditionally: the parent synthesizes
+ * them for calls whose child never started, and they reach the harness only
+ * through the trusted step-result path. Untrusted channels must use
+ * {@link isInboxSubagentResultFromRunningHandle} instead.
+ */
+export function isResultBoundToRunningHandle(
+ state: SessionStateMap | undefined,
+ result: RuntimeActionResult,
+): boolean {
+ if (result.kind !== "subagent-result") {
+ return true;
+ }
+ if (result.origin === "dispatch" || result.backgroundTask !== undefined) {
+ return true;
+ }
+ return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
+}
+
+/**
+ * Strict variant of {@link isResultBoundToRunningHandle} for results arriving
+ * over the shared turn inbox (child notifications and remote callbacks).
+ * An inbox result must bind to a running handle by callId; one with no
+ * matching running handle — including one for a callId whose dispatch
+ * already failed — must not overwrite the dispatch-produced error result.
+ */
+export function isInboxSubagentResultFromRunningHandle(
+ state: SessionStateMap | undefined,
+ result: RuntimeSubagentChildResult,
+): boolean {
+ return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
+}
diff --git a/packages/eve/src/subagents/handles/rebase.ts b/packages/eve/src/subagents/handles/rebase.ts
new file mode 100644
index 000000000..da4763865
--- /dev/null
+++ b/packages/eve/src/subagents/handles/rebase.ts
@@ -0,0 +1,34 @@
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
+import { mergeTaskOwnedAgentHandlesIntoTurnState } from "#subagents/handles/query.js";
+
+/** Preserves handle leases accepted by the driver against a turn's older snapshot. */
+export function rebaseTaskAgentHandleMutations(
+ action: TurnDriverAction,
+ driverState: DurableSessionState,
+ baseState: DurableSessionState,
+): TurnDriverAction {
+ const snapshot = action.sessionState.snapshot;
+ if (snapshot === undefined) {
+ throw new Error(
+ "Cannot merge task-owned agent handles into a session state without a snapshot.",
+ );
+ }
+ return {
+ ...action,
+ sessionState: {
+ ...action.sessionState,
+ snapshot: {
+ ...snapshot,
+ session: {
+ ...snapshot.session,
+ state: mergeTaskOwnedAgentHandlesIntoTurnState({
+ baseState: baseState.snapshot?.session.state,
+ driverState: driverState.snapshot?.session.state,
+ turnState: snapshot.session.state,
+ }),
+ },
+ },
+ },
+ };
+}
diff --git a/packages/eve/src/harness/handles/state-key.ts b/packages/eve/src/subagents/handles/state-key.ts
similarity index 100%
rename from packages/eve/src/harness/handles/state-key.ts
rename to packages/eve/src/subagents/handles/state-key.ts
diff --git a/packages/eve/src/harness/handles/store.test.ts b/packages/eve/src/subagents/handles/store.test.ts
similarity index 92%
rename from packages/eve/src/harness/handles/store.test.ts
rename to packages/eve/src/subagents/handles/store.test.ts
index d9459d4dd..fabd14e37 100644
--- a/packages/eve/src/harness/handles/store.test.ts
+++ b/packages/eve/src/subagents/handles/store.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
import {
AGENT_HANDLES_STATE_KEY,
assertPersistableAgentHandleStore,
@@ -11,7 +11,7 @@ import {
type AgentHandle,
type AgentIdentity,
type StartOperation,
-} from "#harness/handles/store.js";
+} from "#subagents/handles/store.js";
const startOperation: StartOperation = {
callId: "call_1",
@@ -43,12 +43,6 @@ const parkedHandle: AgentHandle = {
phase: "parked",
};
-const addressedHandle: AgentHandle = {
- address,
- identity,
- phase: "addressed",
-};
-
describe("deriveAgentOperationId / deriveAgentId", () => {
it("is deterministic on parent-controlled inputs and independent of the child session", () => {
const again = deriveAgentOperationId({
@@ -111,8 +105,8 @@ describe("getAgentHandleStore", () => {
describe("assertPersistableAgentHandleStore", () => {
it("returns a valid store unchanged in shape", () => {
- expect(assertPersistableAgentHandleStore({ handles: [addressedHandle] })).toEqual({
- handles: [addressedHandle],
+ expect(assertPersistableAgentHandleStore({ handles: [parkedHandle] })).toEqual({
+ handles: [parkedHandle],
});
});
diff --git a/packages/eve/src/harness/handles/store.ts b/packages/eve/src/subagents/handles/store.ts
similarity index 59%
rename from packages/eve/src/harness/handles/store.ts
rename to packages/eve/src/subagents/handles/store.ts
index 6abe6c289..448b11373 100644
--- a/packages/eve/src/harness/handles/store.ts
+++ b/packages/eve/src/subagents/handles/store.ts
@@ -94,21 +94,13 @@ export type AgentAddress =
};
/**
- * Durable ownership record for one delegated child.
- *
- * Outside tasks mode, the store owns the full nonterminal lifecycle:
+ * Parent-turn-owned lifecycle: `starting → running → parked ↔ running`.
*
- * - `starting` — the parent committed intent to start; the child may or
- * may not exist yet.
- * - `running` — one identified child turn is outstanding.
- * - `parked` — the child is idle and resumable; only this phase is
- * model-visible.
- *
- * A terminal child has no legacy handle: settlement deletes it. Tasks mode
- * instead keeps an `addressed` record whose availability is derived from the
- * tasks bound to its persistent child session.
+ * `starting` owns a start intent before the child has an address, `running`
+ * owns one outstanding child turn, and `parked` retains an idle, resumable
+ * child. A terminal child or dead dispatch leaves this union entirely.
*/
-export type AgentHandle =
+export type TurnOwnedAgentHandle =
| {
readonly phase: "starting";
readonly identity: AgentIdentity;
@@ -126,14 +118,50 @@ export type AgentHandle =
readonly identity: AgentIdentity;
readonly address: AgentAddress;
readonly lastStatus: string;
+ };
+
+/**
+ * Workflow-owner lifecycle: `reserved → claimed → available ↔ claimed`.
+ *
+ * `reserved` leases a fresh identity before start, `claimed` leases an
+ * addressed child turn to one task or workflow-tool run, and `available`
+ * retains the idle address between invocations. A terminal child leaves this
+ * union entirely.
+ */
+export type TaskOwnedAgentHandle =
+ | {
+ /** Fresh identity leased to one owner before the child's address is confirmed. */
+ readonly phase: "reserved";
+ readonly identity: AgentIdentity;
+ readonly operationId: string;
+ readonly callId?: string;
+ readonly ownerId: string;
}
| {
- /** Persistent task-mode identity and routing, with no execution claim. */
- readonly phase: "addressed";
+ /** Addressed child turn leased until its owner releases it. */
+ readonly phase: "claimed";
+ readonly identity: AgentIdentity;
+ readonly operationId: string;
+ readonly callId?: string;
+ readonly address: AgentAddress;
+ readonly ownerId: string;
+ }
+ | {
+ /** Idle addressed child with no owner lease, ready for a later invocation to claim. */
+ readonly phase: "available";
readonly identity: AgentIdentity;
readonly address: AgentAddress;
};
+/**
+ * Durable ownership record for one delegated child.
+ *
+ * The two execution policies share an identity namespace and serialized store,
+ * but their lifecycle states and transitions are disjoint. A terminal child has
+ * no handle: settlement deletes it.
+ */
+export type AgentHandle = TurnOwnedAgentHandle | TaskOwnedAgentHandle;
+
/** Lifecycle phase of a delegated agent handle. */
export type AgentHandlePhase = AgentHandle["phase"];
@@ -142,6 +170,42 @@ export interface AgentHandleStore {
readonly handles: readonly AgentHandle[];
}
+export const EMPTY_AGENT_HANDLE_STORE: AgentHandleStore = { handles: [] };
+
+/** One serialized owner-lease mutation against the shared agent handle store. */
+export type AgentHandleStoreCommand =
+ | { readonly kind: "read" }
+ | {
+ readonly identity: AgentIdentity;
+ readonly kind: "reserve";
+ readonly operationId: string;
+ readonly callId?: string;
+ readonly ownerId: string;
+ }
+ | {
+ readonly address: AgentAddress;
+ readonly kind: "confirm";
+ readonly operationId: string;
+ readonly ownerId: string;
+ }
+ | {
+ readonly agentId: string;
+ readonly expectedTarget: "local" | "remote";
+ readonly callId?: string;
+ readonly invokedName: string;
+ readonly kind: "claim";
+ readonly operationId: string;
+ readonly ownerId: string;
+ }
+ | { readonly agentId: string; readonly kind: "remove"; readonly ownerId: string }
+ | { readonly kind: "release-owner"; readonly ownerId: string };
+
+export type AgentHandleStoreCommandResult =
+ | { readonly kind: "ready"; readonly handle?: TaskOwnedAgentHandle }
+ | { readonly kind: "busy"; readonly handle: AgentHandle }
+ | { readonly kind: "mismatch"; readonly handle: AgentHandle }
+ | { readonly kind: "unknown" };
+
const nonEmptyString = z.string().min(1);
const identitySchema = z.strictObject({
@@ -196,7 +260,42 @@ const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [
}),
]);
-const agentHandleSchema: z.ZodType<AgentHandle> = z.discriminatedUnion("phase", [
+const agentHandleStoreCommandSchema: z.ZodType<AgentHandleStoreCommand> = z.discriminatedUnion(
+ "kind",
+ [
+ z.strictObject({ kind: z.literal("read") }),
+ z.strictObject({
+ identity: identitySchema,
+ callId: nonEmptyString.optional(),
+ kind: z.literal("reserve"),
+ operationId: nonEmptyString,
+ ownerId: nonEmptyString,
+ }),
+ z.strictObject({
+ address: addressSchema,
+ kind: z.literal("confirm"),
+ operationId: nonEmptyString,
+ ownerId: nonEmptyString,
+ }),
+ z.strictObject({
+ agentId: nonEmptyString,
+ callId: nonEmptyString.optional(),
+ expectedTarget: z.enum(["local", "remote"]),
+ invokedName: nonEmptyString,
+ kind: z.literal("claim"),
+ operationId: nonEmptyString,
+ ownerId: nonEmptyString,
+ }),
+ z.strictObject({
+ agentId: nonEmptyString,
+ kind: z.literal("remove"),
+ ownerId: nonEmptyString,
+ }),
+ z.strictObject({ kind: z.literal("release-owner"), ownerId: nonEmptyString }),
+ ],
+);
+
+const turnOwnedAgentHandleSchema: z.ZodType<TurnOwnedAgentHandle> = z.discriminatedUnion("phase", [
z.strictObject({
identity: identitySchema,
operation: startOperationSchema,
@@ -215,13 +314,36 @@ const agentHandleSchema: z.ZodType<AgentHandle> = z.discriminatedUnion("phase",
lastStatus: z.string().max(MAX_STATUS_LENGTH),
phase: z.literal("parked"),
}),
+]);
+
+const taskOwnedAgentHandleSchema: z.ZodType<TaskOwnedAgentHandle> = z.discriminatedUnion("phase", [
+ z.strictObject({
+ callId: nonEmptyString.optional(),
+ identity: identitySchema,
+ operationId: nonEmptyString,
+ phase: z.literal("reserved"),
+ ownerId: nonEmptyString,
+ }),
+ z.strictObject({
+ address: addressSchema,
+ callId: nonEmptyString.optional(),
+ identity: identitySchema,
+ operationId: nonEmptyString,
+ phase: z.literal("claimed"),
+ ownerId: nonEmptyString,
+ }),
z.strictObject({
address: addressSchema,
identity: identitySchema,
- phase: z.literal("addressed"),
+ phase: z.literal("available"),
}),
]);
+const agentHandleSchema: z.ZodType<AgentHandle> = z.union([
+ turnOwnedAgentHandleSchema,
+ taskOwnedAgentHandleSchema,
+]);
+
const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z
.strictObject({
handles: z.array(agentHandleSchema),
@@ -257,6 +379,12 @@ export function assertPersistableAgentHandleStore(store: AgentHandleStore): Agen
return parsed.data;
}
+/** Parses one complete command before the session inbox routes it to the handle store. */
+export function parseAgentHandleStoreCommand(value: unknown): AgentHandleStoreCommand | undefined {
+ const parsed = agentHandleStoreCommandSchema.safeParse(value);
+ return parsed.success ? parsed.data : undefined;
+}
+
/**
* Reads and validates the agent handle store from session state.
*
@@ -279,3 +407,25 @@ export function getAgentHandleStore(
}
return parsed.data;
}
+
+/** Writes the validated agent handle store under its single session-state key. */
+export function setAgentHandleStore(
+ state: SessionStateMap | undefined,
+ store: AgentHandleStore,
+): SessionStateMap {
+ return {
+ ...state,
+ [AGENT_HANDLES_STATE_KEY]: assertPersistableAgentHandleStore(store),
+ };
+}
+
+/** Writes a validated handle list to a session-shaped value. */
+export function writeHandles<Session extends { readonly state?: SessionStateMap }>(
+ session: Session,
+ handles: readonly AgentHandle[],
+): Session {
+ return {
+ ...session,
+ state: setAgentHandleStore(session.state, { handles }),
+ };
+}
diff --git a/packages/eve/src/harness/handles/transitions.test.ts b/packages/eve/src/subagents/handles/transitions.test.ts
similarity index 51%
rename from packages/eve/src/harness/handles/transitions.test.ts
rename to packages/eve/src/subagents/handles/transitions.test.ts
index 06b2fd4ad..a1381ca47 100644
--- a/packages/eve/src/harness/handles/transitions.test.ts
+++ b/packages/eve/src/subagents/handles/transitions.test.ts
@@ -1,28 +1,26 @@
import { describe, expect, it } from "vitest";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";
import {
- AGENT_HANDLES_STATE_KEY,
+ EMPTY_AGENT_HANDLE_STORE,
deriveAgentId,
getAgentHandleStore,
+ writeHandles,
type AgentAddress,
type AgentHandle,
type AgentIdentity,
- type ContinueOperation,
type StartOperation,
-} from "#harness/handles/store.js";
+ type TaskOwnedAgentHandle,
+} from "#subagents/handles/store.js";
import {
+ abandonAgentInvocationOwners,
abandonRunningAgentTurns,
+ applyAgentHandleStoreCommand,
confirmAgentStarted,
- confirmTaskAgentAddress,
- prepareAgentContinuation,
prepareAgentStart,
- rebaseAgentHandles,
- recordTaskAgentAddress,
rejectAgentEffect,
- removeTaskAgentAddress,
settleAgentTurn,
-} from "#harness/handles/transitions.js";
+} from "#subagents/handles/transitions.js";
import type { HarnessSession } from "#harness/types.js";
import type { TokenUsage } from "#shared/token-usage.js";
@@ -148,125 +146,6 @@ describe("confirmAgentStarted", () => {
});
});
-describe("task agent addresses", () => {
- it("confirms a persistent address without an execution phase", () => {
- const addressed = confirmTaskAgentAddress(preparedSession(), {
- address,
- operationId: startOperation.id,
- });
-
- expect(handlesOf(addressed)).toEqual([{ address, identity, phase: "addressed" }]);
- });
-
- it("removes only the addressed task agent", () => {
- const addressed = confirmTaskAgentAddress(preparedSession(), {
- address,
- operationId: startOperation.id,
- });
-
- expect(handlesOf(removeTaskAgentAddress(addressed, identity.id))).toEqual([]);
- });
-});
-
-describe("recordTaskAgentAddress", () => {
- it("appends an addressed handle from a delegated task's executor binding", () => {
- const recorded = recordTaskAgentAddress(createSession(), { address, identity });
- expect(handlesOf(recorded)).toEqual([{ address, identity, phase: "addressed" }]);
- });
-
- it("is a replay no-op when the identical handle is already stored", () => {
- const recorded = recordTaskAgentAddress(createSession(), { address, identity });
- expect(recordTaskAgentAddress(recorded, { address, identity })).toBe(recorded);
- });
-
- it("throws when the id already exists with different content", () => {
- const recorded = recordTaskAgentAddress(createSession(), { address, identity });
- expect(() =>
- recordTaskAgentAddress(recorded, {
- address: { ...address, continuationToken: "continuation_divergent" },
- identity,
- }),
- ).toThrow(identity.id);
- });
-});
-
-describe("prepareAgentContinuation", () => {
- const continueOperation: ContinueOperation = {
- callId: "call_2",
- id: deriveAgentOperationId({
- callId: "call_2",
- parentSessionId: "session_parent",
- parentTurnId: "turn_2",
- }),
- kind: "continue",
- parentTurnId: "turn_2",
- previousStatus: "",
- };
-
- it("moves parked to running and captures the previous status", () => {
- const result = prepareAgentContinuation(parkedSession(), {
- agentId: identity.id,
- invokedName: "research",
- operation: continueOperation,
- });
- expect(result.kind).toBe("ready");
- if (result.kind !== "ready") {
- return;
- }
- expect(result.handle.phase).toBe("running");
- expect(result.handle.operation).toEqual({
- ...continueOperation,
- previousStatus: "initial findings",
- });
- expect(handlesOf(result.session)).toEqual([result.handle]);
- });
-
- it("reports unknown, mismatch, and busy without changing the session", () => {
- expect(
- prepareAgentContinuation(parkedSession(), {
- agentId: "ag_missing:000000000000",
- invokedName: "research",
- operation: continueOperation,
- }),
- ).toEqual({ kind: "unknown" });
-
- expect(
- prepareAgentContinuation(parkedSession(), {
- agentId: identity.id,
- invokedName: "writer",
- operation: continueOperation,
- }),
- ).toEqual({ kind: "mismatch" });
-
- expect(
- prepareAgentContinuation(runningSession(), {
- agentId: identity.id,
- invokedName: "research",
- operation: continueOperation,
- }),
- ).toEqual({ kind: "busy" });
- });
-
- it("treats the operation already recorded on a running handle as a replay", () => {
- const running = runningSession();
- const replay = prepareAgentContinuation(running, {
- agentId: identity.id,
- invokedName: "research",
- operation: {
- callId: startOperation.callId,
- id: startOperation.id,
- kind: "continue",
- parentTurnId: startOperation.parentTurnId,
- previousStatus: "",
- },
- });
- expect(replay.kind).toBe("ready");
- if (replay.kind === "ready") {
- expect(replay.session).toBe(running);
- }
- });
-});
-
describe("rejectAgentEffect", () => {
it("deletes a dead start", () => {
const session = rejectAgentEffect(preparedSession(), {
@@ -277,21 +156,18 @@ describe("rejectAgentEffect", () => {
});
it("restores parked with the previous status for a retryable continuation", () => {
- const continueOperation: ContinueOperation = {
+ const continueOperation = {
callId: "call_2",
id: "op_continue",
kind: "continue",
parentTurnId: "turn_2",
- previousStatus: "",
+ previousStatus: "initial findings",
+ } as const;
+ const prepared = {
+ session: writeHandles(parkedSession(), [
+ { address, identity, operation: continueOperation, phase: "running" },
+ ]),
};
- const prepared = prepareAgentContinuation(parkedSession(), {
- agentId: identity.id,
- invokedName: "research",
- operation: continueOperation,
- });
- if (prepared.kind !== "ready") {
- throw new Error("expected ready");
- }
const restored = rejectAgentEffect(prepared.session, {
disposition: "retryable",
@@ -335,101 +211,37 @@ describe("abandonRunningAgentTurns", () => {
});
});
-describe("rebaseAgentHandles", () => {
- const otherHandle: AgentHandle = {
- address: {
- continuationToken: "continuation_other",
- kind: "agent/local",
- sessionId: "session_other",
- },
- identity: { id: "ag_writer:aaaaaaaaaaaa", name: "writer", nodeId: "node_writer" },
- lastStatus: "",
- phase: "parked",
- };
- const continueOperation: ContinueOperation = {
- callId: "call_2",
- id: "op_continue",
- kind: "continue",
- parentTurnId: "turn_2",
- previousStatus: "",
- };
-
- function withHandles(handles: readonly AgentHandle[]): HarnessSession {
- return createSession({ [AGENT_HANDLES_STATE_KEY]: { handles } });
- }
-
- function inPlaceChange(): { base: HarnessSession; next: HarnessSession } {
- const base = parkedSession();
- const prepared = prepareAgentContinuation(base, {
- agentId: identity.id,
- invokedName: "research",
- operation: continueOperation,
- });
- if (prepared.kind !== "ready") {
- throw new Error("expected ready");
- }
- return { base, next: prepared.session };
- }
-
- it("appends a handle the dispatch added onto a diverged working session", () => {
- const next = preparedSession();
- const current = withHandles([otherHandle]);
- const rebased = rebaseAgentHandles(current, {
- base: createSession().state,
- next: next.state,
- });
- expect(handlesOf(rebased)).toEqual([otherHandle, ...handlesOf(next)]);
- });
-
- it("applies a removal the dispatch made", () => {
- const base = confirmTaskAgentAddress(preparedSession(), {
- address,
- operationId: startOperation.id,
- });
- const current = withHandles([...handlesOf(base), otherHandle]);
- const rebased = rebaseAgentHandles(current, {
- base: base.state,
- next: removeTaskAgentAddress(base, identity.id).state,
- });
- expect(handlesOf(rebased)).toEqual([otherHandle]);
- });
-
- it("applies an in-place change the dispatch made", () => {
- const { base, next } = inPlaceChange();
- const current = withHandles([...handlesOf(base), otherHandle]);
- const rebased = rebaseAgentHandles(current, { base: base.state, next: next.state });
- expect(handlesOf(rebased)).toEqual([...handlesOf(next), otherHandle]);
- });
-
- it("throws when the dispatch and another effect changed the same handle differently", () => {
- const { base, next } = inPlaceChange();
- const current = withHandles([{ address, identity, lastStatus: "diverged", phase: "parked" }]);
- expect(() => rebaseAgentHandles(current, { base: base.state, next: next.state })).toThrow(
- identity.id,
- );
- });
-
- it("throws when an added id already exists with different content", () => {
- const current = withHandles([
+describe("owner-scoped handle claims", () => {
+ it("keeps a recorded workflow run's claim separate from a task claim", () => {
+ const available: TaskOwnedAgentHandle = { address, identity, phase: "available" };
+ const workflowClaim = applyAgentHandleStoreCommand(
+ { handles: [available] },
{
- identity,
- operation: startOperation,
- phase: "starting",
- target: { continuationToken: "continuation_divergent", kind: "agent/local" },
+ agentId: identity.id,
+ callId: "call-workflow",
+ expectedTarget: "local",
+ invokedName: identity.name,
+ kind: "claim",
+ operationId: "operation-workflow",
+ ownerId: "workflow-run-1",
},
- ]);
- expect(() =>
- rebaseAgentHandles(current, {
- base: createSession().state,
- next: preparedSession().state,
- }),
- ).toThrow(identity.id);
- });
+ );
- it("returns the working session unchanged when it already contains the delta", () => {
- const { base, next } = inPlaceChange();
- const current = withHandles(handlesOf(next));
- expect(rebaseAgentHandles(current, { base: base.state, next: next.state })).toBe(current);
+ expect(workflowClaim.result).toMatchObject({
+ handle: { ownerId: "workflow-run-1", phase: "claimed" },
+ kind: "ready",
+ });
+ expect(
+ applyAgentHandleStoreCommand(workflowClaim.store, {
+ agentId: identity.id,
+ callId: "call-task",
+ expectedTarget: "local",
+ invokedName: identity.name,
+ kind: "claim",
+ operationId: "operation-task",
+ ownerId: "task_1",
+ }).result,
+ ).toMatchObject({ handle: { ownerId: "workflow-run-1" }, kind: "busy" });
});
});
@@ -498,3 +310,144 @@ describe("settleAgentTurn", () => {
).toEqual({ kind: "ignored", reason: "unknown-operation" });
});
});
+
+describe("agent handle store task leases", () => {
+ it("reserves and confirms a task-owned start, then releases it for another task", () => {
+ const reserved = applyAgentHandleStoreCommand(EMPTY_AGENT_HANDLE_STORE, {
+ identity,
+ kind: "reserve",
+ operationId: "operation-1",
+ ownerId: "task-1",
+ });
+ expect(reserved.result).toMatchObject({ handle: { phase: "reserved" }, kind: "ready" });
+
+ const confirmed = applyAgentHandleStoreCommand(reserved.store, {
+ address,
+ kind: "confirm",
+ operationId: "operation-1",
+ ownerId: "task-1",
+ });
+ expect(confirmed.result).toEqual({
+ kind: "ready",
+ handle: {
+ address,
+ identity,
+ operationId: "operation-1",
+ phase: "claimed",
+ ownerId: "task-1",
+ },
+ });
+
+ const released = applyAgentHandleStoreCommand(confirmed.store, {
+ kind: "release-owner",
+ ownerId: "task-1",
+ });
+ expect(released.store.handles).toEqual([{ address, identity, phase: "available" }]);
+ });
+
+ it("claims a parked child through the owner-scoped continuation path", () => {
+ const parked: AgentHandle = { address, identity, lastStatus: "(cancelled)", phase: "parked" };
+ const claimed = applyAgentHandleStoreCommand(
+ { handles: [parked] },
+ {
+ agentId: identity.id,
+ expectedTarget: "local",
+ invokedName: identity.name,
+ kind: "claim",
+ operationId: "operation-2",
+ ownerId: "workflow-run-2",
+ },
+ );
+
+ expect(claimed.result).toMatchObject({
+ handle: { ownerId: "workflow-run-2", phase: "claimed" },
+ kind: "ready",
+ });
+ });
+
+ it("parks claimed workflow owners as cancelled without changing available handles", () => {
+ const claimed: AgentHandle = {
+ address,
+ identity,
+ operationId: "operation-1",
+ ownerId: "workflow-run-1",
+ phase: "claimed",
+ };
+ const availableIdentity = { ...identity, id: "agent-2" };
+ const session = writeHandles(createSession(), [
+ claimed,
+ { address, identity: availableIdentity, phase: "available" },
+ ]);
+
+ expect(handlesOf(abandonAgentInvocationOwners(session, new Set(["workflow-run-1"])))).toEqual([
+ { address, identity, lastStatus: "(cancelled)", phase: "parked" },
+ { address, identity: availableIdentity, phase: "available" },
+ ]);
+ });
+
+ it("allows only one task to claim an available session agent", () => {
+ const available: TaskOwnedAgentHandle = { address, identity, phase: "available" };
+ const claimed = applyAgentHandleStoreCommand(
+ { handles: [available] },
+ {
+ agentId: identity.id,
+ expectedTarget: "local",
+ invokedName: identity.name,
+ kind: "claim",
+ operationId: "operation-2",
+ ownerId: "task-2",
+ },
+ );
+ expect(claimed.result).toMatchObject({ handle: { phase: "claimed" }, kind: "ready" });
+
+ const competing = applyAgentHandleStoreCommand(claimed.store, {
+ agentId: identity.id,
+ expectedTarget: "local",
+ invokedName: identity.name,
+ kind: "claim",
+ operationId: "operation-3",
+ ownerId: "task-3",
+ });
+ expect(competing.result).toMatchObject({ handle: { ownerId: "task-2" }, kind: "busy" });
+ expect(competing.store).toBe(claimed.store);
+ });
+
+ it("rejects a name or target mismatch without changing the store", () => {
+ const available: TaskOwnedAgentHandle = { address, identity, phase: "available" };
+
+ for (const command of [
+ { expectedTarget: "local" as const, invokedName: "writer" },
+ { expectedTarget: "remote" as const, invokedName: identity.name },
+ ]) {
+ const result = applyAgentHandleStoreCommand(
+ { handles: [available] },
+ {
+ agentId: identity.id,
+ ...command,
+ kind: "claim",
+ operationId: "operation-2",
+ ownerId: "task-2",
+ },
+ );
+ expect(result.result).toMatchObject({ kind: "mismatch" });
+ expect(result.store.handles).toEqual([available]);
+ }
+ });
+
+ it("does not let one task remove another task's claimed agent", () => {
+ const claimed: TaskOwnedAgentHandle = {
+ address,
+ identity,
+ operationId: "operation-1",
+ phase: "claimed",
+ ownerId: "task-1",
+ };
+ const result = applyAgentHandleStoreCommand(
+ { handles: [claimed] },
+ { agentId: identity.id, kind: "remove", ownerId: "task-2" },
+ );
+
+ expect(result.result).toEqual({ handle: claimed, kind: "busy" });
+ expect(result.store.handles).toEqual([claimed]);
+ });
+});
diff --git a/packages/eve/src/subagents/handles/transitions.ts b/packages/eve/src/subagents/handles/transitions.ts
new file mode 100644
index 000000000..0a611133d
--- /dev/null
+++ b/packages/eve/src/subagents/handles/transitions.ts
@@ -0,0 +1,420 @@
+import {
+ formatAgentStatus,
+ EMPTY_AGENT_HANDLE_STORE,
+ getAgentHandleStore,
+ writeHandles,
+ type AgentAddress,
+ type AgentHandle,
+ type AgentHandleStore,
+ type AgentHandleStoreCommand,
+ type AgentHandleStoreCommandResult,
+ type AgentIdentity,
+ type StartOperation,
+ type TaskOwnedAgentHandle,
+ type TurnOwnedAgentHandle,
+} from "#subagents/handles/store.js";
+import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
+
+/**
+ * Records intent to start a fresh child. Must be applied to the step's
+ * working snapshot before the start side effect runs, so the returned state
+ * owns any child the step may have created.
+ *
+ * The guarantee is intra-step, not exactly-once: the prepared handle
+ * durably commits only when the enclosing dispatch step's result commits.
+ * A crash between an accepted start and that commit replays the step from
+ * the pre-step snapshot and re-runs the side effect.
+ *
+ * Throws when the identity or operation already exists: fresh starts mint
+ * a new identity, so a collision means corrupted derivation, not a replay.
+ */
+export function prepareAgentStart(
+ session: HarnessSession,
+ input: {
+ readonly identity: AgentIdentity;
+ readonly operation: StartOperation;
+ readonly target: AgentStartTargetInput;
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ if (handles.some((handle) => handle.identity.id === input.identity.id)) {
+ throw new Error(`Agent handle "${input.identity.id}" already exists.`);
+ }
+ return writeHandles(session, [
+ ...handles,
+ {
+ identity: input.identity,
+ operation: input.operation,
+ phase: "starting",
+ target: input.target,
+ },
+ ]);
+}
+
+type AgentStartTargetInput = Extract<TurnOwnedAgentHandle, { phase: "starting" }>["target"];
+
+type ActiveAgentHandle = Extract<TurnOwnedAgentHandle, { phase: "starting" | "running" }>;
+
+function findActiveHandle(
+ handles: readonly AgentHandle[],
+ operationId: string,
+): ActiveAgentHandle | undefined {
+ return handles.find(
+ (handle): handle is ActiveAgentHandle =>
+ (handle.phase === "starting" || handle.phase === "running") &&
+ handle.operation.id === operationId,
+ );
+}
+
+/**
+ * Confirms a started child: `starting` becomes `running` with the child's
+ * confirmed address. Throws when no starting handle carries the operation,
+ * because confirming an unprepared start means ownership was never
+ * committed. Re-confirming an already-running handle with the same
+ * operation and address is a replay no-op.
+ */
+export function confirmAgentStarted(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly address: AgentAddress;
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = findActiveHandle(handles, input.operationId);
+ if (existing === undefined) {
+ throw new Error(`No prepared agent handle for operation "${input.operationId}".`);
+ }
+ if (existing.phase === "running") {
+ return session;
+ }
+
+ return writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: input.address,
+ identity: existing.identity,
+ operation: existing.operation,
+ phase: "running",
+ }
+ : handle,
+ ),
+ );
+}
+
+/**
+ * Resolves a dispatch that definitively failed.
+ *
+ * - A dead start or dead continuation deletes the handle: there is no
+ * child left to own.
+ * - A retryable continuation failure restores `parked` with the status the
+ * handle showed before the delivery, so the model may retry the same
+ * `agentId` later.
+ *
+ * Unknown operations are a no-op: the failure raced a settlement that
+ * already resolved the handle.
+ */
+export function rejectAgentEffect(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly disposition: "dead" | "retryable";
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = findActiveHandle(handles, input.operationId);
+ if (existing === undefined) {
+ return session;
+ }
+
+ if (input.disposition === "retryable" && existing.phase === "running") {
+ const { operation } = existing;
+ if (operation.kind === "continue") {
+ return writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: existing.address,
+ identity: existing.identity,
+ lastStatus: operation.previousStatus,
+ phase: "parked",
+ }
+ : handle,
+ ),
+ );
+ }
+ }
+
+ return writeHandles(
+ session,
+ handles.filter((handle) => handle !== existing),
+ );
+}
+
+/**
+ * Parks every running child when the parent abandons a cancelled turn.
+ *
+ * Cancellation requests each running descendant's cancellation and then
+ * tears down the turn inbox — the only hook a child settlement can
+ * resume — so no later settlement can move these handles. Without this
+ * transition they would stay `running` forever: invisible to the model,
+ * unresumable, and retried by every future cancellation.
+ *
+ * A cancelled child settles its own turn as a park, so `parked` with
+ * `"(cancelled)"` mirrors {@link settleAgentTurn}'s cancelled outcome. If
+ * the child instead died, a later continuation attempt discovers the dead
+ * session and {@link rejectAgentEffect} deletes the handle.
+ */
+export function abandonRunningAgentTurns(session: HarnessSession): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ if (!handles.some((handle) => handle.phase === "running")) {
+ return session;
+ }
+ return writeHandles(
+ session,
+ handles.map((handle) =>
+ handle.phase === "running"
+ ? {
+ address: handle.address,
+ identity: handle.identity,
+ lastStatus: "(cancelled)",
+ phase: "parked",
+ }
+ : handle,
+ ),
+ );
+}
+
+/** Result of applying a settled child turn to the store. */
+export type SettleAgentTurnResult =
+ | { readonly kind: "settled"; readonly session: HarnessSession }
+ | { readonly kind: "ignored"; readonly reason: "unknown-operation" };
+
+/**
+ * Applies one settled child turn: `running` becomes `parked` for a parked
+ * outcome or is deleted for a terminal outcome.
+ *
+ * The settlement must carry the operation currently recorded on the
+ * running handle; anything else is ignored so a stale delivery can never
+ * move a newer turn.
+ */
+export function settleAgentTurn(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly outcome: AgentTurnOutcome;
+ },
+): SettleAgentTurnResult {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = handles.find(
+ (handle) => handle.phase === "running" && handle.operation.id === input.operationId,
+ );
+ if (existing === undefined || existing.phase !== "running") {
+ return { kind: "ignored", reason: "unknown-operation" };
+ }
+
+ if (input.outcome.kind === "terminal") {
+ return {
+ kind: "settled",
+ session: writeHandles(
+ session,
+ handles.filter((handle) => handle !== existing),
+ ),
+ };
+ }
+
+ const { result } = input.outcome;
+ const lastStatus =
+ result.kind === "succeeded"
+ ? formatAgentStatus(result.output)
+ : result.kind === "failed"
+ ? formatAgentStatus(result.error)
+ : "(cancelled)";
+ return {
+ kind: "settled",
+ session: writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: existing.address,
+ identity: existing.identity,
+ lastStatus,
+ phase: "parked",
+ }
+ : handle,
+ ),
+ ),
+ };
+}
+
+/** Applies one atomic owner lease command to the shared agent handle store. */
+export function applyAgentHandleStoreCommand(
+ store: AgentHandleStore,
+ command: AgentHandleStoreCommand,
+): {
+ readonly result: AgentHandleStoreCommandResult;
+ readonly store: AgentHandleStore;
+} {
+ switch (command.kind) {
+ case "read":
+ return { result: { kind: "ready" }, store };
+ case "reserve": {
+ const existing = store.handles.find((handle) => handle.identity.id === command.identity.id);
+ if (existing !== undefined) {
+ return (existing.phase === "reserved" || existing.phase === "claimed") &&
+ existing.operationId === command.operationId &&
+ existing.ownerId === command.ownerId
+ ? { result: { handle: existing, kind: "ready" }, store }
+ : { result: { handle: existing, kind: "busy" }, store };
+ }
+ const handle: TaskOwnedAgentHandle = {
+ callId: command.callId,
+ identity: command.identity,
+ operationId: command.operationId,
+ phase: "reserved",
+ ownerId: command.ownerId,
+ };
+ return {
+ result: { handle, kind: "ready" },
+ store: { handles: [...store.handles, handle] },
+ };
+ }
+ case "confirm": {
+ const existing = store.handles.find(
+ (
+ handle,
+ ): handle is Extract<TaskOwnedAgentHandle, { readonly phase: "claimed" | "reserved" }> =>
+ (handle.phase === "claimed" || handle.phase === "reserved") &&
+ handle.operationId === command.operationId &&
+ handle.ownerId === command.ownerId,
+ );
+ if (existing === undefined) return { result: { kind: "unknown" }, store };
+ if (existing.phase === "claimed") {
+ return { result: { handle: existing, kind: "ready" }, store };
+ }
+ const handle: TaskOwnedAgentHandle = {
+ address: command.address,
+ callId: existing.callId,
+ identity: existing.identity,
+ operationId: existing.operationId,
+ phase: "claimed",
+ ownerId: existing.ownerId,
+ };
+ return replaceHandle(store, existing, handle);
+ }
+ case "claim": {
+ const existing = store.handles.find((handle) => handle.identity.id === command.agentId);
+ if (existing === undefined) return { result: { kind: "unknown" }, store };
+ if (
+ existing.phase === "starting" ||
+ existing.phase === "running" ||
+ existing.identity.name !== command.invokedName ||
+ (existing.phase !== "reserved" &&
+ (existing.address.kind === "agent/remote") !== (command.expectedTarget === "remote"))
+ ) {
+ return { result: { handle: existing, kind: "mismatch" }, store };
+ }
+ if (existing.phase === "claimed") {
+ return existing.operationId === command.operationId && existing.ownerId === command.ownerId
+ ? { result: { handle: existing, kind: "ready" }, store }
+ : { result: { handle: existing, kind: "busy" }, store };
+ }
+ if (existing.phase === "reserved") {
+ return { result: { handle: existing, kind: "busy" }, store };
+ }
+ const handle: TaskOwnedAgentHandle = {
+ address: existing.address,
+ callId: command.callId,
+ identity: existing.identity,
+ operationId: command.operationId,
+ phase: "claimed",
+ ownerId: command.ownerId,
+ };
+ return replaceHandle(store, existing, handle);
+ }
+ case "remove": {
+ const existing = store.handles.find((handle) => handle.identity.id === command.agentId);
+ if (existing === undefined) return { result: { kind: "ready" }, store };
+ if (existing.phase === "claimed" && existing.ownerId !== command.ownerId) {
+ return { result: { handle: existing, kind: "busy" }, store };
+ }
+ return {
+ result: { kind: "ready" },
+ store: { handles: store.handles.filter((handle) => handle !== existing) },
+ };
+ }
+ case "release-owner": {
+ const handles = store.handles.flatMap((handle): readonly AgentHandle[] => {
+ if (handle.phase === "reserved" && handle.ownerId === command.ownerId) return [];
+ if (handle.phase !== "claimed" || handle.ownerId !== command.ownerId) return [handle];
+ return [{ address: handle.address, identity: handle.identity, phase: "available" }];
+ });
+ return {
+ result: { kind: "ready" },
+ store: handlesEqual(store.handles, handles) ? store : { handles },
+ };
+ }
+ }
+}
+
+/** Parks child turns still owned by workflow runs when their parent turn is cancelled. */
+export function abandonAgentInvocationOwners<Session extends { readonly state?: SessionStateMap }>(
+ session: Session,
+ ownerIds: ReadonlySet<string>,
+): Session {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const abandoned = handles.flatMap((handle): readonly AgentHandle[] => {
+ if (handle.phase === "reserved" && ownerIds.has(handle.ownerId)) return [];
+ if (handle.phase !== "claimed" || !ownerIds.has(handle.ownerId)) return [handle];
+ return [
+ {
+ address: handle.address,
+ identity: handle.identity,
+ lastStatus: "(cancelled)",
+ phase: "parked",
+ },
+ ];
+ });
+ return handlesEqual(handles, abandoned) ? session : writeHandles(session, abandoned);
+}
+
+/** Applies one owner-scoped handle transition to a harness session. */
+export function applyTaskAgentHandleCommand<Session extends { readonly state?: SessionStateMap }>(
+ session: Session,
+ command: AgentHandleStoreCommand,
+): {
+ readonly result: AgentHandleStoreCommandResult;
+ readonly session: Session;
+} {
+ const store = getAgentHandleStore(session.state) ?? EMPTY_AGENT_HANDLE_STORE;
+ const applied = applyAgentHandleStoreCommand(store, command);
+ return {
+ result: applied.result,
+ session: applied.store === store ? session : writeHandles(session, applied.store.handles),
+ };
+}
+
+function replaceHandle(
+ store: AgentHandleStore,
+ existing: AgentHandle,
+ handle: TaskOwnedAgentHandle,
+): {
+ readonly result: AgentHandleStoreCommandResult;
+ readonly store: AgentHandleStore;
+} {
+ return {
+ result: { handle, kind: "ready" },
+ store: {
+ handles: store.handles.map((candidate) => (candidate === existing ? handle : candidate)),
+ },
+ };
+}
+
+function handlesEqual(left: readonly AgentHandle[], right: readonly AgentHandle[]): boolean {
+ return left.length === right.length && left.every((handle, index) => handle === right[index]);
+}
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts b/packages/eve/src/subagents/hitl-proxy.integration.test.ts
similarity index 99%
rename from packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts
rename to packages/eve/src/subagents/hitl-proxy.integration.test.ts
index fd4257c90..9ec6dcf9c 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.integration.test.ts
@@ -17,7 +17,7 @@ import { createRuntimeAdapterRegistry } from "#runtime/channels/registry.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
-import { emitProxiedInputRequest, routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
+import { emitProxiedInputRequest, routeDeliverPayload } from "#subagents/hitl-proxy.js";
/**
* Integration coverage for subagent HITL proxy emission and routing.
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.ts
similarity index 98%
rename from packages/eve/src/execution/subagent-hitl-proxy.test.ts
rename to packages/eve/src/subagents/hitl-proxy.test.ts
index 480ef0114..64f735f3e 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
-import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
+import { routeDeliverPayload } from "#subagents/hitl-proxy.js";
function createSession(state?: Record<string, unknown>): HarnessSession {
return {
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.ts
similarity index 100%
rename from packages/eve/src/execution/subagent-hitl-proxy.ts
rename to packages/eve/src/subagents/hitl-proxy.ts
diff --git a/packages/eve/src/execution/subagent-invocation.test.ts b/packages/eve/src/subagents/invocation.test.ts
similarity index 89%
rename from packages/eve/src/execution/subagent-invocation.test.ts
rename to packages/eve/src/subagents/invocation.test.ts
index f3c0ab46f..c3ed6ad3c 100644
--- a/packages/eve/src/execution/subagent-invocation.test.ts
+++ b/packages/eve/src/subagents/invocation.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { normalizeRequestedOutputSchema } from "#execution/subagent-invocation.js";
+import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";
describe("normalizeRequestedOutputSchema", () => {
it("passes a non-empty object schema through", () => {
diff --git a/packages/eve/src/execution/subagent-invocation.ts b/packages/eve/src/subagents/invocation.ts
similarity index 100%
rename from packages/eve/src/execution/subagent-invocation.ts
rename to packages/eve/src/subagents/invocation.ts
diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/subagents/parent-notification.test.ts
similarity index 87%
rename from packages/eve/src/execution/delegated-parent-notification.test.ts
rename to packages/eve/src/subagents/parent-notification.test.ts
index 84e07cc2d..e044d4f9d 100644
--- a/packages/eve/src/execution/delegated-parent-notification.test.ts
+++ b/packages/eve/src/subagents/parent-notification.test.ts
@@ -2,18 +2,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ContextContainer } from "#context/container.js";
import { serializeContext } from "#context/serialize.js";
-import { ActivityObserverKey, SessionCallbackKey, SessionIdKey } from "#context/keys.js";
+import { SessionCallbackKey, SessionIdKey } from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import {
bindTurnCallerContextStep,
notifyDelegatedParentStep,
- notifyTaskTurnStartedStep,
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
-} from "#execution/delegated-parent-notification.js";
-import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
+} from "#subagents/parent-notification.js";
+import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
@@ -47,7 +46,9 @@ function createSuccessResult(): RuntimeSubagentChildResult {
};
}
-function createSerializedContext(): Record<string, unknown> {
+function createSerializedContext(
+ adapterState: Record<string, unknown> = {},
+): Record<string, unknown> {
const bundle = {
adapterRegistry: {
adaptersByKind: new Map([[SUBAGENT_ADAPTER_KIND, SUBAGENT_ADAPTER]]),
@@ -67,6 +68,7 @@ function createSerializedContext(): Record<string, unknown> {
parentContinuationToken: "parent-tok",
parentSessionId: "parent-session",
subagentName: "research",
+ ...adapterState,
},
});
return serializeContext(ctx);
@@ -185,47 +187,19 @@ describe("turn caller notification", () => {
expect(resumeHookMock).not.toHaveBeenCalled();
});
- it("binds a local task hook to the exact child turn before execution", async () => {
- await notifyTaskTurnStartedStep({
- caller: {
- callId: "call-task",
- replyTo: { kind: "hook", token: "task-token" },
- subagentName: "research",
- taskId: "task-1",
- },
- childSessionId: "child-session",
- childTurnId: "turn_child_7",
- });
-
- expect(resumeHookMock).toHaveBeenCalledWith("task-token", {
- childSessionId: "child-session",
- childTurnId: "turn_child_7",
- kind: "turn-started",
- taskId: "task-1",
- });
- });
-
- it("posts the same task turn identity through a remote callback", async () => {
- await notifyTaskTurnStartedStep({
- caller: {
- callId: "call-task",
- replyTo: {
- kind: "callback",
- token: "task-token",
- url: "https://parent.example/eve/v1/callback/task-token",
- },
- subagentName: "research",
+ it("restores task ownership from a local adapter with an opaque reply hook", async () => {
+ const caller = await resolveInitialTurnCallerStep({
+ serializedContext: createSerializedContext({
+ parentContinuationToken: "invocation-reply-hook",
taskId: "task-1",
- },
- childSessionId: "child-session",
- childTurnId: "turn_child_7",
+ }),
});
- expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
- kind: "turn.started",
- sessionId: "child-session",
+ expect(caller).toEqual({
+ callId: "call-1",
+ replyTo: { kind: "hook", token: "invocation-reply-hook" },
+ subagentName: "research",
taskId: "task-1",
- turnId: "turn_child_7",
});
});
@@ -474,17 +448,6 @@ describe("turn caller binding", () => {
await expect(
bindTurnCallerContextStep({
caller: {
- activityObserver: {
- sink: { url: "https://parent.example/eve/v1/activity/opaque-token", version: 1 },
- workIdentity: {
- callId: "call-new",
- id: "work:new",
- kind: "subagent",
- name: "research",
- rootSessionId: "root",
- rootTurnId: "root-turn",
- },
- },
callId: "call-new",
replyTo: { kind: "hook", token: "turn-new" },
subagentName: "research",
@@ -497,16 +460,20 @@ describe("turn caller binding", () => {
parentContinuationToken: "turn-old",
parentSessionId: "parent",
subagentName: "research",
+ taskId: "task-old",
},
},
},
}),
- ).resolves.toMatchObject({
- [ActivityObserverKey.name]: {
- workIdentity: { id: "work:new" },
- },
+ ).resolves.toEqual({
[ChannelKey.name]: {
- state: { callId: "call-new", parentContinuationToken: "turn-new" },
+ kind: SUBAGENT_ADAPTER_KIND,
+ state: {
+ callId: "call-new",
+ parentContinuationToken: "turn-new",
+ parentSessionId: "parent",
+ subagentName: "research",
+ },
},
});
});
@@ -560,7 +527,7 @@ describe("turn caller binding", () => {
}),
).resolves.toMatchObject({
[ChannelKey.name]: {
- state: { callId: "call-new", parentContinuationToken: "task-new" },
+ state: { callId: "call-new", parentContinuationToken: "task-new", taskId: "task-new" },
},
});
});
diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/subagents/parent-notification.ts
similarity index 86%
rename from packages/eve/src/execution/delegated-parent-notification.ts
rename to packages/eve/src/subagents/parent-notification.ts
index a65915ea7..ba59f03f3 100644
--- a/packages/eve/src/execution/delegated-parent-notification.ts
+++ b/packages/eve/src/subagents/parent-notification.ts
@@ -13,9 +13,9 @@ import {
isSubagentAdapterState,
SUBAGENT_ADAPTER_KIND,
type SubagentAdapterState,
-} from "#execution/subagent-adapter-state.js";
+} from "#subagents/adapter-state.js";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
-import { SUBAGENT_EXECUTION_FAILED } from "#harness/agent-handle-errors.js";
+import { SUBAGENT_EXECUTION_FAILED } from "#subagents/agent-handle-errors.js";
import { createLogger } from "#internal/logging.js";
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
import { toErrorMessage } from "#shared/errors.js";
@@ -23,7 +23,6 @@ import { parseJsonValue } from "#shared/json.js";
import type { TokenUsage } from "#shared/token-usage.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
-import type { TaskInboundTurnStarted } from "#tasks/types.js";
import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
const log = createLogger("execution.delegated-parent-notification");
@@ -132,7 +131,7 @@ export async function notifyTurnCallerStep(input: {
await resumeSettledTurnHook(input.caller.replyTo.token, result);
}
-/** Settles a task-owned caller after the child turn is cooperatively cancelled. */
+/** Settles a workflow-owned caller after the child turn is cooperatively cancelled. */
export async function notifyCancelledTaskCallerStep(input: {
readonly caller: TurnCaller | undefined;
readonly sessionId: string;
@@ -140,10 +139,15 @@ export async function notifyCancelledTaskCallerStep(input: {
}): Promise<void> {
"use step";
- if (input.caller?.taskId === undefined) return;
+ if (input.caller === undefined) return;
const usageDelta = input.usage ?? ZERO_TOKEN_USAGE;
+ const error = {
+ code: SUBAGENT_EXECUTION_FAILED,
+ message: "The agent invocation was cancelled.",
+ };
const base: RuntimeSubagentChildResult = {
callId: input.caller.callId,
+ isError: true,
kind: "subagent-result",
origin: "child",
outcome: {
@@ -151,7 +155,7 @@ export async function notifyCancelledTaskCallerStep(input: {
result: { kind: "cancelled" },
usageDelta,
},
- output: "",
+ output: error,
subagentName: input.caller.subagentName,
};
const result = input.usage === undefined ? base : { ...base, usage: input.usage };
@@ -166,42 +170,6 @@ export async function notifyCancelledTaskCallerStep(input: {
await resumeSettledTurnHook(input.caller.replyTo.token, result);
}
-/** Binds a durable task to the exact child turn before execution starts. */
-export async function notifyTaskTurnStartedStep(input: {
- readonly caller: TurnCaller | undefined;
- readonly childSessionId: string;
- readonly childTurnId: string;
-}): Promise<void> {
- "use step";
-
- const taskId = input.caller?.taskId;
- if (input.caller === undefined || taskId === undefined) return;
- const payload: TaskInboundTurnStarted = {
- childSessionId: input.childSessionId,
- childTurnId: input.childTurnId,
- kind: "turn-started",
- taskId,
- };
- if (input.caller.replyTo.kind === "hook") {
- await resumeHook(input.caller.replyTo.token, payload);
- return;
- }
- const response = await postSessionCallbackRequest({
- body: {
- callId: input.caller.callId,
- kind: "turn.started",
- sessionId: input.childSessionId,
- subagentName: input.caller.subagentName,
- taskId,
- turnId: input.childTurnId,
- },
- url: input.caller.replyTo.url,
- });
- if (!response.ok) {
- throw new Error(`Task turn-start callback failed with HTTP ${response.status}.`);
- }
-}
-
function createSettledTurnResult(input: {
readonly caller: TurnCaller;
readonly lifecycle: AgentTurnOutcome["kind"];
@@ -284,7 +252,7 @@ export async function resolveInitialTurnCallerStep(input: {
callId: adapter.state.callId,
replyTo: { kind: "hook", token: adapter.state.parentContinuationToken },
subagentName: adapter.state.subagentName,
- taskId: readTaskIdFromInboxToken(adapter.state.parentContinuationToken),
+ taskId: adapter.state.taskId ?? readTaskIdFromInboxToken(adapter.state.parentContinuationToken),
};
}
@@ -325,16 +293,19 @@ export async function bindTurnCallerContextStep(input: {
throw new Error("Delegated local turn is missing its subagent adapter binding.");
}
const state = Reflect.get(adapter, "state") as SubagentAdapterState;
+ const { taskId: _priorTaskId, ...stateWithoutTaskId } = state;
+ const nextState: Record<string, unknown> = {
+ ...stateWithoutTaskId,
+ callId: caller.callId,
+ parentContinuationToken: caller.replyTo.token,
+ subagentName: caller.subagentName,
+ };
+ if (caller.taskId !== undefined) nextState.taskId = caller.taskId;
return {
...withActivity,
[ChannelKey.name]: {
...adapter,
- state: {
- ...state,
- callId: caller.callId,
- parentContinuationToken: caller.replyTo.token,
- subagentName: caller.subagentName,
- },
+ state: nextState,
},
};
}
diff --git a/packages/eve/src/execution/delegated-parent-result.ts b/packages/eve/src/subagents/parent-result.ts
similarity index 94%
rename from packages/eve/src/execution/delegated-parent-result.ts
rename to packages/eve/src/subagents/parent-result.ts
index a37ab28c5..fd9695964 100644
--- a/packages/eve/src/execution/delegated-parent-result.ts
+++ b/packages/eve/src/subagents/parent-result.ts
@@ -5,12 +5,12 @@
* step-proxy transform.
*/
-import { SUBAGENT_EXECUTION_FAILED } from "#harness/agent-handle-errors.js";
+import { SUBAGENT_EXECUTION_FAILED } from "#subagents/agent-handle-errors.js";
import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import type { JsonValue } from "#shared/json.js";
import { toErrorMessage } from "#shared/errors.js";
import type { TokenUsage } from "#shared/token-usage.js";
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
const ZERO_TOKEN_USAGE: TokenUsage = {
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/subagents/remote-dispatch.test.ts
similarity index 96%
rename from packages/eve/src/execution/remote-agent-dispatch.test.ts
rename to packages/eve/src/subagents/remote-dispatch.test.ts
index 8bcd1487b..f39881482 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/subagents/remote-dispatch.test.ts
@@ -11,8 +11,8 @@ import {
resolveRemoteAgentForAction,
resolveRemoteAgentStreamHeaders,
startRemoteAgentSession,
-} from "#execution/remote-agent-dispatch.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
+} from "#subagents/remote-dispatch.js";
+import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
describe("resolveRemoteAgentForAction", () => {
@@ -31,6 +31,7 @@ describe("resolveRemoteAgentForAction", () => {
nodeId: "subagents/research.ts",
sourceId: "subagents/research.ts",
sourceKind: "module",
+ workflowId: "workflow//./agent/subagents/research//execute",
} as const;
const credentialsStepId = "eve:dynamic-remote-agent//selected-research";
@@ -274,6 +275,42 @@ describe("startRemoteAgentSession", () => {
});
});
+ it("binds a task id to an opaque invocation callback token", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ Response.json(
+ { ok: true, sessionId: "remote-session", status: "accepted" },
+ { status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await startRemoteAgentSession({
+ action: createAction(),
+ callbackBaseUrl: "https://caller.example.com",
+ callbackToken: "invocation-reply",
+ remote: createRemoteAgent(),
+ session: {
+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100000 },
+ continuationToken: "eve:parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {},
+ },
+ taskId: "task-1",
+ });
+
+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
+ callback: {
+ taskId: "task-1",
+ token: "invocation-reply",
+ url: "https://caller.example.com/eve/v1/callback/invocation-reply",
+ },
+ });
+ });
+
it("rejects the former create-session response shape", async () => {
const fetchMock = vi
.fn()
@@ -1138,7 +1175,7 @@ describe("resetRemoteAgentSession", () => {
});
});
-function createAction(): RuntimeRemoteAgentCallActionRequest {
+function createAction(): RuntimeRemoteAgentDispatchRequest {
return {
callId: "call-remote",
description: "Runtime action event description.",
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/subagents/remote-dispatch.ts
similarity index 97%
rename from packages/eve/src/execution/remote-agent-dispatch.ts
rename to packages/eve/src/subagents/remote-dispatch.ts
index cf78fe461..75bfe98dd 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/subagents/remote-dispatch.ts
@@ -18,14 +18,11 @@ import type { ChannelAudience } from "#shared/channel-audience.js";
import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";
import type { HeadersValue } from "#client/types.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
-import { createRemoteAgentRouteUrl } from "#execution/remote-agent-route-url.js";
+import { createRemoteAgentRouteUrl } from "#subagents/remote-route-url.js";
import { formatTraceparent } from "#protocol/traceparent.js";
-import {
- formatSubagentInput,
- normalizeRequestedOutputSchema,
-} from "#execution/subagent-invocation.js";
+import { formatSubagentInput, normalizeRequestedOutputSchema } from "#subagents/invocation.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
+import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
@@ -57,7 +54,7 @@ class RemoteAgentCancelRequestError extends Error {
}
export async function startRemoteAgentSession(input: {
- readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly action: RuntimeRemoteAgentDispatchRequest;
/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
readonly auth?: SessionAuthContext | null;
readonly callbackBaseUrl: string | undefined;
@@ -75,6 +72,7 @@ export async function startRemoteAgentSession(input: {
readonly parentTraceContext?: SessionTraceContext;
readonly remote: ResolvedRuntimeRemoteAgentNode;
readonly session: HarnessSession;
+ readonly taskId?: string;
}): Promise<RemoteAgentSessionCoordinates> {
const callbackToken = input.callbackToken ?? input.session.continuationToken;
if (!callbackToken) {
@@ -105,7 +103,7 @@ export async function startRemoteAgentSession(input: {
callback: {
callId: input.action.callId,
subagentName: input.action.remoteAgentName,
- taskId: readTaskIdFromInboxToken(callbackToken),
+ taskId: input.taskId ?? readTaskIdFromInboxToken(callbackToken),
token: callbackToken,
url: createWorkflowCallbackUrl(
input.callbackBaseUrl,
@@ -628,7 +626,7 @@ async function resolveRemoteAgentRequestHeaders(
}
function formatRemoteAgentCallInputMessage(input: {
- readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly action: RuntimeRemoteAgentDispatchRequest;
readonly remote: ResolvedRuntimeRemoteAgentNode;
}): string {
const message = typeof input.action.input.message === "string" ? input.action.input.message : "";
diff --git a/packages/eve/src/execution/remote-agent-route-url.test.ts b/packages/eve/src/subagents/remote-route-url.test.ts
similarity index 83%
rename from packages/eve/src/execution/remote-agent-route-url.test.ts
rename to packages/eve/src/subagents/remote-route-url.test.ts
index 33da92373..dd3e48f31 100644
--- a/packages/eve/src/execution/remote-agent-route-url.test.ts
+++ b/packages/eve/src/subagents/remote-route-url.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { createRemoteAgentRouteUrl } from "#execution/remote-agent-route-url.js";
+import { createRemoteAgentRouteUrl } from "#subagents/remote-route-url.js";
describe("createRemoteAgentRouteUrl", () => {
it("preserves a mounted remote agent base path", () => {
diff --git a/packages/eve/src/execution/remote-agent-route-url.ts b/packages/eve/src/subagents/remote-route-url.ts
similarity index 100%
rename from packages/eve/src/execution/remote-agent-route-url.ts
rename to packages/eve/src/subagents/remote-route-url.ts
diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/subagents/start-local.ts
similarity index 63%
rename from packages/eve/src/execution/subagent-start-local.ts
rename to packages/eve/src/subagents/start-local.ts
index cf0403e33..d66e14da1 100644
--- a/packages/eve/src/execution/subagent-start-local.ts
+++ b/packages/eve/src/subagents/start-local.ts
@@ -1,19 +1,11 @@
-import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import type { LocalDevRequestProvenance } from "#context/keys.js";
-import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
-import { mintStartOperation } from "#execution/dispatch-start-operation.js";
-import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
+import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";
import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";
-import { SUBAGENT_START_FAILED } from "#harness/agent-handle-errors.js";
-import {
- confirmAgentStarted,
- confirmTaskAgentAddress,
- prepareAgentStart,
- rejectAgentEffect,
-} from "#harness/handles/transitions.js";
+import { SUBAGENT_START_FAILED } from "#subagents/agent-handle-errors.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";
+import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { toErrorMessage } from "#shared/errors.js";
@@ -25,7 +17,7 @@ type DynamicSubagentAgentConfig = Parameters<
/** Starts one local subagent after dispatch planning has selected its target. */
export async function startLocalSubagent(input: {
- readonly action: RuntimeSubagentCallActionRequest;
+ readonly action: RuntimeSubagentDispatchRequest;
readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
readonly batchEvent: { readonly sequence: number; readonly turnId: string };
readonly bundle: CompiledBundle;
@@ -40,20 +32,11 @@ export async function startLocalSubagent(input: {
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
readonly activityObserver?: Parameters<typeof buildSubagentRunInput>[0]["activityObserver"];
readonly sandboxSessionId: string;
- readonly selfAgent: boolean;
readonly session: RuntimeSession;
readonly source: SubagentInputSource;
- readonly taskOwned: boolean;
+ readonly taskId?: string;
}): Promise<DispatchOutcome> {
const { action, source } = input;
- const activityObserver = deriveChildActivityObserverConfig({
- activityObserver: input.activityObserver,
- callId: action.callId,
- kind: "subagent",
- name: action.subagentName,
- parentSessionId: input.session.sessionId,
- parentTurnId: input.batchEvent.turnId,
- });
const childRuntime = createWorkflowRuntime({
compiledArtifactsSource: input.bundle.compiledArtifactsSource,
dynamicSubagentAgentConfig: input.dynamicSubagentAgentConfig,
@@ -70,39 +53,20 @@ export async function startLocalSubagent(input: {
graph: input.bundle.graph,
parentContinuationToken: input.parentContinuationToken,
parentTraceContext: input.parentTraceContext,
- activityObserver,
+ activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
- selfAgent: input.selfAgent,
session: input.session,
+ selfAgent: source.type === "runtime",
source,
+ taskId: input.taskId,
});
const targetKind = source.type === "runtime" ? ("agent/self" as const) : ("agent/local" as const);
- const { identity, operation } = mintStartOperation({
- callId: action.callId,
- name: action.subagentName,
- nodeId: action.nodeId,
- parentSessionId: input.session.sessionId,
- parentTurnId: input.batchEvent.turnId,
- });
- // Ownership is recorded before the start side effect, and the prepared
- // (or rejected) store rides every outcome into the step result. The
- // guarantee is intra-step: a crash between the accepted start and the
- // step-result commit still replays the whole dispatch step, so the
- // orphan window shrinks to that boundary rather than disappearing.
- const preparedSession = prepareAgentStart(input.currentSession, {
- identity,
- operation,
- target: { continuationToken: childContinuationToken, kind: targetKind },
- });
-
let childSessionId: string;
try {
await contextStorage.run(new ContextContainer({ localDevRequest: input.localDevRequest }), () =>
childRuntime.createSession(runInput),
);
- // This runs inside the replayed dispatch step, which must persist the
- // canonical child rather than the candidate accepted by start().
childSessionId = (await waitForCommandHookOwner(childContinuationToken)).runId;
} catch (error) {
logError(log, "local subagent start failed", error, {
@@ -123,10 +87,7 @@ export async function startLocalSubagent(input: {
},
subagentName: action.subagentName,
},
- session: rejectAgentEffect(preparedSession, {
- disposition: "dead",
- operationId: operation.id,
- }),
+ session: input.currentSession,
};
}
@@ -140,9 +101,7 @@ export async function startLocalSubagent(input: {
callId: action.callId,
kind: "called",
name: action.name,
- session: input.taskOwned
- ? confirmTaskAgentAddress(preparedSession, { address, operationId: operation.id })
- : confirmAgentStarted(preparedSession, { address, operationId: operation.id }),
+ session: input.currentSession,
toolName: action.subagentName,
};
}
diff --git a/packages/eve/src/execution/subagent-start-remote.ts b/packages/eve/src/subagents/start-remote.ts
similarity index 80%
rename from packages/eve/src/execution/subagent-start-remote.ts
rename to packages/eve/src/subagents/start-remote.ts
index 4c001ed1c..a9cb7a1ea 100644
--- a/packages/eve/src/execution/subagent-start-remote.ts
+++ b/packages/eve/src/subagents/start-remote.ts
@@ -1,19 +1,13 @@
-import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";
import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import { createRemoteAgentStartFailureResult } from "#execution/dispatch-action-failures.js";
import { mintStartOperation } from "#execution/dispatch-start-operation.js";
import {
resolveRemoteAgentForAction,
startRemoteAgentSession,
-} from "#execution/remote-agent-dispatch.js";
-import {
- confirmAgentStarted,
- confirmTaskAgentAddress,
- prepareAgentStart,
- rejectAgentEffect,
-} from "#harness/handles/transitions.js";
+} from "#subagents/remote-dispatch.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
+import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
@@ -21,7 +15,7 @@ const log = createLogger("execution.subagent-start-remote");
/** Starts one remote subagent after dispatch planning has selected its target. */
export async function startRemoteSubagent(input: {
- readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly action: RuntimeRemoteAgentDispatchRequest;
readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];
readonly batchEvent: { readonly sequence: number; readonly turnId: string };
readonly bundle: CompiledBundle;
@@ -36,7 +30,7 @@ export async function startRemoteSubagent(input: {
readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];
readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];
readonly session: RuntimeSession;
- readonly taskOwned: boolean;
+ readonly taskId?: string;
}): Promise<DispatchOutcome> {
const { action } = input;
const activityObserver = deriveChildActivityObserverConfig({
@@ -76,7 +70,7 @@ export async function startRemoteSubagent(input: {
};
}
- const { identity, operation } = mintStartOperation({
+ const { operation } = mintStartOperation({
callId: action.callId,
name: action.remoteAgentName,
nodeId: action.nodeId,
@@ -89,12 +83,6 @@ export async function startRemoteSubagent(input: {
? action.nodeId
: input.dynamicRemoteAgent.credentialsStepId,
};
- const preparedSession = prepareAgentStart(input.currentSession, {
- identity,
- operation,
- target: { callbackBaseUrl, credentialResolver, kind: "agent/remote", url: resolvedRemote.url },
- });
-
try {
const child = await startRemoteAgentSession({
action,
@@ -108,6 +96,7 @@ export async function startRemoteSubagent(input: {
activityObserver,
remote: resolvedRemote,
session: input.session,
+ taskId: input.taskId,
});
const address = {
callbackBaseUrl,
@@ -121,9 +110,7 @@ export async function startRemoteSubagent(input: {
callId: action.callId,
kind: "called",
name: action.name,
- session: input.taskOwned
- ? confirmTaskAgentAddress(preparedSession, { address, operationId: operation.id })
- : confirmAgentStarted(preparedSession, { address, operationId: operation.id }),
+ session: input.currentSession,
toolName: action.remoteAgentName,
};
} catch (error) {
@@ -135,10 +122,7 @@ export async function startRemoteSubagent(input: {
return {
kind: "error",
result: createRemoteAgentStartFailureResult({ action, error }),
- session: rejectAgentEffect(preparedSession, {
- disposition: "dead",
- operationId: operation.id,
- }),
+ session: input.currentSession,
};
}
}
diff --git a/packages/eve/src/harness/subagent-token-budget.test.ts b/packages/eve/src/subagents/token-budget.test.ts
similarity index 98%
rename from packages/eve/src/harness/subagent-token-budget.test.ts
rename to packages/eve/src/subagents/token-budget.test.ts
index 1a3fb7543..c0624b294 100644
--- a/packages/eve/src/harness/subagent-token-budget.test.ts
+++ b/packages/eve/src/subagents/token-budget.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { resolveRemainingSessionTokenLimits } from "#harness/subagent-token-budget.js";
+import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
import { bumpSessionRuntimeTokenLimits, setTurnUsageState } from "#harness/turn-tag-state.js";
import type { HarnessSession, SessionLimits } from "#harness/types.js";
diff --git a/packages/eve/src/harness/subagent-token-budget.ts b/packages/eve/src/subagents/token-budget.ts
similarity index 100%
rename from packages/eve/src/harness/subagent-token-budget.ts
rename to packages/eve/src/subagents/token-budget.ts
diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/subagents/tool.test.ts
similarity index 94%
rename from packages/eve/src/execution/subagent-tool.test.ts
rename to packages/eve/src/subagents/tool.test.ts
index 9f14db9d1..909756075 100644
--- a/packages/eve/src/execution/subagent-tool.test.ts
+++ b/packages/eve/src/subagents/tool.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it } from "vitest";
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";
-import { buildSubagentRunInput } from "#execution/subagent-tool.js";
+import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
+import { buildSubagentRunInput } from "#subagents/tool.js";
type BuildSubagentRunInput = Parameters<typeof buildSubagentRunInput>[0];
@@ -21,7 +21,7 @@ function makeSession(): HarnessSession {
};
}
-function makeAction(): RuntimeSubagentCallActionRequest {
+function makeAction(): RuntimeSubagentDispatchRequest {
return {
callId: "call-1",
description: "Delegate to linear.",
@@ -119,6 +119,24 @@ describe("buildSubagentRunInput", () => {
});
});
+ it("retains a background task identity beside an opaque parent reply hook", () => {
+ const { runInput } = buildRuntimeSubagentRunInput({
+ action: makeAction(),
+ auth: null,
+ batchEvent: { sequence: 0, turnId: "turn-0" },
+ initiatorAuth: null,
+ parentContinuationToken: "invocation-reply-hook",
+ session: makeSession(),
+ taskId: "task-1",
+ });
+
+ expect(runInput.adapter.state).toMatchObject({
+ parentContinuationToken: "invocation-reply-hook",
+ taskId: "task-1",
+ });
+ expect(runInput.taskId).toBe("task-1");
+ });
+
it("forwards channelMetadata to the child run input", () => {
const projection = {
kind: "channel:slack",
@@ -193,23 +211,6 @@ describe("buildSubagentRunInput", () => {
});
});
- it("increments subagent depth for the child run input", () => {
- const nestedSession: HarnessSession = {
- ...makeSession(),
- sessionId: "intermediate-session",
- subagentDepth: 2,
- };
- const { runInput } = buildRuntimeSubagentRunInput({
- action: makeAction(),
- auth: null,
- batchEvent: { sequence: 1, turnId: "turn-99" },
- initiatorAuth: null,
- session: nestedSession,
- });
-
- expect(runInput.subagentDepth).toBe(3);
- });
-
it("threads inherited limits through the child run input", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
@@ -229,7 +230,7 @@ describe("buildSubagentRunInput", () => {
it("threads outputSchema from action input to RunInput", () => {
const schema = { type: "object", properties: { result: { type: "string" } } };
- const action: RuntimeSubagentCallActionRequest = {
+ const action: RuntimeSubagentDispatchRequest = {
...makeAction(),
input: { message: "do something", outputSchema: schema },
};
@@ -328,7 +329,7 @@ describe("buildSubagentRunInput", () => {
});
it("does not pass the built-in agent tool description into the child message", () => {
- const action: RuntimeSubagentCallActionRequest = {
+ const action: RuntimeSubagentDispatchRequest = {
...makeAction(),
description: "Delegate a focused subtask to a fresh copy of yourself.",
name: "agent",
@@ -385,7 +386,7 @@ describe("buildSubagentRunInput", () => {
});
it("treats an empty outputSchema as absent", () => {
- const action: RuntimeSubagentCallActionRequest = {
+ const action: RuntimeSubagentDispatchRequest = {
...makeAction(),
input: { message: "do something", outputSchema: {} },
};
@@ -403,7 +404,7 @@ describe("buildSubagentRunInput", () => {
it("includes parentSandboxState and sandboxSessionId for self-delegation", () => {
const sandboxState = { initialized: true, session: null };
const session = { ...makeSession(), sandboxState };
- const action: RuntimeSubagentCallActionRequest = {
+ const action: RuntimeSubagentDispatchRequest = {
...makeAction(),
subagentName: "agent",
};
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/subagents/tool.ts
similarity index 89%
rename from packages/eve/src/execution/subagent-tool.ts
rename to packages/eve/src/subagents/tool.ts
index 824347248..69abb89ac 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -1,8 +1,5 @@
-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
-import {
- formatSubagentInput,
- normalizeRequestedOutputSchema,
-} from "#execution/subagent-invocation.js";
+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
+import { formatSubagentInput, normalizeRequestedOutputSchema } from "#subagents/invocation.js";
import type {
ActivityObserverConfig,
ChannelInstrumentationProjection,
@@ -13,14 +10,13 @@ import type {
SessionTraceContext,
} from "#channel/types.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";
+import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
import { mintSubagentContinuationToken } from "#execution/session.js";
-import { resolveSubagentDepth } from "#harness/subagent-depth.js";
-import { resolveRemainingSessionTokenLimits } from "#harness/subagent-token-budget.js";
+import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
import type { JsonObject } from "#shared/json.js";
/**
- * Pending runtime-action batch event metadata needed for child run lineage.
+ * Pending task batch event metadata needed for child run lineage.
*/
interface BatchEventMetadata {
readonly sequence: number;
@@ -71,7 +67,7 @@ export interface SubagentSandboxGraph {
* Builds the {@link RunInput} for one delegated subagent child run.
*/
export function buildSubagentRunInput(input: {
- readonly action: RuntimeSubagentCallActionRequest;
+ readonly action: RuntimeSubagentDispatchRequest;
readonly auth: SessionAuthContext | null;
readonly batchEvent: BatchEventMetadata;
/**
@@ -103,6 +99,8 @@ export function buildSubagentRunInput(input: {
readonly activityObserver?: ActivityObserverConfig;
readonly session: HarnessSession;
readonly source: SubagentInputSource;
+ /** Owning task when this child starts from a background workflow tool. */
+ readonly taskId?: string;
}): SubagentRunInputBuild {
const {
action,
@@ -127,7 +125,6 @@ export function buildSubagentRunInput(input: {
// explicit root, so its own `sessionId` becomes the root for its
// children.
const rootSessionId = session.rootSessionId ?? session.sessionId;
- const subagentDepth = resolveSubagentDepth(session);
const inheritedLimits: {
-readonly [K in keyof RunSessionLimits]: RunSessionLimits[K];
} = resolveRemainingSessionTokenLimits(session, input.fanoutSize);
@@ -138,6 +135,7 @@ export function buildSubagentRunInput(input: {
parentSessionId: session.sessionId,
subagentName: action.subagentName,
};
+ if (input.taskId !== undefined) adapterState.taskId = input.taskId;
const sharesSandbox =
input.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox?.definition
.inheritsParent === true || input.selfAgent;
@@ -180,8 +178,8 @@ export function buildSubagentRunInput(input: {
},
parentTraceContext: input.parentTraceContext,
activityObserver: input.activityObserver,
- subagentDepth: subagentDepth.nextChildDepth,
};
+ if (input.taskId !== undefined) runInput.taskId = input.taskId;
return { childContinuationToken, runInput };
}
@@ -190,7 +188,7 @@ export function buildSubagentRunInput(input: {
* Formats the synthesized child input message for one delegated subagent call.
*/
function formatSubagentCallInputMessage(input: {
- readonly action: Pick<RuntimeSubagentCallActionRequest, "input" | "subagentName">;
+ readonly action: Pick<RuntimeSubagentDispatchRequest, "input" | "subagentName">;
readonly source: SubagentInputSource;
}): string {
const { message } = input.action.input as { message: string };
diff --git a/packages/eve/src/tasks/delivery-context.test.ts b/packages/eve/src/tasks/delivery-context.test.ts
index 377c98d72..a2ec88fdf 100644
--- a/packages/eve/src/tasks/delivery-context.test.ts
+++ b/packages/eve/src/tasks/delivery-context.test.ts
@@ -72,8 +72,8 @@ describe("resolveInitiatingTaskContext", () => {
expect(
resolveInitiatingTaskContext({
state: taskState([
- taskEntry("task_1", "turn_1", undefined, { data: {}, kind: "subagent" }),
- taskEntry("task_2", "turn_2", undefined, { data: {}, kind: "subagent" }),
+ taskEntry("task_1", "turn_1", undefined, { data: {}, kind: "workflow-tool" }),
+ taskEntry("task_2", "turn_2", undefined, { data: {}, kind: "workflow-tool" }),
]),
turnId: "turn_1",
}),
@@ -174,5 +174,5 @@ function taskEntry(
}
function taskState(tasks: readonly ReturnType<typeof taskEntry>[]): SessionStateMap {
- return { [SESSION_TASKS_STATE_KEY]: { tasks } } as SessionStateMap;
+ return { [SESSION_TASKS_STATE_KEY]: { tasks, version: 2 } } as SessionStateMap;
}
diff --git a/packages/eve/src/tasks/json.test.ts b/packages/eve/src/tasks/json.test.ts
index 801b4b845..d62cc4182 100644
--- a/packages/eve/src/tasks/json.test.ts
+++ b/packages/eve/src/tasks/json.test.ts
@@ -9,15 +9,13 @@ describe("taskViewToJson", () => {
it("projects only the model-visible task fields", () => {
const view: TaskView = {
executor: {
- childSessionId: "child-session-1",
- childTurnId: "child-turn-1",
- lifecycle: "terminal",
+ binding: { data: { runId: "run-1" }, kind: "workflow-tool" },
},
lastOutput: { data: { answer: 42 }, type: "result" },
metadata: {
agentId: "agent-1",
kind: "subagent",
- mode: "local",
+ mode: "remote",
name: "researcher",
},
status: "completed",
@@ -35,7 +33,7 @@ describe("taskViewToJson", () => {
metadata: {
agentId: "agent-1",
kind: "subagent",
- mode: "local",
+ mode: "remote",
name: "researcher",
},
status: "completed",
diff --git a/packages/eve/src/tasks/json.ts b/packages/eve/src/tasks/json.ts
index a90aeb86c..0c36b2291 100644
--- a/packages/eve/src/tasks/json.ts
+++ b/packages/eve/src/tasks/json.ts
@@ -3,7 +3,6 @@ import type { z } from "#compiled/zod/index.js";
import type { JsonValue } from "#shared/json.js";
import { TASK_VIEW_JSON_SCHEMA } from "#tools/framework/task-contract.js";
import type { TaskView } from "#tasks/types.js";
-import { readSubagentTaskMetadata } from "#tasks/types.js";
/**
* Model-visible task view, inferred from {@link TASK_VIEW_JSON_SCHEMA}.
@@ -17,19 +16,9 @@ type TaskViewJson = z.infer<typeof TASK_VIEW_JSON_SCHEMA>;
/** Projects a task view into the JSON value carried by tool results. */
export function taskViewToJson(view: TaskView): TaskViewJson {
- const subagent = readSubagentTaskMetadata(view);
- const metadata =
- subagent === undefined
- ? view.metadata
- : {
- agentId: subagent.agentId,
- kind: subagent.kind,
- mode: subagent.mode,
- name: subagent.name,
- };
// `satisfies` couples the schema to `TaskView` at compile time; the runtime
// parse strips the private fields structural typing would let through.
- return TASK_VIEW_JSON_SCHEMA.parse({ ...view, metadata });
+ return TASK_VIEW_JSON_SCHEMA.parse(view);
}
/** Projects many views into one `{ tasks }` tool output. */
diff --git a/packages/eve/src/tasks/session-index.test.ts b/packages/eve/src/tasks/session-index.test.ts
index 278f09881..9d14670e3 100644
--- a/packages/eve/src/tasks/session-index.test.ts
+++ b/packages/eve/src/tasks/session-index.test.ts
@@ -25,9 +25,7 @@ function createSession(state?: HarnessSession["state"]): HarnessSession {
describe("session task index", () => {
const metadata = {
- agentId: "ag_research:abcdef123456",
- kind: "subagent" as const,
- mode: "local" as const,
+ kind: "tool" as const,
name: "research",
};
it("returns an empty index when the key is absent", () => {
@@ -40,7 +38,6 @@ describe("session task index", () => {
taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
- operationId: "operation-1",
taskId: "task_a",
taskRunId: "run-1",
});
@@ -49,19 +46,36 @@ describe("session task index", () => {
taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
- operationId: "operation-1",
taskId: "task_a",
taskRunId: "run-1",
});
expect(findSessionTaskEntry(session.state, "task_other")).toBeUndefined();
});
+ it("keeps subagent metadata in the persisted task index", () => {
+ const subagentMetadata = {
+ agentId: "ag_worker",
+ kind: "subagent",
+ mode: "remote",
+ name: "research",
+ } as const;
+
+ const session = recordSessionTask(createSession(), {
+ taskInboxToken: "task:token-1",
+ createdByTurnId: "turn-1",
+ metadata: subagentMetadata,
+ taskId: "task_a",
+ taskRunId: "run-1",
+ });
+
+ expect(findSessionTaskEntry(session.state, "task_a")?.metadata).toEqual(subagentMetadata);
+ });
+
it("replaces the entry on replayed creation instead of duplicating it", () => {
let session = recordSessionTask(createSession(), {
taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
- operationId: "operation-1",
taskId: "task_a",
taskRunId: "run-1",
});
@@ -69,7 +83,6 @@ describe("session task index", () => {
taskInboxToken: "task:token-2",
createdByTurnId: "turn-1",
metadata,
- operationId: "operation-1",
taskId: "task_a",
taskRunId: "run-2",
});
@@ -84,7 +97,6 @@ describe("session task index", () => {
taskInboxToken: "task:token-1",
createdByTurnId: "turn-1",
metadata,
- operationId: "operation-1",
taskId: "task_a",
taskRunId: "run-1",
};
@@ -125,6 +137,7 @@ describe("session task index", () => {
getSessionTaskIndex({
[SESSION_TASKS_STATE_KEY]: {
tasks: [{ ...base, terminalView: invalidView }],
+ version: 2,
},
}),
).toThrow(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}"`);
@@ -133,9 +146,19 @@ describe("session task index", () => {
it("throws on a corrupt index instead of treating it as absent", () => {
expect(() =>
- getSessionTaskIndex({ [SESSION_TASKS_STATE_KEY]: { tasks: [{ taskId: 42 }] } }),
+ getSessionTaskIndex({
+ [SESSION_TASKS_STATE_KEY]: { tasks: [{ taskId: 42 }], version: 2 },
+ }),
).toThrow(`Corrupt task index under session state key "${SESSION_TASKS_STATE_KEY}"`);
});
+
+ it("rejects the old task index version explicitly", () => {
+ expect(() =>
+ getSessionTaskIndex({ [SESSION_TASKS_STATE_KEY]: { tasks: [], version: 1 } }),
+ ).toThrow(
+ `Unsupported task index version 1 under session state key "${SESSION_TASKS_STATE_KEY}"`,
+ );
+ });
});
describe("deriveTaskId", () => {
diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.ts
index 206f0a979..a2b022ea1 100644
--- a/packages/eve/src/tasks/session-index.ts
+++ b/packages/eve/src/tasks/session-index.ts
@@ -3,7 +3,7 @@ import { z } from "#compiled/zod/index.js";
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
import type { JsonValue } from "#shared/json.js";
import type { TaskExecutorBinding } from "#tools/task.js";
-import { sameTaskMetadata, type DurableTaskMetadata, type TaskView } from "#tasks/types.js";
+import { sameTaskMetadata, type TaskMetadata, type TaskView } from "#tasks/types.js";
/**
* Session-state key for the parent's live-task index.
@@ -15,6 +15,7 @@ import { sameTaskMetadata, type DurableTaskMetadata, type TaskView } from "#task
* executors must update tasks without holding the current snapshot.
*/
export const SESSION_TASKS_STATE_KEY = "eve.tasks";
+const SESSION_TASKS_STATE_VERSION = 2;
/**
* One task owned by this session. Immutable model-safe metadata keeps the
@@ -34,22 +35,13 @@ export interface SessionTaskIndexEntry {
readonly createdByStepIndex?: number;
readonly createdByTurnId: string;
readonly executor?: TaskExecutorBinding;
- readonly metadata: DurableTaskMetadata;
- readonly operationId?: string;
+ readonly metadata: TaskMetadata;
}
-const taskMetadataSchema: z.ZodType<DurableTaskMetadata> = z.union([
- z.strictObject({
- agentId: z.string().min(1),
- kind: z.literal("subagent"),
- mode: z.enum(["local", "remote"]),
- name: z.string().min(1),
- }),
- z.strictObject({
- kind: z.string().min(1),
- name: z.string().min(1),
- }),
-]);
+const taskMetadataSchema = z.looseObject({
+ kind: z.string().min(1),
+ name: z.string().min(1),
+}) as z.ZodType<TaskMetadata>;
const taskViewBaseShape = {
executor: z
@@ -60,9 +52,6 @@ const taskViewBaseShape = {
kind: z.string().min(1),
})
.optional(),
- childSessionId: z.string().min(1).optional(),
- childTurnId: z.string().min(1).optional(),
- lifecycle: z.enum(["parked", "terminal"]).optional(),
})
.optional(),
metadata: taskMetadataSchema,
@@ -108,7 +97,6 @@ const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictOb
})
.optional(),
metadata: taskMetadataSchema,
- operationId: z.string().min(1).optional(),
taskId: z.string().min(1),
taskRunId: z.string().min(1),
terminalView: taskViewSchema.optional(),
@@ -117,6 +105,7 @@ const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictOb
const sessionTaskIndexSchema = z
.strictObject({
tasks: z.array(sessionTaskIndexEntrySchema),
+ version: z.literal(SESSION_TASKS_STATE_VERSION),
})
.refine(
(index) => new Set(index.tasks.map((entry) => entry.taskId)).size === index.tasks.length,
@@ -137,6 +126,7 @@ const sessionTaskIndexSchema = z
interface SessionTaskIndex {
readonly tasks: readonly SessionTaskIndexEntry[];
+ readonly version: typeof SESSION_TASKS_STATE_VERSION;
}
/**
@@ -152,6 +142,12 @@ export function getSessionTaskIndex(
if (raw === undefined) {
return [];
}
+ const version = typeof raw === "object" && raw !== null ? Reflect.get(raw, "version") : undefined;
+ if (version !== SESSION_TASKS_STATE_VERSION) {
+ throw new Error(
+ `Unsupported task index version ${JSON.stringify(version)} under session state key "${SESSION_TASKS_STATE_KEY}"; expected version ${SESSION_TASKS_STATE_VERSION}.`,
+ );
+ }
const parsed = sessionTaskIndexSchema.safeParse(raw);
if (!parsed.success) {
throw new Error(
@@ -177,7 +173,10 @@ export function cacheTerminalTaskView(
}
const tasks = [...entries];
tasks[index] = { ...tasks[index]!, terminalView: view };
- return { ...state, [SESSION_TASKS_STATE_KEY]: { tasks } };
+ return {
+ ...state,
+ [SESSION_TASKS_STATE_KEY]: { tasks, version: SESSION_TASKS_STATE_VERSION },
+ };
}
function isValidTerminalView(view: TaskView): boolean {
@@ -217,7 +216,10 @@ export function recordSessionTask(
...session,
state: {
...session.state,
- [SESSION_TASKS_STATE_KEY]: { tasks } satisfies SessionTaskIndex,
+ [SESSION_TASKS_STATE_KEY]: {
+ tasks,
+ version: SESSION_TASKS_STATE_VERSION,
+ } satisfies SessionTaskIndex,
},
};
}
diff --git a/packages/eve/src/tasks/task-id.ts b/packages/eve/src/tasks/task-id.ts
index d910172be..94cc70113 100644
--- a/packages/eve/src/tasks/task-id.ts
+++ b/packages/eve/src/tasks/task-id.ts
@@ -1,13 +1,10 @@
import { createHash } from "node:crypto";
-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-
/**
- * Derives the stable task id for one originating subagent call.
+ * Derives the stable task id for one originating background call.
*
- * Reuses the agent-handle operation-id derivation —
- * `hash(parentSessionId, parentTurnId, callId)` — so replayed creation
- * for the same call yields the same task without new machinery, and a
+ * Uses `hash(parentSessionId, parentTurnId, callId)` so replayed creation
+ * for the same call yields the same task, and a
* task can never be confused with a child session id or continuation
* token.
*
@@ -20,7 +17,10 @@ export function deriveTaskId(input: {
readonly parentSessionId: string;
readonly parentTurnId: string;
}): string {
- return `task_${deriveAgentOperationId(input).slice(0, 24)}`;
+ return `task_${createHash("sha256")
+ .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)
+ .digest("hex")
+ .slice(0, 24)}`;
}
/**
diff --git a/packages/eve/src/tasks/task-inbox-token.test.ts b/packages/eve/src/tasks/task-inbox-token.test.ts
new file mode 100644
index 000000000..658d020f5
--- /dev/null
+++ b/packages/eve/src/tasks/task-inbox-token.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+
+import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
+
+describe("readTaskIdFromInboxToken", () => {
+ const taskToken = `task:task_abc:${"a".repeat(32)}`;
+
+ it("reads an ordinary task token", () => {
+ expect(readTaskIdFromInboxToken(taskToken)).toBe("task_abc");
+ });
+
+ it("rejects executor-specific suffixes", () => {
+ expect(readTaskIdFromInboxToken(`${taskToken}:executor:${"b".repeat(16)}`)).toBeUndefined();
+ expect(readTaskIdFromInboxToken(`${taskToken}:other:${"b".repeat(16)}`)).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/tasks/transitions.test.ts b/packages/eve/src/tasks/transitions.test.ts
index 7bdd06a44..a0b16d943 100644
--- a/packages/eve/src/tasks/transitions.test.ts
+++ b/packages/eve/src/tasks/transitions.test.ts
@@ -1,363 +1,79 @@
import { describe, expect, it } from "vitest";
import { applyTaskTransition } from "#tasks/transitions.js";
-import type { TaskCommand, TaskStatus, TaskView } from "#tasks/types.js";
+import type { TaskStatus, TaskView } from "#tasks/types.js";
-function createView(status: TaskStatus, overrides: Partial<TaskView> = {}): TaskView {
- // Cast on purpose: tests probe the transition function's runtime guards
- // with shapes the TaskView union already forbids (e.g. terminal, no output).
+function view(status: TaskStatus, overrides: Partial<TaskView> = {}): TaskView {
return {
- metadata: {
- agentId: "ag_research:abcdef123456",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
+ metadata: { kind: "tool", name: "export" },
status,
- taskId: "task_abc123",
+ taskId: "task-1",
...overrides,
} as TaskView;
}
-const TERMINAL_STATUSES: readonly TaskStatus[] = ["completed", "failed", "cancelled"];
-const ALL_COMMANDS: readonly TaskCommand[] = [
- {
- executor: { data: { operationId: "operation-1" }, kind: "export" },
- kind: "bind",
- },
- { data: { answer: 42 }, kind: "complete" },
- { data: { message: "boom" }, kind: "fail" },
- { data: { message: "unindexed" }, kind: "reject-dispatch" },
- { kind: "cancel" },
- { kind: "require-authorization", requestId: "auth-1" },
- { inputRequests: [{ question: "which?" }], kind: "require-input" },
- { kind: "ready" },
- { kind: "answered", requestIds: ["req-1"] },
-];
-
describe("applyTaskTransition", () => {
- it("binds an opaque executor binding idempotently", () => {
+ it("binds one opaque executor idempotently", () => {
const command = {
- executor: { data: { operationId: "operation-1" }, kind: "export" },
+ executor: { data: { runId: "run-1" }, kind: "workflow-tool" },
kind: "bind",
} as const;
-
- const bound = applyTaskTransition(createView("working"), command);
+ const bound = applyTaskTransition(view("working"), command);
expect(bound).toMatchObject({
action: "accepted",
- view: {
- executor: { binding: command.executor },
- metadata: createView("working").metadata,
- status: "working",
- },
- });
- expect(applyTaskTransition(bound.view, command)).toEqual({
- action: "noop",
- view: bound.view,
+ view: { executor: { binding: command.executor } },
});
+ expect(applyTaskTransition(bound.view, command).action).toBe("noop");
expect(
applyTaskTransition(bound.view, {
- executor: { data: { operationId: "operation-2" }, kind: "export" },
+ executor: { data: { runId: "run-2" }, kind: "workflow-tool" },
kind: "bind",
- }),
- ).toMatchObject({ action: "rejected", view: bound.view });
+ }).action,
+ ).toBe("rejected");
});
- it("retains a late executor binding after fast task completion", () => {
- const completed = applyTaskTransition(createView("working"), {
- data: { answer: 42 },
- kind: "complete",
- });
- const executor = { data: { operationId: "operation-1" }, kind: "export" };
-
- const bound = applyTaskTransition(completed.view, { executor, kind: "bind" });
-
- expect(bound).toMatchObject({
- action: "accepted",
- view: {
- executor: { binding: executor },
- lastOutput: { data: { answer: 42 }, type: "result" },
- status: "completed",
- },
- });
- });
-
- it("completes a working task with a result output", () => {
- const result = applyTaskTransition(createView("working"), {
- data: { answer: 42 },
- kind: "complete",
+ it("retains a late binding after fast completion", () => {
+ const completed = applyTaskTransition(view("working"), { data: "done", kind: "complete" });
+ const bound = applyTaskTransition(completed.view, {
+ executor: { data: { runId: "run-1" }, kind: "workflow-tool" },
+ kind: "bind",
});
-
- expect(result.action).toBe("accepted");
- expect(result.view.status).toBe("completed");
- expect(result.view.lastOutput).toEqual({ data: { answer: 42 }, type: "result" });
+ expect(bound).toMatchObject({ action: "accepted", view: { status: "completed" } });
});
- it("retains reported child usage on the terminal view only", () => {
- const usage = { cacheReadTokens: 1, cacheWriteTokens: 2, inputTokens: 300, outputTokens: 40 };
- for (const command of [
- { data: "done", kind: "complete", usage },
- { data: "boom", kind: "fail", usage },
- { kind: "cancel", usage },
- ] as const) {
- const result = applyTaskTransition(createView("working"), command);
- expect(result.action).toBe("accepted");
- expect(result.view.usage).toEqual(usage);
- }
-
- const withoutUsage = applyTaskTransition(createView("working"), {
- data: "done",
- kind: "complete",
- });
- expect(withoutUsage.view.usage).toBeUndefined();
-
- const blocked = applyTaskTransition(createView("working"), {
- inputRequests: [{ question: "which?", requestId: "req-1" }],
+ it("moves through input, answer, and completion", () => {
+ const blocked = applyTaskTransition(view("working"), {
+ inputRequests: [{ prompt: "Continue?", requestId: "req-1" }],
kind: "require-input",
});
- expect(blocked.view.usage).toBeUndefined();
- });
-
- it("fails a working task and carries the error as its output", () => {
- const result = applyTaskTransition(createView("working"), {
- data: { message: "boom" },
- kind: "fail",
+ expect(blocked).toMatchObject({ action: "accepted", view: { status: "input_required" } });
+ const resumed = applyTaskTransition(blocked.view, { kind: "answered", requestIds: ["req-1"] });
+ expect(resumed).toMatchObject({ action: "accepted", view: { status: "working" } });
+ const completed = applyTaskTransition(resumed.view, { data: { answer: 42 }, kind: "complete" });
+ expect(completed).toMatchObject({
+ action: "accepted",
+ view: { lastOutput: { data: { answer: 42 }, type: "result" }, status: "completed" },
});
-
- expect(result.action).toBe("accepted");
- expect(result.view.status).toBe("failed");
- expect(result.view.lastOutput).toEqual({ data: { message: "boom" }, type: "error" });
});
- it("moves working to input_required carrying the outstanding batch", () => {
- const result = applyTaskTransition(createView("working"), {
- inputRequests: [{ question: "which region?", requestId: "req-1" }],
- kind: "require-input",
- });
-
- expect(result.action).toBe("accepted");
- expect(result.view.status).toBe("input_required");
- expect(result.view.inputRequests).toEqual([{ question: "which region?", requestId: "req-1" }]);
- });
-
- it("rejects empty, unidentified, and duplicate input request batches", () => {
+ it("rejects malformed input batches", () => {
for (const inputRequests of [
[],
- [{ question: "missing id" }],
- [
- { question: "first", requestId: "same" },
- { question: "second", requestId: "same" },
- ],
+ [{ prompt: "missing id" }],
+ [{ requestId: "same" }, { requestId: "same" }],
]) {
- const result = applyTaskTransition(createView("working"), {
- inputRequests,
- kind: "require-input",
- });
- expect(result.action).toBe("rejected");
- expect(result.view.status).toBe("working");
+ expect(
+ applyTaskTransition(view("working"), { inputRequests, kind: "require-input" }).action,
+ ).toBe("rejected");
}
});
- it("returns input_required to working once the whole batch is answered", () => {
- const blocked = applyTaskTransition(createView("working"), {
- inputRequests: [{ question: "which region?", requestId: "req-1" }],
- kind: "require-input",
- });
- expect(blocked.action).toBe("accepted");
-
- const result = applyTaskTransition(blocked.view, { kind: "answered", requestIds: ["req-1"] });
-
- expect(result.action).toBe("accepted");
- expect(result.view.status).toBe("working");
- expect(result.view.inputRequests).toBeUndefined();
- });
-
- it("keeps the task blocked on the remainder of a partly answered batch", () => {
- const blocked = applyTaskTransition(createView("working"), {
- inputRequests: [
- { question: "which region?", requestId: "req-1" },
- { question: "which size?", requestId: "req-2" },
- ],
- kind: "require-input",
- });
- expect(blocked.action).toBe("accepted");
-
- const result = applyTaskTransition(blocked.view, { kind: "answered", requestIds: ["req-1"] });
-
- expect(result.action).toBe("accepted");
- expect(result.view.status).toBe("input_required");
- expect(result.view.inputRequests).toEqual([{ question: "which size?", requestId: "req-2" }]);
- });
-
- it("ignores an answer to a batch that was already replaced", () => {
- const first = applyTaskTransition(createView("working"), {
- inputRequests: [{ question: "first", requestId: "req-1" }],
- kind: "require-input",
- });
- const second = applyTaskTransition(first.view, {
- inputRequests: [{ question: "second", requestId: "req-2" }],
- kind: "require-input",
- });
- expect(second.action).toBe("accepted");
-
- const stale = applyTaskTransition(second.view, { kind: "answered", requestIds: ["req-1"] });
-
- expect(stale.action).toBe("noop");
- expect(stale.view.status).toBe("input_required");
- expect(stale.view.inputRequests).toEqual([{ question: "second", requestId: "req-2" }]);
- });
-
- it("keeps independent authorization attempts blocked until each completes", () => {
- const first = applyTaskTransition(createView("working"), {
- kind: "require-authorization",
- requestId: "auth-1",
- });
- const second = applyTaskTransition(first.view, {
- kind: "require-authorization",
- requestId: "auth-2",
- });
- const completedFirst = applyTaskTransition(second.view, {
- kind: "answered",
- requestIds: ["auth-1"],
- });
-
- expect(second.view).toMatchObject({
- inputRequests: [
- { blockedOn: "authorization", requestId: "auth-1" },
- { blockedOn: "authorization", requestId: "auth-2" },
- ],
- status: "input_required",
- });
- expect(completedFirst.view).toMatchObject({
- inputRequests: [{ blockedOn: "authorization", requestId: "auth-2" }],
- status: "input_required",
- });
- });
-
- it("replaces the outstanding batch on repeated require-input", () => {
- const first = applyTaskTransition(createView("working"), {
- inputRequests: [{ question: "first", requestId: "req-1" }],
- kind: "require-input",
- });
- expect(first.action).toBe("accepted");
-
- const second = applyTaskTransition(first.view, {
- inputRequests: [{ question: "second", requestId: "req-2" }],
- kind: "require-input",
- });
-
- expect(second.action).toBe("accepted");
- expect(second.view.inputRequests).toEqual([{ question: "second", requestId: "req-2" }]);
- });
-
- it("completes and cancels an input_required task", () => {
- const blocked = applyTaskTransition(createView("working"), {
- inputRequests: [{ question: "which?", requestId: "req-1" }],
- kind: "require-input",
- });
- expect(blocked.action).toBe("accepted");
-
- const completed = applyTaskTransition(blocked.view, { data: "done", kind: "complete" });
- expect(completed.action).toBe("accepted");
- expect(completed.view.status).toBe("completed");
-
- const cancelled = applyTaskTransition(blocked.view, { kind: "cancel" });
- expect(cancelled.action).toBe("accepted");
- expect(cancelled.view.status).toBe("cancelled");
- });
-
- it("treats an answer to a working task as a noop", () => {
- const result = applyTaskTransition(createView("working"), {
- kind: "answered",
- requestIds: ["req-1"],
- });
-
- expect(result.action).toBe("noop");
- expect(result.view.status).toBe("working");
- });
-
- it("rejects a late completion after cancellation", () => {
- const cancelled = applyTaskTransition(createView("working"), { kind: "cancel" });
- expect(cancelled.action).toBe("accepted");
-
- const late = applyTaskTransition(cancelled.view, { data: "too late", kind: "complete" });
-
- expect(late.action).toBe("rejected");
- expect(late.view.status).toBe("cancelled");
- expect(late.view.lastOutput).toBeUndefined();
- });
-
- it("treats repeated cancellation as an idempotent noop", () => {
- const cancelled = applyTaskTransition(createView("working"), { kind: "cancel" });
- expect(cancelled.action).toBe("accepted");
-
- const again = applyTaskTransition(cancelled.view, { kind: "cancel" });
-
- expect(again.action).toBe("noop");
- expect(again.view.status).toBe("cancelled");
- });
-
- it.each(TERMINAL_STATUSES)("keeps %s final against every lifecycle command", (status) => {
- const view = createView(status);
- for (const command of ALL_COMMANDS) {
- if (command.kind === "bind") continue;
- if (command.kind === "cancel" && status === "cancelled") continue;
- const result = applyTaskTransition(view, command);
- expect(result.action).toBe("rejected");
- expect(result.view).toBe(view);
- }
- });
-
- it("rejects cancel on completed and failed tasks", () => {
- for (const status of ["completed", "failed"] as const) {
- const result = applyTaskTransition(createView(status), { kind: "cancel" });
- expect(result.action).toBe("rejected");
- }
- });
-
- it("is deterministic for replayed commands", () => {
- const view = createView("working");
- const command: TaskCommand = { data: { answer: 1 }, kind: "complete" };
-
- const first = applyTaskTransition(view, command);
- const second = applyTaskTransition(view, command);
-
- expect(first).toEqual(second);
- });
-
- it("never rebinds a task turn to a different child session", () => {
- const result = applyTaskTransition(
- createView("working", {
- executor: { childSessionId: "child-session-1" },
- metadata: {
- agentId: "ag_research:abcdef123456",
- kind: "subagent",
- mode: "local",
- name: "research",
- },
- }),
- {
- childSessionId: "other-child",
- childTurnId: "turn_9",
- kind: "start-turn",
- taskId: "task_abc123",
- },
+ it("keeps terminal states final and cancellation idempotent", () => {
+ const cancelled = applyTaskTransition(view("working"), { kind: "cancel" });
+ expect(cancelled).toMatchObject({ action: "accepted", view: { status: "cancelled" } });
+ expect(applyTaskTransition(cancelled.view, { kind: "cancel" }).action).toBe("noop");
+ expect(applyTaskTransition(cancelled.view, { data: "late", kind: "complete" }).action).toBe(
+ "rejected",
);
-
- expect(result.action).toBe("rejected");
- expect(result.view.executor?.childSessionId).toBe("child-session-1");
- });
-
- it("retains late usage on a terminal task without reviving it", () => {
- const usage = { cacheReadTokens: 1, cacheWriteTokens: 2, inputTokens: 300, outputTokens: 40 };
- const cancelled = applyTaskTransition(createView("working"), { kind: "cancel" });
- if (cancelled.action !== "accepted") throw new Error("Expected cancellation to commit.");
-
- const result = applyTaskTransition(cancelled.view, { kind: "settle-executor", usage });
-
- expect(result).toEqual({
- action: "accepted",
- view: { ...cancelled.view, executor: { lifecycle: "terminal" }, usage },
- });
});
});
diff --git a/packages/eve/src/tasks/transitions.ts b/packages/eve/src/tasks/transitions.ts
index 460f4ff55..bdfebdf48 100644
--- a/packages/eve/src/tasks/transitions.ts
+++ b/packages/eve/src/tasks/transitions.ts
@@ -1,52 +1,34 @@
-import type {
- TaskCommand,
- TaskInputRequest,
- TaskOutput,
- TaskUsage,
- TaskView,
-} from "#tasks/types.js";
-import { isTerminalTaskStatus, readTaskInputRequestId } from "#tasks/types.js";
import { jsonValuesEqual } from "#shared/json.js";
+import {
+ isTerminalTaskStatus,
+ readTaskInputRequestId,
+ type TaskCommand,
+ type TaskInputRequest,
+ type TaskOutput,
+ type TaskUsage,
+ type TaskView,
+} from "#tasks/types.js";
-/**
- * Action taken on one command applied to a task view.
- *
- * - `accepted`: the view changed; the new view must be appended.
- * - `noop`: the command is recognized and benign (idempotent cancel,
- * stale answer); nothing changed and nothing is appended.
- * - `rejected`: the command is invalid for the current status; the
- * reason is diagnostic only.
- */
-type TaskTransitionResult =
+export type TaskTransitionResult =
| { readonly action: "accepted"; readonly view: TaskView }
| { readonly action: "noop"; readonly view: TaskView }
| { readonly action: "rejected"; readonly view: TaskView; readonly reason: string };
-/**
- * Builds the settled view for one terminal command, carrying the
- * child's lifecycle verdict and reported usage when present. Usage is
- * retention-only: nothing folds it into parent budgets yet.
- */
function terminalView(
view: TaskView,
command: Extract<TaskCommand, { kind: "complete" | "fail" | "reject-dispatch" | "cancel" }>,
settled:
- | {
- readonly lastOutput: Extract<TaskOutput, { type: "result" }>;
- readonly status: "completed";
- }
+ | { readonly lastOutput: Extract<TaskOutput, { type: "result" }>; readonly status: "completed" }
| { readonly lastOutput: Extract<TaskOutput, { type: "error" }>; readonly status: "failed" }
| { readonly status: "cancelled" },
): TaskView {
+ const usage = "usage" in command ? command.usage : undefined;
const base: Pick<TaskView, "executor" | "metadata" | "taskId"> & { usage?: TaskUsage } = {
- executor:
- command.lifecycle === undefined
- ? view.executor
- : { ...view.executor, lifecycle: command.lifecycle },
+ executor: view.executor,
metadata: view.metadata,
taskId: view.taskId,
};
- if (command.usage !== undefined) base.usage = command.usage;
+ if (usage !== undefined) base.usage = usage;
switch (settled.status) {
case "completed":
return { ...base, lastOutput: settled.lastOutput, status: "completed" };
@@ -57,41 +39,7 @@ function terminalView(
}
}
-/**
- * Pure transition function for the task lifecycle:
- *
- * ```text
- * working <-> input_required
- * | |
- * +-----> completed
- * +-----> failed
- * +-----> cancelled
- * ```
- *
- * Terminal states are final: a late child result can never revive a
- * cancelled task, and repeated cancellation is idempotent. The durable
- * task run is the only caller that persists accepted views, which is
- * what serializes competing completion, cancellation, and input
- * transitions.
- *
- * Orthogonal to the status, the view carries private executor state
- * (`TaskExecutorState`) with its own lifecycle. These commands move
- * executor fields, never the status above:
- *
- * ```text
- * binding: unset --bind-------> bound (replay noop, conflict rejected)
- * address: unset --start-turn-> session pinned (turn id updated per delivery)
- * verdict: unset --complete/fail/cancel/settle-executor-> parked | terminal
- * ```
- *
- * - `bind` writes the executor binding exactly once: replaying the
- * same binding is a noop, a different one is rejected.
- * - `start-turn` records the child session/turn ids used to address
- * the executor, rejecting a child-session mismatch.
- * - Terminal commands and a late `settle-executor` record the child's
- * lifecycle verdict: `parked` means the child session survived and
- * can take another delivery, `terminal` means it ended with the turn.
- */
+/** Pure, executor-neutral transition function for one durable task. */
export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskTransitionResult {
if (command.kind === "bind") {
const binding = view.executor?.binding;
@@ -116,21 +64,9 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
}
if (isTerminalTaskStatus(view.status)) {
- if (command.kind === "settle-executor") {
- const executor = { ...view.executor, lifecycle: "terminal" as const };
- if (sameUsage(view.usage, command.usage) && view.executor?.lifecycle === "terminal") {
- return { action: "noop", view };
- }
- const next = { ...view, executor };
- return {
- action: "accepted",
- view: command.usage === undefined ? next : { ...next, usage: command.usage },
- };
- }
if (command.kind === "cancel" && view.status === "cancelled") {
return { action: "noop", view };
}
-
return {
action: "rejected",
reason: `Task "${view.taskId}" is already ${view.status}; "${command.kind}" cannot change a terminal task.`,
@@ -157,42 +93,7 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
}),
};
case "cancel":
- return {
- action: "accepted",
- view: terminalView(view, command, { status: "cancelled" }),
- };
- case "settle-executor":
- return {
- action: "rejected",
- reason: `Task "${view.taskId}" is not terminal; usage settles with its terminal command.`,
- view,
- };
- case "require-authorization": {
- const blocker = { blockedOn: "authorization", requestId: command.requestId };
- if (view.status === "input_required") {
- if (
- view.inputRequests.some(
- (request) => readTaskInputRequestId(request) === command.requestId,
- )
- ) {
- return { action: "noop", view };
- }
- return {
- action: "accepted",
- view: { ...view, inputRequests: [...view.inputRequests, blocker] },
- };
- }
- return {
- action: "accepted",
- view: {
- inputRequests: [blocker],
- executor: view.executor,
- metadata: view.metadata,
- status: "input_required",
- taskId: view.taskId,
- },
- };
- }
+ return { action: "accepted", view: terminalView(view, command, { status: "cancelled" }) };
case "require-input":
if (!isValidInputRequestBatch(command.inputRequests)) {
return {
@@ -212,40 +113,21 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
},
};
case "ready":
- // The readiness command is also the barrier that releases a fast,
- // pre-acknowledgement HITL batch, so the workflow must observe it.
return { action: "accepted", view };
case "answered": {
- if (view.status !== "input_required") {
- return { action: "noop", view };
- }
-
+ if (view.status !== "input_required") return { action: "noop", view };
const answered = new Set(command.requestIds);
- const outstanding = view.inputRequests;
- const remaining = outstanding.filter((request) => {
+ const remaining = view.inputRequests.filter((request) => {
const requestId = readTaskInputRequestId(request);
return requestId === undefined || !answered.has(requestId);
});
- // An answer that matches nothing outstanding is stale: the batch
- // it was written against was already cleared or replaced. Leaving
- // the current batch intact is what stops it from unblocking a
- // question the human never saw.
- if (remaining.length === outstanding.length) {
- return { action: "noop", view };
- }
+ if (remaining.length === view.inputRequests.length) return { action: "noop", view };
if (remaining.length > 0) {
return {
action: "accepted",
- view: {
- inputRequests: remaining,
- executor: view.executor,
- metadata: view.metadata,
- status: "input_required",
- taskId: view.taskId,
- },
+ view: { ...view, inputRequests: remaining },
};
}
-
return {
action: "accepted",
view: {
@@ -256,42 +138,6 @@ export function applyTaskTransition(view: TaskView, command: TaskCommand): TaskT
},
};
}
- case "start-turn": {
- if (command.taskId !== view.taskId) {
- return {
- action: "rejected",
- reason: `Task turn identity "${command.taskId}" does not match "${view.taskId}".`,
- view,
- };
- }
- if (
- view.executor?.childSessionId !== undefined &&
- view.executor.childSessionId !== command.childSessionId
- ) {
- return {
- action: "rejected",
- reason: `Task child session "${command.childSessionId}" does not match "${view.executor.childSessionId}".`,
- view,
- };
- }
- if (
- view.executor?.childSessionId === command.childSessionId &&
- view.executor.childTurnId === command.childTurnId
- ) {
- return { action: "noop", view };
- }
- return {
- action: "accepted",
- view: {
- ...view,
- executor: {
- ...view.executor,
- childSessionId: command.childSessionId,
- childTurnId: command.childTurnId,
- },
- },
- };
- }
}
}
@@ -303,13 +149,3 @@ function isValidInputRequestBatch(requests: readonly TaskInputRequest[]): boolea
new Set(ids).size === ids.length
);
}
-
-function sameUsage(left: TaskUsage | undefined, right: TaskUsage | undefined): boolean {
- if (left === undefined || right === undefined) return left === right;
- return (
- left?.cacheReadTokens === right.cacheReadTokens &&
- left.cacheWriteTokens === right.cacheWriteTokens &&
- left.inputTokens === right.inputTokens &&
- left.outputTokens === right.outputTokens
- );
-}
diff --git a/packages/eve/src/tasks/types.test.ts b/packages/eve/src/tasks/types.test.ts
index 308f8136a..84dc6638a 100644
--- a/packages/eve/src/tasks/types.test.ts
+++ b/packages/eve/src/tasks/types.test.ts
@@ -1,79 +1,32 @@
import { describe, expect, it } from "vitest";
-import type { AgentAddress, AgentIdentity } from "#harness/handles/store.js";
-import {
- createSubagentExecutorBinding,
- readSubagentExecutor,
- readSubagentTaskMetadata,
-} from "#tasks/types.js";
+import { readTaskInputRequestId, readTaskUsage, sameTaskMetadata } from "#tasks/types.js";
-const identity: AgentIdentity = {
- id: "ag_research:operation1",
- name: "research",
- nodeId: "node_research",
-};
-
-const localAddress: AgentAddress = {
- continuationToken: "continuation_child",
- kind: "agent/local",
- sessionId: "session_child",
-};
-
-const remoteAddress: AgentAddress = {
- callbackBaseUrl: "https://parent.example",
- credentialResolver: { resolverId: "dynamic-credentials-step" },
- kind: "agent/remote",
- sessionId: "session_child",
- url: "https://child.example",
-};
-
-describe("subagent executor binding", () => {
- it("round-trips a local child through the durable binding", () => {
- const binding = createSubagentExecutorBinding({ address: localAddress, identity });
- expect(binding.kind).toBe("subagent");
- expect(readSubagentExecutor(binding)).toEqual({ address: localAddress, identity });
- });
-
- it("round-trips a remote child through the durable binding", () => {
- const binding = createSubagentExecutorBinding({ address: remoteAddress, identity });
- expect(readSubagentExecutor(binding)).toEqual({ address: remoteAddress, identity });
- });
-
- it("round-trips an explicit no-credential remote resolver", () => {
- const address: AgentAddress = {
- ...remoteAddress,
- credentialResolver: {},
- };
- const binding = createSubagentExecutorBinding({ address, identity });
-
- expect(readSubagentExecutor(binding)).toEqual({ address, identity });
- });
-
- it("reads the binding recorded on task executor state", () => {
- const binding = createSubagentExecutorBinding({ address: localAddress, identity });
- expect(readSubagentExecutor({ binding })).toEqual({ address: localAddress, identity });
+describe("task kernel types", () => {
+ it("compares only generic metadata identity", () => {
+ expect(
+ sameTaskMetadata({ kind: "tool", name: "export" }, { kind: "tool", name: "export" }),
+ ).toBe(true);
+ expect(
+ sameTaskMetadata({ kind: "tool", name: "export" }, { kind: "tool", name: "import" }),
+ ).toBe(false);
+ expect(
+ sameTaskMetadata(
+ { agentId: "ag_1", kind: "subagent", mode: "remote", name: "research" },
+ { agentId: "ag_2", kind: "subagent", mode: "remote", name: "research" },
+ ),
+ ).toBe(false);
});
- it("derives subagent task metadata from the binding of a generic tool task", () => {
- const executor = createSubagentExecutorBinding({ address: remoteAddress, identity });
- expect(
- readSubagentTaskMetadata({ executor, metadata: { kind: "tool", name: "research" } }),
- ).toEqual({ agentId: identity.id, kind: "subagent", mode: "remote", name: identity.name });
+ it("reads opaque input request ids", () => {
+ expect(readTaskInputRequestId({ prompt: "Continue?", requestId: "req-1" })).toBe("req-1");
+ expect(readTaskInputRequestId({ prompt: "Continue?" })).toBeUndefined();
});
- it("returns undefined for other executor kinds and incomplete addresses", () => {
- expect(readSubagentExecutor(undefined)).toBeUndefined();
- expect(readSubagentExecutor({ data: { exportId: "x" }, kind: "export" })).toBeUndefined();
- expect(
- readSubagentExecutor({
- // A local address without its continuation token cannot route a
- // cancel; the reader rejects it instead of returning a partial value.
- data: {
- address: { kind: "agent/local", sessionId: "session_child" },
- identity: { id: identity.id, name: identity.name, nodeId: identity.nodeId },
- },
- kind: "subagent",
- }),
- ).toBeUndefined();
+ it("accepts complete non-negative usage and drops malformed usage", () => {
+ const usage = { cacheReadTokens: 1, cacheWriteTokens: 2, inputTokens: 3, outputTokens: 4 };
+ expect(readTaskUsage(usage)).toEqual(usage);
+ expect(readTaskUsage({ ...usage, inputTokens: -1 })).toBeUndefined();
+ expect(readTaskUsage({ inputTokens: 1 })).toBeUndefined();
});
});
diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.ts
index 05addd3f5..025b4e394 100644
--- a/packages/eve/src/tasks/types.ts
+++ b/packages/eve/src/tasks/types.ts
@@ -1,202 +1,32 @@
-import type { AgentAddress, AgentIdentity } from "#harness/handles/store.js";
-import { isJsonObjectValue, type JsonValue } from "#shared/json.js";
+import type {
+ SubagentAuthorizationEvent,
+ SubagentAuthorizationEventHookPayload,
+} from "#channel/types.js";
+import type { WorkflowToolAgentRequest } from "#execution/tools/workflow/messages.js";
+import { jsonValuesEqual, type JsonValue } from "#shared/json.js";
import type { TaskExecutorBinding } from "#tools/task.js";
-import type { SubagentAuthorizationEvent } from "#channel/types.js";
-/**
- * Task lifecycle contract for `experimental.tasks`.
- *
- * A task is one durable unit of delegated work owned by a parent session.
- * The durable task run is the single writer for lifecycle transitions
- * (see `#execution/tasks/child/workflow.js`); every other path submits
- * commands and reads views. This module is dependency-free on
- * purpose: it is bundled into workflow bodies, which reject Node.js
- * builtins and heavyweight validators.
- */
-
-/**
- * Task lifecycle status.
- *
- * `completed`, `failed`, and `cancelled` are terminal and final.
- * `input_required` is not terminal but is ready for parent action; the
- * child must wake its parent rather than deadlock while waiting for input.
- */
+/** Durable lifecycle status for one unit of background work. */
export type TaskStatus = "working" | "input_required" | "completed" | "failed" | "cancelled";
-/**
- * Immutable identity of the delegated work behind a task.
- *
- * `agentId` is parent-controlled and exists before the child acknowledges its
- * private address, so the durable task can bind to persistent identity before
- * the dispatch side effect runs.
- */
+/** Executor-neutral identity shown for one task. */
export interface TaskMetadata {
- /** Stable model-visible identity of the persistent child session. */
- readonly agentId: string;
- readonly kind: "subagent";
- readonly mode: "local" | "remote";
- /** Authored subagent name the parent dispatched. */
- readonly name: string;
-}
-
-export type SubagentTaskMetadata = TaskMetadata;
-
-/** Executor-neutral metadata retained by a non-subagent durable task. */
-export interface BackgroundTaskMetadata {
readonly kind: string;
readonly name: string;
+ readonly [key: string]: JsonValue | undefined;
}
-export type DurableTaskMetadata = BackgroundTaskMetadata | TaskMetadata;
-
-export function createSubagentTaskMetadata(
- metadata: Omit<SubagentTaskMetadata, "kind" | "name"> & { readonly name: string },
-): SubagentTaskMetadata {
- return { ...metadata, kind: "subagent" };
-}
-
-export function readSubagentTaskMetadata(task: {
- readonly executor?: TaskExecutorBinding | TaskExecutorState;
- readonly metadata: DurableTaskMetadata;
-}): SubagentTaskMetadata | undefined {
- if (task.metadata.kind === "subagent" && "agentId" in task.metadata) {
- return task.metadata;
- }
- const executor = readSubagentExecutor(task.executor);
- if (executor === undefined) return undefined;
- return {
- agentId: executor.identity.id,
- kind: "subagent",
- mode: executor.address.kind === "agent/remote" ? "remote" : "local",
- name: executor.identity.name,
- };
-}
-
-/**
- * Durable subagent executor binding payload: the child's stable identity and
- * private delivery address, copied from the parent's agent handle store at
- * delegation time. Every field derives deterministically from the
- * originating call (operation-hashed id, dispatch-chosen continuation
- * token), so a replayed delegation produces a deep-equal binding — the
- * equality the task run's `bind` replay check compares.
- */
-export interface SubagentExecutorData {
- readonly address: AgentAddress;
- readonly identity: AgentIdentity;
-}
-
-export function createSubagentExecutorBinding(executor: SubagentExecutorData): TaskExecutorBinding {
- const { address, identity } = executor;
- return {
- data: {
- address: { ...address },
- identity: { id: identity.id, name: identity.name, nodeId: identity.nodeId },
- },
- kind: "subagent",
- };
-}
-
-export function readSubagentExecutor(
- executor: TaskExecutorBinding | TaskExecutorState | undefined,
-): SubagentExecutorData | undefined {
- const binding = executor !== undefined && "kind" in executor ? executor : executor?.binding;
- if (binding?.kind !== "subagent") return undefined;
- const identity = readAgentIdentity(binding.data.identity);
- const address = readAgentAddress(binding.data.address);
- return identity === undefined || address === undefined ? undefined : { address, identity };
-}
-
-function readAgentIdentity(value: JsonValue | undefined): AgentIdentity | undefined {
- if (value === undefined || !isJsonObjectValue(value)) return undefined;
- const { id, name, nodeId } = value;
- return typeof id === "string" && typeof name === "string" && typeof nodeId === "string"
- ? { id, name, nodeId }
- : undefined;
-}
-
-function readAgentAddress(value: JsonValue | undefined): AgentAddress | undefined {
- if (value === undefined || !isJsonObjectValue(value)) return undefined;
- const { callbackBaseUrl, continuationToken, credentialResolver, kind, sessionId, url } = value;
- if (typeof sessionId !== "string") return undefined;
- if (kind === "agent/local" || kind === "agent/self") {
- return typeof continuationToken === "string"
- ? { continuationToken, kind, sessionId }
- : undefined;
- }
- if (kind === "agent/remote") {
- const resolver = readCredentialResolver(credentialResolver);
- if (credentialResolver !== undefined && resolver === undefined) return undefined;
- if (typeof url !== "string" || typeof callbackBaseUrl !== "string") return undefined;
- const address: {
- callbackBaseUrl: string;
- credentialResolver?: { readonly resolverId?: string };
- kind: "agent/remote";
- sessionId: string;
- url: string;
- } = { callbackBaseUrl, kind, sessionId, url };
- if (resolver !== undefined) address.credentialResolver = resolver;
- return address;
- }
- return undefined;
-}
-
-function readCredentialResolver(
- value: JsonValue | undefined,
-): { readonly resolverId?: string } | undefined {
- if (value === undefined) return undefined;
- if (!isJsonObjectValue(value)) return undefined;
- const { resolverId } = value;
- if (resolverId !== undefined && typeof resolverId !== "string") return undefined;
- return resolverId === undefined ? {} : { resolverId };
-}
-
-export function sameTaskMetadata(left: DurableTaskMetadata, right: DurableTaskMetadata): boolean {
- if (left.kind !== right.kind || left.name !== right.name) return false;
- const leftSubagent = "agentId" in left;
- const rightSubagent = "agentId" in right;
- return (
- leftSubagent === rightSubagent &&
- (!leftSubagent ||
- !rightSubagent ||
- (left.agentId === right.agentId && left.mode === right.mode))
- );
-}
-
-/** Private executor state retained for cancellation and address reconciliation. */
-export interface TaskExecutorState {
- /** Write-once executor address recorded by the `bind` command. */
- readonly binding?: TaskExecutorBinding;
- readonly childSessionId?: string;
- readonly childTurnId?: string;
- /**
- * Child-session verdict from the last settled turn: `parked` survived
- * and can take another delivery, `terminal` ended with the turn.
- */
- readonly lifecycle?: "parked" | "terminal";
+export function sameTaskMetadata(left: TaskMetadata, right: TaskMetadata): boolean {
+ return jsonValuesEqual(left, right);
}
-/**
- * Terminal task output. Failure is the state (`failed`); the `error`
- * output is its consequence — a `failed` task always carries one.
- * This intentionally diverges from MCP, which reserves `failed` for
- * protocol-level errors.
- */
export type TaskOutput =
| { readonly type: "result"; readonly data: JsonValue }
| { readonly type: "error"; readonly data: JsonValue };
-/**
- * One outstanding request forwarded from a blocked child. Carried
- * opaquely: the task layer routes the batch, the input contract owns
- * its shape.
- */
+/** An outstanding request carried opaquely by the task lifecycle. */
export type TaskInputRequest = JsonValue;
-/**
- * Provider token usage a child turn reported. Structural on purpose: it
- * mirrors `TokenUsage` (#shared/token-usage.js) without importing its
- * zod-backed module into a workflow-bundled file.
- */
export interface TaskUsage {
readonly cacheReadTokens: number;
readonly cacheWriteTokens: number;
@@ -204,11 +34,7 @@ export interface TaskUsage {
readonly outputTokens: number;
}
-/**
- * Validates one wire-carried usage value into {@link TaskUsage}.
- * Anything malformed is dropped rather than rejected: retention is
- * best-effort and must never fail a lifecycle transition.
- */
+/** Reads valid provider usage without making task settlement depend on it. */
export function readTaskUsage(value: unknown): TaskUsage | undefined {
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
const cacheReadTokens = readUsageAxis(value, "cacheReadTokens");
@@ -231,65 +57,22 @@ function readUsageAxis(value: object, key: string): number | undefined {
return typeof field === "number" && Number.isFinite(field) && field >= 0 ? field : undefined;
}
-/**
- * One human answer to an outstanding request. Structural on purpose: it
- * mirrors the input contract's `InputResponse` without importing its
- * zod-backed module into a workflow-bundled file.
- */
-export interface TaskInputResponse {
- readonly optionId?: string;
- readonly requestId: string;
- readonly text?: string;
-}
-
-/**
- * Request id of the synthetic entry that blocks a task while its child
- * waits for authorization. Giving the block an id keeps its release
- * bound to the same entry, so completing authorization can never clear
- * an unrelated request batch the child raised in the meantime.
- */
-const TASK_AUTHORIZATION_REQUEST_ID_PREFIX = "task:authorization";
-
-/** Stable task blocker id shared by one authorization attempt's events. */
-export function taskAuthorizationRequestId(event: SubagentAuthorizationEvent): string {
- if (event.type === "approval.candidate" || event.type === "approval.settled") {
- return `${TASK_AUTHORIZATION_REQUEST_ID_PREFIX}:${event.data.requestId}`;
- }
- return `${TASK_AUTHORIZATION_REQUEST_ID_PREFIX}:${event.data.attemptId ?? event.data.name}`;
-}
-
-/** Reads the `requestId` of one opaque outstanding request. */
+/** Reads the request identity from one opaque request. */
export function readTaskInputRequestId(request: TaskInputRequest): string | undefined {
if (request === null || typeof request !== "object" || Array.isArray(request)) return undefined;
const requestId = Reflect.get(request, "requestId");
return typeof requestId === "string" ? requestId : undefined;
}
-/** Fields shared by every durable task view. */
interface TaskViewBase {
readonly taskId: string;
- readonly metadata: DurableTaskMetadata;
- /** Private executor state; deliberately excluded from model-visible JSON. */
- readonly executor?: TaskExecutorState;
- /**
- * Provider usage the child reported at settlement; present when the
- * terminal command carried it. Retained for later accounting only —
- * budgets stay best-effort until a reservation model lands — and
- * deliberately excluded from model-visible task views (tasks/json.ts).
- */
+ readonly metadata: TaskMetadata;
+ /** Private executor state, excluded from model-visible JSON. */
+ readonly executor?: { readonly binding?: TaskExecutorBinding };
+ /** Retained for accounting, excluded from model-visible JSON. */
readonly usage?: TaskUsage;
}
-/**
- * Full durable task view discriminated by lifecycle status.
- *
- * The task run appends one per accepted command; readers always observe a
- * complete view, never a delta. A view never contains routing credentials,
- * continuation tokens, or authorization capabilities.
- *
- * Completed and failed tasks carry their corresponding output, cancelled
- * tasks carry no output, and only input-required tasks carry requests.
- */
export type TaskView = TaskViewBase &
(
| {
@@ -319,181 +102,121 @@ export type TaskView = TaskViewBase &
}
);
-/** Commands accepted by the durable task run's transition function. */
+/** Executor-neutral commands accepted by the durable task run. */
export type TaskCommand =
- | {
- readonly executor: TaskExecutorBinding;
- readonly kind: "bind";
- }
+ | { readonly executor: TaskExecutorBinding; readonly kind: "bind" }
| {
readonly kind: "complete";
readonly data: JsonValue;
- readonly lifecycle?: "parked" | "terminal";
readonly usage?: TaskUsage;
}
| {
readonly kind: "fail";
readonly data: JsonValue;
- readonly lifecycle?: "parked" | "terminal";
readonly usage?: TaskUsage;
}
- /** Terminal dispatch rejection for a task that was never indexed by its parent. */
- | {
- readonly kind: "reject-dispatch";
- readonly data: JsonValue;
- readonly lifecycle?: never;
- readonly usage?: never;
- }
+ | { readonly kind: "reject-dispatch"; readonly data: JsonValue }
| {
readonly kind: "cancel";
- readonly lifecycle?: "parked" | "terminal";
readonly usage?: TaskUsage;
}
- /** Retains a late executor settlement without changing task terminal status. */
- | { readonly kind: "settle-executor"; readonly usage?: TaskUsage }
- | { readonly kind: "require-authorization"; readonly requestId: string }
| { readonly kind: "require-input"; readonly inputRequests: readonly TaskInputRequest[] }
| { readonly kind: "ready" }
- /**
- * Clears the listed requests from the outstanding batch. Bound to
- * ids rather than unbound like the former `resume`, so an answer can
- * only ever release the batch it was written against.
- */
- | { readonly kind: "answered"; readonly requestIds: readonly string[] }
- | {
- readonly kind: "start-turn";
- readonly childSessionId: string;
- readonly childTurnId: string;
- readonly taskId: string;
- };
+ | { readonly kind: "answered"; readonly requestIds: readonly string[] };
-/** Hook payload envelope commanding a durable task run. */
export interface TaskCommandHookPayload {
readonly kind: "task-command";
readonly command: TaskCommand;
}
-/**
- * Structural shapes of the child wire payloads a task run consumes.
- *
- * These mirror the existing parent-notification contracts (the local
- * `notifyDelegatedParentStep`, the subagent adapter's HITL forwarding,
- * and the remote callback route) without importing their zod-backed
- * modules: this file is bundled into workflow bodies. The wire itself
- * is unchanged — delegated dispatch only points it at the task run's
- * hook instead of the parent turn's inbox.
- */
-export interface TaskInboundChildResult {
- readonly kind: "runtime-action-result";
- readonly results: readonly {
- readonly isError?: boolean;
- readonly outcome?: {
- readonly kind: "parked" | "terminal";
- readonly result:
- | { readonly kind: "succeeded"; readonly output: JsonValue }
- | { readonly error: JsonValue; readonly kind: "failed" }
- | { readonly kind: "cancelled" };
- /**
- * Provider usage this turn added. Retained on the terminal task
- * view ({@link TaskView.usage}); folding it into parent
- * budgets is deferred until a reservation model lands.
- */
- readonly usageDelta?: unknown;
- };
- readonly output: JsonValue;
- }[];
-}
-
-/**
- * Arrives when the delegated child emits `input.requested`. After dispatch is
- * acknowledged, the task run exposes the batch in an `input_required`
- * view and forwards the request to the parent session.
- */
-export interface TaskInboundInputRequest {
- readonly callId: string;
- readonly childContinuationToken: string;
- readonly childSessionId: string;
- readonly kind: "subagent-input-request";
- readonly event: {
- readonly requests: readonly TaskInputRequest[];
- readonly sequence: number;
- readonly stepIndex: number;
- readonly turnId: string;
- };
- readonly subagentName: string;
-}
-
-/**
- * Arrives when a delegated child turn starts and its session and turn ids are
- * known. The task run records those ids for executor addressing; this payload
- * does not itself make the task ready or wake the parent.
- */
-export interface TaskInboundTurnStarted {
- readonly childSessionId: string;
- readonly childTurnId: string;
- readonly kind: "turn-started";
- readonly taskId: string;
-}
-
-/** Intermediate progress sent by a running child to its parent agent. */
+/** Intermediate progress reported by an executor. */
export interface TaskInboundUpdate {
readonly callId: string;
- /** Executor-neutral monotonic index within {@link updateEpoch}. */
readonly updateIndex: number;
- /** Executor-neutral epoch id used with {@link updateIndex} for update dedupe. */
readonly updateEpoch: string;
readonly kind: "task-update";
readonly message: string;
}
-/**
- * Arrives when the delegated child emits `authorization.required` or
- * `authorization.completed`. The former exposes an authorization blocker in
- * the task view; the latter clears it. The event is forwarded separately
- * to the parent and is never copied into the view.
- */
-export interface TaskInboundAuthorizationEvent {
- readonly callId: string;
- readonly childSessionId: string;
- readonly kind: "authorization-event";
- readonly event: SubagentAuthorizationEvent;
- readonly subagentName: string;
+/** One workflow-executor request bound to its private answer hook. */
+export interface TaskInboundInputRequest {
+ readonly kind: "task-input-request";
+ readonly replyTo: string;
+ readonly requests: readonly TaskInputRequest[];
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
}
-/**
- * Human answers routed to the task run rather than straight to the
- * child. The run owns both the delivery and the state change, so the
- * batch it clears is exactly the batch it forwarded — the parent can no
- * longer unblock the child while the run still believes it is blocked.
- */
+/** One human answer routed through the task that owns the blocked executor. */
export interface TaskInboundAnswerInput {
readonly auth?: unknown;
readonly childContinuationToken: string;
readonly childResponseUrl?: string;
- readonly inputResponses: readonly TaskInputResponse[];
+ readonly inputResponses: readonly {
+ readonly optionId?: string;
+ readonly requestId: string;
+ readonly text?: string;
+ }[];
readonly kind: "input-response";
readonly taskId: string;
}
-/** Everything a task run's inbound continuation hook may receive. */
export type TaskRunInboundPayload =
| TaskCommandHookPayload
- | TaskInboundChildResult
- | TaskInboundInputRequest
- | TaskInboundTurnStarted
- | TaskInboundUpdate
- | TaskInboundAuthorizationEvent
- | TaskInboundAnswerInput;
+ | TaskInboundAnswerInput
+ | TaskInboundUpdate;
+
+/** Generic task-owned request sent through the parent session payload. */
+interface TaskInputRequestDeliveryBase {
+ readonly replyTo: string;
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly taskId: string;
+ readonly turnId: string;
+}
+
+export type TaskInputRequestDelivery = TaskInputRequestDeliveryBase &
+ (
+ | { readonly request: TaskInputRequest; readonly requests?: never }
+ | { readonly request?: never; readonly requests: readonly TaskInputRequest[] }
+ );
+
+/**
+ * Child authorization event projected through the parent channel. Display
+ * only: the authorization callback completes against the child directly.
+ */
+export interface TaskAuthorizationEventDelivery {
+ readonly hookPayload: SubagentAuthorizationEventHookPayload;
+ readonly taskId: string;
+}
+
+const TASK_AUTHORIZATION_REQUEST_ID_PREFIX = "task:authorization";
+
+/** Stable id shared by one authorization attempt's events, used to dedupe deliveries. */
+export function taskAuthorizationRequestId(event: SubagentAuthorizationEvent): string {
+ if (event.type === "approval.candidate" || event.type === "approval.settled") {
+ return `${TASK_AUTHORIZATION_REQUEST_ID_PREFIX}:${event.data.requestId}`;
+ }
+ return `${TASK_AUTHORIZATION_REQUEST_ID_PREFIX}:${event.data.attemptId ?? event.data.name}`;
+}
+
+/**
+ * Agent spawn or settlement a task-owned workflow tool run asks its parent to
+ * apply, forwarded after task admission. `replyTo` is the run's reply hook.
+ */
+export interface TaskAgentRequestDelivery {
+ readonly replyTo: string;
+ readonly request: WorkflowToolAgentRequest;
+ readonly taskId: string;
+}
-/** Namespaced run stream carrying appended `TaskView` records. */
export const TASK_VIEW_STREAM_NAMESPACE = "eve.task";
-/** True when the status can never change again. */
export function isTerminalTaskStatus(status: TaskStatus): boolean {
return status === "completed" || status === "failed" || status === "cancelled";
}
-/** True when a transition into this status should wake the parent. */
export function isReadyTaskStatus(status: TaskStatus): boolean {
return status === "input_required" || isTerminalTaskStatus(status);
}
diff --git a/packages/eve/src/tasks/wire.test.ts b/packages/eve/src/tasks/wire.test.ts
deleted file mode 100644
index 6461e61f3..000000000
--- a/packages/eve/src/tasks/wire.test.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { translateTaskInboundPayload } from "#tasks/wire.js";
-
-const ZERO_USAGE = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };
-const USAGE = { cacheReadTokens: 1, cacheWriteTokens: 2, inputTokens: 300, outputTokens: 40 };
-
-describe("translateTaskInboundPayload", () => {
- it("passes explicit task commands through", () => {
- expect(
- translateTaskInboundPayload({ command: { kind: "cancel" }, kind: "task-command" }),
- ).toEqual({ kind: "cancel" });
- });
-
- it("completes on a succeeded child turn outcome, parked or terminal", () => {
- for (const kind of ["parked", "terminal"] as const) {
- expect(
- translateTaskInboundPayload({
- kind: "runtime-action-result",
- results: [
- {
- outcome: {
- kind,
- result: { kind: "succeeded", output: "answer" },
- usageDelta: ZERO_USAGE,
- },
- output: "answer",
- },
- ],
- }),
- ).toEqual({ data: "answer", kind: "complete", lifecycle: kind, usage: ZERO_USAGE });
- }
- });
-
- it("retains nonzero child usage on complete, fail, and cancel commands", () => {
- const outcomes = [
- {
- expected: { data: "done", kind: "complete" },
- result: { kind: "succeeded", output: "done" },
- },
- { expected: { data: "done", kind: "fail" }, result: { error: "boom", kind: "failed" } },
- { expected: { kind: "cancel" }, result: { kind: "cancelled" } },
- ] as const;
- for (const { expected, result } of outcomes) {
- expect(
- translateTaskInboundPayload({
- kind: "runtime-action-result",
- results: [{ outcome: { kind: "terminal", result, usageDelta: USAGE }, output: "done" }],
- }),
- ).toEqual({ ...expected, lifecycle: "terminal", usage: USAGE });
- }
- });
-
- it("drops malformed usage rather than failing the transition command", () => {
- for (const usageDelta of [null, "n/a", { inputTokens: -1 }, { inputTokens: 1 }]) {
- expect(
- translateTaskInboundPayload({
- kind: "runtime-action-result",
- results: [
- {
- outcome: {
- kind: "terminal",
- result: { kind: "succeeded", output: "ok" },
- usageDelta,
- },
- output: "ok",
- },
- ],
- }),
- ).toEqual({ data: "ok", kind: "complete", lifecycle: "terminal" });
- }
- });
-
- it("fails on a failed outcome and cancels on a cancelled outcome", () => {
- expect(
- translateTaskInboundPayload({
- kind: "runtime-action-result",
- results: [
- {
- outcome: {
- kind: "terminal",
- result: { error: { message: "boom" }, kind: "failed" },
- usageDelta: ZERO_USAGE,
- },
- output: { message: "boom" },
- },
- ],
- }),
- ).toEqual({
- data: { message: "boom" },
- kind: "fail",
- lifecycle: "terminal",
- usage: ZERO_USAGE,
- });
-
- expect(
- translateTaskInboundPayload({
- kind: "runtime-action-result",
- results: [
- {
- outcome: { kind: "terminal", result: { kind: "cancelled" }, usageDelta: ZERO_USAGE },
- output: null,
- },
- ],
- }),
- ).toEqual({ kind: "cancel", lifecycle: "terminal", usage: ZERO_USAGE });
- });
-
- it("ignores results without an explicit lifecycle outcome", () => {
- expect(
- translateTaskInboundPayload({
- kind: "runtime-action-result",
- results: [{ isError: true, output: "broken" }],
- }),
- ).toBeUndefined();
- expect(
- translateTaskInboundPayload({ kind: "runtime-action-result", results: [{ output: "ok" }] }),
- ).toBeUndefined();
- });
-
- it("ignores empty result payloads", () => {
- expect(
- translateTaskInboundPayload({ kind: "runtime-action-result", results: [] }),
- ).toBeUndefined();
- });
-
- it("marks the task input_required on a forwarded HITL batch", () => {
- expect(
- translateTaskInboundPayload({
- callId: "call-1",
- childContinuationToken: "child-token",
- childSessionId: "child-session",
- event: {
- requests: [{ prompt: "Which region?" }],
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- },
- kind: "subagent-input-request",
- subagentName: "research",
- }),
- ).toEqual({ inputRequests: [{ prompt: "Which region?" }], kind: "require-input" });
- });
-
- it("blocks authorization under a reserved id that only its completion clears", () => {
- const requestId = "task:authorization:attempt-1";
- expect(
- translateTaskInboundPayload({
- callId: "call-1",
- childSessionId: "child-session",
- event: {
- data: {
- attemptId: "attempt-1",
- description: "Authorize GitHub",
- name: "github",
- sequence: 1,
- stepIndex: 2,
- turnId: "turn-1",
- },
- type: "authorization.required",
- },
- kind: "authorization-event",
- subagentName: "research",
- }),
- ).toEqual({
- kind: "require-authorization",
- requestId,
- });
- expect(
- translateTaskInboundPayload({
- callId: "call-1",
- childSessionId: "child-session",
- event: {
- data: {
- attemptId: "attempt-1",
- name: "github",
- outcome: "authorized",
- sequence: 2,
- stepIndex: 2,
- turnId: "turn-1",
- },
- type: "authorization.completed",
- },
- kind: "authorization-event",
- subagentName: "research",
- }),
- ).toEqual({ kind: "answered", requestIds: [requestId] });
- });
-
- it("leaves answered input to the run, which must deliver before recording it", () => {
- expect(
- translateTaskInboundPayload({
- childContinuationToken: "child-token",
- inputResponses: [{ requestId: "req-1", text: "west" }],
- kind: "input-response",
- taskId: "task-1",
- }),
- ).toBeUndefined();
- });
-});
diff --git a/packages/eve/src/tasks/wire.ts b/packages/eve/src/tasks/wire.ts
deleted file mode 100644
index 1a41ac4d2..000000000
--- a/packages/eve/src/tasks/wire.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import type { TaskCommand, TaskRunInboundPayload, TaskUsage } from "#tasks/types.js";
-import { readTaskUsage, taskAuthorizationRequestId } from "#tasks/types.js";
-
-/**
- * Translates one inbound hook payload into a lifecycle command.
- *
- * Delegated dispatch hands children the task run's hook token, so the
- * payloads that used to resume the parent turn arrive here instead:
- *
- * - a settled child turn (local notification or remote callback)
- * carries an explicit outcome — its result status decides
- * `complete`, `fail`, or `cancel`;
- * - a forwarded HITL batch marks the task `input_required` with the
- * outstanding requests;
- * - `authorization.required` also blocks the task (the child cannot
- * proceed without the parent's user) under a reserved request id, and
- * `authorization.completed` clears exactly that id. Authorization
- * payloads never enter the view — only the fact that the child is
- * blocked does.
- *
- * `input-response` is deliberately absent: the run must forward the
- * answers to the child before it may record them, so it builds that
- * command itself rather than translating one here.
- *
- * Returns `undefined` for unrecognized payloads, which the run ignores.
- */
-export function translateTaskInboundPayload(
- payload: TaskRunInboundPayload,
-): TaskCommand | undefined {
- switch (payload.kind) {
- case "task-command":
- return payload.command;
- case "runtime-action-result": {
- const result = payload.results[0];
- if (result === undefined) return undefined;
- if (result.outcome !== undefined) {
- // Usage retention: the settled outcome's `usageDelta` survives into
- // the terminal command so the view keeps the child's spend.
- const usage = readTaskUsage(result.outcome.usageDelta);
- switch (result.outcome.result.kind) {
- case "succeeded":
- return withUsage(
- { data: result.output, kind: "complete", lifecycle: result.outcome.kind },
- usage,
- );
- case "failed":
- return withUsage(
- { data: result.output, kind: "fail", lifecycle: result.outcome.kind },
- usage,
- );
- case "cancelled":
- return withUsage({ kind: "cancel", lifecycle: result.outcome.kind }, usage);
- }
- }
- return undefined;
- }
- case "subagent-input-request":
- return { inputRequests: payload.event.requests, kind: "require-input" };
- case "turn-started":
- return {
- childSessionId: payload.childSessionId,
- childTurnId: payload.childTurnId,
- kind: "start-turn",
- taskId: payload.taskId,
- };
- case "authorization-event": {
- const requestId = taskAuthorizationRequestId(payload.event);
- return payload.event.type === "authorization.required"
- ? { kind: "require-authorization", requestId }
- : { kind: "answered", requestIds: [requestId] };
- }
- default:
- return undefined;
- }
-}
-
-function withUsage(
- command: Extract<TaskCommand, { kind: "complete" | "fail" | "cancel" }>,
- usage: TaskUsage | undefined,
-): TaskCommand {
- if (usage === undefined) return command;
- return { ...command, usage };
-}
diff --git a/packages/eve/src/tools/framework/agent.ts b/packages/eve/src/tools/framework/agent.ts
index cadc69485..581c5ffaa 100644
--- a/packages/eve/src/tools/framework/agent.ts
+++ b/packages/eve/src/tools/framework/agent.ts
@@ -1,18 +1,28 @@
+import type { z } from "#compiled/zod/index.js";
+import { defineTool } from "#tools/definition.js";
import {
AGENT_TOOL_DESCRIPTION,
SUBAGENT_TOOL_INPUT_SCHEMA,
} from "#tools/framework/agent-contract.js";
-import { defineNativeTool } from "#tools/native-definition.js";
+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";
+import { attachToolBehavior } from "#tools/behavior.js";
-export const agent = defineNativeTool(
- {
- description: AGENT_TOOL_DESCRIPTION,
+export const agent = attachToolBehavior(
+ defineTool({
+ description: `${AGENT_TOOL_DESCRIPTION} This call starts a background task and returns a task receipt immediately.`,
+ execution: "background",
inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- },
- {
- availability: ["root-session"],
- handling: { action: "self-agent", kind: "dispatch" },
- },
+ outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,
+ // `defineTool` requires a body, but the runtime tool registry rebinds this
+ // tool to the shared subagent workflow before it can ever run.
+ execute(): z.infer<typeof SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA> {
+ "use workflow";
+ throw new Error(
+ 'The framework "agent" tool was executed directly. It must be resolved through the runtime tool registry, which dispatches it to the shared subagent workflow.',
+ );
+ },
+ }),
+ { availability: ["root-session"], handling: { action: "self-agent", kind: "dispatch" } },
);
export default agent;
diff --git a/packages/eve/src/tools/framework/task-contract.ts b/packages/eve/src/tools/framework/task-contract.ts
index e59e10dcd..7090353df 100644
--- a/packages/eve/src/tools/framework/task-contract.ts
+++ b/packages/eve/src/tools/framework/task-contract.ts
@@ -4,6 +4,12 @@ import { jsonValueSchema } from "#shared/json-schemas.js";
export const TASK_CANCEL_TOOL_NAME = "task_cancel";
export const TASK_UPDATE_TOOL_NAME = "task_update";
+/** Framework task-control tool names lowered by the runtime. */
+export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([
+ TASK_CANCEL_TOOL_NAME,
+ TASK_UPDATE_TOOL_NAME,
+]);
+
const TASK_IDS_SCHEMA = z
.array(z.string().min(1))
.min(1)
@@ -15,18 +21,12 @@ export const TASK_UPDATE_INPUT_SCHEMA = z.strictObject({
message: z.string().min(1).describe("Brief description of what this task is currently doing."),
});
-const taskMetadataJsonSchema = z.union([
- z.object({
- agentId: z.string(),
- kind: z.literal("subagent"),
- mode: z.enum(["local", "remote"]),
- name: z.string(),
- }),
- z.object({
- kind: z.string(),
- name: z.string(),
- }),
-]);
+const taskMetadataJsonSchema = z.object({
+ agentId: z.string().optional(),
+ kind: z.string(),
+ mode: z.enum(["local", "remote"]).optional(),
+ name: z.string(),
+});
const taskOutputJsonSchema = z.object({
data: jsonValueSchema,
@@ -68,19 +68,12 @@ export const TASK_VIEW_OUTPUT_SCHEMA = z.object({
type: z.enum(["result", "error"]),
})
.optional(),
- metadata: z.union([
- z.object({
- agentId: z.string(),
- kind: z.literal("subagent"),
- mode: z.enum(["local", "remote"]),
- name: z.string(),
- }),
- z.object({
- data: z.record(z.string(), z.unknown()).optional(),
- kind: z.string(),
- name: z.string(),
- }),
- ]),
+ metadata: z.object({
+ agentId: z.string().optional(),
+ kind: z.string(),
+ mode: z.enum(["local", "remote"]).optional(),
+ name: z.string(),
+ }),
status: z.enum(["working", "input_required", "completed", "failed", "cancelled"]),
taskId: z.string(),
});
diff --git a/packages/eve/src/tools/framework/task-update.ts b/packages/eve/src/tools/framework/task-update.ts
index affdc9efa..8ea8ec512 100644
--- a/packages/eve/src/tools/framework/task-update.ts
+++ b/packages/eve/src/tools/framework/task-update.ts
@@ -1,6 +1,9 @@
import { TASK_UPDATE_INPUT_SCHEMA } from "#tools/framework/task-contract.js";
import { defineNativeTool } from "#tools/native-definition.js";
+export const TASK_UPDATE_SESSION_INSTRUCTION =
+ "Background task updates\nYou are running as a background task. For multi-step work, use `task_update` at meaningful milestones to briefly state what you are currently doing. Keep updates terse and activity-focused; do not include preliminary findings or results. Do not wait for a response, and return your final result normally.";
+
export const taskUpdate = defineNativeTool(
{
description:
diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.ts
index ada70d21a..9978ebee4 100644
--- a/packages/eve/test/runtime-subagent-registry.test.ts
+++ b/packages/eve/test/runtime-subagent-registry.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";
-import { createRuntimeSubagentRegistry } from "../src/runtime/subagents/registry.js";
+import {
+ createPreparedRuntimeSubagentTool,
+ createRuntimeSubagentRegistry,
+} from "../src/runtime/subagents/registry.js";
import { SUBAGENT_TOOL_INPUT_SCHEMA as subagentToolInputSchema } from "../src/tools/framework/agent-contract.js";
import type { ResolvedRuntimeSubagentNode } from "../src/runtime/types.js";
@@ -55,7 +58,9 @@ describe("createRuntimeSubagentRegistry", () => {
expect(registry.preparedTools).toMatchObject([
{
- description: "Investigate one task in depth.",
+ description:
+ "Investigate one task in depth.\n\nThis call starts a background task and returns a task receipt immediately.",
+ execution: "background",
inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
kind: "subagent",
logicalPath: "subagents/researcher",
@@ -64,7 +69,9 @@ describe("createRuntimeSubagentRegistry", () => {
sourceId: "subagents/researcher",
},
{
- description: "Review one draft for clarity.",
+ description:
+ "Review one draft for clarity.\n\nThis call starts a background task and returns a task receipt immediately.",
+ execution: "background",
inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
kind: "subagent",
logicalPath: "subagents/reviewer",
@@ -91,6 +98,25 @@ describe("createRuntimeSubagentRegistry", () => {
}),
).toThrowError(RuntimeRegistryError);
});
+
+ it("always prepares subagent tools for background execution", () => {
+ const definition = createResolvedRuntimeSubagentNode({
+ description: "Investigate one task in depth.",
+ logicalPath: "subagents/researcher",
+ name: "researcher",
+ nodeId: "subagents/researcher",
+ sourceId: "subagents/researcher",
+ });
+
+ const prepared = createPreparedRuntimeSubagentTool(definition);
+
+ expect(prepared.execution).toBe("background");
+ expect(prepared.task).toEqual({
+ nodeId: definition.nodeId,
+ resultKind: "subagent",
+ workflowId: expect.stringContaining("subagentToolExecuteWorkflow"),
+ });
+ });
});
function createResolvedRuntimeSubagentNode(input: {
diff --git a/packages/eve/test/runtime-tool-registry.test.ts b/packages/eve/test/runtime-tool-registry.test.ts
index 8e9a03c66..2efa2f3b8 100644
--- a/packages/eve/test/runtime-tool-registry.test.ts
+++ b/packages/eve/test/runtime-tool-registry.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";
+import { subagentToolExecuteWorkflowReference } from "../src/runtime/subagents/workflow-reference.js";
import { createRuntimeToolRegistry } from "../src/runtime/tools/registry.js";
import type { ResolvedToolDefinition } from "../src/runtime/types.js";
import { toInputSchema } from "../src/tools/schema.js";
@@ -45,6 +46,92 @@ describe("createRuntimeToolRegistry", () => {
});
});
+ it("carries task_update availability into the prepared tool descriptor", async () => {
+ const registry = await createRuntimeToolRegistry({
+ tools: [
+ createResolvedToolDefinition({
+ behavior: {
+ availability: ["delegated-task-child"],
+ handling: { action: "task-update", kind: "dispatch" },
+ },
+ logicalPath: "tools/task_update.ts",
+ name: "task_update",
+ sourceId: "framework:tools/task_update.ts",
+ }),
+ ],
+ });
+
+ expect(registry.preparedTools[0]?.behavior).toEqual({
+ availability: ["delegated-task-child"],
+ handling: { kind: "dispatch", target: { kind: "task-update" } },
+ presentation: undefined,
+ });
+ });
+
+ it("keeps authored workflow execution metadata grouped", async () => {
+ const workflowId = "workflow//./agent/tools/deploy//execute";
+ const registry = await createRuntimeToolRegistry({
+ tools: [
+ createResolvedToolDefinition({
+ behavior: {
+ availability: [],
+ handling: { kind: "workflow-tool", workflowId },
+ },
+ logicalPath: "tools/deploy.ts",
+ name: "deploy",
+ sourceId: "tools/deploy.ts",
+ }),
+ ],
+ });
+
+ expect(registry.preparedTools[0]).toMatchObject({
+ behavior: {
+ handling: { kind: "dispatch", target: { kind: "workflow-tool-call", workflowId } },
+ },
+ });
+ expect(registry.preparedTools[0]?.task).toEqual({ workflowId });
+ expect(registry.preparedTools[0]).not.toHaveProperty("workflowId");
+ expect(registry.preparedTools[0]).not.toHaveProperty("nodeId");
+ expect(registry.preparedTools[0]).not.toHaveProperty("resultKind");
+ });
+
+ it("uses the shared stable workflow for the framework agent tool", async () => {
+ const registry = await createRuntimeToolRegistry({
+ tools: [
+ createResolvedToolDefinition({
+ behavior: {
+ availability: [],
+ handling: {
+ kind: "workflow-tool",
+ workflowId: "workflow//./agent/tools/agent//execute",
+ },
+ },
+ logicalPath: "tools/agent.ts",
+ name: "agent",
+ owner: { feature: "root-defaults", kind: "framework" },
+ sourceId: "eve:root-defaults:tools/agent.ts",
+ }),
+ ],
+ });
+
+ const prepared = registry.preparedTools[0];
+ expect(subagentToolExecuteWorkflowReference.workflowId).toMatch(
+ /^workflow\/\/[^/]+\/\/subagentToolExecuteWorkflow$/,
+ );
+ expect(prepared?.task).toEqual({
+ nodeId: "__root__",
+ resultKind: "subagent",
+ workflowId: subagentToolExecuteWorkflowReference.workflowId,
+ });
+ expect(prepared?.behavior?.handling).toEqual({
+ kind: "dispatch",
+ target: {
+ kind: "workflow-tool-call",
+ workflowId: subagentToolExecuteWorkflowReference.workflowId,
+ },
+ });
+ });
+
it("rejects duplicate authored tool names", async () => {
await expect(
createRuntimeToolRegistry({
@@ -85,13 +172,16 @@ describe("createRuntimeToolRegistry", () => {
});
function createResolvedToolDefinition(input: {
+ readonly behavior?: ResolvedToolDefinition["behavior"];
readonly description?: string;
readonly inputSchema?: ResolvedToolDefinition["inputSchema"];
readonly logicalPath: string;
readonly name: string;
+ readonly owner?: ResolvedToolDefinition["owner"];
readonly sourceId: string;
}): ResolvedToolDefinition {
return {
+ behavior: input.behavior,
inputSchema: input.inputSchema ?? null,
description: input.description ?? "Get the weather.",
execute(inputValue: unknown) {
@@ -99,7 +189,7 @@ function createResolvedToolDefinition(input: {
},
logicalPath: input.logicalPath,
name: input.name,
- owner: { kind: "application" },
+ owner: input.owner ?? { kind: "application" },
sourceId: input.sourceId,
sourceKind: "module",
};
diff --git a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
index 24d829876..608e947b2 100644
--- a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
+++ b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
@@ -73,8 +73,8 @@ describe("eve dist single-chunk module evaluation", () => {
// workflow's `steps.mjs`.
const stepSources = [
"src/internal/workflow/builtins.ts",
- "src/execution/session-callback-step.ts",
- "src/execution/subagent-adapter.ts",
+ "src/subagents/callback-step.ts",
+ "src/subagents/adapter.ts",
"src/execution/turn-workflow.ts",
"src/execution/workflow-entry.ts",
"src/execution/workflow-steps.ts",
diff --git a/packages/eve/test/scenarios/dev-server-harness.ts b/packages/eve/test/scenarios/dev-server-harness.ts
index 36f294e6c..336093102 100644
--- a/packages/eve/test/scenarios/dev-server-harness.ts
+++ b/packages/eve/test/scenarios/dev-server-harness.ts
@@ -224,8 +224,8 @@ function spawnEveDev(
cwd: appRoot,
env: {
...process.env,
- ...options.env,
NODE_ENV: "test",
+ ...options.env,
},
stdio: ["ignore", "pipe", "pipe"],
});
diff --git a/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts
index 6350a14b7..c6f4a64ac 100644
--- a/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts
@@ -192,7 +192,7 @@ describe("mounted extension via directory form with override", () => {
kind: "eve-extension",
formatVersion: 1,
builtWithEve: "0.0.0-test",
- requires: { extension: 1, subagent: 3 },
+ requires: { extension: 1, subagent: 6 },
}),
"node_modules/@acme/crm/extension/extension.mjs": [
'import { defineExtension } from "eve/extension";',
diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
index 10dce105e..2aef2b0b2 100644
--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {
);
expect(
JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),
- ).toMatchObject({ requires: { channel: 13, schedule: 6, subagent: 6 } });
+ ).toMatchObject({ requires: { channel: 14, schedule: 7, subagent: 7 } });
const app = await scenarioApp({
name: "mounted-extension-installed",
installDependencies: true,
diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
index c6abaa4ce..0c1ec6612 100644
--- a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
import type { SessionAuthContext } from "../../src/channel/types.js";
-import { startRemoteAgentSession } from "../../src/execution/remote-agent-dispatch.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "../../src/shared/action-types.js";
+import { startRemoteAgentSession } from "../../src/subagents/remote-dispatch.js";
+import type { RuntimeRemoteAgentDispatchRequest } from "../../src/shared/action-types.js";
import type { ResolvedRuntimeRemoteAgentNode } from "../../src/runtime/types.js";
import {
type ScenarioAppDescriptor,
@@ -127,7 +127,7 @@ describe("remote agent auth forwarding", () => {
);
});
-function createAction(): RuntimeRemoteAgentCallActionRequest {
+function createAction(): RuntimeRemoteAgentDispatchRequest {
return {
callId: "call-forwarded",
description: "Runtime action event description.",
diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
index bb90a99f8..17367c018 100644
--- a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts
@@ -18,8 +18,16 @@ const REMOTE_DESCRIPTOR: ScenarioAppDescriptor = {
dependencies: { zod: "^4.3.6" },
files: {
"agent/agent.ts": `import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
-export default defineAgent({ model: "openai/gpt-5.4-mini" });
+export default defineAgent({
+ model: mockModel(({ lastUserMessage }) =>
+ lastUserMessage?.includes("wait-for-cancel") === true
+ ? { toolCalls: [{ name: "wait-for-cancel", input: {} }] }
+ : "cancelled",
+ ),
+ modelContextWindowTokens: 32_000,
+});
`,
"agent/channels/eve.ts": `import { eveChannel } from "eve/channels/eve";
@@ -61,15 +69,43 @@ function createParentDescriptor(remoteUrl: string): ScenarioAppDescriptor {
dependencies: { zod: "^4.3.6" },
files: {
"agent/agent.ts": `import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
-export default defineAgent({ model: "openai/gpt-5.4-mini" });
+const model = mockModel((request) => {
+ const message = request.lastUserMessage ?? "";
+ if (message.includes("Use Workflow exactly once")) {
+ return {
+ toolCalls: [
+ {
+ name: "Workflow",
+ input: {
+ js: 'return await Promise.all([tools["local-sleeper"]({ message: "Use wait-for-cancel." }), tools["remote-sleeper"]({ message: "Use wait-for-cancel." })]);',
+ },
+ },
+ ],
+ };
+ }
+ return "still-alive";
+});
+
+export default defineAgent({ model, modelContextWindowTokens: 32_000 });
`,
"agent/instructions.md": "Delegate cancellation waits as requested.\n",
+ "agent/tools/workflow.ts": `import { experimental_workflow } from "eve/tools/workflow";
+
+export default experimental_workflow();
+`,
"agent/subagents/local-sleeper/agent.ts": `import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
export default defineAgent({
description: "Runs the wait-for-cancel tool and waits for cancellation.",
- model: "openai/gpt-5.4-mini",
+ model: mockModel(({ lastUserMessage }) =>
+ lastUserMessage?.includes("wait-for-cancel") === true
+ ? { toolCalls: [{ name: "wait-for-cancel", input: {} }] }
+ : "cancelled",
+ ),
+ modelContextWindowTokens: 32_000,
});
`,
"agent/subagents/local-sleeper/instructions.md":
@@ -113,14 +149,16 @@ describe("turn cancellation descendant cascade", () => {
try {
const parentApp = await scenarioApp(createParentDescriptor(remoteServer.url));
- const parentServer = await startEveDev(parentApp.appRoot);
+ const parentServer = await startEveDev(parentApp.appRoot, {
+ env: { EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },
+ });
try {
const parentClient = new Client({ host: parentServer.url });
const { session: parentSession, response } = await parentClient.sessions.create({
message: [
- "Call tools in parallel: local-sleeper, remote-sleeper",
- 'message: "Use wait-for-cancel."',
+ "Use Workflow exactly once to call local-sleeper and remote-sleeper in parallel.",
+ 'Pass both the message "Use wait-for-cancel." and return Promise.all of their results.',
].join("\n"),
});
const parentIterator = response[Symbol.asyncIterator]();
diff --git a/packages/eve/test/setup/workflow-global-setup.ts b/packages/eve/test/setup/workflow-global-setup.ts
index 51f260080..abbe8d3fc 100644
--- a/packages/eve/test/setup/workflow-global-setup.ts
+++ b/packages/eve/test/setup/workflow-global-setup.ts
@@ -56,6 +56,10 @@ async function discoverWorkflowEntries(): Promise<WorkflowBundleDiscoveredEntrie
const inputFiles = [
...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/execution"))),
...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/internal/testing"))),
+ ...(await collectWorkflowInputFiles(
+ resolvePackageSourceDirectoryPath("src/runtime/subagents"),
+ )),
+ ...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/subagents"))),
resolvePackageSourceFilePath("test/setup/compiled-artifacts-bootstrap.mjs"),
];
const discovered: WorkflowBundleDiscoveredEntries = {
diff --git a/packages/eve/test/tui-client/tui-subagents-weather.ts b/packages/eve/test/tui-client/tui-subagents-weather.ts
index 3f7560a4e..abc140469 100644
--- a/packages/eve/test/tui-client/tui-subagents-weather.ts
+++ b/packages/eve/test/tui-client/tui-subagents-weather.ts
@@ -40,7 +40,7 @@ const WEATHER_SMOKE_TARGET: RunOptions = {
kind: "local-build",
// The spawned server must use the deterministic authored-model adapter;
// otherwise this TUI rendering smoke depends on an AI Gateway credential.
- startEnv: { ...process.env, EVE_MOCK_AUTHORED_MODELS: "1" },
+ startEnv: { ...process.env, EVE_E2E_MODEL: "mock" },
};
run(WEATHER_SMOKE_TARGET, async (target) => {
diff --git a/research/executor-neutral-core.md b/research/executor-neutral-core.md
new file mode 100644
index 000000000..92d626ba8
--- /dev/null
+++ b/research/executor-neutral-core.md
@@ -0,0 +1,271 @@
+---
+issue: https://github.com/vercel/eve/pull/2690
+status: in-progress
+last_updated: "2026-09-02"
+---
+
+# Subagent execution boundaries
+
+## Scope of the current PR
+
+[#2690](https://github.com/vercel/eve/pull/2690) lands sequence steps 1–3
+below, plus the parts of steps 7 and 8 that had no dependency on the
+remaining work: `subagentDepth` is removed, and the vocabulary-count guards
+are replaced by import-direction rules 42–43. Concrete subagent code moves
+under `src/subagents/**` and `src/execution/tools/subagent/**` unchanged.
+
+Not in that PR: steps 4–6 and the rest of 7. `background-tool-execution.ts`
+still branches on `resultKind: "subagent"`, projects subagent tasks, and
+reserves handles inline; `workflowEntry` still carries its existing
+finalizers. Those are follow-ups against this document.
+
+## Summary
+
+The useful boundary is narrower than removing subagent concepts from all of
+`execution/**` and `harness/**`. Session and turn workflows are composition
+roots for eve's agent runtime. They may call the built-in task, workflow-tool,
+and subagent implementations directly. A runtime executor registry would add
+indirection without a second child executor to select.
+
+The reusable task kernel must remain neutral. A task owns readiness, progress,
+input obligations, cancellation, terminal caching, and dedupe. It carries an
+opaque executor binding; it does not resolve agent targets, mutate agent
+handles, translate child events, or know local from remote.
+
+The current implementation starts both a task workflow and a workflow-tool
+workflow for every background call. It also duplicates subagent admission and
+splits handle lifecycle ownership across the session driver, task run, and
+harness. The target design keeps one shared subagent workflow body, one task
+run for background execution, and one subagent executor shared by background
+and blocking calls.
+
+No public behavior changes. Model-visible subagent calls remain background
+tasks, `Workflow` calls remain blocking and return child outputs, `agent()`
+remains available inside authored background workflows, and receipts, events,
+HITL, continuation, and callback shapes remain stable.
+
+## Runtime topology
+
+```text
+direct model subagent call
+ -> task run (wait for admission, then execute shared subagent body)
+ -> subagent executor
+ -> child session
+
+authored background workflow tool
+ -> task run (wait for admission, then execute authored body)
+ -> agent(), when used
+ -> subagent executor
+ -> child session
+
+model-authored Workflow subagent call
+ -> blocking workflow-tool run
+ -> shared subagent body
+ -> subagent executor
+ -> child result resumes Workflow
+
+blocking authored workflow tool
+ -> workflow-tool run
+ -> result resumes the turn
+```
+
+`taskRunWorkflow` owns both lifecycle and body execution for background tools.
+`workflowToolRunWorkflow` remains the owner for blocking workflow calls. Both
+can execute the same registered workflow body; background execution does not
+need a second workflow run.
+
+The shared subagent body remains registered once under its stable framework
+workflow ID. Its target comes from the tool name and node binding. Per-subagent
+workflow IDs, manifest fields, and generated registrations add no behavior.
+
+## Ownership
+
+| State or behavior | Sole owner |
+| ------------------------------------------------------------------- | ----------------- |
+| Stable inbox, continuation alias, timeout, terminal event | Session driver |
+| Session snapshot and agent-handle store | Session driver |
+| Active turn snapshot and blocking child wait | Turn workflow |
+| Task state, readiness, progress, and input obligations | Task run |
+| Background workflow body | Its task run |
+| Blocking workflow body | Workflow-tool run |
+| Agent planning, handles, local/remote transport, and child cleanup | Subagent executor |
+| Model history, tool projection, approvals, and public action events | Harness |
+
+The parent session remains the canonical writer for agent handles. Background
+tasks can outlive turns, so they send handle commands to that owner. A turn may
+return an older snapshot, so the driver must preserve handle mutations accepted
+while the turn was running.
+
+This command-and-rebase mechanism is required by the current storage model, but
+its implementation should be one cohesive subagent handle-owner operation. It
+should not be spread across the generic inbox, router, cursor, task workflow,
+and background executor. Moving handles to an independent durable store could
+remove rebasing, but would add another service and migration and is out of
+scope.
+
+## Admission and settlement
+
+The parent task index is the ownership barrier. No authored body or child may
+start before the parent commits that index entry.
+
+```text
+prepare task and optional subagent lease
+start task run and claim its command hook
+wait for ready, reject-dispatch, or cancel
+
+ready -> execute the registered body
+reject-dispatch -> release admission state; do not execute the body
+cancel -> abort the body; await cleanup; then finish the task
+```
+
+The task run handles workflow progress, input requests, outcome, and
+cancellation generically. It does not interpret `agent.invoke`, construct
+`subagent-result`, or release agent handles. The workflow-safe `agent()` helper
+emits an opaque effect through the workflow owner. The parent execution
+composition interprets that effect and applies subagent state transitions to
+the live session snapshot.
+
+The subagent executor consumes the full child settlement before returning only
+the authored output to `agent()`:
+
+- A parked child makes the handle available for continuation.
+- A terminal child removes the handle and pending child-input routes.
+- Usage is reported to the task and parent before output is unwrapped.
+
+Task cancellation commits the cancelled view first, routes cancellation to the
+child, waits for the child dispatch to settle or become unreachable, then
+releases or removes the handle. Releasing first can advertise a child as
+available while its previous turn is still running.
+
+Child input remains a batch. One child event becomes one task input obligation,
+and only request IDs whose answers were delivered successfully are cleared.
+
+## Session composition
+
+`workflowEntry` remains a composition root for this sequence:
+
+```text
+create session
+claim inbox and timeout
+dispatch and adopt turns
+notify the accepted turn caller
+wait for session commands
+finalize once
+```
+
+The entry legitimately coordinates four subagent-owned obligations:
+
+- Apply task-owned handle commands and preserve them across turn adoption.
+- Notify a caller waiting for a delegated conversation turn.
+- Cancel blocking descendants with a cancelled turn.
+- Terminate tasks and child sessions when the parent ends.
+
+These should be cohesive calls into the subagent boundary. The entry should not
+parse handle phases, derive local/remote transport, or construct agent result
+variants.
+
+The driver carries an explicit neutral caller descriptor with a correlation
+ID, optional task ID, activity observer, and hook or callback reply target. The
+subagent boundary translates it to the existing agent result and callback
+wires. `mode` controls whether a session may park; it does not select the
+subagent result protocol.
+
+Additional entry simplifications:
+
+- Remove `subagentDepth`. Its remaining decisions only ask whether a session is
+ delegated, which `rootSessionId` already states.
+- Treat dynamic child configuration as effective agent bootstrap data rather
+ than making the driver interpret a dynamic-subagent type.
+- Resolve the initial caller while translating `RunInput`, not by deserializing
+ every new session's context.
+- Use one terminal finalizer for done, expiry, reset, inbox closure, and
+ failure. It records terminal emission before callbacks and uses the latest
+ context and turn ID. A cleanup or callback failure cannot emit a contradictory
+ second terminal event.
+
+## Tool and harness boundaries
+
+Prepared tool execution variants remain grouped so invalid combinations cannot
+be represented. `workflowId`, `nodeId`, `resultKind`, and `executeInput` should
+not become unrelated optional fields on every harness tool.
+
+Generic task and workflow protocols do not need
+`resultKind: "subagent"`. Subagent preparation selects the shared workflow body
+and supplies an opaque executor binding. A background owner runs that body in
+the task run; a blocking owner runs it in the workflow-tool run.
+
+The harness is an agent harness, not the neutral task kernel. Dynamic subagent
+tools, agent availability, and public `subagent.called` and
+`subagent.completed` events are legitimate harness behavior. Generic hooks for
+each would make the call graph harder to follow without enabling another
+implementation.
+
+Agent state transitions and transport do not belong in the harness. The
+subagent executor validates child identity, applies parked or terminal handle
+transitions, and clears child routes before a result reaches generic history
+coordination. It emits `subagent.called` after obtaining the child address;
+generic task code only carries the projected event.
+
+## Sequence
+
+1. Restore one coherent prepared-tool representation and a passing typecheck.
+ Split out the unrelated per-subagent workflow-ID and flattened metadata
+ changes.
+2. Fix the current behavioral regressions: blocking `Workflow` calls, missing
+ `subagent.called`, startup rollback, cancellation ordering, terminal-event
+ duplication, reset and closure finalization, multi-request HITL, terminal
+ handle removal, and nested usage.
+3. Gate background bodies on task admission and execute them inside
+ `taskRunWorkflow`. Keep a separate workflow-tool run only for blocking calls.
+4. Centralize subagent admission so the outer background step reserves or
+ claims once and passes that lease to the subagent executor.
+5. Route `agent()` through the workflow owner's opaque effect channel. Move
+ agent-effect parsing, result construction, handle release, and callback
+ transport from the task kernel to parent execution composition.
+6. Consolidate handle command application, reconciliation, cancellation, and
+ finalization under the subagent handle owner.
+7. Simplify `workflowEntry` with an explicit caller, no `subagentDepth`, one
+ terminal finalizer, and current crash context. Delete superseded finalizers
+ and unused dispatch helpers.
+8. Remove subagent state transitions from harness coordination and replace
+ vocabulary-count guards with import and ownership invariants.
+
+## Worktree disposition
+
+Keep explicit `taskId` session ownership, behavior-based tool availability, the
+shared subagent workflow body, and extraction of concrete start and cancel code
+under the subagent executor tree.
+
+Drop per-subagent workflow IDs, manifest v48, generated subagent workflow
+registrations, and flattened workflow metadata. Reconsider the separate
+session-command router: splitting one handle command path across an inbox,
+router, command protocol, and store adds code while the driver retains the same
+mutation responsibility. The neutral boundary is `src/tasks/**`;
+`execution/tasks/**` is parent/child task composition and may compose the
+subagent executor directly.
+
+## Compatibility and validation
+
+- Preserve immutable session-inbox v1 and v2. V3 already denotes generic task
+ `inputRequests` and `effects`; do not reuse that version for renamed child
+ messages.
+- Preserve the shared subagent workflow ID, workflow function identities,
+ operation hashes, ID formats, callback paths, receipt fields, and handle state
+ key.
+- Migrate persisted parked handles before deleting old phase readers. Do not
+ advertise an `agentId` that the task-owned claim path rejects.
+- Keep `NextDriverAction` changes additive because a session driver can outlive
+ its originating deployment.
+- Cover background admission rollback, cancellation ordering, local and remote
+ HITL, parked and terminal continuation, usage, and exactly-once terminal
+ notification in focused integration tests.
+
+Mechanical guards enforce dependency direction:
+
+- `src/tasks/**` imports neither `src/subagents/**` nor executor code.
+- `taskRunWorkflow` does not parse agent effects or mutate agent handles.
+- Generic inbox and cursor modules import no subagent types.
+- Immutable wire history is exempt from vocabulary counts.
+- Composition roots may import built-in executors directly.
+- No executor registry is added until two implementations require runtime
+ selection.
diff --git a/research/remote-agent-auth-forwarding.md b/research/remote-agent-auth-forwarding.md
index 1caf5482c..861befaf8 100644
--- a/research/remote-agent-auth-forwarding.md
+++ b/research/remote-agent-auth-forwarding.md
@@ -154,15 +154,15 @@ export default eveChannel({
## Boundaries and surfaces
-| Surface | Change |
-| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
-| `public/definitions/remote-agent.ts` | `forwardPrincipal?: boolean` |
-| `execution/dispatch-runtime-actions-step.ts` | pass `auth` / `initiatorAuth` (already in scope) to remote dispatch |
-| `execution/tasks/parent/dispatch-task-step.ts`, `execution/agent-handle-dispatch.ts` | pass active `auth` through persistent local and remote continuation |
-| `execution/remote-agent-dispatch.ts` | build `forwardedPrincipal` body field |
-| `channel/forwarded-principal.ts` (new) | strict wire schema for `{ current, initiator? }` (open `authenticator` / `principalType`), beside `session-callback.ts` |
-| `public/channels/eve.ts` | `trustedForwarders` option; forwarded-principal gate + principal replacement on create and continuation routes |
-| `docs/guides/remote-agents.md`, `docs/guides/auth-and-route-protection.md` | forwarding section on each side + trust-model warning |
+| Surface | Change |
+| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
+| `public/definitions/remote-agent.ts` | `forwardPrincipal?: boolean` |
+| `execution/dispatch-runtime-actions-step.ts` | pass `auth` / `initiatorAuth` (already in scope) to remote dispatch |
+| `execution/tasks/parent/dispatch-task-step.ts`, `harness/handles/dispatch.ts` | pass active `auth` through persistent local and remote continuation |
+| `execution/remote-agent-dispatch.ts` | build `forwardedPrincipal` body field |
+| `channel/forwarded-principal.ts` (new) | strict wire schema for `{ current, initiator? }` (open `authenticator` / `principalType`), beside `session-callback.ts` |
+| `public/channels/eve.ts` | `trustedForwarders` option; forwarded-principal gate + principal replacement on create and continuation routes |
+| `docs/guides/remote-agents.md`, `docs/guides/auth-and-route-protection.md` | forwarding section on each side + trust-model warning |
Docs must carry the security guidance explicitly: match the transport principal precisely (e.g.
`subject === vercelSubject({ teamSlug, projectName })`); a permissive predicate (`() => true`)
diff --git a/research/subagents-as-tasks-implementation.md b/research/subagents-as-tasks-implementation.md
index 4b64695f4..9296e44e7 100644
--- a/research/subagents-as-tasks-implementation.md
+++ b/research/subagents-as-tasks-implementation.md
@@ -24,7 +24,7 @@ session-addressing dependency the design doc declares:
replay-safe operation ids, commit-before-side-effect dispatch, and `starting/running/parked`
phases. Handles hold the child `continuationToken` (local) or `url` + `continuationToken`
(remote); credentials never render to the model.
-- **Follow-up delivery**: `dispatchToAgentHandle` / `continueRemoteAgentSession`, with
+- **Follow-up delivery**: `dispatchToTaskAgentAddress` / `continueRemoteAgentSession`, with
`AGENT_BUSY` / `AGENT_MISMATCH` / `AGENT_UNREACHABLE` classification and `intent: "resume"`
sends that 404 instead of silently starting a new session.
- **Reply envelope**: `TurnCaller` (`replyTo: hook token | callback URL`) and the
diff --git a/research/tools-as-workflows.md b/research/tools-as-workflows.md
index 42e9b0871..559cb8e9b 100644
--- a/research/tools-as-workflows.md
+++ b/research/tools-as-workflows.md
@@ -177,8 +177,8 @@ module map: those sources are compiled into the workflow driver and the step reg
## Boundaries
```
-turn / task (owner) tool run
- inbox hook ──────── starts ───────────────▶ toolRunWorkflow(execute)
+turn / task (owner) workflow tool run
+ inbox hook ──────── starts ───────────────▶ workflowToolRunWorkflow(execute)
<inbox>:report ◀── yield ───────────────── body
<inbox>:request ◀── ask (replyTo = answer) ─ body
<inbox>:outcome ◀── return / throw / cancel body
@@ -215,7 +215,7 @@ self-agent tools take, so the harness parks the turn instead of calling `execute
vendored copy everywhere authored code is bundled, and ships the types as `eve/workflow-modules`,
an ambient declaration listed in the scaffolded tsconfig's `types`. An installed `workflow`
package takes precedence for types if an application adds one.
-- The run-to-owner protocol (three owner hooks, `RunRef`, message shapes) stayed internal. Nothing
+- The run-to-owner protocol (three owner hooks, `WorkflowToolRunRef`, message shapes) stayed internal. Nothing
authored needs to construct those messages.
## Open questions
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index 13d7df9f2..d931678d3 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -108,7 +108,17 @@
* module, and identify its highest version as current. Wire versions
* are append-only protocol history: change the contract by adding a
* version and migration, never by updating historical data and its
- * snapshot together.
+ * snapshot together. The workflow-safe decoder must not import
+ * schemas or validation libraries at runtime.
+ * rule 42 — The shared subagent workflow body is framework-authored
+ * userspace. It must not import task, harness, or context
+ * internals or recover private state through `Symbol.for`.
+ * Privileged dispatch belongs in ordinary step-backed APIs that
+ * the workflow body consumes through a public contract.
+ * rule 43 — Reusable session plumbing stays independent of the subagent
+ * executor. The generic inbox and state cursor must not
+ * import subagent modules; session/turn composition roots may
+ * compose built-in executors directly.
*
* Baselines for rules with pre-existing violations live in
* `guard-invariants-baseline.json`. Counts and allowlists in that file
@@ -205,6 +215,8 @@ function isTsLike(relPath) {
* rule33: Violation[];
* rule35: Violation[];
* rule37: Violation[];
+ * rule42: Violation[];
+ * rule43: Violation[];
* symlinks: string[];
* }} state
*/
@@ -234,9 +246,71 @@ async function scanRepo(state) {
checkRule33(posix, lines, state.rule33);
checkRule35(posix, lines, state.rule35);
checkRule37(posix, content, state.rule37);
+ checkRule42(posix, lines, state.rule42);
+ checkRule43(posix, lines, state.rule43);
}
}
+// ---------- Rule 42: userspace subagent workflow ----------
+
+const SUBAGENT_WORKFLOW_PATH = "packages/eve/src/runtime/subagents/workflow.ts";
+const SUBAGENT_WORKFLOW_PRIVATE_IMPORT_RE =
+ /["']#(?:tasks|execution|harness|context|shared)(?:\/|\.js)/;
+// The shared body owns its invocation id, so it consumes the framework-internal
+// entry rather than the public `agent()`; that import is the one exception.
+const SUBAGENT_WORKFLOW_ALLOWED_IMPORT = '"#execution/tools/subagent/invoke-agent.js"';
+
+/**
+ * @param {string} posix
+ * @param {string[]} lines
+ * @param {Violation[]} violations
+ */
+function checkRule42(posix, lines, violations) {
+ if (posix !== SUBAGENT_WORKFLOW_PATH) return;
+
+ lines.forEach((line, idx) => {
+ if (line.includes(SUBAGENT_WORKFLOW_ALLOWED_IMPORT)) return;
+ if (!SUBAGENT_WORKFLOW_PRIVATE_IMPORT_RE.test(line) && !line.includes("Symbol.for(")) return;
+ violations.push({
+ rule: 42,
+ file: posix,
+ line: idx + 1,
+ message:
+ "the shared subagent workflow reaches into task, harness, or context internals. Keep the body userspace-shaped and call a public workflow-safe agent API instead.",
+ });
+ });
+}
+
+// ---------- Rule 43: executor-neutral session plumbing ----------
+
+// Matches both `#` alias specifiers and relative paths into the executor trees.
+const SUBAGENT_IMPORT_RE =
+ /from ["'](?:#|(?:\.\.?\/)+(?:[\w-]+\/)*)(?:subagents|execution\/tools\/subagent|tools\/subagent)(?:\/|\.js|["'])/;
+
+const RULE43_GENERIC_SESSION_FILES = new Set([
+ "packages/eve/src/execution/session-command-inbox.ts",
+ "packages/eve/src/execution/session-state-cursor.ts",
+]);
+
+/**
+ * @param {string} posix
+ * @param {string[]} lines
+ * @param {Violation[]} violations
+ */
+function checkRule43(posix, lines, violations) {
+ if (!RULE43_GENERIC_SESSION_FILES.has(posix)) return;
+ lines.forEach((line, idx) => {
+ if (!SUBAGENT_IMPORT_RE.test(line)) return;
+ violations.push({
+ rule: 43,
+ file: posix,
+ line: idx + 1,
+ message:
+ "generic session plumbing imports the subagent executor. Move executor-specific behavior to composition roots or subagent-owned modules.",
+ });
+ });
+}
+
// ---------- Rule 13: spread-ternary object composition ----------
/** Matches `...(<expr> ? {} : { ... })` or the mirrored form. */
@@ -536,6 +610,7 @@ function importSpecifier(node) {
const WIRE_FAMILY_DIR = "packages/eve/src/execution/wire";
const SESSION_INBOX_WIRE_CONTRACT = `${WIRE_FAMILY_DIR}/session-inbox-contract.ts`;
+const SESSION_INBOX_WIRE_DECODER = `${WIRE_FAMILY_DIR}/session-inbox-wire.ts`;
const VERSIONED_WIRE_HISTORY_RE = new RegExp(
`^${WIRE_FAMILY_DIR}/(?:__snapshots__/)?[a-z0-9-]+-wire\\.v\\d+(?:\\.migration)?(?:\\.test\\.ts(?:\\.snap)?|\\.ts)$`,
);
@@ -552,6 +627,16 @@ const PURE_MIGRATION_IMPORTS = new Map([
["#execution/durable-session-migrations/chain.js", new Map([["VersionMigration", "type"]])],
["#shared/guards.js", new Map([["isObject", "value"]])],
]);
+const WORKFLOW_DECODER_RUNTIME_IMPORTS = new Set([
+ "#execution/durable-session-migrations/chain.js",
+ "#execution/wire/session-inbox-contract.js",
+ "#execution/wire/session-inbox-wire.v0.js",
+ "#execution/wire/session-inbox-wire.v2-migration.js",
+ "#execution/wire/session-inbox-wire.v2.migration.js",
+ "#execution/wire/session-inbox-wire.v3.migration.js",
+ "#execution/wire/session-inbox-wire.v4.migration.js",
+ "#shared/guards.js",
+]);
function gitOutput(args) {
try {
@@ -654,6 +739,56 @@ function checkRule40MigrationPurity(path, source) {
return violations;
}
+function checkRule40WorkflowDecoderImports(source) {
+ const sourceFile = ts.createSourceFile(
+ SESSION_INBOX_WIRE_DECODER,
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TS,
+ );
+ /** @type {Violation[]} */
+ const violations = [];
+ const visit = (node) => {
+ const specifier = importSpecifier(node);
+ if (
+ specifier !== undefined &&
+ isRuntimeImportReference(node) &&
+ !WORKFLOW_DECODER_RUNTIME_IMPORTS.has(specifier.text)
+ ) {
+ violations.push({
+ rule: 40,
+ file: SESSION_INBOX_WIRE_DECODER,
+ line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,
+ message: `imports "${specifier.text}" at runtime. The session-inbox decoder is embedded with inline sources in every workflow driver; keep schema and validation dependencies in the encoder and import only the inferred wire type here.`,
+ });
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sourceFile);
+ return violations;
+}
+
+function isRuntimeImportReference(node) {
+ if (ts.isImportTypeNode(node)) return false;
+ if (ts.isImportDeclaration(node)) {
+ const clause = node.importClause;
+ if (clause?.isTypeOnly === true) return false;
+ if (clause?.namedBindings !== undefined && ts.isNamedImports(clause.namedBindings)) {
+ return clause.namedBindings.elements.some((element) => !element.isTypeOnly);
+ }
+ return true;
+ }
+ if (ts.isExportDeclaration(node)) {
+ if (node.isTypeOnly) return false;
+ if (node.exportClause !== undefined && ts.isNamedExports(node.exportClause)) {
+ return node.exportClause.elements.some((element) => !element.isTypeOnly);
+ }
+ return true;
+ }
+ return true;
+}
+
async function checkRule40WireContracts() {
const violations = checkRule40ImmutableWireHistory();
let entries;
@@ -686,6 +821,8 @@ async function checkRule40WireContracts() {
}
const contractSource = await readFile(join(REPO_ROOT, SESSION_INBOX_WIRE_CONTRACT), "utf8");
+ const decoderSource = await readFile(join(REPO_ROOT, SESSION_INBOX_WIRE_DECODER), "utf8");
+ violations.push(...checkRule40WorkflowDecoderImports(decoderSource));
const registryMatch = contractSource.match(
/SESSION_INBOX_WIRE_VERSIONS\s*=\s*\[([^\]]*)\]\s*as const/,
);
@@ -1486,6 +1623,8 @@ async function main() {
rule33: /** @type {Violation[]} */ ([]),
rule35: /** @type {Violation[]} */ ([]),
rule37: /** @type {Violation[]} */ ([]),
+ rule42: /** @type {Violation[]} */ ([]),
+ rule43: /** @type {Violation[]} */ ([]),
symlinks: /** @type {string[]} */ ([]),
};
@@ -1591,6 +1730,12 @@ async function main() {
// Rule 40
violations.push(...(await checkRule40WireContracts()));
+ // Rule 42
+ violations.push(...state.rule42);
+
+ // Rule 43
+ violations.push(...state.rule43);
+
if (violations.length === 0) {
process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");
return;